message_editor.rs

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