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