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