message_editor.rs

   1use crate::{
   2    acp::completion_provider::ContextPickerCompletionProvider,
   3    context_picker::{ContextPickerAction, fetch_context_picker::fetch_url_content},
   4};
   5use acp_thread::{MentionUri, selection_name};
   6use agent_client_protocol as acp;
   7use agent_servers::{AgentServer, AgentServerDelegate};
   8use agent2::HistoryStore;
   9use anyhow::{Result, anyhow};
  10use assistant_slash_commands::codeblock_fence_for_path;
  11use collections::{HashMap, HashSet};
  12use editor::{
  13    Addon, Anchor, AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement,
  14    EditorEvent, EditorMode, EditorSnapshot, EditorStyle, ExcerptId, FoldPlaceholder, MultiBuffer,
  15    SemanticsProvider, ToOffset,
  16    actions::Paste,
  17    display_map::{Crease, CreaseId, FoldId},
  18};
  19use futures::{
  20    FutureExt as _,
  21    future::{Shared, join_all},
  22};
  23use gpui::{
  24    Animation, AnimationExt as _, AppContext, ClipboardEntry, Context, Entity, EntityId,
  25    EventEmitter, FocusHandle, Focusable, HighlightStyle, Image, ImageFormat, Img, KeyContext,
  26    Subscription, Task, TextStyle, UnderlineStyle, WeakEntity, pulsating_between,
  27};
  28use language::{Buffer, Language};
  29use language_model::LanguageModelImage;
  30use postage::stream::Stream as _;
  31use project::{CompletionIntent, Project, ProjectItem, ProjectPath, Worktree};
  32use prompt_store::{PromptId, PromptStore};
  33use rope::Point;
  34use settings::Settings;
  35use std::{
  36    cell::Cell,
  37    ffi::OsStr,
  38    fmt::Write,
  39    ops::{Range, RangeInclusive},
  40    path::{Path, PathBuf},
  41    rc::Rc,
  42    sync::Arc,
  43    time::Duration,
  44};
  45use text::{OffsetRangeExt, ToOffset as _};
  46use theme::ThemeSettings;
  47use ui::{
  48    ActiveTheme, AnyElement, App, ButtonCommon, ButtonLike, ButtonStyle, Color, Element as _,
  49    FluentBuilder as _, Icon, IconName, IconSize, InteractiveElement, IntoElement, Label,
  50    LabelCommon, LabelSize, ParentElement, Render, SelectableButton, SharedString, Styled,
  51    TextSize, TintColor, Toggleable, Window, div, h_flex, px,
  52};
  53use util::{ResultExt, debug_panic};
  54use workspace::{Workspace, notifications::NotifyResultExt as _};
  55use zed_actions::agent::Chat;
  56
  57const PARSE_SLASH_COMMAND_DEBOUNCE: Duration = Duration::from_millis(50);
  58
  59pub struct MessageEditor {
  60    mention_set: MentionSet,
  61    editor: Entity<Editor>,
  62    project: Entity<Project>,
  63    workspace: WeakEntity<Workspace>,
  64    history_store: Entity<HistoryStore>,
  65    prompt_store: Option<Entity<PromptStore>>,
  66    prevent_slash_commands: bool,
  67    prompt_capabilities: Rc<Cell<acp::PromptCapabilities>>,
  68    _subscriptions: Vec<Subscription>,
  69    _parse_slash_command_task: Task<()>,
  70}
  71
  72#[derive(Clone, Copy, Debug)]
  73pub enum MessageEditorEvent {
  74    Send,
  75    Cancel,
  76    Focus,
  77    LostFocus,
  78}
  79
  80impl EventEmitter<MessageEditorEvent> for MessageEditor {}
  81
  82impl MessageEditor {
  83    pub fn new(
  84        workspace: WeakEntity<Workspace>,
  85        project: Entity<Project>,
  86        history_store: Entity<HistoryStore>,
  87        prompt_store: Option<Entity<PromptStore>>,
  88        prompt_capabilities: Rc<Cell<acp::PromptCapabilities>>,
  89        placeholder: impl Into<Arc<str>>,
  90        prevent_slash_commands: bool,
  91        mode: EditorMode,
  92        window: &mut Window,
  93        cx: &mut Context<Self>,
  94    ) -> Self {
  95        let language = Language::new(
  96            language::LanguageConfig {
  97                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
  98                ..Default::default()
  99            },
 100            None,
 101        );
 102        let completion_provider = ContextPickerCompletionProvider::new(
 103            cx.weak_entity(),
 104            workspace.clone(),
 105            history_store.clone(),
 106            prompt_store.clone(),
 107            prompt_capabilities.clone(),
 108        );
 109        let semantics_provider = Rc::new(SlashCommandSemanticsProvider {
 110            range: Cell::new(None),
 111        });
 112        let mention_set = MentionSet::default();
 113        let editor = cx.new(|cx| {
 114            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 115            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 116
 117            let mut editor = Editor::new(mode, buffer, None, window, cx);
 118            editor.set_placeholder_text(placeholder, cx);
 119            editor.set_show_indent_guides(false, cx);
 120            editor.set_soft_wrap();
 121            editor.set_use_modal_editing(true);
 122            editor.set_completion_provider(Some(Rc::new(completion_provider)));
 123            editor.set_context_menu_options(ContextMenuOptions {
 124                min_entries_visible: 12,
 125                max_entries_visible: 12,
 126                placement: Some(ContextMenuPlacement::Above),
 127            });
 128            if prevent_slash_commands {
 129                editor.set_semantics_provider(Some(semantics_provider.clone()));
 130            }
 131            editor.register_addon(MessageEditorAddon::new());
 132            editor
 133        });
 134
 135        cx.on_focus_in(&editor.focus_handle(cx), window, |_, _, cx| {
 136            cx.emit(MessageEditorEvent::Focus)
 137        })
 138        .detach();
 139        cx.on_focus_out(&editor.focus_handle(cx), window, |_, _, _, cx| {
 140            cx.emit(MessageEditorEvent::LostFocus)
 141        })
 142        .detach();
 143
 144        let mut subscriptions = Vec::new();
 145        subscriptions.push(cx.subscribe_in(&editor, window, {
 146            let semantics_provider = semantics_provider.clone();
 147            move |this, editor, event, window, cx| {
 148                if let EditorEvent::Edited { .. } = event {
 149                    if prevent_slash_commands {
 150                        this.highlight_slash_command(
 151                            semantics_provider.clone(),
 152                            editor.clone(),
 153                            window,
 154                            cx,
 155                        );
 156                    }
 157                    let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 158                    this.mention_set.remove_invalid(snapshot);
 159                    cx.notify();
 160                }
 161            }
 162        }));
 163
 164        Self {
 165            editor,
 166            project,
 167            mention_set,
 168            workspace,
 169            history_store,
 170            prompt_store,
 171            prevent_slash_commands,
 172            prompt_capabilities,
 173            _subscriptions: subscriptions,
 174            _parse_slash_command_task: Task::ready(()),
 175        }
 176    }
 177
 178    pub fn insert_thread_summary(
 179        &mut self,
 180        thread: agent2::DbThreadMetadata,
 181        window: &mut Window,
 182        cx: &mut Context<Self>,
 183    ) {
 184        let start = self.editor.update(cx, |editor, cx| {
 185            editor.set_text(format!("{}\n", thread.title), window, cx);
 186            editor
 187                .buffer()
 188                .read(cx)
 189                .snapshot(cx)
 190                .anchor_before(Point::zero())
 191                .text_anchor
 192        });
 193
 194        self.confirm_completion(
 195            thread.title.clone(),
 196            start,
 197            thread.title.len(),
 198            MentionUri::Thread {
 199                id: thread.id.clone(),
 200                name: thread.title.to_string(),
 201            },
 202            window,
 203            cx,
 204        )
 205        .detach();
 206    }
 207
 208    #[cfg(test)]
 209    pub(crate) fn editor(&self) -> &Entity<Editor> {
 210        &self.editor
 211    }
 212
 213    #[cfg(test)]
 214    pub(crate) fn mention_set(&mut self) -> &mut MentionSet {
 215        &mut self.mention_set
 216    }
 217
 218    pub fn is_empty(&self, cx: &App) -> bool {
 219        self.editor.read(cx).is_empty(cx)
 220    }
 221
 222    pub fn mentions(&self) -> HashSet<MentionUri> {
 223        self.mention_set
 224            .mentions
 225            .values()
 226            .map(|(uri, _)| uri.clone())
 227            .collect()
 228    }
 229
 230    pub fn confirm_completion(
 231        &mut self,
 232        crease_text: SharedString,
 233        start: text::Anchor,
 234        content_len: usize,
 235        mention_uri: MentionUri,
 236        window: &mut Window,
 237        cx: &mut Context<Self>,
 238    ) -> Task<()> {
 239        let snapshot = self
 240            .editor
 241            .update(cx, |editor, cx| editor.snapshot(window, cx));
 242        let Some((excerpt_id, _, _)) = snapshot.buffer_snapshot.as_singleton() else {
 243            return Task::ready(());
 244        };
 245        let Some(start_anchor) = snapshot
 246            .buffer_snapshot
 247            .anchor_in_excerpt(*excerpt_id, start)
 248        else {
 249            return Task::ready(());
 250        };
 251        let end_anchor = snapshot
 252            .buffer_snapshot
 253            .anchor_before(start_anchor.to_offset(&snapshot.buffer_snapshot) + content_len + 1);
 254
 255        let crease = if let MentionUri::File { abs_path } = &mention_uri
 256            && let Some(extension) = abs_path.extension()
 257            && let Some(extension) = extension.to_str()
 258            && Img::extensions().contains(&extension)
 259            && !extension.contains("svg")
 260        {
 261            let Some(project_path) = self
 262                .project
 263                .read(cx)
 264                .project_path_for_absolute_path(&abs_path, cx)
 265            else {
 266                log::error!("project path not found");
 267                return Task::ready(());
 268            };
 269            let image = self
 270                .project
 271                .update(cx, |project, cx| project.open_image(project_path, cx));
 272            let image = cx
 273                .spawn(async move |_, cx| {
 274                    let image = image.await.map_err(|e| e.to_string())?;
 275                    let image = image
 276                        .update(cx, |image, _| image.image.clone())
 277                        .map_err(|e| e.to_string())?;
 278                    Ok(image)
 279                })
 280                .shared();
 281            insert_crease_for_mention(
 282                *excerpt_id,
 283                start,
 284                content_len,
 285                mention_uri.name().into(),
 286                IconName::Image.path().into(),
 287                Some(image),
 288                self.editor.clone(),
 289                window,
 290                cx,
 291            )
 292        } else {
 293            insert_crease_for_mention(
 294                *excerpt_id,
 295                start,
 296                content_len,
 297                crease_text,
 298                mention_uri.icon_path(cx),
 299                None,
 300                self.editor.clone(),
 301                window,
 302                cx,
 303            )
 304        };
 305        let Some((crease_id, tx)) = crease else {
 306            return Task::ready(());
 307        };
 308
 309        let task = match mention_uri.clone() {
 310            MentionUri::Fetch { url } => self.confirm_mention_for_fetch(url, cx),
 311            MentionUri::Directory { abs_path } => self.confirm_mention_for_directory(abs_path, cx),
 312            MentionUri::Thread { id, .. } => self.confirm_mention_for_thread(id, cx),
 313            MentionUri::TextThread { path, .. } => self.confirm_mention_for_text_thread(path, cx),
 314            MentionUri::File { abs_path } => self.confirm_mention_for_file(abs_path, cx),
 315            MentionUri::Symbol {
 316                abs_path,
 317                line_range,
 318                ..
 319            } => self.confirm_mention_for_symbol(abs_path, line_range, cx),
 320            MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
 321            MentionUri::PastedImage => {
 322                debug_panic!("pasted image URI should not be included in completions");
 323                Task::ready(Err(anyhow!(
 324                    "pasted imaged URI should not be included in completions"
 325                )))
 326            }
 327            MentionUri::Selection { .. } => {
 328                // Handled elsewhere
 329                debug_panic!("unexpected selection URI");
 330                Task::ready(Err(anyhow!("unexpected selection URI")))
 331            }
 332        };
 333        let task = cx
 334            .spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
 335            .shared();
 336        self.mention_set
 337            .mentions
 338            .insert(crease_id, (mention_uri, task.clone()));
 339
 340        // Notify the user if we failed to load the mentioned context
 341        cx.spawn_in(window, async move |this, cx| {
 342            let result = task.await.notify_async_err(cx);
 343            drop(tx);
 344            if result.is_none() {
 345                this.update(cx, |this, cx| {
 346                    this.editor.update(cx, |editor, cx| {
 347                        // Remove mention
 348                        editor.edit([(start_anchor..end_anchor, "")], cx);
 349                    });
 350                    this.mention_set.mentions.remove(&crease_id);
 351                })
 352                .ok();
 353            }
 354        })
 355    }
 356
 357    fn confirm_mention_for_file(
 358        &mut self,
 359        abs_path: PathBuf,
 360        cx: &mut Context<Self>,
 361    ) -> Task<Result<Mention>> {
 362        let Some(project_path) = self
 363            .project
 364            .read(cx)
 365            .project_path_for_absolute_path(&abs_path, cx)
 366        else {
 367            return Task::ready(Err(anyhow!("project path not found")));
 368        };
 369        let extension = abs_path
 370            .extension()
 371            .and_then(OsStr::to_str)
 372            .unwrap_or_default();
 373
 374        if Img::extensions().contains(&extension) && !extension.contains("svg") {
 375            if !self.prompt_capabilities.get().image {
 376                return Task::ready(Err(anyhow!("This model does not support images yet")));
 377            }
 378            let task = self
 379                .project
 380                .update(cx, |project, cx| project.open_image(project_path, cx));
 381            return cx.spawn(async move |_, cx| {
 382                let image = task.await?;
 383                let image = image.update(cx, |image, _| image.image.clone())?;
 384                let format = image.format;
 385                let image = cx
 386                    .update(|cx| LanguageModelImage::from_image(image, cx))?
 387                    .await;
 388                if let Some(image) = image {
 389                    Ok(Mention::Image(MentionImage {
 390                        data: image.source,
 391                        format,
 392                    }))
 393                } else {
 394                    Err(anyhow!("Failed to convert image"))
 395                }
 396            });
 397        }
 398
 399        let buffer = self
 400            .project
 401            .update(cx, |project, cx| project.open_buffer(project_path, cx));
 402        cx.spawn(async move |_, cx| {
 403            let buffer = buffer.await?;
 404            let mention = buffer.update(cx, |buffer, cx| Mention::Text {
 405                content: buffer.text(),
 406                tracked_buffers: vec![cx.entity()],
 407            })?;
 408            anyhow::Ok(mention)
 409        })
 410    }
 411
 412    fn confirm_mention_for_directory(
 413        &mut self,
 414        abs_path: PathBuf,
 415        cx: &mut Context<Self>,
 416    ) -> Task<Result<Mention>> {
 417        fn collect_files_in_path(worktree: &Worktree, path: &Path) -> Vec<(Arc<Path>, PathBuf)> {
 418            let mut files = Vec::new();
 419
 420            for entry in worktree.child_entries(path) {
 421                if entry.is_dir() {
 422                    files.extend(collect_files_in_path(worktree, &entry.path));
 423                } else if entry.is_file() {
 424                    files.push((entry.path.clone(), worktree.full_path(&entry.path)));
 425                }
 426            }
 427
 428            files
 429        }
 430
 431        let Some(project_path) = self
 432            .project
 433            .read(cx)
 434            .project_path_for_absolute_path(&abs_path, cx)
 435        else {
 436            return Task::ready(Err(anyhow!("project path not found")));
 437        };
 438        let Some(entry) = self.project.read(cx).entry_for_path(&project_path, cx) else {
 439            return Task::ready(Err(anyhow!("project entry not found")));
 440        };
 441        let directory_path = entry.path.clone();
 442        let Some(worktree) = self
 443            .project
 444            .read(cx)
 445            .worktree_for_id(project_path.worktree_id, cx)
 446        else {
 447            return Task::ready(Err(anyhow!("worktree not found")));
 448        };
 449        let project = self.project.clone();
 450        cx.spawn(async move |_, cx| {
 451            let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
 452            let file_paths = worktree.read_with(cx, |worktree, _cx| {
 453                collect_files_in_path(worktree, &directory_path)
 454            })?;
 455            let descendants_future = cx.update(|cx| {
 456                join_all(file_paths.into_iter().map(|(worktree_path, full_path)| {
 457                    let rel_path = worktree_path
 458                        .strip_prefix(&directory_path)
 459                        .log_err()
 460                        .map_or_else(|| worktree_path.clone(), |rel_path| rel_path.into());
 461
 462                    let open_task = project.update(cx, |project, cx| {
 463                        project.buffer_store().update(cx, |buffer_store, cx| {
 464                            let project_path = ProjectPath {
 465                                worktree_id,
 466                                path: worktree_path,
 467                            };
 468                            buffer_store.open_buffer(project_path, cx)
 469                        })
 470                    });
 471
 472                    // TODO: report load errors instead of just logging
 473                    let rope_task = cx.spawn(async move |cx| {
 474                        let buffer = open_task.await.log_err()?;
 475                        let rope = buffer
 476                            .read_with(cx, |buffer, _cx| buffer.as_rope().clone())
 477                            .log_err()?;
 478                        Some((rope, buffer))
 479                    });
 480
 481                    cx.background_spawn(async move {
 482                        let (rope, buffer) = rope_task.await?;
 483                        Some((rel_path, full_path, rope.to_string(), buffer))
 484                    })
 485                }))
 486            })?;
 487
 488            let contents = cx
 489                .background_spawn(async move {
 490                    let (contents, tracked_buffers) = descendants_future
 491                        .await
 492                        .into_iter()
 493                        .flatten()
 494                        .map(|(rel_path, full_path, rope, buffer)| {
 495                            ((rel_path, full_path, rope), buffer)
 496                        })
 497                        .unzip();
 498                    Mention::Text {
 499                        content: render_directory_contents(contents),
 500                        tracked_buffers,
 501                    }
 502                })
 503                .await;
 504            anyhow::Ok(contents)
 505        })
 506    }
 507
 508    fn confirm_mention_for_fetch(
 509        &mut self,
 510        url: url::Url,
 511        cx: &mut Context<Self>,
 512    ) -> Task<Result<Mention>> {
 513        let http_client = match self
 514            .workspace
 515            .update(cx, |workspace, _| workspace.client().http_client())
 516        {
 517            Ok(http_client) => http_client,
 518            Err(e) => return Task::ready(Err(e)),
 519        };
 520        cx.background_executor().spawn(async move {
 521            let content = fetch_url_content(http_client, url.to_string()).await?;
 522            Ok(Mention::Text {
 523                content,
 524                tracked_buffers: Vec::new(),
 525            })
 526        })
 527    }
 528
 529    fn confirm_mention_for_symbol(
 530        &mut self,
 531        abs_path: PathBuf,
 532        line_range: RangeInclusive<u32>,
 533        cx: &mut Context<Self>,
 534    ) -> Task<Result<Mention>> {
 535        let Some(project_path) = self
 536            .project
 537            .read(cx)
 538            .project_path_for_absolute_path(&abs_path, cx)
 539        else {
 540            return Task::ready(Err(anyhow!("project path not found")));
 541        };
 542        let buffer = self
 543            .project
 544            .update(cx, |project, cx| project.open_buffer(project_path, cx));
 545        cx.spawn(async move |_, cx| {
 546            let buffer = buffer.await?;
 547            let mention = buffer.update(cx, |buffer, cx| {
 548                let start = Point::new(*line_range.start(), 0).min(buffer.max_point());
 549                let end = Point::new(*line_range.end() + 1, 0).min(buffer.max_point());
 550                let content = buffer.text_for_range(start..end).collect();
 551                Mention::Text {
 552                    content,
 553                    tracked_buffers: vec![cx.entity()],
 554                }
 555            })?;
 556            anyhow::Ok(mention)
 557        })
 558    }
 559
 560    fn confirm_mention_for_rule(
 561        &mut self,
 562        id: PromptId,
 563        cx: &mut Context<Self>,
 564    ) -> Task<Result<Mention>> {
 565        let Some(prompt_store) = self.prompt_store.clone() else {
 566            return Task::ready(Err(anyhow!("missing prompt store")));
 567        };
 568        let prompt = prompt_store.read(cx).load(id, cx);
 569        cx.spawn(async move |_, _| {
 570            let prompt = prompt.await?;
 571            Ok(Mention::Text {
 572                content: prompt,
 573                tracked_buffers: Vec::new(),
 574            })
 575        })
 576    }
 577
 578    pub fn confirm_mention_for_selection(
 579        &mut self,
 580        source_range: Range<text::Anchor>,
 581        selections: Vec<(Entity<Buffer>, Range<text::Anchor>, Range<usize>)>,
 582        window: &mut Window,
 583        cx: &mut Context<Self>,
 584    ) {
 585        let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
 586        let Some((&excerpt_id, _, _)) = snapshot.as_singleton() else {
 587            return;
 588        };
 589        let Some(start) = snapshot.anchor_in_excerpt(excerpt_id, source_range.start) else {
 590            return;
 591        };
 592
 593        let offset = start.to_offset(&snapshot);
 594
 595        for (buffer, selection_range, range_to_fold) in selections {
 596            let range = snapshot.anchor_after(offset + range_to_fold.start)
 597                ..snapshot.anchor_after(offset + range_to_fold.end);
 598
 599            let abs_path = buffer
 600                .read(cx)
 601                .project_path(cx)
 602                .and_then(|project_path| self.project.read(cx).absolute_path(&project_path, cx));
 603            let snapshot = buffer.read(cx).snapshot();
 604
 605            let text = snapshot
 606                .text_for_range(selection_range.clone())
 607                .collect::<String>();
 608            let point_range = selection_range.to_point(&snapshot);
 609            let line_range = point_range.start.row..=point_range.end.row;
 610
 611            let uri = MentionUri::Selection {
 612                abs_path: abs_path.clone(),
 613                line_range: line_range.clone(),
 614            };
 615            let crease = crate::context_picker::crease_for_mention(
 616                selection_name(abs_path.as_deref(), &line_range).into(),
 617                uri.icon_path(cx),
 618                range,
 619                self.editor.downgrade(),
 620            );
 621
 622            let crease_id = self.editor.update(cx, |editor, cx| {
 623                let crease_ids = editor.insert_creases(vec![crease.clone()], cx);
 624                editor.fold_creases(vec![crease], false, window, cx);
 625                crease_ids.first().copied().unwrap()
 626            });
 627
 628            self.mention_set.mentions.insert(
 629                crease_id,
 630                (
 631                    uri,
 632                    Task::ready(Ok(Mention::Text {
 633                        content: text,
 634                        tracked_buffers: vec![buffer],
 635                    }))
 636                    .shared(),
 637                ),
 638            );
 639        }
 640    }
 641
 642    fn confirm_mention_for_thread(
 643        &mut self,
 644        id: acp::SessionId,
 645        cx: &mut Context<Self>,
 646    ) -> Task<Result<Mention>> {
 647        let server = Rc::new(agent2::NativeAgentServer::new(
 648            self.project.read(cx).fs().clone(),
 649            self.history_store.clone(),
 650        ));
 651        let delegate = AgentServerDelegate::new(self.project.clone(), None);
 652        let connection = server.connect(Path::new(""), delegate, cx);
 653        cx.spawn(async move |_, cx| {
 654            let agent = connection.await?;
 655            let agent = agent.downcast::<agent2::NativeAgentConnection>().unwrap();
 656            let summary = agent
 657                .0
 658                .update(cx, |agent, cx| agent.thread_summary(id, cx))?
 659                .await?;
 660            anyhow::Ok(Mention::Text {
 661                content: summary.to_string(),
 662                tracked_buffers: Vec::new(),
 663            })
 664        })
 665    }
 666
 667    fn confirm_mention_for_text_thread(
 668        &mut self,
 669        path: PathBuf,
 670        cx: &mut Context<Self>,
 671    ) -> Task<Result<Mention>> {
 672        let context = self.history_store.update(cx, |text_thread_store, cx| {
 673            text_thread_store.load_text_thread(path.as_path().into(), cx)
 674        });
 675        cx.spawn(async move |_, cx| {
 676            let context = context.await?;
 677            let xml = context.update(cx, |context, cx| context.to_xml(cx))?;
 678            Ok(Mention::Text {
 679                content: xml,
 680                tracked_buffers: Vec::new(),
 681            })
 682        })
 683    }
 684
 685    pub fn contents(
 686        &self,
 687        cx: &mut Context<Self>,
 688    ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
 689        let contents = self
 690            .mention_set
 691            .contents(&self.prompt_capabilities.get(), cx);
 692        let editor = self.editor.clone();
 693        let prevent_slash_commands = self.prevent_slash_commands;
 694
 695        cx.spawn(async move |_, cx| {
 696            let contents = contents.await?;
 697            let mut all_tracked_buffers = Vec::new();
 698
 699            editor.update(cx, |editor, cx| {
 700                let mut ix = 0;
 701                let mut chunks: Vec<acp::ContentBlock> = Vec::new();
 702                let text = editor.text(cx);
 703                editor.display_map.update(cx, |map, cx| {
 704                    let snapshot = map.snapshot(cx);
 705                    for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 706                        let Some((uri, mention)) = contents.get(&crease_id) else {
 707                            continue;
 708                        };
 709
 710                        let crease_range = crease.range().to_offset(&snapshot.buffer_snapshot);
 711                        if crease_range.start > ix {
 712                            let chunk = if prevent_slash_commands
 713                                && ix == 0
 714                                && parse_slash_command(&text[ix..]).is_some()
 715                            {
 716                                format!(" {}", &text[ix..crease_range.start]).into()
 717                            } else {
 718                                text[ix..crease_range.start].into()
 719                            };
 720                            chunks.push(chunk);
 721                        }
 722                        let chunk = match mention {
 723                            Mention::Text {
 724                                content,
 725                                tracked_buffers,
 726                            } => {
 727                                all_tracked_buffers.extend(tracked_buffers.iter().cloned());
 728                                acp::ContentBlock::Resource(acp::EmbeddedResource {
 729                                    annotations: None,
 730                                    resource: acp::EmbeddedResourceResource::TextResourceContents(
 731                                        acp::TextResourceContents {
 732                                            mime_type: None,
 733                                            text: content.clone(),
 734                                            uri: uri.to_uri().to_string(),
 735                                        },
 736                                    ),
 737                                })
 738                            }
 739                            Mention::Image(mention_image) => {
 740                                let uri = match uri {
 741                                    MentionUri::File { .. } => Some(uri.to_uri().to_string()),
 742                                    MentionUri::PastedImage => None,
 743                                    other => {
 744                                        debug_panic!(
 745                                            "unexpected mention uri for image: {:?}",
 746                                            other
 747                                        );
 748                                        None
 749                                    }
 750                                };
 751                                acp::ContentBlock::Image(acp::ImageContent {
 752                                    annotations: None,
 753                                    data: mention_image.data.to_string(),
 754                                    mime_type: mention_image.format.mime_type().into(),
 755                                    uri,
 756                                })
 757                            }
 758                            Mention::UriOnly => {
 759                                acp::ContentBlock::ResourceLink(acp::ResourceLink {
 760                                    name: uri.name(),
 761                                    uri: uri.to_uri().to_string(),
 762                                    annotations: None,
 763                                    description: None,
 764                                    mime_type: None,
 765                                    size: None,
 766                                    title: None,
 767                                })
 768                            }
 769                        };
 770                        chunks.push(chunk);
 771                        ix = crease_range.end;
 772                    }
 773
 774                    if ix < text.len() {
 775                        let last_chunk = if prevent_slash_commands
 776                            && ix == 0
 777                            && parse_slash_command(&text[ix..]).is_some()
 778                        {
 779                            format!(" {}", text[ix..].trim_end())
 780                        } else {
 781                            text[ix..].trim_end().to_owned()
 782                        };
 783                        if !last_chunk.is_empty() {
 784                            chunks.push(last_chunk.into());
 785                        }
 786                    }
 787                });
 788
 789                (chunks, all_tracked_buffers)
 790            })
 791        })
 792    }
 793
 794    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 795        self.editor.update(cx, |editor, cx| {
 796            editor.clear(window, cx);
 797            editor.remove_creases(
 798                self.mention_set
 799                    .mentions
 800                    .drain()
 801                    .map(|(crease_id, _)| crease_id),
 802                cx,
 803            )
 804        });
 805    }
 806
 807    fn send(&mut self, _: &Chat, _: &mut Window, cx: &mut Context<Self>) {
 808        if self.is_empty(cx) {
 809            return;
 810        }
 811        cx.emit(MessageEditorEvent::Send)
 812    }
 813
 814    fn cancel(&mut self, _: &editor::actions::Cancel, _: &mut Window, cx: &mut Context<Self>) {
 815        cx.emit(MessageEditorEvent::Cancel)
 816    }
 817
 818    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 819        if !self.prompt_capabilities.get().image {
 820            return;
 821        }
 822
 823        let images = cx
 824            .read_from_clipboard()
 825            .map(|item| {
 826                item.into_entries()
 827                    .filter_map(|entry| {
 828                        if let ClipboardEntry::Image(image) = entry {
 829                            Some(image)
 830                        } else {
 831                            None
 832                        }
 833                    })
 834                    .collect::<Vec<_>>()
 835            })
 836            .unwrap_or_default();
 837
 838        if images.is_empty() {
 839            return;
 840        }
 841        cx.stop_propagation();
 842
 843        let replacement_text = MentionUri::PastedImage.as_link().to_string();
 844        for image in images {
 845            let (excerpt_id, text_anchor, multibuffer_anchor) =
 846                self.editor.update(cx, |message_editor, cx| {
 847                    let snapshot = message_editor.snapshot(window, cx);
 848                    let (excerpt_id, _, buffer_snapshot) =
 849                        snapshot.buffer_snapshot.as_singleton().unwrap();
 850
 851                    let text_anchor = buffer_snapshot.anchor_before(buffer_snapshot.len());
 852                    let multibuffer_anchor = snapshot
 853                        .buffer_snapshot
 854                        .anchor_in_excerpt(*excerpt_id, text_anchor);
 855                    message_editor.edit(
 856                        [(
 857                            multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
 858                            format!("{replacement_text} "),
 859                        )],
 860                        cx,
 861                    );
 862                    (*excerpt_id, text_anchor, multibuffer_anchor)
 863                });
 864
 865            let content_len = replacement_text.len();
 866            let Some(start_anchor) = multibuffer_anchor else {
 867                continue;
 868            };
 869            let end_anchor = self.editor.update(cx, |editor, cx| {
 870                let snapshot = editor.buffer().read(cx).snapshot(cx);
 871                snapshot.anchor_before(start_anchor.to_offset(&snapshot) + content_len)
 872            });
 873            let image = Arc::new(image);
 874            let Some((crease_id, tx)) = insert_crease_for_mention(
 875                excerpt_id,
 876                text_anchor,
 877                content_len,
 878                MentionUri::PastedImage.name().into(),
 879                IconName::Image.path().into(),
 880                Some(Task::ready(Ok(image.clone())).shared()),
 881                self.editor.clone(),
 882                window,
 883                cx,
 884            ) else {
 885                continue;
 886            };
 887            let task = cx
 888                .spawn_in(window, {
 889                    async move |_, cx| {
 890                        let format = image.format;
 891                        let image = cx
 892                            .update(|_, cx| LanguageModelImage::from_image(image, cx))
 893                            .map_err(|e| e.to_string())?
 894                            .await;
 895                        drop(tx);
 896                        if let Some(image) = image {
 897                            Ok(Mention::Image(MentionImage {
 898                                data: image.source,
 899                                format,
 900                            }))
 901                        } else {
 902                            Err("Failed to convert image".into())
 903                        }
 904                    }
 905                })
 906                .shared();
 907
 908            self.mention_set
 909                .mentions
 910                .insert(crease_id, (MentionUri::PastedImage, task.clone()));
 911
 912            cx.spawn_in(window, async move |this, cx| {
 913                if task.await.notify_async_err(cx).is_none() {
 914                    this.update(cx, |this, cx| {
 915                        this.editor.update(cx, |editor, cx| {
 916                            editor.edit([(start_anchor..end_anchor, "")], cx);
 917                        });
 918                        this.mention_set.mentions.remove(&crease_id);
 919                    })
 920                    .ok();
 921                }
 922            })
 923            .detach();
 924        }
 925    }
 926
 927    pub fn insert_dragged_files(
 928        &mut self,
 929        paths: Vec<project::ProjectPath>,
 930        added_worktrees: Vec<Entity<Worktree>>,
 931        window: &mut Window,
 932        cx: &mut Context<Self>,
 933    ) {
 934        let buffer = self.editor.read(cx).buffer().clone();
 935        let Some(buffer) = buffer.read(cx).as_singleton() else {
 936            return;
 937        };
 938        let mut tasks = Vec::new();
 939        for path in paths {
 940            let Some(entry) = self.project.read(cx).entry_for_path(&path, cx) else {
 941                continue;
 942            };
 943            let Some(abs_path) = self.project.read(cx).absolute_path(&path, cx) else {
 944                continue;
 945            };
 946            let path_prefix = abs_path
 947                .file_name()
 948                .unwrap_or(path.path.as_os_str())
 949                .display()
 950                .to_string();
 951            let (file_name, _) =
 952                crate::context_picker::file_context_picker::extract_file_name_and_directory(
 953                    &path.path,
 954                    &path_prefix,
 955                );
 956
 957            let uri = if entry.is_dir() {
 958                MentionUri::Directory { abs_path }
 959            } else {
 960                MentionUri::File { abs_path }
 961            };
 962
 963            let new_text = format!("{} ", uri.as_link());
 964            let content_len = new_text.len() - 1;
 965
 966            let anchor = buffer.update(cx, |buffer, _cx| buffer.anchor_before(buffer.len()));
 967
 968            self.editor.update(cx, |message_editor, cx| {
 969                message_editor.edit(
 970                    [(
 971                        multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
 972                        new_text,
 973                    )],
 974                    cx,
 975                );
 976            });
 977            tasks.push(self.confirm_completion(file_name, anchor, content_len, uri, window, cx));
 978        }
 979        cx.spawn(async move |_, _| {
 980            join_all(tasks).await;
 981            drop(added_worktrees);
 982        })
 983        .detach();
 984    }
 985
 986    pub fn insert_selections(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 987        let buffer = self.editor.read(cx).buffer().clone();
 988        let Some(buffer) = buffer.read(cx).as_singleton() else {
 989            return;
 990        };
 991        let anchor = buffer.update(cx, |buffer, _cx| buffer.anchor_before(buffer.len()));
 992        let Some(workspace) = self.workspace.upgrade() else {
 993            return;
 994        };
 995        let Some(completion) = ContextPickerCompletionProvider::completion_for_action(
 996            ContextPickerAction::AddSelections,
 997            anchor..anchor,
 998            cx.weak_entity(),
 999            &workspace,
1000            cx,
1001        ) else {
1002            return;
1003        };
1004        self.editor.update(cx, |message_editor, cx| {
1005            message_editor.edit(
1006                [(
1007                    multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
1008                    completion.new_text,
1009                )],
1010                cx,
1011            );
1012        });
1013        if let Some(confirm) = completion.confirm {
1014            confirm(CompletionIntent::Complete, window, cx);
1015        }
1016    }
1017
1018    pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context<Self>) {
1019        self.editor.update(cx, |message_editor, cx| {
1020            message_editor.set_read_only(read_only);
1021            cx.notify()
1022        })
1023    }
1024
1025    pub fn set_mode(&mut self, mode: EditorMode, cx: &mut Context<Self>) {
1026        self.editor.update(cx, |editor, cx| {
1027            editor.set_mode(mode);
1028            cx.notify()
1029        });
1030    }
1031
1032    pub fn set_message(
1033        &mut self,
1034        message: Vec<acp::ContentBlock>,
1035        window: &mut Window,
1036        cx: &mut Context<Self>,
1037    ) {
1038        self.clear(window, cx);
1039
1040        let mut text = String::new();
1041        let mut mentions = Vec::new();
1042
1043        for chunk in message {
1044            match chunk {
1045                acp::ContentBlock::Text(text_content) => {
1046                    text.push_str(&text_content.text);
1047                }
1048                acp::ContentBlock::Resource(acp::EmbeddedResource {
1049                    resource: acp::EmbeddedResourceResource::TextResourceContents(resource),
1050                    ..
1051                }) => {
1052                    let Some(mention_uri) = MentionUri::parse(&resource.uri).log_err() else {
1053                        continue;
1054                    };
1055                    let start = text.len();
1056                    write!(&mut text, "{}", mention_uri.as_link()).ok();
1057                    let end = text.len();
1058                    mentions.push((
1059                        start..end,
1060                        mention_uri,
1061                        Mention::Text {
1062                            content: resource.text,
1063                            tracked_buffers: Vec::new(),
1064                        },
1065                    ));
1066                }
1067                acp::ContentBlock::ResourceLink(resource) => {
1068                    if let Some(mention_uri) = MentionUri::parse(&resource.uri).log_err() {
1069                        let start = text.len();
1070                        write!(&mut text, "{}", mention_uri.as_link()).ok();
1071                        let end = text.len();
1072                        mentions.push((start..end, mention_uri, Mention::UriOnly));
1073                    }
1074                }
1075                acp::ContentBlock::Image(acp::ImageContent {
1076                    uri,
1077                    data,
1078                    mime_type,
1079                    annotations: _,
1080                }) => {
1081                    let mention_uri = if let Some(uri) = uri {
1082                        MentionUri::parse(&uri)
1083                    } else {
1084                        Ok(MentionUri::PastedImage)
1085                    };
1086                    let Some(mention_uri) = mention_uri.log_err() else {
1087                        continue;
1088                    };
1089                    let Some(format) = ImageFormat::from_mime_type(&mime_type) else {
1090                        log::error!("failed to parse MIME type for image: {mime_type:?}");
1091                        continue;
1092                    };
1093                    let start = text.len();
1094                    write!(&mut text, "{}", mention_uri.as_link()).ok();
1095                    let end = text.len();
1096                    mentions.push((
1097                        start..end,
1098                        mention_uri,
1099                        Mention::Image(MentionImage {
1100                            data: data.into(),
1101                            format,
1102                        }),
1103                    ));
1104                }
1105                acp::ContentBlock::Audio(_) | acp::ContentBlock::Resource(_) => {}
1106            }
1107        }
1108
1109        let snapshot = self.editor.update(cx, |editor, cx| {
1110            editor.set_text(text, window, cx);
1111            editor.buffer().read(cx).snapshot(cx)
1112        });
1113
1114        for (range, mention_uri, mention) in mentions {
1115            let anchor = snapshot.anchor_before(range.start);
1116            let Some((crease_id, tx)) = insert_crease_for_mention(
1117                anchor.excerpt_id,
1118                anchor.text_anchor,
1119                range.end - range.start,
1120                mention_uri.name().into(),
1121                mention_uri.icon_path(cx),
1122                None,
1123                self.editor.clone(),
1124                window,
1125                cx,
1126            ) else {
1127                continue;
1128            };
1129            drop(tx);
1130
1131            self.mention_set.mentions.insert(
1132                crease_id,
1133                (mention_uri.clone(), Task::ready(Ok(mention)).shared()),
1134            );
1135        }
1136        cx.notify();
1137    }
1138
1139    fn highlight_slash_command(
1140        &mut self,
1141        semantics_provider: Rc<SlashCommandSemanticsProvider>,
1142        editor: Entity<Editor>,
1143        window: &mut Window,
1144        cx: &mut Context<Self>,
1145    ) {
1146        struct InvalidSlashCommand;
1147
1148        self._parse_slash_command_task = cx.spawn_in(window, async move |_, cx| {
1149            cx.background_executor()
1150                .timer(PARSE_SLASH_COMMAND_DEBOUNCE)
1151                .await;
1152            editor
1153                .update_in(cx, |editor, window, cx| {
1154                    let snapshot = editor.snapshot(window, cx);
1155                    let range = parse_slash_command(&editor.text(cx));
1156                    semantics_provider.range.set(range);
1157                    if let Some((start, end)) = range {
1158                        editor.highlight_text::<InvalidSlashCommand>(
1159                            vec![
1160                                snapshot.buffer_snapshot.anchor_after(start)
1161                                    ..snapshot.buffer_snapshot.anchor_before(end),
1162                            ],
1163                            HighlightStyle {
1164                                underline: Some(UnderlineStyle {
1165                                    thickness: px(1.),
1166                                    color: Some(gpui::red()),
1167                                    wavy: true,
1168                                }),
1169                                ..Default::default()
1170                            },
1171                            cx,
1172                        );
1173                    } else {
1174                        editor.clear_highlights::<InvalidSlashCommand>(cx);
1175                    }
1176                })
1177                .ok();
1178        })
1179    }
1180
1181    pub fn text(&self, cx: &App) -> String {
1182        self.editor.read(cx).text(cx)
1183    }
1184
1185    #[cfg(test)]
1186    pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1187        self.editor.update(cx, |editor, cx| {
1188            editor.set_text(text, window, cx);
1189        });
1190    }
1191}
1192
1193fn render_directory_contents(entries: Vec<(Arc<Path>, PathBuf, String)>) -> String {
1194    let mut output = String::new();
1195    for (_relative_path, full_path, content) in entries {
1196        let fence = codeblock_fence_for_path(Some(&full_path), None);
1197        write!(output, "\n{fence}\n{content}\n```").unwrap();
1198    }
1199    output
1200}
1201
1202impl Focusable for MessageEditor {
1203    fn focus_handle(&self, cx: &App) -> FocusHandle {
1204        self.editor.focus_handle(cx)
1205    }
1206}
1207
1208impl Render for MessageEditor {
1209    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1210        div()
1211            .key_context("MessageEditor")
1212            .on_action(cx.listener(Self::send))
1213            .on_action(cx.listener(Self::cancel))
1214            .capture_action(cx.listener(Self::paste))
1215            .flex_1()
1216            .child({
1217                let settings = ThemeSettings::get_global(cx);
1218                let font_size = TextSize::Small
1219                    .rems(cx)
1220                    .to_pixels(settings.agent_font_size(cx));
1221                let line_height = settings.buffer_line_height.value() * font_size;
1222
1223                let text_style = TextStyle {
1224                    color: cx.theme().colors().text,
1225                    font_family: settings.buffer_font.family.clone(),
1226                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
1227                    font_features: settings.buffer_font.features.clone(),
1228                    font_size: font_size.into(),
1229                    line_height: line_height.into(),
1230                    ..Default::default()
1231                };
1232
1233                EditorElement::new(
1234                    &self.editor,
1235                    EditorStyle {
1236                        background: cx.theme().colors().editor_background,
1237                        local_player: cx.theme().players().local(),
1238                        text: text_style,
1239                        syntax: cx.theme().syntax().clone(),
1240                        ..Default::default()
1241                    },
1242                )
1243            })
1244    }
1245}
1246
1247pub(crate) fn insert_crease_for_mention(
1248    excerpt_id: ExcerptId,
1249    anchor: text::Anchor,
1250    content_len: usize,
1251    crease_label: SharedString,
1252    crease_icon: SharedString,
1253    // abs_path: Option<Arc<Path>>,
1254    image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1255    editor: Entity<Editor>,
1256    window: &mut Window,
1257    cx: &mut App,
1258) -> Option<(CreaseId, postage::barrier::Sender)> {
1259    let (tx, rx) = postage::barrier::channel();
1260
1261    let crease_id = editor.update(cx, |editor, cx| {
1262        let snapshot = editor.buffer().read(cx).snapshot(cx);
1263
1264        let start = snapshot.anchor_in_excerpt(excerpt_id, anchor)?;
1265
1266        let start = start.bias_right(&snapshot);
1267        let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
1268
1269        let placeholder = FoldPlaceholder {
1270            render: render_fold_icon_button(
1271                crease_label,
1272                crease_icon,
1273                start..end,
1274                rx,
1275                image,
1276                cx.weak_entity(),
1277                cx,
1278            ),
1279            merge_adjacent: false,
1280            ..Default::default()
1281        };
1282
1283        let crease = Crease::Inline {
1284            range: start..end,
1285            placeholder,
1286            render_toggle: None,
1287            render_trailer: None,
1288            metadata: None,
1289        };
1290
1291        let ids = editor.insert_creases(vec![crease.clone()], cx);
1292        editor.fold_creases(vec![crease], false, window, cx);
1293
1294        Some(ids[0])
1295    })?;
1296
1297    Some((crease_id, tx))
1298}
1299
1300fn render_fold_icon_button(
1301    label: SharedString,
1302    icon: SharedString,
1303    range: Range<Anchor>,
1304    mut loading_finished: postage::barrier::Receiver,
1305    image_task: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1306    editor: WeakEntity<Editor>,
1307    cx: &mut App,
1308) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
1309    let loading = cx.new(|cx| {
1310        let loading = cx.spawn(async move |this, cx| {
1311            loading_finished.recv().await;
1312            this.update(cx, |this: &mut LoadingContext, cx| {
1313                this.loading = None;
1314                cx.notify();
1315            })
1316            .ok();
1317        });
1318        LoadingContext {
1319            id: cx.entity_id(),
1320            label,
1321            icon,
1322            range,
1323            editor,
1324            loading: Some(loading),
1325            image: image_task.clone(),
1326        }
1327    });
1328    Arc::new(move |_fold_id, _fold_range, _cx| loading.clone().into_any_element())
1329}
1330
1331struct LoadingContext {
1332    id: EntityId,
1333    label: SharedString,
1334    icon: SharedString,
1335    range: Range<Anchor>,
1336    editor: WeakEntity<Editor>,
1337    loading: Option<Task<()>>,
1338    image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
1339}
1340
1341impl Render for LoadingContext {
1342    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1343        let is_in_text_selection = self
1344            .editor
1345            .update(cx, |editor, cx| editor.is_range_selected(&self.range, cx))
1346            .unwrap_or_default();
1347        ButtonLike::new(("loading-context", self.id))
1348            .style(ButtonStyle::Filled)
1349            .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1350            .toggle_state(is_in_text_selection)
1351            .when_some(self.image.clone(), |el, image_task| {
1352                el.hoverable_tooltip(move |_, cx| {
1353                    let image = image_task.peek().cloned().transpose().ok().flatten();
1354                    let image_task = image_task.clone();
1355                    cx.new::<ImageHover>(|cx| ImageHover {
1356                        image,
1357                        _task: cx.spawn(async move |this, cx| {
1358                            if let Ok(image) = image_task.clone().await {
1359                                this.update(cx, |this, cx| {
1360                                    if this.image.replace(image).is_none() {
1361                                        cx.notify();
1362                                    }
1363                                })
1364                                .ok();
1365                            }
1366                        }),
1367                    })
1368                    .into()
1369                })
1370            })
1371            .child(
1372                h_flex()
1373                    .gap_1()
1374                    .child(
1375                        Icon::from_path(self.icon.clone())
1376                            .size(IconSize::XSmall)
1377                            .color(Color::Muted),
1378                    )
1379                    .child(
1380                        Label::new(self.label.clone())
1381                            .size(LabelSize::Small)
1382                            .buffer_font(cx)
1383                            .single_line(),
1384                    )
1385                    .map(|el| {
1386                        if self.loading.is_some() {
1387                            el.with_animation(
1388                                "loading-context-crease",
1389                                Animation::new(Duration::from_secs(2))
1390                                    .repeat()
1391                                    .with_easing(pulsating_between(0.4, 0.8)),
1392                                |label, delta| label.opacity(delta),
1393                            )
1394                            .into_any()
1395                        } else {
1396                            el.into_any()
1397                        }
1398                    }),
1399            )
1400    }
1401}
1402
1403struct ImageHover {
1404    image: Option<Arc<Image>>,
1405    _task: Task<()>,
1406}
1407
1408impl Render for ImageHover {
1409    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1410        if let Some(image) = self.image.clone() {
1411            gpui::img(image).max_w_96().max_h_96().into_any_element()
1412        } else {
1413            gpui::Empty.into_any_element()
1414        }
1415    }
1416}
1417
1418#[derive(Debug, Clone, Eq, PartialEq)]
1419pub enum Mention {
1420    Text {
1421        content: String,
1422        tracked_buffers: Vec<Entity<Buffer>>,
1423    },
1424    Image(MentionImage),
1425    UriOnly,
1426}
1427
1428#[derive(Clone, Debug, Eq, PartialEq)]
1429pub struct MentionImage {
1430    pub data: SharedString,
1431    pub format: ImageFormat,
1432}
1433
1434#[derive(Default)]
1435pub struct MentionSet {
1436    mentions: HashMap<CreaseId, (MentionUri, Shared<Task<Result<Mention, String>>>)>,
1437}
1438
1439impl MentionSet {
1440    fn contents(
1441        &self,
1442        prompt_capabilities: &acp::PromptCapabilities,
1443        cx: &mut App,
1444    ) -> Task<Result<HashMap<CreaseId, (MentionUri, Mention)>>> {
1445        if !prompt_capabilities.embedded_context {
1446            let mentions = self
1447                .mentions
1448                .iter()
1449                .map(|(crease_id, (uri, _))| (*crease_id, (uri.clone(), Mention::UriOnly)))
1450                .collect();
1451
1452            return Task::ready(Ok(mentions));
1453        }
1454
1455        let mentions = self.mentions.clone();
1456        cx.spawn(async move |_cx| {
1457            let mut contents = HashMap::default();
1458            for (crease_id, (mention_uri, task)) in mentions {
1459                contents.insert(
1460                    crease_id,
1461                    (mention_uri, task.await.map_err(|e| anyhow!("{e}"))?),
1462                );
1463            }
1464            Ok(contents)
1465        })
1466    }
1467
1468    fn remove_invalid(&mut self, snapshot: EditorSnapshot) {
1469        for (crease_id, crease) in snapshot.crease_snapshot.creases() {
1470            if !crease.range().start.is_valid(&snapshot.buffer_snapshot) {
1471                self.mentions.remove(&crease_id);
1472            }
1473        }
1474    }
1475}
1476
1477struct SlashCommandSemanticsProvider {
1478    range: Cell<Option<(usize, usize)>>,
1479}
1480
1481impl SemanticsProvider for SlashCommandSemanticsProvider {
1482    fn hover(
1483        &self,
1484        buffer: &Entity<Buffer>,
1485        position: text::Anchor,
1486        cx: &mut App,
1487    ) -> Option<Task<Option<Vec<project::Hover>>>> {
1488        let snapshot = buffer.read(cx).snapshot();
1489        let offset = position.to_offset(&snapshot);
1490        let (start, end) = self.range.get()?;
1491        if !(start..end).contains(&offset) {
1492            return None;
1493        }
1494        let range = snapshot.anchor_after(start)..snapshot.anchor_after(end);
1495        Some(Task::ready(Some(vec![project::Hover {
1496            contents: vec![project::HoverBlock {
1497                text: "Slash commands are not supported".into(),
1498                kind: project::HoverBlockKind::PlainText,
1499            }],
1500            range: Some(range),
1501            language: None,
1502        }])))
1503    }
1504
1505    fn inline_values(
1506        &self,
1507        _buffer_handle: Entity<Buffer>,
1508        _range: Range<text::Anchor>,
1509        _cx: &mut App,
1510    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
1511        None
1512    }
1513
1514    fn inlay_hints(
1515        &self,
1516        _buffer_handle: Entity<Buffer>,
1517        _range: Range<text::Anchor>,
1518        _cx: &mut App,
1519    ) -> Option<Task<anyhow::Result<Vec<project::InlayHint>>>> {
1520        None
1521    }
1522
1523    fn resolve_inlay_hint(
1524        &self,
1525        _hint: project::InlayHint,
1526        _buffer_handle: Entity<Buffer>,
1527        _server_id: lsp::LanguageServerId,
1528        _cx: &mut App,
1529    ) -> Option<Task<anyhow::Result<project::InlayHint>>> {
1530        None
1531    }
1532
1533    fn supports_inlay_hints(&self, _buffer: &Entity<Buffer>, _cx: &mut App) -> bool {
1534        false
1535    }
1536
1537    fn document_highlights(
1538        &self,
1539        _buffer: &Entity<Buffer>,
1540        _position: text::Anchor,
1541        _cx: &mut App,
1542    ) -> Option<Task<Result<Vec<project::DocumentHighlight>>>> {
1543        None
1544    }
1545
1546    fn definitions(
1547        &self,
1548        _buffer: &Entity<Buffer>,
1549        _position: text::Anchor,
1550        _kind: editor::GotoDefinitionKind,
1551        _cx: &mut App,
1552    ) -> Option<Task<Result<Option<Vec<project::LocationLink>>>>> {
1553        None
1554    }
1555
1556    fn range_for_rename(
1557        &self,
1558        _buffer: &Entity<Buffer>,
1559        _position: text::Anchor,
1560        _cx: &mut App,
1561    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
1562        None
1563    }
1564
1565    fn perform_rename(
1566        &self,
1567        _buffer: &Entity<Buffer>,
1568        _position: text::Anchor,
1569        _new_name: String,
1570        _cx: &mut App,
1571    ) -> Option<Task<Result<project::ProjectTransaction>>> {
1572        None
1573    }
1574}
1575
1576fn parse_slash_command(text: &str) -> Option<(usize, usize)> {
1577    if let Some(remainder) = text.strip_prefix('/') {
1578        let pos = remainder
1579            .find(char::is_whitespace)
1580            .unwrap_or(remainder.len());
1581        let command = &remainder[..pos];
1582        if !command.is_empty() && command.chars().all(char::is_alphanumeric) {
1583            return Some((0, 1 + command.len()));
1584        }
1585    }
1586    None
1587}
1588
1589pub struct MessageEditorAddon {}
1590
1591impl MessageEditorAddon {
1592    pub fn new() -> Self {
1593        Self {}
1594    }
1595}
1596
1597impl Addon for MessageEditorAddon {
1598    fn to_any(&self) -> &dyn std::any::Any {
1599        self
1600    }
1601
1602    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1603        Some(self)
1604    }
1605
1606    fn extend_key_context(&self, key_context: &mut KeyContext, cx: &App) {
1607        let settings = agent_settings::AgentSettings::get_global(cx);
1608        if settings.use_modifier_to_send {
1609            key_context.add("use_modifier_to_send");
1610        }
1611    }
1612}
1613
1614#[cfg(test)]
1615mod tests {
1616    use std::{cell::Cell, ops::Range, path::Path, rc::Rc, sync::Arc};
1617
1618    use acp_thread::MentionUri;
1619    use agent_client_protocol as acp;
1620    use agent2::HistoryStore;
1621    use assistant_context::ContextStore;
1622    use editor::{AnchorRangeExt as _, Editor, EditorMode};
1623    use fs::FakeFs;
1624    use futures::StreamExt as _;
1625    use gpui::{
1626        AppContext, Entity, EventEmitter, FocusHandle, Focusable, TestAppContext, VisualTestContext,
1627    };
1628    use lsp::{CompletionContext, CompletionTriggerKind};
1629    use project::{CompletionIntent, Project, ProjectPath};
1630    use serde_json::json;
1631    use text::Point;
1632    use ui::{App, Context, IntoElement, Render, SharedString, Window};
1633    use util::{path, uri};
1634    use workspace::{AppState, Item, Workspace};
1635
1636    use crate::acp::{
1637        message_editor::{Mention, MessageEditor},
1638        thread_view::tests::init_test,
1639    };
1640
1641    #[gpui::test]
1642    async fn test_at_mention_removal(cx: &mut TestAppContext) {
1643        init_test(cx);
1644
1645        let fs = FakeFs::new(cx.executor());
1646        fs.insert_tree("/project", json!({"file": ""})).await;
1647        let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
1648
1649        let (workspace, cx) =
1650            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
1651
1652        let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
1653        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1654
1655        let message_editor = cx.update(|window, cx| {
1656            cx.new(|cx| {
1657                MessageEditor::new(
1658                    workspace.downgrade(),
1659                    project.clone(),
1660                    history_store.clone(),
1661                    None,
1662                    Default::default(),
1663                    "Test",
1664                    false,
1665                    EditorMode::AutoHeight {
1666                        min_lines: 1,
1667                        max_lines: None,
1668                    },
1669                    window,
1670                    cx,
1671                )
1672            })
1673        });
1674        let editor = message_editor.update(cx, |message_editor, _| message_editor.editor.clone());
1675
1676        cx.run_until_parked();
1677
1678        let excerpt_id = editor.update(cx, |editor, cx| {
1679            editor
1680                .buffer()
1681                .read(cx)
1682                .excerpt_ids()
1683                .into_iter()
1684                .next()
1685                .unwrap()
1686        });
1687        let completions = editor.update_in(cx, |editor, window, cx| {
1688            editor.set_text("Hello @file ", window, cx);
1689            let buffer = editor.buffer().read(cx).as_singleton().unwrap();
1690            let completion_provider = editor.completion_provider().unwrap();
1691            completion_provider.completions(
1692                excerpt_id,
1693                &buffer,
1694                text::Anchor::MAX,
1695                CompletionContext {
1696                    trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER,
1697                    trigger_character: Some("@".into()),
1698                },
1699                window,
1700                cx,
1701            )
1702        });
1703        let [_, completion]: [_; 2] = completions
1704            .await
1705            .unwrap()
1706            .into_iter()
1707            .flat_map(|response| response.completions)
1708            .collect::<Vec<_>>()
1709            .try_into()
1710            .unwrap();
1711
1712        editor.update_in(cx, |editor, window, cx| {
1713            let snapshot = editor.buffer().read(cx).snapshot(cx);
1714            let start = snapshot
1715                .anchor_in_excerpt(excerpt_id, completion.replace_range.start)
1716                .unwrap();
1717            let end = snapshot
1718                .anchor_in_excerpt(excerpt_id, completion.replace_range.end)
1719                .unwrap();
1720            editor.edit([(start..end, completion.new_text)], cx);
1721            (completion.confirm.unwrap())(CompletionIntent::Complete, window, cx);
1722        });
1723
1724        cx.run_until_parked();
1725
1726        // Backspace over the inserted crease (and the following space).
1727        editor.update_in(cx, |editor, window, cx| {
1728            editor.backspace(&Default::default(), window, cx);
1729            editor.backspace(&Default::default(), window, cx);
1730        });
1731
1732        let (content, _) = message_editor
1733            .update(cx, |message_editor, cx| message_editor.contents(cx))
1734            .await
1735            .unwrap();
1736
1737        // We don't send a resource link for the deleted crease.
1738        pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
1739    }
1740
1741    struct MessageEditorItem(Entity<MessageEditor>);
1742
1743    impl Item for MessageEditorItem {
1744        type Event = ();
1745
1746        fn include_in_nav_history() -> bool {
1747            false
1748        }
1749
1750        fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1751            "Test".into()
1752        }
1753    }
1754
1755    impl EventEmitter<()> for MessageEditorItem {}
1756
1757    impl Focusable for MessageEditorItem {
1758        fn focus_handle(&self, cx: &App) -> FocusHandle {
1759            self.0.read(cx).focus_handle(cx)
1760        }
1761    }
1762
1763    impl Render for MessageEditorItem {
1764        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1765            self.0.clone().into_any_element()
1766        }
1767    }
1768
1769    #[gpui::test]
1770    async fn test_context_completion_provider(cx: &mut TestAppContext) {
1771        init_test(cx);
1772
1773        let app_state = cx.update(AppState::test);
1774
1775        cx.update(|cx| {
1776            language::init(cx);
1777            editor::init(cx);
1778            workspace::init(app_state.clone(), cx);
1779            Project::init_settings(cx);
1780        });
1781
1782        app_state
1783            .fs
1784            .as_fake()
1785            .insert_tree(
1786                path!("/dir"),
1787                json!({
1788                    "editor": "",
1789                    "a": {
1790                        "one.txt": "1",
1791                        "two.txt": "2",
1792                        "three.txt": "3",
1793                        "four.txt": "4"
1794                    },
1795                    "b": {
1796                        "five.txt": "5",
1797                        "six.txt": "6",
1798                        "seven.txt": "7",
1799                        "eight.txt": "8",
1800                    },
1801                    "x.png": "",
1802                }),
1803            )
1804            .await;
1805
1806        let project = Project::test(app_state.fs.clone(), [path!("/dir").as_ref()], cx).await;
1807        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
1808        let workspace = window.root(cx).unwrap();
1809
1810        let worktree = project.update(cx, |project, cx| {
1811            let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
1812            assert_eq!(worktrees.len(), 1);
1813            worktrees.pop().unwrap()
1814        });
1815        let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
1816
1817        let mut cx = VisualTestContext::from_window(*window, cx);
1818
1819        let paths = vec![
1820            path!("a/one.txt"),
1821            path!("a/two.txt"),
1822            path!("a/three.txt"),
1823            path!("a/four.txt"),
1824            path!("b/five.txt"),
1825            path!("b/six.txt"),
1826            path!("b/seven.txt"),
1827            path!("b/eight.txt"),
1828        ];
1829
1830        let mut opened_editors = Vec::new();
1831        for path in paths {
1832            let buffer = workspace
1833                .update_in(&mut cx, |workspace, window, cx| {
1834                    workspace.open_path(
1835                        ProjectPath {
1836                            worktree_id,
1837                            path: Path::new(path).into(),
1838                        },
1839                        None,
1840                        false,
1841                        window,
1842                        cx,
1843                    )
1844                })
1845                .await
1846                .unwrap();
1847            opened_editors.push(buffer);
1848        }
1849
1850        let context_store = cx.new(|cx| ContextStore::fake(project.clone(), cx));
1851        let history_store = cx.new(|cx| HistoryStore::new(context_store, cx));
1852        let prompt_capabilities = Rc::new(Cell::new(acp::PromptCapabilities::default()));
1853
1854        let (message_editor, editor) = workspace.update_in(&mut cx, |workspace, window, cx| {
1855            let workspace_handle = cx.weak_entity();
1856            let message_editor = cx.new(|cx| {
1857                MessageEditor::new(
1858                    workspace_handle,
1859                    project.clone(),
1860                    history_store.clone(),
1861                    None,
1862                    prompt_capabilities.clone(),
1863                    "Test",
1864                    false,
1865                    EditorMode::AutoHeight {
1866                        max_lines: None,
1867                        min_lines: 1,
1868                    },
1869                    window,
1870                    cx,
1871                )
1872            });
1873            workspace.active_pane().update(cx, |pane, cx| {
1874                pane.add_item(
1875                    Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
1876                    true,
1877                    true,
1878                    None,
1879                    window,
1880                    cx,
1881                );
1882            });
1883            message_editor.read(cx).focus_handle(cx).focus(window);
1884            let editor = message_editor.read(cx).editor().clone();
1885            (message_editor, editor)
1886        });
1887
1888        cx.simulate_input("Lorem @");
1889
1890        editor.update_in(&mut cx, |editor, window, cx| {
1891            assert_eq!(editor.text(cx), "Lorem @");
1892            assert!(editor.has_visible_completions_menu());
1893
1894            // Only files since we have default capabilities
1895            assert_eq!(
1896                current_completion_labels(editor),
1897                &[
1898                    "eight.txt dir/b/",
1899                    "seven.txt dir/b/",
1900                    "six.txt dir/b/",
1901                    "five.txt dir/b/",
1902                ]
1903            );
1904            editor.set_text("", window, cx);
1905        });
1906
1907        prompt_capabilities.set(acp::PromptCapabilities {
1908            image: true,
1909            audio: true,
1910            embedded_context: true,
1911        });
1912
1913        cx.simulate_input("Lorem ");
1914
1915        editor.update(&mut cx, |editor, cx| {
1916            assert_eq!(editor.text(cx), "Lorem ");
1917            assert!(!editor.has_visible_completions_menu());
1918        });
1919
1920        cx.simulate_input("@");
1921
1922        editor.update(&mut cx, |editor, cx| {
1923            assert_eq!(editor.text(cx), "Lorem @");
1924            assert!(editor.has_visible_completions_menu());
1925            assert_eq!(
1926                current_completion_labels(editor),
1927                &[
1928                    "eight.txt dir/b/",
1929                    "seven.txt dir/b/",
1930                    "six.txt dir/b/",
1931                    "five.txt dir/b/",
1932                    "Files & Directories",
1933                    "Symbols",
1934                    "Threads",
1935                    "Fetch"
1936                ]
1937            );
1938        });
1939
1940        // Select and confirm "File"
1941        editor.update_in(&mut cx, |editor, window, cx| {
1942            assert!(editor.has_visible_completions_menu());
1943            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1944            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1945            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1946            editor.context_menu_next(&editor::actions::ContextMenuNext, window, cx);
1947            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1948        });
1949
1950        cx.run_until_parked();
1951
1952        editor.update(&mut cx, |editor, cx| {
1953            assert_eq!(editor.text(cx), "Lorem @file ");
1954            assert!(editor.has_visible_completions_menu());
1955        });
1956
1957        cx.simulate_input("one");
1958
1959        editor.update(&mut cx, |editor, cx| {
1960            assert_eq!(editor.text(cx), "Lorem @file one");
1961            assert!(editor.has_visible_completions_menu());
1962            assert_eq!(current_completion_labels(editor), vec!["one.txt dir/a/"]);
1963        });
1964
1965        editor.update_in(&mut cx, |editor, window, cx| {
1966            assert!(editor.has_visible_completions_menu());
1967            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
1968        });
1969
1970        let url_one = uri!("file:///dir/a/one.txt");
1971        editor.update(&mut cx, |editor, cx| {
1972            let text = editor.text(cx);
1973            assert_eq!(text, format!("Lorem [@one.txt]({url_one}) "));
1974            assert!(!editor.has_visible_completions_menu());
1975            assert_eq!(fold_ranges(editor, cx).len(), 1);
1976        });
1977
1978        let all_prompt_capabilities = acp::PromptCapabilities {
1979            image: true,
1980            audio: true,
1981            embedded_context: true,
1982        };
1983
1984        let contents = message_editor
1985            .update(&mut cx, |message_editor, cx| {
1986                message_editor
1987                    .mention_set()
1988                    .contents(&all_prompt_capabilities, cx)
1989            })
1990            .await
1991            .unwrap()
1992            .into_values()
1993            .collect::<Vec<_>>();
1994
1995        {
1996            let [(uri, Mention::Text { content, .. })] = contents.as_slice() else {
1997                panic!("Unexpected mentions");
1998            };
1999            pretty_assertions::assert_eq!(content, "1");
2000            pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2001        }
2002
2003        let contents = message_editor
2004            .update(&mut cx, |message_editor, cx| {
2005                message_editor
2006                    .mention_set()
2007                    .contents(&acp::PromptCapabilities::default(), cx)
2008            })
2009            .await
2010            .unwrap()
2011            .into_values()
2012            .collect::<Vec<_>>();
2013
2014        {
2015            let [(uri, Mention::UriOnly)] = contents.as_slice() else {
2016                panic!("Unexpected mentions");
2017            };
2018            pretty_assertions::assert_eq!(uri, &url_one.parse::<MentionUri>().unwrap());
2019        }
2020
2021        cx.simulate_input(" ");
2022
2023        editor.update(&mut cx, |editor, cx| {
2024            let text = editor.text(cx);
2025            assert_eq!(text, format!("Lorem [@one.txt]({url_one})  "));
2026            assert!(!editor.has_visible_completions_menu());
2027            assert_eq!(fold_ranges(editor, cx).len(), 1);
2028        });
2029
2030        cx.simulate_input("Ipsum ");
2031
2032        editor.update(&mut cx, |editor, cx| {
2033            let text = editor.text(cx);
2034            assert_eq!(text, format!("Lorem [@one.txt]({url_one})  Ipsum "),);
2035            assert!(!editor.has_visible_completions_menu());
2036            assert_eq!(fold_ranges(editor, cx).len(), 1);
2037        });
2038
2039        cx.simulate_input("@file ");
2040
2041        editor.update(&mut cx, |editor, cx| {
2042            let text = editor.text(cx);
2043            assert_eq!(text, format!("Lorem [@one.txt]({url_one})  Ipsum @file "),);
2044            assert!(editor.has_visible_completions_menu());
2045            assert_eq!(fold_ranges(editor, cx).len(), 1);
2046        });
2047
2048        editor.update_in(&mut cx, |editor, window, cx| {
2049            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2050        });
2051
2052        cx.run_until_parked();
2053
2054        let contents = message_editor
2055            .update(&mut cx, |message_editor, cx| {
2056                message_editor
2057                    .mention_set()
2058                    .contents(&all_prompt_capabilities, cx)
2059            })
2060            .await
2061            .unwrap()
2062            .into_values()
2063            .collect::<Vec<_>>();
2064
2065        let url_eight = uri!("file:///dir/b/eight.txt");
2066
2067        {
2068            let [_, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2069                panic!("Unexpected mentions");
2070            };
2071            pretty_assertions::assert_eq!(content, "8");
2072            pretty_assertions::assert_eq!(uri, &url_eight.parse::<MentionUri>().unwrap());
2073        }
2074
2075        editor.update(&mut cx, |editor, cx| {
2076            assert_eq!(
2077                editor.text(cx),
2078                format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) ")
2079            );
2080            assert!(!editor.has_visible_completions_menu());
2081            assert_eq!(fold_ranges(editor, cx).len(), 2);
2082        });
2083
2084        let plain_text_language = Arc::new(language::Language::new(
2085            language::LanguageConfig {
2086                name: "Plain Text".into(),
2087                matcher: language::LanguageMatcher {
2088                    path_suffixes: vec!["txt".to_string()],
2089                    ..Default::default()
2090                },
2091                ..Default::default()
2092            },
2093            None,
2094        ));
2095
2096        // Register the language and fake LSP
2097        let language_registry = project.read_with(&cx, |project, _| project.languages().clone());
2098        language_registry.add(plain_text_language);
2099
2100        let mut fake_language_servers = language_registry.register_fake_lsp(
2101            "Plain Text",
2102            language::FakeLspAdapter {
2103                capabilities: lsp::ServerCapabilities {
2104                    workspace_symbol_provider: Some(lsp::OneOf::Left(true)),
2105                    ..Default::default()
2106                },
2107                ..Default::default()
2108            },
2109        );
2110
2111        // Open the buffer to trigger LSP initialization
2112        let buffer = project
2113            .update(&mut cx, |project, cx| {
2114                project.open_local_buffer(path!("/dir/a/one.txt"), cx)
2115            })
2116            .await
2117            .unwrap();
2118
2119        // Register the buffer with language servers
2120        let _handle = project.update(&mut cx, |project, cx| {
2121            project.register_buffer_with_language_servers(&buffer, cx)
2122        });
2123
2124        cx.run_until_parked();
2125
2126        let fake_language_server = fake_language_servers.next().await.unwrap();
2127        fake_language_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
2128            move |_, _| async move {
2129                Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
2130                    #[allow(deprecated)]
2131                    lsp::SymbolInformation {
2132                        name: "MySymbol".into(),
2133                        location: lsp::Location {
2134                            uri: lsp::Uri::from_file_path(path!("/dir/a/one.txt")).unwrap(),
2135                            range: lsp::Range::new(
2136                                lsp::Position::new(0, 0),
2137                                lsp::Position::new(0, 1),
2138                            ),
2139                        },
2140                        kind: lsp::SymbolKind::CONSTANT,
2141                        tags: None,
2142                        container_name: None,
2143                        deprecated: None,
2144                    },
2145                ])))
2146            },
2147        );
2148
2149        cx.simulate_input("@symbol ");
2150
2151        editor.update(&mut cx, |editor, cx| {
2152            assert_eq!(
2153                editor.text(cx),
2154                format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) @symbol ")
2155            );
2156            assert!(editor.has_visible_completions_menu());
2157            assert_eq!(current_completion_labels(editor), &["MySymbol"]);
2158        });
2159
2160        editor.update_in(&mut cx, |editor, window, cx| {
2161            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2162        });
2163
2164        let contents = message_editor
2165            .update(&mut cx, |message_editor, cx| {
2166                message_editor
2167                    .mention_set()
2168                    .contents(&all_prompt_capabilities, cx)
2169            })
2170            .await
2171            .unwrap()
2172            .into_values()
2173            .collect::<Vec<_>>();
2174
2175        {
2176            let [_, _, (uri, Mention::Text { content, .. })] = contents.as_slice() else {
2177                panic!("Unexpected mentions");
2178            };
2179            pretty_assertions::assert_eq!(content, "1");
2180            pretty_assertions::assert_eq!(
2181                uri,
2182                &format!("{url_one}?symbol=MySymbol#L1:1")
2183                    .parse::<MentionUri>()
2184                    .unwrap()
2185            );
2186        }
2187
2188        cx.run_until_parked();
2189
2190        editor.read_with(&cx, |editor, cx| {
2191            assert_eq!(
2192                editor.text(cx),
2193                format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) [@MySymbol]({url_one}?symbol=MySymbol#L1:1) ")
2194            );
2195        });
2196
2197        // Try to mention an "image" file that will fail to load
2198        cx.simulate_input("@file x.png");
2199
2200        editor.update(&mut cx, |editor, cx| {
2201            assert_eq!(
2202                editor.text(cx),
2203                format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) [@MySymbol]({url_one}?symbol=MySymbol#L1:1) @file x.png")
2204            );
2205            assert!(editor.has_visible_completions_menu());
2206            assert_eq!(current_completion_labels(editor), &["x.png dir/"]);
2207        });
2208
2209        editor.update_in(&mut cx, |editor, window, cx| {
2210            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2211        });
2212
2213        // Getting the message contents fails
2214        message_editor
2215            .update(&mut cx, |message_editor, cx| {
2216                message_editor
2217                    .mention_set()
2218                    .contents(&all_prompt_capabilities, cx)
2219            })
2220            .await
2221            .expect_err("Should fail to load x.png");
2222
2223        cx.run_until_parked();
2224
2225        // Mention was removed
2226        editor.read_with(&cx, |editor, cx| {
2227            assert_eq!(
2228                editor.text(cx),
2229                format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) [@MySymbol]({url_one}?symbol=MySymbol#L1:1) ")
2230            );
2231        });
2232
2233        // Once more
2234        cx.simulate_input("@file x.png");
2235
2236        editor.update(&mut cx, |editor, cx| {
2237                    assert_eq!(
2238                        editor.text(cx),
2239                        format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) [@MySymbol]({url_one}?symbol=MySymbol#L1:1) @file x.png")
2240                    );
2241                    assert!(editor.has_visible_completions_menu());
2242                    assert_eq!(current_completion_labels(editor), &["x.png dir/"]);
2243                });
2244
2245        editor.update_in(&mut cx, |editor, window, cx| {
2246            editor.confirm_completion(&editor::actions::ConfirmCompletion::default(), window, cx);
2247        });
2248
2249        // This time don't immediately get the contents, just let the confirmed completion settle
2250        cx.run_until_parked();
2251
2252        // Mention was removed
2253        editor.read_with(&cx, |editor, cx| {
2254                    assert_eq!(
2255                        editor.text(cx),
2256                        format!("Lorem [@one.txt]({url_one})  Ipsum [@eight.txt]({url_eight}) [@MySymbol]({url_one}?symbol=MySymbol#L1:1) ")
2257                    );
2258                });
2259
2260        // Now getting the contents succeeds, because the invalid mention was removed
2261        let contents = message_editor
2262            .update(&mut cx, |message_editor, cx| {
2263                message_editor
2264                    .mention_set()
2265                    .contents(&all_prompt_capabilities, cx)
2266            })
2267            .await
2268            .unwrap();
2269        assert_eq!(contents.len(), 3);
2270    }
2271
2272    fn fold_ranges(editor: &Editor, cx: &mut App) -> Vec<Range<Point>> {
2273        let snapshot = editor.buffer().read(cx).snapshot(cx);
2274        editor.display_map.update(cx, |display_map, cx| {
2275            display_map
2276                .snapshot(cx)
2277                .folds_in_range(0..snapshot.len())
2278                .map(|fold| fold.range.to_point(&snapshot))
2279                .collect()
2280        })
2281    }
2282
2283    fn current_completion_labels(editor: &Editor) -> Vec<String> {
2284        let completions = editor.current_completions().expect("Missing completions");
2285        completions
2286            .into_iter()
2287            .map(|completion| completion.label.text)
2288            .collect::<Vec<_>>()
2289    }
2290}