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