thread_view.rs

   1use acp_thread::{AgentConnection, Plan};
   2use agent_servers::AgentServer;
   3use agent_settings::{AgentSettings, NotifyWhenAgentWaiting};
   4use audio::{Audio, Sound};
   5use std::cell::RefCell;
   6use std::collections::BTreeMap;
   7use std::path::Path;
   8use std::process::ExitStatus;
   9use std::rc::Rc;
  10use std::sync::Arc;
  11use std::time::Duration;
  12
  13use agent_client_protocol as acp;
  14use assistant_tool::ActionLog;
  15use buffer_diff::BufferDiff;
  16use collections::{HashMap, HashSet};
  17use editor::{
  18    AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorMode,
  19    EditorStyle, MinimapVisibility, MultiBuffer, PathKey,
  20};
  21use file_icons::FileIcons;
  22use gpui::{
  23    Action, Animation, AnimationExt, App, BorderStyle, EdgesRefinement, Empty, Entity, EntityId,
  24    FocusHandle, Focusable, Hsla, Length, ListOffset, ListState, MouseButton, PlatformDisplay,
  25    SharedString, Stateful, StyleRefinement, Subscription, Task, TextStyle, TextStyleRefinement,
  26    Transformation, UnderlineStyle, WeakEntity, Window, WindowHandle, div, linear_color_stop,
  27    linear_gradient, list, percentage, point, prelude::*, pulsating_between,
  28};
  29use language::language_settings::SoftWrap;
  30use language::{Buffer, Language};
  31use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  32use parking_lot::Mutex;
  33use project::Project;
  34use settings::Settings as _;
  35use text::{Anchor, BufferSnapshot};
  36use theme::ThemeSettings;
  37use ui::{
  38    Disclosure, Divider, DividerColor, KeyBinding, Scrollbar, ScrollbarState, Tooltip, prelude::*,
  39};
  40use util::ResultExt;
  41use workspace::{CollaboratorId, Workspace};
  42use zed_actions::agent::{Chat, NextHistoryMessage, PreviousHistoryMessage};
  43
  44use ::acp_thread::{
  45    AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, Diff,
  46    LoadError, MentionPath, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
  47};
  48
  49use crate::acp::completion_provider::{ContextPickerCompletionProvider, MentionSet};
  50use crate::acp::message_history::MessageHistory;
  51use crate::agent_diff::AgentDiff;
  52use crate::message_editor::{MAX_EDITOR_LINES, MIN_EDITOR_LINES};
  53use crate::ui::{AgentNotification, AgentNotificationEvent};
  54use crate::{
  55    AgentDiffPane, AgentPanel, ExpandMessageEditor, Follow, KeepAll, OpenAgentDiff, RejectAll,
  56};
  57
  58const RESPONSE_PADDING_X: Pixels = px(19.);
  59
  60pub struct AcpThreadView {
  61    agent: Rc<dyn AgentServer>,
  62    workspace: WeakEntity<Workspace>,
  63    project: Entity<Project>,
  64    thread_state: ThreadState,
  65    diff_editors: HashMap<EntityId, Entity<Editor>>,
  66    message_editor: Entity<Editor>,
  67    message_set_from_history: Option<BufferSnapshot>,
  68    _message_editor_subscription: Subscription,
  69    mention_set: Arc<Mutex<MentionSet>>,
  70    notifications: Vec<WindowHandle<AgentNotification>>,
  71    notification_subscriptions: HashMap<WindowHandle<AgentNotification>, Vec<Subscription>>,
  72    last_error: Option<Entity<Markdown>>,
  73    list_state: ListState,
  74    scrollbar_state: ScrollbarState,
  75    auth_task: Option<Task<()>>,
  76    expanded_tool_calls: HashSet<acp::ToolCallId>,
  77    expanded_thinking_blocks: HashSet<(usize, usize)>,
  78    edits_expanded: bool,
  79    plan_expanded: bool,
  80    editor_expanded: bool,
  81    message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
  82    _cancel_task: Option<Task<()>>,
  83}
  84
  85enum ThreadState {
  86    Loading {
  87        _task: Task<()>,
  88    },
  89    Ready {
  90        thread: Entity<AcpThread>,
  91        _subscription: [Subscription; 2],
  92    },
  93    LoadError(LoadError),
  94    Unauthenticated {
  95        connection: Rc<dyn AgentConnection>,
  96    },
  97    ServerExited {
  98        status: ExitStatus,
  99    },
 100}
 101
 102impl AcpThreadView {
 103    pub fn new(
 104        agent: Rc<dyn AgentServer>,
 105        workspace: WeakEntity<Workspace>,
 106        project: Entity<Project>,
 107        message_history: Rc<RefCell<MessageHistory<Vec<acp::ContentBlock>>>>,
 108        min_lines: usize,
 109        max_lines: Option<usize>,
 110        window: &mut Window,
 111        cx: &mut Context<Self>,
 112    ) -> Self {
 113        let language = Language::new(
 114            language::LanguageConfig {
 115                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
 116                ..Default::default()
 117            },
 118            None,
 119        );
 120
 121        let mention_set = Arc::new(Mutex::new(MentionSet::default()));
 122
 123        let message_editor = cx.new(|cx| {
 124            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 125            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 126
 127            let mut editor = Editor::new(
 128                editor::EditorMode::AutoHeight {
 129                    min_lines,
 130                    max_lines: max_lines,
 131                },
 132                buffer,
 133                None,
 134                window,
 135                cx,
 136            );
 137            editor.set_placeholder_text("Message the agent - @ to include files", cx);
 138            editor.set_show_indent_guides(false, cx);
 139            editor.set_soft_wrap();
 140            editor.set_use_modal_editing(true);
 141            editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
 142                mention_set.clone(),
 143                workspace.clone(),
 144                cx.weak_entity(),
 145            ))));
 146            editor.set_context_menu_options(ContextMenuOptions {
 147                min_entries_visible: 12,
 148                max_entries_visible: 12,
 149                placement: Some(ContextMenuPlacement::Above),
 150            });
 151            editor
 152        });
 153
 154        let message_editor_subscription =
 155            cx.subscribe(&message_editor, |this, editor, event, cx| {
 156                if let editor::EditorEvent::BufferEdited = &event {
 157                    let buffer = editor
 158                        .read(cx)
 159                        .buffer()
 160                        .read(cx)
 161                        .as_singleton()
 162                        .unwrap()
 163                        .read(cx)
 164                        .snapshot();
 165                    if let Some(message) = this.message_set_from_history.clone()
 166                        && message.version() != buffer.version()
 167                    {
 168                        this.message_set_from_history = None;
 169                    }
 170
 171                    if this.message_set_from_history.is_none() {
 172                        this.message_history.borrow_mut().reset_position();
 173                    }
 174                }
 175            });
 176
 177        let mention_set = mention_set.clone();
 178
 179        let list_state = ListState::new(0, gpui::ListAlignment::Bottom, px(2048.0));
 180
 181        Self {
 182            agent: agent.clone(),
 183            workspace: workspace.clone(),
 184            project: project.clone(),
 185            thread_state: Self::initial_state(agent, workspace, project, window, cx),
 186            message_editor,
 187            message_set_from_history: None,
 188            _message_editor_subscription: message_editor_subscription,
 189            mention_set,
 190            notifications: Vec::new(),
 191            notification_subscriptions: HashMap::default(),
 192            diff_editors: Default::default(),
 193            list_state: list_state.clone(),
 194            scrollbar_state: ScrollbarState::new(list_state).parent_entity(&cx.entity()),
 195            last_error: None,
 196            auth_task: None,
 197            expanded_tool_calls: HashSet::default(),
 198            expanded_thinking_blocks: HashSet::default(),
 199            edits_expanded: false,
 200            plan_expanded: false,
 201            editor_expanded: false,
 202            message_history,
 203            _cancel_task: None,
 204        }
 205    }
 206
 207    fn initial_state(
 208        agent: Rc<dyn AgentServer>,
 209        workspace: WeakEntity<Workspace>,
 210        project: Entity<Project>,
 211        window: &mut Window,
 212        cx: &mut Context<Self>,
 213    ) -> ThreadState {
 214        let root_dir = project
 215            .read(cx)
 216            .visible_worktrees(cx)
 217            .next()
 218            .map(|worktree| worktree.read(cx).abs_path())
 219            .unwrap_or_else(|| paths::home_dir().as_path().into());
 220
 221        let connect_task = agent.connect(&root_dir, &project, cx);
 222        let load_task = cx.spawn_in(window, async move |this, cx| {
 223            let connection = match connect_task.await {
 224                Ok(connection) => connection,
 225                Err(err) => {
 226                    this.update(cx, |this, cx| {
 227                        this.handle_load_error(err, cx);
 228                        cx.notify();
 229                    })
 230                    .log_err();
 231                    return;
 232                }
 233            };
 234
 235            // this.update_in(cx, |_this, _window, cx| {
 236            //     let status = connection.exit_status(cx);
 237            //     cx.spawn(async move |this, cx| {
 238            //         let status = status.await.ok();
 239            //         this.update(cx, |this, cx| {
 240            //             this.thread_state = ThreadState::ServerExited { status };
 241            //             cx.notify();
 242            //         })
 243            //         .ok();
 244            //     })
 245            //     .detach();
 246            // })
 247            // .ok();
 248
 249            let result = match connection
 250                .clone()
 251                .new_thread(project.clone(), &root_dir, cx)
 252                .await
 253            {
 254                Err(e) => {
 255                    let mut cx = cx.clone();
 256                    if e.is::<acp_thread::AuthRequired>() {
 257                        this.update(&mut cx, |this, cx| {
 258                            this.thread_state = ThreadState::Unauthenticated { connection };
 259                            cx.notify();
 260                        })
 261                        .ok();
 262                        return;
 263                    } else {
 264                        Err(e)
 265                    }
 266                }
 267                Ok(session_id) => Ok(session_id),
 268            };
 269
 270            this.update_in(cx, |this, window, cx| {
 271                match result {
 272                    Ok(thread) => {
 273                        let thread_subscription =
 274                            cx.subscribe_in(&thread, window, Self::handle_thread_event);
 275
 276                        let action_log = thread.read(cx).action_log().clone();
 277                        let action_log_subscription =
 278                            cx.observe(&action_log, |_, _, cx| cx.notify());
 279
 280                        this.list_state
 281                            .splice(0..0, thread.read(cx).entries().len());
 282
 283                        AgentDiff::set_active_thread(&workspace, thread.clone(), window, cx);
 284
 285                        this.thread_state = ThreadState::Ready {
 286                            thread,
 287                            _subscription: [thread_subscription, action_log_subscription],
 288                        };
 289
 290                        cx.notify();
 291                    }
 292                    Err(err) => {
 293                        this.handle_load_error(err, cx);
 294                    }
 295                };
 296            })
 297            .log_err();
 298        });
 299
 300        ThreadState::Loading { _task: load_task }
 301    }
 302
 303    fn handle_load_error(&mut self, err: anyhow::Error, cx: &mut Context<Self>) {
 304        if let Some(load_err) = err.downcast_ref::<LoadError>() {
 305            self.thread_state = ThreadState::LoadError(load_err.clone());
 306        } else {
 307            self.thread_state = ThreadState::LoadError(LoadError::Other(err.to_string().into()))
 308        }
 309        cx.notify();
 310    }
 311
 312    pub fn thread(&self) -> Option<&Entity<AcpThread>> {
 313        match &self.thread_state {
 314            ThreadState::Ready { thread, .. } => Some(thread),
 315            ThreadState::Unauthenticated { .. }
 316            | ThreadState::Loading { .. }
 317            | ThreadState::LoadError(..)
 318            | ThreadState::ServerExited { .. } => None,
 319        }
 320    }
 321
 322    pub fn title(&self, cx: &App) -> SharedString {
 323        match &self.thread_state {
 324            ThreadState::Ready { thread, .. } => thread.read(cx).title(),
 325            ThreadState::Loading { .. } => "Loading…".into(),
 326            ThreadState::LoadError(_) => "Failed to load".into(),
 327            ThreadState::Unauthenticated { .. } => "Not authenticated".into(),
 328            ThreadState::ServerExited { .. } => "Server exited unexpectedly".into(),
 329        }
 330    }
 331
 332    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 333        self.last_error.take();
 334
 335        if let Some(thread) = self.thread() {
 336            self._cancel_task = Some(thread.update(cx, |thread, cx| thread.cancel(cx)));
 337        }
 338    }
 339
 340    pub fn expand_message_editor(
 341        &mut self,
 342        _: &ExpandMessageEditor,
 343        _window: &mut Window,
 344        cx: &mut Context<Self>,
 345    ) {
 346        self.set_editor_is_expanded(!self.editor_expanded, cx);
 347        cx.notify();
 348    }
 349
 350    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 351        self.editor_expanded = is_expanded;
 352        self.message_editor.update(cx, |editor, _| {
 353            if self.editor_expanded {
 354                editor.set_mode(EditorMode::Full {
 355                    scale_ui_elements_with_buffer_font_size: false,
 356                    show_active_line_background: false,
 357                    sized_by_content: false,
 358                })
 359            } else {
 360                editor.set_mode(EditorMode::AutoHeight {
 361                    min_lines: MIN_EDITOR_LINES,
 362                    max_lines: Some(MAX_EDITOR_LINES),
 363                })
 364            }
 365        });
 366        cx.notify();
 367    }
 368
 369    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 370        self.last_error.take();
 371
 372        let mut ix = 0;
 373        let mut chunks: Vec<acp::ContentBlock> = Vec::new();
 374        let project = self.project.clone();
 375        self.message_editor.update(cx, |editor, cx| {
 376            let text = editor.text(cx);
 377            editor.display_map.update(cx, |map, cx| {
 378                let snapshot = map.snapshot(cx);
 379                for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 380                    if let Some(project_path) =
 381                        self.mention_set.lock().path_for_crease_id(crease_id)
 382                    {
 383                        let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
 384                        if crease_range.start > ix {
 385                            chunks.push(text[ix..crease_range.start].into());
 386                        }
 387                        if let Some(abs_path) = project.read(cx).absolute_path(&project_path, cx) {
 388                            let path_str = abs_path.display().to_string();
 389                            chunks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink {
 390                                uri: path_str.clone(),
 391                                name: path_str,
 392                                annotations: None,
 393                                description: None,
 394                                mime_type: None,
 395                                size: None,
 396                                title: None,
 397                            }));
 398                        }
 399                        ix = crease_range.end;
 400                    }
 401                }
 402
 403                if ix < text.len() {
 404                    let last_chunk = text[ix..].trim();
 405                    if !last_chunk.is_empty() {
 406                        chunks.push(last_chunk.into());
 407                    }
 408                }
 409            })
 410        });
 411
 412        if chunks.is_empty() {
 413            return;
 414        }
 415
 416        let Some(thread) = self.thread() else {
 417            return;
 418        };
 419        let task = thread.update(cx, |thread, cx| thread.send(chunks.clone(), cx));
 420
 421        cx.spawn(async move |this, cx| {
 422            let result = task.await;
 423
 424            this.update(cx, |this, cx| {
 425                if let Err(err) = result {
 426                    this.last_error =
 427                        Some(cx.new(|cx| Markdown::new(err.to_string().into(), None, None, cx)))
 428                }
 429            })
 430        })
 431        .detach();
 432
 433        let mention_set = self.mention_set.clone();
 434
 435        self.set_editor_is_expanded(false, cx);
 436
 437        self.message_editor.update(cx, |editor, cx| {
 438            editor.clear(window, cx);
 439            editor.remove_creases(mention_set.lock().drain(), cx)
 440        });
 441
 442        self.scroll_to_bottom(cx);
 443
 444        self.message_history.borrow_mut().push(chunks);
 445    }
 446
 447    fn previous_history_message(
 448        &mut self,
 449        _: &PreviousHistoryMessage,
 450        window: &mut Window,
 451        cx: &mut Context<Self>,
 452    ) {
 453        if self.message_set_from_history.is_none() && !self.message_editor.read(cx).is_empty(cx) {
 454            self.message_editor.update(cx, |editor, cx| {
 455                editor.move_up(&Default::default(), window, cx);
 456            });
 457            return;
 458        }
 459
 460        self.message_set_from_history = Self::set_draft_message(
 461            self.message_editor.clone(),
 462            self.mention_set.clone(),
 463            self.project.clone(),
 464            self.message_history
 465                .borrow_mut()
 466                .prev()
 467                .map(|blocks| blocks.as_slice()),
 468            window,
 469            cx,
 470        );
 471    }
 472
 473    fn next_history_message(
 474        &mut self,
 475        _: &NextHistoryMessage,
 476        window: &mut Window,
 477        cx: &mut Context<Self>,
 478    ) {
 479        if self.message_set_from_history.is_none() {
 480            self.message_editor.update(cx, |editor, cx| {
 481                editor.move_down(&Default::default(), window, cx);
 482            });
 483            return;
 484        }
 485
 486        let mut message_history = self.message_history.borrow_mut();
 487        let next_history = message_history.next();
 488
 489        let set_draft_message = Self::set_draft_message(
 490            self.message_editor.clone(),
 491            self.mention_set.clone(),
 492            self.project.clone(),
 493            Some(
 494                next_history
 495                    .map(|blocks| blocks.as_slice())
 496                    .unwrap_or_else(|| &[]),
 497            ),
 498            window,
 499            cx,
 500        );
 501        // If we reset the text to an empty string because we ran out of history,
 502        // we don't want to mark it as coming from the history
 503        self.message_set_from_history = if next_history.is_some() {
 504            set_draft_message
 505        } else {
 506            None
 507        };
 508    }
 509
 510    fn open_agent_diff(&mut self, _: &OpenAgentDiff, window: &mut Window, cx: &mut Context<Self>) {
 511        if let Some(thread) = self.thread() {
 512            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err();
 513        }
 514    }
 515
 516    fn open_edited_buffer(
 517        &mut self,
 518        buffer: &Entity<Buffer>,
 519        window: &mut Window,
 520        cx: &mut Context<Self>,
 521    ) {
 522        let Some(thread) = self.thread() else {
 523            return;
 524        };
 525
 526        let Some(diff) =
 527            AgentDiffPane::deploy(thread.clone(), self.workspace.clone(), window, cx).log_err()
 528        else {
 529            return;
 530        };
 531
 532        diff.update(cx, |diff, cx| {
 533            diff.move_to_path(PathKey::for_buffer(&buffer, cx), window, cx)
 534        })
 535    }
 536
 537    fn set_draft_message(
 538        message_editor: Entity<Editor>,
 539        mention_set: Arc<Mutex<MentionSet>>,
 540        project: Entity<Project>,
 541        message: Option<&[acp::ContentBlock]>,
 542        window: &mut Window,
 543        cx: &mut Context<Self>,
 544    ) -> Option<BufferSnapshot> {
 545        cx.notify();
 546
 547        let message = message?;
 548
 549        let mut text = String::new();
 550        let mut mentions = Vec::new();
 551
 552        for chunk in message {
 553            match chunk {
 554                acp::ContentBlock::Text(text_content) => {
 555                    text.push_str(&text_content.text);
 556                }
 557                acp::ContentBlock::ResourceLink(resource_link) => {
 558                    let path = Path::new(&resource_link.uri);
 559                    let start = text.len();
 560                    let content = MentionPath::new(&path).to_string();
 561                    text.push_str(&content);
 562                    let end = text.len();
 563                    if let Some(project_path) =
 564                        project.read(cx).project_path_for_absolute_path(&path, cx)
 565                    {
 566                        let filename: SharedString = path
 567                            .file_name()
 568                            .unwrap_or_default()
 569                            .to_string_lossy()
 570                            .to_string()
 571                            .into();
 572                        mentions.push((start..end, project_path, filename));
 573                    }
 574                }
 575                acp::ContentBlock::Image(_)
 576                | acp::ContentBlock::Audio(_)
 577                | acp::ContentBlock::Resource(_) => {}
 578            }
 579        }
 580
 581        let snapshot = message_editor.update(cx, |editor, cx| {
 582            editor.set_text(text, window, cx);
 583            editor.buffer().read(cx).snapshot(cx)
 584        });
 585
 586        for (range, project_path, filename) in mentions {
 587            let crease_icon_path = if project_path.path.is_dir() {
 588                FileIcons::get_folder_icon(false, cx)
 589                    .unwrap_or_else(|| IconName::Folder.path().into())
 590            } else {
 591                FileIcons::get_icon(Path::new(project_path.path.as_ref()), cx)
 592                    .unwrap_or_else(|| IconName::File.path().into())
 593            };
 594
 595            let anchor = snapshot.anchor_before(range.start);
 596            let crease_id = crate::context_picker::insert_crease_for_mention(
 597                anchor.excerpt_id,
 598                anchor.text_anchor,
 599                range.end - range.start,
 600                filename,
 601                crease_icon_path,
 602                message_editor.clone(),
 603                window,
 604                cx,
 605            );
 606            if let Some(crease_id) = crease_id {
 607                mention_set.lock().insert(crease_id, project_path);
 608            }
 609        }
 610
 611        let snapshot = snapshot.as_singleton().unwrap().2.clone();
 612        Some(snapshot.text)
 613    }
 614
 615    fn handle_thread_event(
 616        &mut self,
 617        thread: &Entity<AcpThread>,
 618        event: &AcpThreadEvent,
 619        window: &mut Window,
 620        cx: &mut Context<Self>,
 621    ) {
 622        let count = self.list_state.item_count();
 623        match event {
 624            AcpThreadEvent::NewEntry => {
 625                let index = thread.read(cx).entries().len() - 1;
 626                self.sync_thread_entry_view(index, window, cx);
 627                self.list_state.splice(count..count, 1);
 628            }
 629            AcpThreadEvent::EntryUpdated(index) => {
 630                let index = *index;
 631                self.sync_thread_entry_view(index, window, cx);
 632                self.list_state.splice(index..index + 1, 1);
 633            }
 634            AcpThreadEvent::ToolAuthorizationRequired => {
 635                self.notify_with_sound("Waiting for tool confirmation", IconName::Info, window, cx);
 636            }
 637            AcpThreadEvent::Stopped => {
 638                let used_tools = thread.read(cx).used_tools_since_last_user_message();
 639                self.notify_with_sound(
 640                    if used_tools {
 641                        "Finished running tools"
 642                    } else {
 643                        "New message"
 644                    },
 645                    IconName::ZedAssistant,
 646                    window,
 647                    cx,
 648                );
 649            }
 650            AcpThreadEvent::Error => {
 651                self.notify_with_sound(
 652                    "Agent stopped due to an error",
 653                    IconName::Warning,
 654                    window,
 655                    cx,
 656                );
 657            }
 658            AcpThreadEvent::ServerExited(status) => {
 659                self.thread_state = ThreadState::ServerExited { status: *status };
 660            }
 661        }
 662        cx.notify();
 663    }
 664
 665    fn sync_thread_entry_view(
 666        &mut self,
 667        entry_ix: usize,
 668        window: &mut Window,
 669        cx: &mut Context<Self>,
 670    ) {
 671        let Some(multibuffers) = self.entry_diff_multibuffers(entry_ix, cx) else {
 672            return;
 673        };
 674
 675        let multibuffers = multibuffers.collect::<Vec<_>>();
 676
 677        for multibuffer in multibuffers {
 678            if self.diff_editors.contains_key(&multibuffer.entity_id()) {
 679                return;
 680            }
 681
 682            let editor = cx.new(|cx| {
 683                let mut editor = Editor::new(
 684                    EditorMode::Full {
 685                        scale_ui_elements_with_buffer_font_size: false,
 686                        show_active_line_background: false,
 687                        sized_by_content: true,
 688                    },
 689                    multibuffer.clone(),
 690                    None,
 691                    window,
 692                    cx,
 693                );
 694                editor.set_show_gutter(false, cx);
 695                editor.disable_inline_diagnostics();
 696                editor.disable_expand_excerpt_buttons(cx);
 697                editor.set_show_vertical_scrollbar(false, cx);
 698                editor.set_minimap_visibility(MinimapVisibility::Disabled, window, cx);
 699                editor.set_soft_wrap_mode(SoftWrap::None, cx);
 700                editor.scroll_manager.set_forbid_vertical_scroll(true);
 701                editor.set_show_indent_guides(false, cx);
 702                editor.set_read_only(true);
 703                editor.set_show_breakpoints(false, cx);
 704                editor.set_show_code_actions(false, cx);
 705                editor.set_show_git_diff_gutter(false, cx);
 706                editor.set_expand_all_diff_hunks(cx);
 707                editor.set_text_style_refinement(TextStyleRefinement {
 708                    font_size: Some(
 709                        TextSize::Small
 710                            .rems(cx)
 711                            .to_pixels(ThemeSettings::get_global(cx).agent_font_size(cx))
 712                            .into(),
 713                    ),
 714                    ..Default::default()
 715                });
 716                editor
 717            });
 718            let entity_id = multibuffer.entity_id();
 719            cx.observe_release(&multibuffer, move |this, _, _| {
 720                this.diff_editors.remove(&entity_id);
 721            })
 722            .detach();
 723
 724            self.diff_editors.insert(entity_id, editor);
 725        }
 726    }
 727
 728    fn entry_diff_multibuffers(
 729        &self,
 730        entry_ix: usize,
 731        cx: &App,
 732    ) -> Option<impl Iterator<Item = Entity<MultiBuffer>>> {
 733        let entry = self.thread()?.read(cx).entries().get(entry_ix)?;
 734        Some(entry.diffs().map(|diff| diff.multibuffer.clone()))
 735    }
 736
 737    fn authenticate(
 738        &mut self,
 739        method: acp::AuthMethodId,
 740        window: &mut Window,
 741        cx: &mut Context<Self>,
 742    ) {
 743        let ThreadState::Unauthenticated { ref connection } = self.thread_state else {
 744            return;
 745        };
 746
 747        self.last_error.take();
 748        let authenticate = connection.authenticate(method, cx);
 749        self.auth_task = Some(cx.spawn_in(window, {
 750            let project = self.project.clone();
 751            let agent = self.agent.clone();
 752            async move |this, cx| {
 753                let result = authenticate.await;
 754
 755                this.update_in(cx, |this, window, cx| {
 756                    if let Err(err) = result {
 757                        this.last_error = Some(cx.new(|cx| {
 758                            Markdown::new(format!("Error: {err}").into(), None, None, cx)
 759                        }))
 760                    } else {
 761                        this.thread_state = Self::initial_state(
 762                            agent,
 763                            this.workspace.clone(),
 764                            project.clone(),
 765                            window,
 766                            cx,
 767                        )
 768                    }
 769                    this.auth_task.take()
 770                })
 771                .ok();
 772            }
 773        }));
 774    }
 775
 776    fn authorize_tool_call(
 777        &mut self,
 778        tool_call_id: acp::ToolCallId,
 779        option_id: acp::PermissionOptionId,
 780        option_kind: acp::PermissionOptionKind,
 781        cx: &mut Context<Self>,
 782    ) {
 783        let Some(thread) = self.thread() else {
 784            return;
 785        };
 786        thread.update(cx, |thread, cx| {
 787            thread.authorize_tool_call(tool_call_id, option_id, option_kind, cx);
 788        });
 789        cx.notify();
 790    }
 791
 792    fn render_entry(
 793        &self,
 794        index: usize,
 795        total_entries: usize,
 796        entry: &AgentThreadEntry,
 797        window: &mut Window,
 798        cx: &Context<Self>,
 799    ) -> AnyElement {
 800        let primary = match &entry {
 801            AgentThreadEntry::UserMessage(message) => div()
 802                .py_4()
 803                .px_2()
 804                .child(
 805                    v_flex()
 806                        .p_3()
 807                        .gap_1p5()
 808                        .rounded_lg()
 809                        .shadow_md()
 810                        .bg(cx.theme().colors().editor_background)
 811                        .border_1()
 812                        .border_color(cx.theme().colors().border)
 813                        .text_xs()
 814                        .children(message.content.markdown().map(|md| {
 815                            self.render_markdown(
 816                                md.clone(),
 817                                user_message_markdown_style(window, cx),
 818                            )
 819                        })),
 820                )
 821                .into_any(),
 822            AgentThreadEntry::AssistantMessage(AssistantMessage { chunks }) => {
 823                let style = default_markdown_style(false, window, cx);
 824                let message_body = v_flex()
 825                    .w_full()
 826                    .gap_2p5()
 827                    .children(chunks.iter().enumerate().filter_map(
 828                        |(chunk_ix, chunk)| match chunk {
 829                            AssistantMessageChunk::Message { block } => {
 830                                block.markdown().map(|md| {
 831                                    self.render_markdown(md.clone(), style.clone())
 832                                        .into_any_element()
 833                                })
 834                            }
 835                            AssistantMessageChunk::Thought { block } => {
 836                                block.markdown().map(|md| {
 837                                    self.render_thinking_block(
 838                                        index,
 839                                        chunk_ix,
 840                                        md.clone(),
 841                                        window,
 842                                        cx,
 843                                    )
 844                                    .into_any_element()
 845                                })
 846                            }
 847                        },
 848                    ))
 849                    .into_any();
 850
 851                v_flex()
 852                    .px_5()
 853                    .py_1()
 854                    .when(index + 1 == total_entries, |this| this.pb_4())
 855                    .w_full()
 856                    .text_ui(cx)
 857                    .child(message_body)
 858                    .into_any()
 859            }
 860            AgentThreadEntry::ToolCall(tool_call) => div()
 861                .py_1p5()
 862                .px_5()
 863                .child(self.render_tool_call(index, tool_call, window, cx))
 864                .into_any(),
 865        };
 866
 867        let Some(thread) = self.thread() else {
 868            return primary;
 869        };
 870        let is_generating = matches!(thread.read(cx).status(), ThreadStatus::Generating);
 871        if index == total_entries - 1 && !is_generating {
 872            v_flex()
 873                .w_full()
 874                .child(primary)
 875                .child(self.render_thread_controls(cx))
 876                .into_any_element()
 877        } else {
 878            primary
 879        }
 880    }
 881
 882    fn tool_card_header_bg(&self, cx: &Context<Self>) -> Hsla {
 883        cx.theme()
 884            .colors()
 885            .element_background
 886            .blend(cx.theme().colors().editor_foreground.opacity(0.025))
 887    }
 888
 889    fn tool_card_border_color(&self, cx: &Context<Self>) -> Hsla {
 890        cx.theme().colors().border.opacity(0.6)
 891    }
 892
 893    fn tool_name_font_size(&self) -> Rems {
 894        rems_from_px(13.)
 895    }
 896
 897    fn render_thinking_block(
 898        &self,
 899        entry_ix: usize,
 900        chunk_ix: usize,
 901        chunk: Entity<Markdown>,
 902        window: &Window,
 903        cx: &Context<Self>,
 904    ) -> AnyElement {
 905        let header_id = SharedString::from(format!("thinking-block-header-{}", entry_ix));
 906        let key = (entry_ix, chunk_ix);
 907        let is_open = self.expanded_thinking_blocks.contains(&key);
 908
 909        v_flex()
 910            .child(
 911                h_flex()
 912                    .id(header_id)
 913                    .group("disclosure-header")
 914                    .w_full()
 915                    .justify_between()
 916                    .opacity(0.8)
 917                    .hover(|style| style.opacity(1.))
 918                    .child(
 919                        h_flex()
 920                            .gap_1p5()
 921                            .child(
 922                                Icon::new(IconName::ToolBulb)
 923                                    .size(IconSize::Small)
 924                                    .color(Color::Muted),
 925                            )
 926                            .child(
 927                                div()
 928                                    .text_size(self.tool_name_font_size())
 929                                    .child("Thinking"),
 930                            ),
 931                    )
 932                    .child(
 933                        div().visible_on_hover("disclosure-header").child(
 934                            Disclosure::new("thinking-disclosure", is_open)
 935                                .opened_icon(IconName::ChevronUp)
 936                                .closed_icon(IconName::ChevronDown)
 937                                .on_click(cx.listener({
 938                                    move |this, _event, _window, cx| {
 939                                        if is_open {
 940                                            this.expanded_thinking_blocks.remove(&key);
 941                                        } else {
 942                                            this.expanded_thinking_blocks.insert(key);
 943                                        }
 944                                        cx.notify();
 945                                    }
 946                                })),
 947                        ),
 948                    )
 949                    .on_click(cx.listener({
 950                        move |this, _event, _window, cx| {
 951                            if is_open {
 952                                this.expanded_thinking_blocks.remove(&key);
 953                            } else {
 954                                this.expanded_thinking_blocks.insert(key);
 955                            }
 956                            cx.notify();
 957                        }
 958                    })),
 959            )
 960            .when(is_open, |this| {
 961                this.child(
 962                    div()
 963                        .relative()
 964                        .mt_1p5()
 965                        .ml(px(7.))
 966                        .pl_4()
 967                        .border_l_1()
 968                        .border_color(self.tool_card_border_color(cx))
 969                        .text_ui_sm(cx)
 970                        .child(
 971                            self.render_markdown(chunk, default_markdown_style(false, window, cx)),
 972                        ),
 973                )
 974            })
 975            .into_any_element()
 976    }
 977
 978    fn render_tool_call(
 979        &self,
 980        entry_ix: usize,
 981        tool_call: &ToolCall,
 982        window: &Window,
 983        cx: &Context<Self>,
 984    ) -> Div {
 985        let header_id = SharedString::from(format!("tool-call-header-{}", entry_ix));
 986
 987        let status_icon = match &tool_call.status {
 988            ToolCallStatus::Allowed {
 989                status: acp::ToolCallStatus::Pending,
 990            }
 991            | ToolCallStatus::WaitingForConfirmation { .. } => None,
 992            ToolCallStatus::Allowed {
 993                status: acp::ToolCallStatus::InProgress,
 994                ..
 995            } => Some(
 996                Icon::new(IconName::ArrowCircle)
 997                    .color(Color::Accent)
 998                    .size(IconSize::Small)
 999                    .with_animation(
1000                        "running",
1001                        Animation::new(Duration::from_secs(2)).repeat(),
1002                        |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1003                    )
1004                    .into_any(),
1005            ),
1006            ToolCallStatus::Allowed {
1007                status: acp::ToolCallStatus::Completed,
1008                ..
1009            } => None,
1010            ToolCallStatus::Rejected
1011            | ToolCallStatus::Canceled
1012            | ToolCallStatus::Allowed {
1013                status: acp::ToolCallStatus::Failed,
1014                ..
1015            } => Some(
1016                Icon::new(IconName::X)
1017                    .color(Color::Error)
1018                    .size(IconSize::Small)
1019                    .into_any_element(),
1020            ),
1021        };
1022
1023        let needs_confirmation = match &tool_call.status {
1024            ToolCallStatus::WaitingForConfirmation { .. } => true,
1025            _ => tool_call
1026                .content
1027                .iter()
1028                .any(|content| matches!(content, ToolCallContent::Diff { .. })),
1029        };
1030
1031        let is_collapsible = !tool_call.content.is_empty() && !needs_confirmation;
1032        let is_open = !is_collapsible || self.expanded_tool_calls.contains(&tool_call.id);
1033
1034        v_flex()
1035            .when(needs_confirmation, |this| {
1036                this.rounded_lg()
1037                    .border_1()
1038                    .border_color(self.tool_card_border_color(cx))
1039                    .bg(cx.theme().colors().editor_background)
1040                    .overflow_hidden()
1041            })
1042            .child(
1043                h_flex()
1044                    .id(header_id)
1045                    .w_full()
1046                    .gap_1()
1047                    .justify_between()
1048                    .map(|this| {
1049                        if needs_confirmation {
1050                            this.px_2()
1051                                .py_1()
1052                                .rounded_t_md()
1053                                .bg(self.tool_card_header_bg(cx))
1054                                .border_b_1()
1055                                .border_color(self.tool_card_border_color(cx))
1056                        } else {
1057                            this.opacity(0.8).hover(|style| style.opacity(1.))
1058                        }
1059                    })
1060                    .child(
1061                        h_flex()
1062                            .id("tool-call-header")
1063                            .overflow_x_scroll()
1064                            .map(|this| {
1065                                if needs_confirmation {
1066                                    this.text_xs()
1067                                } else {
1068                                    this.text_size(self.tool_name_font_size())
1069                                }
1070                            })
1071                            .gap_1p5()
1072                            .child(
1073                                Icon::new(match tool_call.kind {
1074                                    acp::ToolKind::Read => IconName::ToolRead,
1075                                    acp::ToolKind::Edit => IconName::ToolPencil,
1076                                    acp::ToolKind::Delete => IconName::ToolDeleteFile,
1077                                    acp::ToolKind::Move => IconName::ArrowRightLeft,
1078                                    acp::ToolKind::Search => IconName::ToolSearch,
1079                                    acp::ToolKind::Execute => IconName::ToolTerminal,
1080                                    acp::ToolKind::Think => IconName::ToolBulb,
1081                                    acp::ToolKind::Fetch => IconName::ToolWeb,
1082                                    acp::ToolKind::Other => IconName::ToolHammer,
1083                                })
1084                                .size(IconSize::Small)
1085                                .color(Color::Muted),
1086                            )
1087                            .child(if tool_call.locations.len() == 1 {
1088                                let name = tool_call.locations[0]
1089                                    .path
1090                                    .file_name()
1091                                    .unwrap_or_default()
1092                                    .display()
1093                                    .to_string();
1094
1095                                h_flex()
1096                                    .id(("open-tool-call-location", entry_ix))
1097                                    .child(name)
1098                                    .w_full()
1099                                    .max_w_full()
1100                                    .pr_1()
1101                                    .gap_0p5()
1102                                    .cursor_pointer()
1103                                    .rounded_sm()
1104                                    .opacity(0.8)
1105                                    .hover(|label| {
1106                                        label.opacity(1.).bg(cx
1107                                            .theme()
1108                                            .colors()
1109                                            .element_hover
1110                                            .opacity(0.5))
1111                                    })
1112                                    .tooltip(Tooltip::text("Jump to File"))
1113                                    .on_click(cx.listener(move |this, _, window, cx| {
1114                                        this.open_tool_call_location(entry_ix, 0, window, cx);
1115                                    }))
1116                                    .into_any_element()
1117                            } else {
1118                                self.render_markdown(
1119                                    tool_call.label.clone(),
1120                                    default_markdown_style(needs_confirmation, window, cx),
1121                                )
1122                                .into_any()
1123                            }),
1124                    )
1125                    .child(
1126                        h_flex()
1127                            .gap_0p5()
1128                            .when(is_collapsible, |this| {
1129                                this.child(
1130                                    Disclosure::new(("expand", entry_ix), is_open)
1131                                        .opened_icon(IconName::ChevronUp)
1132                                        .closed_icon(IconName::ChevronDown)
1133                                        .on_click(cx.listener({
1134                                            let id = tool_call.id.clone();
1135                                            move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1136                                                if is_open {
1137                                                    this.expanded_tool_calls.remove(&id);
1138                                                } else {
1139                                                    this.expanded_tool_calls.insert(id.clone());
1140                                                }
1141                                                cx.notify();
1142                                            }
1143                                        })),
1144                                )
1145                            })
1146                            .children(status_icon),
1147                    )
1148                    .on_click(cx.listener({
1149                        let id = tool_call.id.clone();
1150                        move |this: &mut Self, _, _, cx: &mut Context<Self>| {
1151                            if is_open {
1152                                this.expanded_tool_calls.remove(&id);
1153                            } else {
1154                                this.expanded_tool_calls.insert(id.clone());
1155                            }
1156                            cx.notify();
1157                        }
1158                    })),
1159            )
1160            .when(is_open, |this| {
1161                this.child(
1162                    v_flex()
1163                        .text_xs()
1164                        .when(is_collapsible, |this| {
1165                            this.mt_1()
1166                                .border_1()
1167                                .border_color(self.tool_card_border_color(cx))
1168                                .bg(cx.theme().colors().editor_background)
1169                                .rounded_lg()
1170                        })
1171                        .map(|this| {
1172                            if is_open {
1173                                match &tool_call.status {
1174                                    ToolCallStatus::WaitingForConfirmation { options, .. } => this
1175                                        .children(tool_call.content.iter().map(|content| {
1176                                            div()
1177                                                .py_1p5()
1178                                                .child(
1179                                                    self.render_tool_call_content(
1180                                                        content, window, cx,
1181                                                    ),
1182                                                )
1183                                                .into_any_element()
1184                                        }))
1185                                        .child(self.render_permission_buttons(
1186                                            options,
1187                                            entry_ix,
1188                                            tool_call.id.clone(),
1189                                            tool_call.content.is_empty(),
1190                                            cx,
1191                                        )),
1192                                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Canceled => {
1193                                        this.children(tool_call.content.iter().map(|content| {
1194                                            div()
1195                                                .py_1p5()
1196                                                .child(
1197                                                    self.render_tool_call_content(
1198                                                        content, window, cx,
1199                                                    ),
1200                                                )
1201                                                .into_any_element()
1202                                        }))
1203                                    }
1204                                    ToolCallStatus::Rejected => this,
1205                                }
1206                            } else {
1207                                this
1208                            }
1209                        }),
1210                )
1211            })
1212    }
1213
1214    fn render_tool_call_content(
1215        &self,
1216        content: &ToolCallContent,
1217        window: &Window,
1218        cx: &Context<Self>,
1219    ) -> AnyElement {
1220        match content {
1221            ToolCallContent::ContentBlock { content } => {
1222                if let Some(md) = content.markdown() {
1223                    div()
1224                        .p_2()
1225                        .child(
1226                            self.render_markdown(
1227                                md.clone(),
1228                                default_markdown_style(false, window, cx),
1229                            ),
1230                        )
1231                        .into_any_element()
1232                } else {
1233                    Empty.into_any_element()
1234                }
1235            }
1236            ToolCallContent::Diff {
1237                diff: Diff { multibuffer, .. },
1238                ..
1239            } => self.render_diff_editor(multibuffer),
1240        }
1241    }
1242
1243    fn render_permission_buttons(
1244        &self,
1245        options: &[acp::PermissionOption],
1246        entry_ix: usize,
1247        tool_call_id: acp::ToolCallId,
1248        empty_content: bool,
1249        cx: &Context<Self>,
1250    ) -> Div {
1251        h_flex()
1252            .py_1p5()
1253            .px_1p5()
1254            .gap_1()
1255            .justify_end()
1256            .when(!empty_content, |this| {
1257                this.border_t_1()
1258                    .border_color(self.tool_card_border_color(cx))
1259            })
1260            .children(options.iter().map(|option| {
1261                let option_id = SharedString::from(option.id.0.clone());
1262                Button::new((option_id, entry_ix), option.name.clone())
1263                    .map(|this| match option.kind {
1264                        acp::PermissionOptionKind::AllowOnce => {
1265                            this.icon(IconName::Check).icon_color(Color::Success)
1266                        }
1267                        acp::PermissionOptionKind::AllowAlways => {
1268                            this.icon(IconName::CheckDouble).icon_color(Color::Success)
1269                        }
1270                        acp::PermissionOptionKind::RejectOnce => {
1271                            this.icon(IconName::X).icon_color(Color::Error)
1272                        }
1273                        acp::PermissionOptionKind::RejectAlways => {
1274                            this.icon(IconName::X).icon_color(Color::Error)
1275                        }
1276                    })
1277                    .icon_position(IconPosition::Start)
1278                    .icon_size(IconSize::XSmall)
1279                    .on_click(cx.listener({
1280                        let tool_call_id = tool_call_id.clone();
1281                        let option_id = option.id.clone();
1282                        let option_kind = option.kind;
1283                        move |this, _, _, cx| {
1284                            this.authorize_tool_call(
1285                                tool_call_id.clone(),
1286                                option_id.clone(),
1287                                option_kind,
1288                                cx,
1289                            );
1290                        }
1291                    }))
1292            }))
1293    }
1294
1295    fn render_diff_editor(&self, multibuffer: &Entity<MultiBuffer>) -> AnyElement {
1296        v_flex()
1297            .h_full()
1298            .child(
1299                if let Some(editor) = self.diff_editors.get(&multibuffer.entity_id()) {
1300                    editor.clone().into_any_element()
1301                } else {
1302                    Empty.into_any()
1303                },
1304            )
1305            .into_any()
1306    }
1307
1308    fn render_agent_logo(&self) -> AnyElement {
1309        Icon::new(self.agent.logo())
1310            .color(Color::Muted)
1311            .size(IconSize::XLarge)
1312            .into_any_element()
1313    }
1314
1315    fn render_error_agent_logo(&self) -> AnyElement {
1316        let logo = Icon::new(self.agent.logo())
1317            .color(Color::Muted)
1318            .size(IconSize::XLarge)
1319            .into_any_element();
1320
1321        h_flex()
1322            .relative()
1323            .justify_center()
1324            .child(div().opacity(0.3).child(logo))
1325            .child(
1326                h_flex().absolute().right_1().bottom_0().child(
1327                    Icon::new(IconName::XCircle)
1328                        .color(Color::Error)
1329                        .size(IconSize::Small),
1330                ),
1331            )
1332            .into_any_element()
1333    }
1334
1335    fn render_empty_state(&self, cx: &App) -> AnyElement {
1336        let loading = matches!(&self.thread_state, ThreadState::Loading { .. });
1337
1338        v_flex()
1339            .size_full()
1340            .items_center()
1341            .justify_center()
1342            .child(if loading {
1343                h_flex()
1344                    .justify_center()
1345                    .child(self.render_agent_logo())
1346                    .with_animation(
1347                        "pulsating_icon",
1348                        Animation::new(Duration::from_secs(2))
1349                            .repeat()
1350                            .with_easing(pulsating_between(0.4, 1.0)),
1351                        |icon, delta| icon.opacity(delta),
1352                    )
1353                    .into_any()
1354            } else {
1355                self.render_agent_logo().into_any_element()
1356            })
1357            .child(h_flex().mt_4().mb_1().justify_center().child(if loading {
1358                div()
1359                    .child(LoadingLabel::new("").size(LabelSize::Large))
1360                    .into_any_element()
1361            } else {
1362                Headline::new(self.agent.empty_state_headline())
1363                    .size(HeadlineSize::Medium)
1364                    .into_any_element()
1365            }))
1366            .child(
1367                div()
1368                    .max_w_1_2()
1369                    .text_sm()
1370                    .text_center()
1371                    .map(|this| {
1372                        if loading {
1373                            this.invisible()
1374                        } else {
1375                            this.text_color(cx.theme().colors().text_muted)
1376                        }
1377                    })
1378                    .child(self.agent.empty_state_message()),
1379            )
1380            .into_any()
1381    }
1382
1383    fn render_pending_auth_state(&self) -> AnyElement {
1384        v_flex()
1385            .items_center()
1386            .justify_center()
1387            .child(self.render_error_agent_logo())
1388            .child(
1389                h_flex()
1390                    .mt_4()
1391                    .mb_1()
1392                    .justify_center()
1393                    .child(Headline::new("Not Authenticated").size(HeadlineSize::Medium)),
1394            )
1395            .into_any()
1396    }
1397
1398    fn render_server_exited(&self, status: ExitStatus, _cx: &Context<Self>) -> AnyElement {
1399        v_flex()
1400            .items_center()
1401            .justify_center()
1402            .child(self.render_error_agent_logo())
1403            .child(
1404                v_flex()
1405                    .mt_4()
1406                    .mb_2()
1407                    .gap_0p5()
1408                    .text_center()
1409                    .items_center()
1410                    .child(Headline::new("Server exited unexpectedly").size(HeadlineSize::Medium))
1411                    .child(
1412                        Label::new(format!("Exit status: {}", status.code().unwrap_or(-127)))
1413                            .size(LabelSize::Small)
1414                            .color(Color::Muted),
1415                    ),
1416            )
1417            .into_any_element()
1418    }
1419
1420    fn render_load_error(&self, e: &LoadError, cx: &Context<Self>) -> AnyElement {
1421        let mut container = v_flex()
1422            .items_center()
1423            .justify_center()
1424            .child(self.render_error_agent_logo())
1425            .child(
1426                v_flex()
1427                    .mt_4()
1428                    .mb_2()
1429                    .gap_0p5()
1430                    .text_center()
1431                    .items_center()
1432                    .child(Headline::new("Failed to launch").size(HeadlineSize::Medium))
1433                    .child(
1434                        Label::new(e.to_string())
1435                            .size(LabelSize::Small)
1436                            .color(Color::Muted),
1437                    ),
1438            );
1439
1440        if let LoadError::Unsupported {
1441            upgrade_message,
1442            upgrade_command,
1443            ..
1444        } = &e
1445        {
1446            let upgrade_message = upgrade_message.clone();
1447            let upgrade_command = upgrade_command.clone();
1448            container = container.child(Button::new("upgrade", upgrade_message).on_click(
1449                cx.listener(move |this, _, window, cx| {
1450                    this.workspace
1451                        .update(cx, |workspace, cx| {
1452                            let project = workspace.project().read(cx);
1453                            let cwd = project.first_project_directory(cx);
1454                            let shell = project.terminal_settings(&cwd, cx).shell.clone();
1455                            let spawn_in_terminal = task::SpawnInTerminal {
1456                                id: task::TaskId("install".to_string()),
1457                                full_label: upgrade_command.clone(),
1458                                label: upgrade_command.clone(),
1459                                command: Some(upgrade_command.clone()),
1460                                args: Vec::new(),
1461                                command_label: upgrade_command.clone(),
1462                                cwd,
1463                                env: Default::default(),
1464                                use_new_terminal: true,
1465                                allow_concurrent_runs: true,
1466                                reveal: Default::default(),
1467                                reveal_target: Default::default(),
1468                                hide: Default::default(),
1469                                shell,
1470                                show_summary: true,
1471                                show_command: true,
1472                                show_rerun: false,
1473                            };
1474                            workspace
1475                                .spawn_in_terminal(spawn_in_terminal, window, cx)
1476                                .detach();
1477                        })
1478                        .ok();
1479                }),
1480            ));
1481        }
1482
1483        container.into_any()
1484    }
1485
1486    fn render_activity_bar(
1487        &self,
1488        thread_entity: &Entity<AcpThread>,
1489        window: &mut Window,
1490        cx: &Context<Self>,
1491    ) -> Option<AnyElement> {
1492        let thread = thread_entity.read(cx);
1493        let action_log = thread.action_log();
1494        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1495        let plan = thread.plan();
1496
1497        if changed_buffers.is_empty() && plan.is_empty() {
1498            return None;
1499        }
1500
1501        let editor_bg_color = cx.theme().colors().editor_background;
1502        let active_color = cx.theme().colors().element_selected;
1503        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
1504
1505        let pending_edits = thread.has_pending_edit_tool_calls();
1506
1507        v_flex()
1508            .mt_1()
1509            .mx_2()
1510            .bg(bg_edit_files_disclosure)
1511            .border_1()
1512            .border_b_0()
1513            .border_color(cx.theme().colors().border)
1514            .rounded_t_md()
1515            .shadow(vec![gpui::BoxShadow {
1516                color: gpui::black().opacity(0.15),
1517                offset: point(px(1.), px(-1.)),
1518                blur_radius: px(3.),
1519                spread_radius: px(0.),
1520            }])
1521            .when(!plan.is_empty(), |this| {
1522                this.child(self.render_plan_summary(plan, window, cx))
1523                    .when(self.plan_expanded, |parent| {
1524                        parent.child(self.render_plan_entries(plan, window, cx))
1525                    })
1526            })
1527            .when(!changed_buffers.is_empty(), |this| {
1528                this.child(Divider::horizontal())
1529                    .child(self.render_edits_summary(
1530                        action_log,
1531                        &changed_buffers,
1532                        self.edits_expanded,
1533                        pending_edits,
1534                        window,
1535                        cx,
1536                    ))
1537                    .when(self.edits_expanded, |parent| {
1538                        parent.child(self.render_edited_files(
1539                            action_log,
1540                            &changed_buffers,
1541                            pending_edits,
1542                            cx,
1543                        ))
1544                    })
1545            })
1546            .into_any()
1547            .into()
1548    }
1549
1550    fn render_plan_summary(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1551        let stats = plan.stats();
1552
1553        let title = if let Some(entry) = stats.in_progress_entry
1554            && !self.plan_expanded
1555        {
1556            h_flex()
1557                .w_full()
1558                .gap_1()
1559                .text_xs()
1560                .text_color(cx.theme().colors().text_muted)
1561                .justify_between()
1562                .child(
1563                    h_flex()
1564                        .gap_1()
1565                        .child(
1566                            Label::new("Current:")
1567                                .size(LabelSize::Small)
1568                                .color(Color::Muted),
1569                        )
1570                        .child(MarkdownElement::new(
1571                            entry.content.clone(),
1572                            plan_label_markdown_style(&entry.status, window, cx),
1573                        )),
1574                )
1575                .when(stats.pending > 0, |this| {
1576                    this.child(
1577                        Label::new(format!("{} left", stats.pending))
1578                            .size(LabelSize::Small)
1579                            .color(Color::Muted)
1580                            .mr_1(),
1581                    )
1582                })
1583        } else {
1584            let status_label = if stats.pending == 0 {
1585                "All Done".to_string()
1586            } else if stats.completed == 0 {
1587                format!("{}", plan.entries.len())
1588            } else {
1589                format!("{}/{}", stats.completed, plan.entries.len())
1590            };
1591
1592            h_flex()
1593                .w_full()
1594                .gap_1()
1595                .justify_between()
1596                .child(
1597                    Label::new("Plan")
1598                        .size(LabelSize::Small)
1599                        .color(Color::Muted),
1600                )
1601                .child(
1602                    Label::new(status_label)
1603                        .size(LabelSize::Small)
1604                        .color(Color::Muted)
1605                        .mr_1(),
1606                )
1607        };
1608
1609        h_flex()
1610            .p_1()
1611            .justify_between()
1612            .when(self.plan_expanded, |this| {
1613                this.border_b_1().border_color(cx.theme().colors().border)
1614            })
1615            .child(
1616                h_flex()
1617                    .id("plan_summary")
1618                    .w_full()
1619                    .gap_1()
1620                    .child(Disclosure::new("plan_disclosure", self.plan_expanded))
1621                    .child(title)
1622                    .on_click(cx.listener(|this, _, _, cx| {
1623                        this.plan_expanded = !this.plan_expanded;
1624                        cx.notify();
1625                    })),
1626            )
1627    }
1628
1629    fn render_plan_entries(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {
1630        v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {
1631            let element = h_flex()
1632                .py_1()
1633                .px_2()
1634                .gap_2()
1635                .justify_between()
1636                .bg(cx.theme().colors().editor_background)
1637                .when(index < plan.entries.len() - 1, |parent| {
1638                    parent.border_color(cx.theme().colors().border).border_b_1()
1639                })
1640                .child(
1641                    h_flex()
1642                        .id(("plan_entry", index))
1643                        .gap_1p5()
1644                        .max_w_full()
1645                        .overflow_x_scroll()
1646                        .text_xs()
1647                        .text_color(cx.theme().colors().text_muted)
1648                        .child(match entry.status {
1649                            acp::PlanEntryStatus::Pending => Icon::new(IconName::TodoPending)
1650                                .size(IconSize::Small)
1651                                .color(Color::Muted)
1652                                .into_any_element(),
1653                            acp::PlanEntryStatus::InProgress => Icon::new(IconName::TodoProgress)
1654                                .size(IconSize::Small)
1655                                .color(Color::Accent)
1656                                .with_animation(
1657                                    "running",
1658                                    Animation::new(Duration::from_secs(2)).repeat(),
1659                                    |icon, delta| {
1660                                        icon.transform(Transformation::rotate(percentage(delta)))
1661                                    },
1662                                )
1663                                .into_any_element(),
1664                            acp::PlanEntryStatus::Completed => Icon::new(IconName::TodoComplete)
1665                                .size(IconSize::Small)
1666                                .color(Color::Success)
1667                                .into_any_element(),
1668                        })
1669                        .child(MarkdownElement::new(
1670                            entry.content.clone(),
1671                            plan_label_markdown_style(&entry.status, window, cx),
1672                        )),
1673                );
1674
1675            Some(element)
1676        }))
1677    }
1678
1679    fn render_edits_summary(
1680        &self,
1681        action_log: &Entity<ActionLog>,
1682        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1683        expanded: bool,
1684        pending_edits: bool,
1685        window: &mut Window,
1686        cx: &Context<Self>,
1687    ) -> Div {
1688        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
1689
1690        let focus_handle = self.focus_handle(cx);
1691
1692        h_flex()
1693            .p_1()
1694            .justify_between()
1695            .when(expanded, |this| {
1696                this.border_b_1().border_color(cx.theme().colors().border)
1697            })
1698            .child(
1699                h_flex()
1700                    .id("edits-container")
1701                    .cursor_pointer()
1702                    .w_full()
1703                    .gap_1()
1704                    .child(Disclosure::new("edits-disclosure", expanded))
1705                    .map(|this| {
1706                        if pending_edits {
1707                            this.child(
1708                                Label::new(format!(
1709                                    "Editing {} {}",
1710                                    changed_buffers.len(),
1711                                    if changed_buffers.len() == 1 {
1712                                        "file"
1713                                    } else {
1714                                        "files"
1715                                    }
1716                                ))
1717                                .color(Color::Muted)
1718                                .size(LabelSize::Small)
1719                                .with_animation(
1720                                    "edit-label",
1721                                    Animation::new(Duration::from_secs(2))
1722                                        .repeat()
1723                                        .with_easing(pulsating_between(0.3, 0.7)),
1724                                    |label, delta| label.alpha(delta),
1725                                ),
1726                            )
1727                        } else {
1728                            this.child(
1729                                Label::new("Edits")
1730                                    .size(LabelSize::Small)
1731                                    .color(Color::Muted),
1732                            )
1733                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
1734                            .child(
1735                                Label::new(format!(
1736                                    "{} {}",
1737                                    changed_buffers.len(),
1738                                    if changed_buffers.len() == 1 {
1739                                        "file"
1740                                    } else {
1741                                        "files"
1742                                    }
1743                                ))
1744                                .size(LabelSize::Small)
1745                                .color(Color::Muted),
1746                            )
1747                        }
1748                    })
1749                    .on_click(cx.listener(|this, _, _, cx| {
1750                        this.edits_expanded = !this.edits_expanded;
1751                        cx.notify();
1752                    })),
1753            )
1754            .child(
1755                h_flex()
1756                    .gap_1()
1757                    .child(
1758                        IconButton::new("review-changes", IconName::ListTodo)
1759                            .icon_size(IconSize::Small)
1760                            .tooltip({
1761                                let focus_handle = focus_handle.clone();
1762                                move |window, cx| {
1763                                    Tooltip::for_action_in(
1764                                        "Review Changes",
1765                                        &OpenAgentDiff,
1766                                        &focus_handle,
1767                                        window,
1768                                        cx,
1769                                    )
1770                                }
1771                            })
1772                            .on_click(cx.listener(|_, _, window, cx| {
1773                                window.dispatch_action(OpenAgentDiff.boxed_clone(), cx);
1774                            })),
1775                    )
1776                    .child(Divider::vertical().color(DividerColor::Border))
1777                    .child(
1778                        Button::new("reject-all-changes", "Reject All")
1779                            .label_size(LabelSize::Small)
1780                            .disabled(pending_edits)
1781                            .when(pending_edits, |this| {
1782                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1783                            })
1784                            .key_binding(
1785                                KeyBinding::for_action_in(
1786                                    &RejectAll,
1787                                    &focus_handle.clone(),
1788                                    window,
1789                                    cx,
1790                                )
1791                                .map(|kb| kb.size(rems_from_px(10.))),
1792                            )
1793                            .on_click({
1794                                let action_log = action_log.clone();
1795                                cx.listener(move |_, _, _, cx| {
1796                                    action_log.update(cx, |action_log, cx| {
1797                                        action_log.reject_all_edits(cx).detach();
1798                                    })
1799                                })
1800                            }),
1801                    )
1802                    .child(
1803                        Button::new("keep-all-changes", "Keep All")
1804                            .label_size(LabelSize::Small)
1805                            .disabled(pending_edits)
1806                            .when(pending_edits, |this| {
1807                                this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1808                            })
1809                            .key_binding(
1810                                KeyBinding::for_action_in(&KeepAll, &focus_handle, window, cx)
1811                                    .map(|kb| kb.size(rems_from_px(10.))),
1812                            )
1813                            .on_click({
1814                                let action_log = action_log.clone();
1815                                cx.listener(move |_, _, _, cx| {
1816                                    action_log.update(cx, |action_log, cx| {
1817                                        action_log.keep_all_edits(cx);
1818                                    })
1819                                })
1820                            }),
1821                    ),
1822            )
1823    }
1824
1825    fn render_edited_files(
1826        &self,
1827        action_log: &Entity<ActionLog>,
1828        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
1829        pending_edits: bool,
1830        cx: &Context<Self>,
1831    ) -> Div {
1832        let editor_bg_color = cx.theme().colors().editor_background;
1833
1834        v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1835            |(index, (buffer, _diff))| {
1836                let file = buffer.read(cx).file()?;
1837                let path = file.path();
1838
1839                let file_path = path.parent().and_then(|parent| {
1840                    let parent_str = parent.to_string_lossy();
1841
1842                    if parent_str.is_empty() {
1843                        None
1844                    } else {
1845                        Some(
1846                            Label::new(format!("/{}{}", parent_str, std::path::MAIN_SEPARATOR_STR))
1847                                .color(Color::Muted)
1848                                .size(LabelSize::XSmall)
1849                                .buffer_font(cx),
1850                        )
1851                    }
1852                });
1853
1854                let file_name = path.file_name().map(|name| {
1855                    Label::new(name.to_string_lossy().to_string())
1856                        .size(LabelSize::XSmall)
1857                        .buffer_font(cx)
1858                });
1859
1860                let file_icon = FileIcons::get_icon(&path, cx)
1861                    .map(Icon::from_path)
1862                    .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1863                    .unwrap_or_else(|| {
1864                        Icon::new(IconName::File)
1865                            .color(Color::Muted)
1866                            .size(IconSize::Small)
1867                    });
1868
1869                let overlay_gradient = linear_gradient(
1870                    90.,
1871                    linear_color_stop(editor_bg_color, 1.),
1872                    linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1873                );
1874
1875                let element = h_flex()
1876                    .group("edited-code")
1877                    .id(("file-container", index))
1878                    .relative()
1879                    .py_1()
1880                    .pl_2()
1881                    .pr_1()
1882                    .gap_2()
1883                    .justify_between()
1884                    .bg(editor_bg_color)
1885                    .when(index < changed_buffers.len() - 1, |parent| {
1886                        parent.border_color(cx.theme().colors().border).border_b_1()
1887                    })
1888                    .child(
1889                        h_flex()
1890                            .id(("file-name", index))
1891                            .pr_8()
1892                            .gap_1p5()
1893                            .max_w_full()
1894                            .overflow_x_scroll()
1895                            .child(file_icon)
1896                            .child(h_flex().gap_0p5().children(file_name).children(file_path))
1897                            .on_click({
1898                                let buffer = buffer.clone();
1899                                cx.listener(move |this, _, window, cx| {
1900                                    this.open_edited_buffer(&buffer, window, cx);
1901                                })
1902                            }),
1903                    )
1904                    .child(
1905                        h_flex()
1906                            .gap_1()
1907                            .visible_on_hover("edited-code")
1908                            .child(
1909                                Button::new("review", "Review")
1910                                    .label_size(LabelSize::Small)
1911                                    .on_click({
1912                                        let buffer = buffer.clone();
1913                                        cx.listener(move |this, _, window, cx| {
1914                                            this.open_edited_buffer(&buffer, window, cx);
1915                                        })
1916                                    }),
1917                            )
1918                            .child(Divider::vertical().color(DividerColor::BorderVariant))
1919                            .child(
1920                                Button::new("reject-file", "Reject")
1921                                    .label_size(LabelSize::Small)
1922                                    .disabled(pending_edits)
1923                                    .on_click({
1924                                        let buffer = buffer.clone();
1925                                        let action_log = action_log.clone();
1926                                        move |_, _, cx| {
1927                                            action_log.update(cx, |action_log, cx| {
1928                                                action_log
1929                                                    .reject_edits_in_ranges(
1930                                                        buffer.clone(),
1931                                                        vec![Anchor::MIN..Anchor::MAX],
1932                                                        cx,
1933                                                    )
1934                                                    .detach_and_log_err(cx);
1935                                            })
1936                                        }
1937                                    }),
1938                            )
1939                            .child(
1940                                Button::new("keep-file", "Keep")
1941                                    .label_size(LabelSize::Small)
1942                                    .disabled(pending_edits)
1943                                    .on_click({
1944                                        let buffer = buffer.clone();
1945                                        let action_log = action_log.clone();
1946                                        move |_, _, cx| {
1947                                            action_log.update(cx, |action_log, cx| {
1948                                                action_log.keep_edits_in_range(
1949                                                    buffer.clone(),
1950                                                    Anchor::MIN..Anchor::MAX,
1951                                                    cx,
1952                                                );
1953                                            })
1954                                        }
1955                                    }),
1956                            ),
1957                    )
1958                    .child(
1959                        div()
1960                            .id("gradient-overlay")
1961                            .absolute()
1962                            .h_full()
1963                            .w_12()
1964                            .top_0()
1965                            .bottom_0()
1966                            .right(px(152.))
1967                            .bg(overlay_gradient),
1968                    );
1969
1970                Some(element)
1971            },
1972        ))
1973    }
1974
1975    fn render_message_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1976        let focus_handle = self.message_editor.focus_handle(cx);
1977        let editor_bg_color = cx.theme().colors().editor_background;
1978        let (expand_icon, expand_tooltip) = if self.editor_expanded {
1979            (IconName::Minimize, "Minimize Message Editor")
1980        } else {
1981            (IconName::Maximize, "Expand Message Editor")
1982        };
1983
1984        v_flex()
1985            .on_action(cx.listener(Self::expand_message_editor))
1986            .p_2()
1987            .gap_2()
1988            .border_t_1()
1989            .border_color(cx.theme().colors().border)
1990            .bg(editor_bg_color)
1991            .when(self.editor_expanded, |this| {
1992                this.h(vh(0.8, window)).size_full().justify_between()
1993            })
1994            .child(
1995                v_flex()
1996                    .relative()
1997                    .size_full()
1998                    .pt_1()
1999                    .pr_2p5()
2000                    .child(div().flex_1().child({
2001                        let settings = ThemeSettings::get_global(cx);
2002                        let font_size = TextSize::Small
2003                            .rems(cx)
2004                            .to_pixels(settings.agent_font_size(cx));
2005                        let line_height = settings.buffer_line_height.value() * font_size;
2006
2007                        let text_style = TextStyle {
2008                            color: cx.theme().colors().text,
2009                            font_family: settings.buffer_font.family.clone(),
2010                            font_fallbacks: settings.buffer_font.fallbacks.clone(),
2011                            font_features: settings.buffer_font.features.clone(),
2012                            font_size: font_size.into(),
2013                            line_height: line_height.into(),
2014                            ..Default::default()
2015                        };
2016
2017                        EditorElement::new(
2018                            &self.message_editor,
2019                            EditorStyle {
2020                                background: editor_bg_color,
2021                                local_player: cx.theme().players().local(),
2022                                text: text_style,
2023                                syntax: cx.theme().syntax().clone(),
2024                                ..Default::default()
2025                            },
2026                        )
2027                    }))
2028                    .child(
2029                        h_flex()
2030                            .absolute()
2031                            .top_0()
2032                            .right_0()
2033                            .opacity(0.5)
2034                            .hover(|this| this.opacity(1.0))
2035                            .child(
2036                                IconButton::new("toggle-height", expand_icon)
2037                                    .icon_size(IconSize::XSmall)
2038                                    .icon_color(Color::Muted)
2039                                    .tooltip({
2040                                        let focus_handle = focus_handle.clone();
2041                                        move |window, cx| {
2042                                            Tooltip::for_action_in(
2043                                                expand_tooltip,
2044                                                &ExpandMessageEditor,
2045                                                &focus_handle,
2046                                                window,
2047                                                cx,
2048                                            )
2049                                        }
2050                                    })
2051                                    .on_click(cx.listener(|_, _, window, cx| {
2052                                        window.dispatch_action(Box::new(ExpandMessageEditor), cx);
2053                                    })),
2054                            ),
2055                    ),
2056            )
2057            .child(
2058                h_flex()
2059                    .flex_none()
2060                    .justify_between()
2061                    .child(self.render_follow_toggle(cx))
2062                    .child(self.render_send_button(cx)),
2063            )
2064            .into_any()
2065    }
2066
2067    fn render_send_button(&self, cx: &mut Context<Self>) -> AnyElement {
2068        if self.thread().map_or(true, |thread| {
2069            thread.read(cx).status() == ThreadStatus::Idle
2070        }) {
2071            let is_editor_empty = self.message_editor.read(cx).is_empty(cx);
2072            IconButton::new("send-message", IconName::Send)
2073                .icon_color(Color::Accent)
2074                .style(ButtonStyle::Filled)
2075                .disabled(self.thread().is_none() || is_editor_empty)
2076                .when(!is_editor_empty, |button| {
2077                    button.tooltip(move |window, cx| Tooltip::for_action("Send", &Chat, window, cx))
2078                })
2079                .when(is_editor_empty, |button| {
2080                    button.tooltip(Tooltip::text("Type a message to submit"))
2081                })
2082                .on_click(cx.listener(|this, _, window, cx| {
2083                    this.chat(&Chat, window, cx);
2084                }))
2085                .into_any_element()
2086        } else {
2087            IconButton::new("stop-generation", IconName::StopFilled)
2088                .icon_color(Color::Error)
2089                .style(ButtonStyle::Tinted(ui::TintColor::Error))
2090                .tooltip(move |window, cx| {
2091                    Tooltip::for_action("Stop Generation", &editor::actions::Cancel, window, cx)
2092                })
2093                .on_click(cx.listener(|this, _event, _, cx| this.cancel(cx)))
2094                .into_any_element()
2095        }
2096    }
2097
2098    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
2099        let following = self
2100            .workspace
2101            .read_with(cx, |workspace, _| {
2102                workspace.is_being_followed(CollaboratorId::Agent)
2103            })
2104            .unwrap_or(false);
2105
2106        IconButton::new("follow-agent", IconName::Crosshair)
2107            .icon_size(IconSize::Small)
2108            .icon_color(Color::Muted)
2109            .toggle_state(following)
2110            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
2111            .tooltip(move |window, cx| {
2112                if following {
2113                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
2114                } else {
2115                    Tooltip::with_meta(
2116                        "Follow Agent",
2117                        Some(&Follow),
2118                        "Track the agent's location as it reads and edits files.",
2119                        window,
2120                        cx,
2121                    )
2122                }
2123            })
2124            .on_click(cx.listener(move |this, _, window, cx| {
2125                this.workspace
2126                    .update(cx, |workspace, cx| {
2127                        if following {
2128                            workspace.unfollow(CollaboratorId::Agent, window, cx);
2129                        } else {
2130                            workspace.follow(CollaboratorId::Agent, window, cx);
2131                        }
2132                    })
2133                    .ok();
2134            }))
2135    }
2136
2137    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
2138        let workspace = self.workspace.clone();
2139        MarkdownElement::new(markdown, style).on_url_click(move |text, window, cx| {
2140            Self::open_link(text, &workspace, window, cx);
2141        })
2142    }
2143
2144    fn open_link(
2145        url: SharedString,
2146        workspace: &WeakEntity<Workspace>,
2147        window: &mut Window,
2148        cx: &mut App,
2149    ) {
2150        let Some(workspace) = workspace.upgrade() else {
2151            cx.open_url(&url);
2152            return;
2153        };
2154
2155        if let Some(mention_path) = MentionPath::try_parse(&url) {
2156            workspace.update(cx, |workspace, cx| {
2157                let project = workspace.project();
2158                let Some((path, entry)) = project.update(cx, |project, cx| {
2159                    let path = project.find_project_path(mention_path.path(), cx)?;
2160                    let entry = project.entry_for_path(&path, cx)?;
2161                    Some((path, entry))
2162                }) else {
2163                    return;
2164                };
2165
2166                if entry.is_dir() {
2167                    project.update(cx, |_, cx| {
2168                        cx.emit(project::Event::RevealInProjectPanel(entry.id));
2169                    });
2170                } else {
2171                    workspace
2172                        .open_path(path, None, true, window, cx)
2173                        .detach_and_log_err(cx);
2174                }
2175            })
2176        } else {
2177            cx.open_url(&url);
2178        }
2179    }
2180
2181    fn open_tool_call_location(
2182        &self,
2183        entry_ix: usize,
2184        location_ix: usize,
2185        window: &mut Window,
2186        cx: &mut Context<Self>,
2187    ) -> Option<()> {
2188        let location = self
2189            .thread()?
2190            .read(cx)
2191            .entries()
2192            .get(entry_ix)?
2193            .locations()?
2194            .get(location_ix)?;
2195
2196        let project_path = self
2197            .project
2198            .read(cx)
2199            .find_project_path(&location.path, cx)?;
2200
2201        let open_task = self
2202            .workspace
2203            .update(cx, |worskpace, cx| {
2204                worskpace.open_path(project_path, None, true, window, cx)
2205            })
2206            .log_err()?;
2207
2208        window
2209            .spawn(cx, async move |cx| {
2210                let item = open_task.await?;
2211
2212                let Some(active_editor) = item.downcast::<Editor>() else {
2213                    return anyhow::Ok(());
2214                };
2215
2216                active_editor.update_in(cx, |editor, window, cx| {
2217                    let snapshot = editor.buffer().read(cx).snapshot(cx);
2218                    let first_hunk = editor
2219                        .diff_hunks_in_ranges(
2220                            &[editor::Anchor::min()..editor::Anchor::max()],
2221                            &snapshot,
2222                        )
2223                        .next();
2224                    if let Some(first_hunk) = first_hunk {
2225                        let first_hunk_start = first_hunk.multi_buffer_range().start;
2226                        editor.change_selections(Default::default(), window, cx, |selections| {
2227                            selections.select_anchor_ranges([first_hunk_start..first_hunk_start]);
2228                        })
2229                    }
2230                })?;
2231
2232                anyhow::Ok(())
2233            })
2234            .detach_and_log_err(cx);
2235
2236        None
2237    }
2238
2239    pub fn open_thread_as_markdown(
2240        &self,
2241        workspace: Entity<Workspace>,
2242        window: &mut Window,
2243        cx: &mut App,
2244    ) -> Task<anyhow::Result<()>> {
2245        let markdown_language_task = workspace
2246            .read(cx)
2247            .app_state()
2248            .languages
2249            .language_for_name("Markdown");
2250
2251        let (thread_summary, markdown) = if let Some(thread) = self.thread() {
2252            let thread = thread.read(cx);
2253            (thread.title().to_string(), thread.to_markdown(cx))
2254        } else {
2255            return Task::ready(Ok(()));
2256        };
2257
2258        window.spawn(cx, async move |cx| {
2259            let markdown_language = markdown_language_task.await?;
2260
2261            workspace.update_in(cx, |workspace, window, cx| {
2262                let project = workspace.project().clone();
2263
2264                if !project.read(cx).is_local() {
2265                    anyhow::bail!("failed to open active thread as markdown in remote project");
2266                }
2267
2268                let buffer = project.update(cx, |project, cx| {
2269                    project.create_local_buffer(&markdown, Some(markdown_language), cx)
2270                });
2271                let buffer = cx.new(|cx| {
2272                    MultiBuffer::singleton(buffer, cx).with_title(thread_summary.clone())
2273                });
2274
2275                workspace.add_item_to_active_pane(
2276                    Box::new(cx.new(|cx| {
2277                        let mut editor =
2278                            Editor::for_multibuffer(buffer, Some(project.clone()), window, cx);
2279                        editor.set_breadcrumb_header(thread_summary);
2280                        editor
2281                    })),
2282                    None,
2283                    true,
2284                    window,
2285                    cx,
2286                );
2287
2288                anyhow::Ok(())
2289            })??;
2290            anyhow::Ok(())
2291        })
2292    }
2293
2294    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
2295        self.list_state.scroll_to(ListOffset::default());
2296        cx.notify();
2297    }
2298
2299    pub fn scroll_to_bottom(&mut self, cx: &mut Context<Self>) {
2300        if let Some(thread) = self.thread() {
2301            let entry_count = thread.read(cx).entries().len();
2302            self.list_state.reset(entry_count);
2303            cx.notify();
2304        }
2305    }
2306
2307    fn notify_with_sound(
2308        &mut self,
2309        caption: impl Into<SharedString>,
2310        icon: IconName,
2311        window: &mut Window,
2312        cx: &mut Context<Self>,
2313    ) {
2314        self.play_notification_sound(window, cx);
2315        self.show_notification(caption, icon, window, cx);
2316    }
2317
2318    fn play_notification_sound(&self, window: &Window, cx: &mut App) {
2319        let settings = AgentSettings::get_global(cx);
2320        if settings.play_sound_when_agent_done && !window.is_window_active() {
2321            Audio::play_sound(Sound::AgentDone, cx);
2322        }
2323    }
2324
2325    fn show_notification(
2326        &mut self,
2327        caption: impl Into<SharedString>,
2328        icon: IconName,
2329        window: &mut Window,
2330        cx: &mut Context<Self>,
2331    ) {
2332        if window.is_window_active() || !self.notifications.is_empty() {
2333            return;
2334        }
2335
2336        let title = self.title(cx);
2337
2338        match AgentSettings::get_global(cx).notify_when_agent_waiting {
2339            NotifyWhenAgentWaiting::PrimaryScreen => {
2340                if let Some(primary) = cx.primary_display() {
2341                    self.pop_up(icon, caption.into(), title, window, primary, cx);
2342                }
2343            }
2344            NotifyWhenAgentWaiting::AllScreens => {
2345                let caption = caption.into();
2346                for screen in cx.displays() {
2347                    self.pop_up(icon, caption.clone(), title.clone(), window, screen, cx);
2348                }
2349            }
2350            NotifyWhenAgentWaiting::Never => {
2351                // Don't show anything
2352            }
2353        }
2354    }
2355
2356    fn pop_up(
2357        &mut self,
2358        icon: IconName,
2359        caption: SharedString,
2360        title: SharedString,
2361        window: &mut Window,
2362        screen: Rc<dyn PlatformDisplay>,
2363        cx: &mut Context<Self>,
2364    ) {
2365        let options = AgentNotification::window_options(screen, cx);
2366
2367        let project_name = self.workspace.upgrade().and_then(|workspace| {
2368            workspace
2369                .read(cx)
2370                .project()
2371                .read(cx)
2372                .visible_worktrees(cx)
2373                .next()
2374                .map(|worktree| worktree.read(cx).root_name().to_string())
2375        });
2376
2377        if let Some(screen_window) = cx
2378            .open_window(options, |_, cx| {
2379                cx.new(|_| {
2380                    AgentNotification::new(title.clone(), caption.clone(), icon, project_name)
2381                })
2382            })
2383            .log_err()
2384        {
2385            if let Some(pop_up) = screen_window.entity(cx).log_err() {
2386                self.notification_subscriptions
2387                    .entry(screen_window)
2388                    .or_insert_with(Vec::new)
2389                    .push(cx.subscribe_in(&pop_up, window, {
2390                        |this, _, event, window, cx| match event {
2391                            AgentNotificationEvent::Accepted => {
2392                                let handle = window.window_handle();
2393                                cx.activate(true);
2394
2395                                let workspace_handle = this.workspace.clone();
2396
2397                                // If there are multiple Zed windows, activate the correct one.
2398                                cx.defer(move |cx| {
2399                                    handle
2400                                        .update(cx, |_view, window, _cx| {
2401                                            window.activate_window();
2402
2403                                            if let Some(workspace) = workspace_handle.upgrade() {
2404                                                workspace.update(_cx, |workspace, cx| {
2405                                                    workspace.focus_panel::<AgentPanel>(window, cx);
2406                                                });
2407                                            }
2408                                        })
2409                                        .log_err();
2410                                });
2411
2412                                this.dismiss_notifications(cx);
2413                            }
2414                            AgentNotificationEvent::Dismissed => {
2415                                this.dismiss_notifications(cx);
2416                            }
2417                        }
2418                    }));
2419
2420                self.notifications.push(screen_window);
2421
2422                // If the user manually refocuses the original window, dismiss the popup.
2423                self.notification_subscriptions
2424                    .entry(screen_window)
2425                    .or_insert_with(Vec::new)
2426                    .push({
2427                        let pop_up_weak = pop_up.downgrade();
2428
2429                        cx.observe_window_activation(window, move |_, window, cx| {
2430                            if window.is_window_active() {
2431                                if let Some(pop_up) = pop_up_weak.upgrade() {
2432                                    pop_up.update(cx, |_, cx| {
2433                                        cx.emit(AgentNotificationEvent::Dismissed);
2434                                    });
2435                                }
2436                            }
2437                        })
2438                    });
2439            }
2440        }
2441    }
2442
2443    fn dismiss_notifications(&mut self, cx: &mut Context<Self>) {
2444        for window in self.notifications.drain(..) {
2445            window
2446                .update(cx, |_, window, _| {
2447                    window.remove_window();
2448                })
2449                .ok();
2450
2451            self.notification_subscriptions.remove(&window);
2452        }
2453    }
2454
2455    fn render_thread_controls(&self, cx: &Context<Self>) -> impl IntoElement {
2456        let open_as_markdown = IconButton::new("open-as-markdown", IconName::FileText)
2457            .icon_size(IconSize::XSmall)
2458            .icon_color(Color::Ignored)
2459            .tooltip(Tooltip::text("Open Thread as Markdown"))
2460            .on_click(cx.listener(move |this, _, window, cx| {
2461                if let Some(workspace) = this.workspace.upgrade() {
2462                    this.open_thread_as_markdown(workspace, window, cx)
2463                        .detach_and_log_err(cx);
2464                }
2465            }));
2466
2467        let scroll_to_top = IconButton::new("scroll_to_top", IconName::ArrowUpAlt)
2468            .icon_size(IconSize::XSmall)
2469            .icon_color(Color::Ignored)
2470            .tooltip(Tooltip::text("Scroll To Top"))
2471            .on_click(cx.listener(move |this, _, _, cx| {
2472                this.scroll_to_top(cx);
2473            }));
2474
2475        h_flex()
2476            .mr_1()
2477            .pb_2()
2478            .px(RESPONSE_PADDING_X)
2479            .opacity(0.4)
2480            .hover(|style| style.opacity(1.))
2481            .flex_wrap()
2482            .justify_end()
2483            .child(open_as_markdown)
2484            .child(scroll_to_top)
2485    }
2486
2487    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
2488        div()
2489            .id("acp-thread-scrollbar")
2490            .occlude()
2491            .on_mouse_move(cx.listener(|_, _, _, cx| {
2492                cx.notify();
2493                cx.stop_propagation()
2494            }))
2495            .on_hover(|_, _, cx| {
2496                cx.stop_propagation();
2497            })
2498            .on_any_mouse_down(|_, _, cx| {
2499                cx.stop_propagation();
2500            })
2501            .on_mouse_up(
2502                MouseButton::Left,
2503                cx.listener(|_, _, _, cx| {
2504                    cx.stop_propagation();
2505                }),
2506            )
2507            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2508                cx.notify();
2509            }))
2510            .h_full()
2511            .absolute()
2512            .right_1()
2513            .top_1()
2514            .bottom_0()
2515            .w(px(12.))
2516            .cursor_default()
2517            .children(Scrollbar::vertical(self.scrollbar_state.clone()).map(|s| s.auto_hide(cx)))
2518    }
2519}
2520
2521impl Focusable for AcpThreadView {
2522    fn focus_handle(&self, cx: &App) -> FocusHandle {
2523        self.message_editor.focus_handle(cx)
2524    }
2525}
2526
2527impl Render for AcpThreadView {
2528    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2529        v_flex()
2530            .size_full()
2531            .key_context("AcpThread")
2532            .on_action(cx.listener(Self::chat))
2533            .on_action(cx.listener(Self::previous_history_message))
2534            .on_action(cx.listener(Self::next_history_message))
2535            .on_action(cx.listener(Self::open_agent_diff))
2536            .bg(cx.theme().colors().panel_background)
2537            .child(match &self.thread_state {
2538                ThreadState::Unauthenticated { connection } => v_flex()
2539                    .p_2()
2540                    .flex_1()
2541                    .items_center()
2542                    .justify_center()
2543                    .child(self.render_pending_auth_state())
2544                    .child(h_flex().mt_1p5().justify_center().children(
2545                        connection.auth_methods().into_iter().map(|method| {
2546                            Button::new(
2547                                SharedString::from(method.id.0.clone()),
2548                                method.name.clone(),
2549                            )
2550                            .on_click({
2551                                let method_id = method.id.clone();
2552                                cx.listener(move |this, _, window, cx| {
2553                                    this.authenticate(method_id.clone(), window, cx)
2554                                })
2555                            })
2556                        }),
2557                    )),
2558                ThreadState::Loading { .. } => v_flex().flex_1().child(self.render_empty_state(cx)),
2559                ThreadState::LoadError(e) => v_flex()
2560                    .p_2()
2561                    .flex_1()
2562                    .items_center()
2563                    .justify_center()
2564                    .child(self.render_load_error(e, cx)),
2565                ThreadState::ServerExited { status } => v_flex()
2566                    .p_2()
2567                    .flex_1()
2568                    .items_center()
2569                    .justify_center()
2570                    .child(self.render_server_exited(*status, cx)),
2571                ThreadState::Ready { thread, .. } => {
2572                    let thread_clone = thread.clone();
2573
2574                    v_flex().flex_1().map(|this| {
2575                        if self.list_state.item_count() > 0 {
2576                            this.child(
2577                                list(
2578                                    self.list_state.clone(),
2579                                    cx.processor(|this, index: usize, window, cx| {
2580                                        let Some((entry, len)) = this.thread().and_then(|thread| {
2581                                            let entries = &thread.read(cx).entries();
2582                                            Some((entries.get(index)?, entries.len()))
2583                                        }) else {
2584                                            return Empty.into_any();
2585                                        };
2586                                        this.render_entry(index, len, entry, window, cx)
2587                                    }),
2588                                )
2589                                .with_sizing_behavior(gpui::ListSizingBehavior::Auto)
2590                                .flex_grow()
2591                                .into_any(),
2592                            )
2593                            .child(self.render_vertical_scrollbar(cx))
2594                            .children(match thread_clone.read(cx).status() {
2595                                ThreadStatus::Idle | ThreadStatus::WaitingForToolConfirmation => {
2596                                    None
2597                                }
2598                                ThreadStatus::Generating => div()
2599                                    .px_5()
2600                                    .py_2()
2601                                    .child(LoadingLabel::new("").size(LabelSize::Small))
2602                                    .into(),
2603                            })
2604                            .children(self.render_activity_bar(&thread_clone, window, cx))
2605                        } else {
2606                            this.child(self.render_empty_state(cx))
2607                        }
2608                    })
2609                }
2610            })
2611            .when_some(self.last_error.clone(), |el, error| {
2612                el.child(
2613                    div()
2614                        .p_2()
2615                        .text_xs()
2616                        .border_t_1()
2617                        .border_color(cx.theme().colors().border)
2618                        .bg(cx.theme().status().error_background)
2619                        .child(
2620                            self.render_markdown(error, default_markdown_style(false, window, cx)),
2621                        ),
2622                )
2623            })
2624            .child(self.render_message_editor(window, cx))
2625    }
2626}
2627
2628fn user_message_markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
2629    let mut style = default_markdown_style(false, window, cx);
2630    let mut text_style = window.text_style();
2631    let theme_settings = ThemeSettings::get_global(cx);
2632
2633    let buffer_font = theme_settings.buffer_font.family.clone();
2634    let buffer_font_size = TextSize::Small.rems(cx);
2635
2636    text_style.refine(&TextStyleRefinement {
2637        font_family: Some(buffer_font),
2638        font_size: Some(buffer_font_size.into()),
2639        ..Default::default()
2640    });
2641
2642    style.base_text_style = text_style;
2643    style.link_callback = Some(Rc::new(move |url, cx| {
2644        if MentionPath::try_parse(url).is_some() {
2645            let colors = cx.theme().colors();
2646            Some(TextStyleRefinement {
2647                background_color: Some(colors.element_background),
2648                ..Default::default()
2649            })
2650        } else {
2651            None
2652        }
2653    }));
2654    style
2655}
2656
2657fn default_markdown_style(buffer_font: bool, window: &Window, cx: &App) -> MarkdownStyle {
2658    let theme_settings = ThemeSettings::get_global(cx);
2659    let colors = cx.theme().colors();
2660
2661    let buffer_font_size = TextSize::Small.rems(cx);
2662
2663    let mut text_style = window.text_style();
2664    let line_height = buffer_font_size * 1.75;
2665
2666    let font_family = if buffer_font {
2667        theme_settings.buffer_font.family.clone()
2668    } else {
2669        theme_settings.ui_font.family.clone()
2670    };
2671
2672    let font_size = if buffer_font {
2673        TextSize::Small.rems(cx)
2674    } else {
2675        TextSize::Default.rems(cx)
2676    };
2677
2678    text_style.refine(&TextStyleRefinement {
2679        font_family: Some(font_family),
2680        font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
2681        font_features: Some(theme_settings.ui_font.features.clone()),
2682        font_size: Some(font_size.into()),
2683        line_height: Some(line_height.into()),
2684        color: Some(cx.theme().colors().text),
2685        ..Default::default()
2686    });
2687
2688    MarkdownStyle {
2689        base_text_style: text_style.clone(),
2690        syntax: cx.theme().syntax().clone(),
2691        selection_background_color: cx.theme().colors().element_selection_background,
2692        code_block_overflow_x_scroll: true,
2693        table_overflow_x_scroll: true,
2694        heading_level_styles: Some(HeadingLevelStyles {
2695            h1: Some(TextStyleRefinement {
2696                font_size: Some(rems(1.15).into()),
2697                ..Default::default()
2698            }),
2699            h2: Some(TextStyleRefinement {
2700                font_size: Some(rems(1.1).into()),
2701                ..Default::default()
2702            }),
2703            h3: Some(TextStyleRefinement {
2704                font_size: Some(rems(1.05).into()),
2705                ..Default::default()
2706            }),
2707            h4: Some(TextStyleRefinement {
2708                font_size: Some(rems(1.).into()),
2709                ..Default::default()
2710            }),
2711            h5: Some(TextStyleRefinement {
2712                font_size: Some(rems(0.95).into()),
2713                ..Default::default()
2714            }),
2715            h6: Some(TextStyleRefinement {
2716                font_size: Some(rems(0.875).into()),
2717                ..Default::default()
2718            }),
2719        }),
2720        code_block: StyleRefinement {
2721            padding: EdgesRefinement {
2722                top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2723                left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2724                right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2725                bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(Pixels(8.)))),
2726            },
2727            margin: EdgesRefinement {
2728                top: Some(Length::Definite(Pixels(8.).into())),
2729                left: Some(Length::Definite(Pixels(0.).into())),
2730                right: Some(Length::Definite(Pixels(0.).into())),
2731                bottom: Some(Length::Definite(Pixels(12.).into())),
2732            },
2733            border_style: Some(BorderStyle::Solid),
2734            border_widths: EdgesRefinement {
2735                top: Some(AbsoluteLength::Pixels(Pixels(1.))),
2736                left: Some(AbsoluteLength::Pixels(Pixels(1.))),
2737                right: Some(AbsoluteLength::Pixels(Pixels(1.))),
2738                bottom: Some(AbsoluteLength::Pixels(Pixels(1.))),
2739            },
2740            border_color: Some(colors.border_variant),
2741            background: Some(colors.editor_background.into()),
2742            text: Some(TextStyleRefinement {
2743                font_family: Some(theme_settings.buffer_font.family.clone()),
2744                font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2745                font_features: Some(theme_settings.buffer_font.features.clone()),
2746                font_size: Some(buffer_font_size.into()),
2747                ..Default::default()
2748            }),
2749            ..Default::default()
2750        },
2751        inline_code: TextStyleRefinement {
2752            font_family: Some(theme_settings.buffer_font.family.clone()),
2753            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
2754            font_features: Some(theme_settings.buffer_font.features.clone()),
2755            font_size: Some(buffer_font_size.into()),
2756            background_color: Some(colors.editor_foreground.opacity(0.08)),
2757            ..Default::default()
2758        },
2759        link: TextStyleRefinement {
2760            background_color: Some(colors.editor_foreground.opacity(0.025)),
2761            underline: Some(UnderlineStyle {
2762                color: Some(colors.text_accent.opacity(0.5)),
2763                thickness: px(1.),
2764                ..Default::default()
2765            }),
2766            ..Default::default()
2767        },
2768        ..Default::default()
2769    }
2770}
2771
2772fn plan_label_markdown_style(
2773    status: &acp::PlanEntryStatus,
2774    window: &Window,
2775    cx: &App,
2776) -> MarkdownStyle {
2777    let default_md_style = default_markdown_style(false, window, cx);
2778
2779    MarkdownStyle {
2780        base_text_style: TextStyle {
2781            color: cx.theme().colors().text_muted,
2782            strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
2783                Some(gpui::StrikethroughStyle {
2784                    thickness: px(1.),
2785                    color: Some(cx.theme().colors().text_muted.opacity(0.8)),
2786                })
2787            } else {
2788                None
2789            },
2790            ..default_md_style.base_text_style
2791        },
2792        ..default_md_style
2793    }
2794}
2795
2796#[cfg(test)]
2797mod tests {
2798    use agent_client_protocol::SessionId;
2799    use editor::EditorSettings;
2800    use fs::FakeFs;
2801    use futures::future::try_join_all;
2802    use gpui::{SemanticVersion, TestAppContext, VisualTestContext};
2803    use rand::Rng;
2804    use settings::SettingsStore;
2805
2806    use super::*;
2807
2808    #[gpui::test]
2809    async fn test_drop(cx: &mut TestAppContext) {
2810        init_test(cx);
2811
2812        let (thread_view, _cx) = setup_thread_view(StubAgentServer::default(), cx).await;
2813        let weak_view = thread_view.downgrade();
2814        drop(thread_view);
2815        assert!(!weak_view.is_upgradable());
2816    }
2817
2818    #[gpui::test]
2819    async fn test_notification_for_stop_event(cx: &mut TestAppContext) {
2820        init_test(cx);
2821
2822        let (thread_view, cx) = setup_thread_view(StubAgentServer::default(), cx).await;
2823
2824        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2825        message_editor.update_in(cx, |editor, window, cx| {
2826            editor.set_text("Hello", window, cx);
2827        });
2828
2829        cx.deactivate_window();
2830
2831        thread_view.update_in(cx, |thread_view, window, cx| {
2832            thread_view.chat(&Chat, window, cx);
2833        });
2834
2835        cx.run_until_parked();
2836
2837        assert!(
2838            cx.windows()
2839                .iter()
2840                .any(|window| window.downcast::<AgentNotification>().is_some())
2841        );
2842    }
2843
2844    #[gpui::test]
2845    async fn test_notification_for_error(cx: &mut TestAppContext) {
2846        init_test(cx);
2847
2848        let (thread_view, cx) =
2849            setup_thread_view(StubAgentServer::new(SaboteurAgentConnection), cx).await;
2850
2851        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2852        message_editor.update_in(cx, |editor, window, cx| {
2853            editor.set_text("Hello", window, cx);
2854        });
2855
2856        cx.deactivate_window();
2857
2858        thread_view.update_in(cx, |thread_view, window, cx| {
2859            thread_view.chat(&Chat, window, cx);
2860        });
2861
2862        cx.run_until_parked();
2863
2864        assert!(
2865            cx.windows()
2866                .iter()
2867                .any(|window| window.downcast::<AgentNotification>().is_some())
2868        );
2869    }
2870
2871    #[gpui::test]
2872    async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
2873        init_test(cx);
2874
2875        let tool_call_id = acp::ToolCallId("1".into());
2876        let tool_call = acp::ToolCall {
2877            id: tool_call_id.clone(),
2878            title: "Label".into(),
2879            kind: acp::ToolKind::Edit,
2880            status: acp::ToolCallStatus::Pending,
2881            content: vec!["hi".into()],
2882            locations: vec![],
2883            raw_input: None,
2884        };
2885        let connection = StubAgentConnection::new(vec![acp::SessionUpdate::ToolCall(tool_call)])
2886            .with_permission_requests(HashMap::from_iter([(
2887                tool_call_id,
2888                vec![acp::PermissionOption {
2889                    id: acp::PermissionOptionId("1".into()),
2890                    name: "Allow".into(),
2891                    kind: acp::PermissionOptionKind::AllowOnce,
2892                }],
2893            )]));
2894        let (thread_view, cx) = setup_thread_view(StubAgentServer::new(connection), cx).await;
2895
2896        let message_editor = cx.read(|cx| thread_view.read(cx).message_editor.clone());
2897        message_editor.update_in(cx, |editor, window, cx| {
2898            editor.set_text("Hello", window, cx);
2899        });
2900
2901        cx.deactivate_window();
2902
2903        thread_view.update_in(cx, |thread_view, window, cx| {
2904            thread_view.chat(&Chat, window, cx);
2905        });
2906
2907        cx.run_until_parked();
2908
2909        assert!(
2910            cx.windows()
2911                .iter()
2912                .any(|window| window.downcast::<AgentNotification>().is_some())
2913        );
2914    }
2915
2916    async fn setup_thread_view(
2917        agent: impl AgentServer + 'static,
2918        cx: &mut TestAppContext,
2919    ) -> (Entity<AcpThreadView>, &mut VisualTestContext) {
2920        let fs = FakeFs::new(cx.executor());
2921        let project = Project::test(fs, [], cx).await;
2922        let (workspace, cx) =
2923            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
2924
2925        let thread_view = cx.update(|window, cx| {
2926            cx.new(|cx| {
2927                AcpThreadView::new(
2928                    Rc::new(agent),
2929                    workspace.downgrade(),
2930                    project,
2931                    Rc::new(RefCell::new(MessageHistory::default())),
2932                    1,
2933                    None,
2934                    window,
2935                    cx,
2936                )
2937            })
2938        });
2939        cx.run_until_parked();
2940        (thread_view, cx)
2941    }
2942
2943    struct StubAgentServer<C> {
2944        connection: C,
2945    }
2946
2947    impl<C> StubAgentServer<C> {
2948        fn new(connection: C) -> Self {
2949            Self { connection }
2950        }
2951    }
2952
2953    impl StubAgentServer<StubAgentConnection> {
2954        fn default() -> Self {
2955            Self::new(StubAgentConnection::default())
2956        }
2957    }
2958
2959    impl<C> AgentServer for StubAgentServer<C>
2960    where
2961        C: 'static + AgentConnection + Send + Clone,
2962    {
2963        fn logo(&self) -> ui::IconName {
2964            unimplemented!()
2965        }
2966
2967        fn name(&self) -> &'static str {
2968            unimplemented!()
2969        }
2970
2971        fn empty_state_headline(&self) -> &'static str {
2972            unimplemented!()
2973        }
2974
2975        fn empty_state_message(&self) -> &'static str {
2976            unimplemented!()
2977        }
2978
2979        fn connect(
2980            &self,
2981            _root_dir: &Path,
2982            _project: &Entity<Project>,
2983            _cx: &mut App,
2984        ) -> Task<gpui::Result<Rc<dyn AgentConnection>>> {
2985            Task::ready(Ok(Rc::new(self.connection.clone())))
2986        }
2987    }
2988
2989    #[derive(Clone, Default)]
2990    struct StubAgentConnection {
2991        sessions: Arc<Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
2992        permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
2993        updates: Vec<acp::SessionUpdate>,
2994    }
2995
2996    impl StubAgentConnection {
2997        fn new(updates: Vec<acp::SessionUpdate>) -> Self {
2998            Self {
2999                updates,
3000                permission_requests: HashMap::default(),
3001                sessions: Arc::default(),
3002            }
3003        }
3004
3005        fn with_permission_requests(
3006            mut self,
3007            permission_requests: HashMap<acp::ToolCallId, Vec<acp::PermissionOption>>,
3008        ) -> Self {
3009            self.permission_requests = permission_requests;
3010            self
3011        }
3012    }
3013
3014    impl AgentConnection for StubAgentConnection {
3015        fn auth_methods(&self) -> &[acp::AuthMethod] {
3016            &[]
3017        }
3018
3019        fn new_thread(
3020            self: Rc<Self>,
3021            project: Entity<Project>,
3022            _cwd: &Path,
3023            cx: &mut gpui::AsyncApp,
3024        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3025            let session_id = SessionId(
3026                rand::thread_rng()
3027                    .sample_iter(&rand::distributions::Alphanumeric)
3028                    .take(7)
3029                    .map(char::from)
3030                    .collect::<String>()
3031                    .into(),
3032            );
3033            let thread = cx
3034                .new(|cx| AcpThread::new("Test", self.clone(), project, session_id.clone(), cx))
3035                .unwrap();
3036            self.sessions.lock().insert(session_id, thread.downgrade());
3037            Task::ready(Ok(thread))
3038        }
3039
3040        fn authenticate(
3041            &self,
3042            _method_id: acp::AuthMethodId,
3043            _cx: &mut App,
3044        ) -> Task<gpui::Result<()>> {
3045            unimplemented!()
3046        }
3047
3048        fn prompt(
3049            &self,
3050            params: acp::PromptRequest,
3051            cx: &mut App,
3052        ) -> Task<gpui::Result<acp::PromptResponse>> {
3053            let sessions = self.sessions.lock();
3054            let thread = sessions.get(&params.session_id).unwrap();
3055            let mut tasks = vec![];
3056            for update in &self.updates {
3057                let thread = thread.clone();
3058                let update = update.clone();
3059                let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) = &update
3060                    && let Some(options) = self.permission_requests.get(&tool_call.id)
3061                {
3062                    Some((tool_call.clone(), options.clone()))
3063                } else {
3064                    None
3065                };
3066                let task = cx.spawn(async move |cx| {
3067                    if let Some((tool_call, options)) = permission_request {
3068                        let permission = thread.update(cx, |thread, cx| {
3069                            thread.request_tool_call_permission(
3070                                tool_call.clone(),
3071                                options.clone(),
3072                                cx,
3073                            )
3074                        })?;
3075                        permission.await?;
3076                    }
3077                    thread.update(cx, |thread, cx| {
3078                        thread.handle_session_update(update.clone(), cx).unwrap();
3079                    })?;
3080                    anyhow::Ok(())
3081                });
3082                tasks.push(task);
3083            }
3084            cx.spawn(async move |_| {
3085                try_join_all(tasks).await?;
3086                Ok(acp::PromptResponse {
3087                    stop_reason: acp::StopReason::EndTurn,
3088                })
3089            })
3090        }
3091
3092        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3093            unimplemented!()
3094        }
3095    }
3096
3097    #[derive(Clone)]
3098    struct SaboteurAgentConnection;
3099
3100    impl AgentConnection for SaboteurAgentConnection {
3101        fn new_thread(
3102            self: Rc<Self>,
3103            project: Entity<Project>,
3104            _cwd: &Path,
3105            cx: &mut gpui::AsyncApp,
3106        ) -> Task<gpui::Result<Entity<AcpThread>>> {
3107            Task::ready(Ok(cx
3108                .new(|cx| {
3109                    AcpThread::new(
3110                        "SaboteurAgentConnection",
3111                        self,
3112                        project,
3113                        SessionId("test".into()),
3114                        cx,
3115                    )
3116                })
3117                .unwrap()))
3118        }
3119
3120        fn auth_methods(&self) -> &[acp::AuthMethod] {
3121            &[]
3122        }
3123
3124        fn authenticate(
3125            &self,
3126            _method_id: acp::AuthMethodId,
3127            _cx: &mut App,
3128        ) -> Task<gpui::Result<()>> {
3129            unimplemented!()
3130        }
3131
3132        fn prompt(
3133            &self,
3134            _params: acp::PromptRequest,
3135            _cx: &mut App,
3136        ) -> Task<gpui::Result<acp::PromptResponse>> {
3137            Task::ready(Err(anyhow::anyhow!("Error prompting")))
3138        }
3139
3140        fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
3141            unimplemented!()
3142        }
3143    }
3144
3145    fn init_test(cx: &mut TestAppContext) {
3146        cx.update(|cx| {
3147            let settings_store = SettingsStore::test(cx);
3148            cx.set_global(settings_store);
3149            language::init(cx);
3150            Project::init_settings(cx);
3151            AgentSettings::register(cx);
3152            workspace::init_settings(cx);
3153            ThemeSettings::register(cx);
3154            release_channel::init(SemanticVersion::default(), cx);
3155            EditorSettings::register(cx);
3156        });
3157    }
3158}