mention_set.rs

   1use acp_thread::{MentionUri, selection_name};
   2use agent::{ThreadStore, outline};
   3use agent_client_protocol as acp;
   4use agent_servers::{AgentServer, AgentServerDelegate};
   5use anyhow::{Context as _, Result, anyhow};
   6use assistant_slash_commands::codeblock_fence_for_path;
   7use collections::{HashMap, HashSet};
   8use editor::{
   9    Anchor, Editor, EditorSnapshot, ExcerptId, FoldPlaceholder, ToOffset,
  10    display_map::{Crease, CreaseId, CreaseMetadata, FoldId},
  11    scroll::Autoscroll,
  12};
  13use futures::{AsyncReadExt as _, FutureExt as _, future::Shared};
  14use gpui::{
  15    AppContext, ClipboardEntry, Context, Empty, Entity, EntityId, Image, ImageFormat, Img,
  16    SharedString, Task, WeakEntity,
  17};
  18use http_client::{AsyncBody, HttpClientWithUrl};
  19use itertools::Either;
  20use language::Buffer;
  21use language_model::LanguageModelImage;
  22use multi_buffer::MultiBufferRow;
  23use postage::stream::Stream as _;
  24use project::{Project, ProjectItem, ProjectPath, Worktree};
  25use prompt_store::{PromptId, PromptStore};
  26use rope::Point;
  27use std::{
  28    cell::RefCell,
  29    ffi::OsStr,
  30    fmt::Write,
  31    ops::{Range, RangeInclusive},
  32    path::{Path, PathBuf},
  33    rc::Rc,
  34    sync::Arc,
  35};
  36use text::OffsetRangeExt;
  37use ui::{Disclosure, Toggleable, prelude::*};
  38use util::{ResultExt, debug_panic, rel_path::RelPath};
  39use workspace::{Workspace, notifications::NotifyResultExt as _};
  40
  41use crate::ui::MentionCrease;
  42
  43pub type MentionTask = Shared<Task<Result<Mention, String>>>;
  44
  45#[derive(Debug, Clone, Eq, PartialEq)]
  46pub enum Mention {
  47    Text {
  48        content: String,
  49        tracked_buffers: Vec<Entity<Buffer>>,
  50    },
  51    Image(MentionImage),
  52    Link,
  53}
  54
  55#[derive(Clone, Debug, Eq, PartialEq)]
  56pub struct MentionImage {
  57    pub data: SharedString,
  58    pub format: ImageFormat,
  59}
  60
  61pub struct MentionSet {
  62    project: WeakEntity<Project>,
  63    thread_store: Entity<ThreadStore>,
  64    prompt_store: Option<Entity<PromptStore>>,
  65    mentions: HashMap<CreaseId, (MentionUri, MentionTask)>,
  66}
  67
  68impl MentionSet {
  69    pub fn new(
  70        project: WeakEntity<Project>,
  71        thread_store: Entity<ThreadStore>,
  72        prompt_store: Option<Entity<PromptStore>>,
  73    ) -> Self {
  74        Self {
  75            project,
  76            thread_store,
  77            prompt_store,
  78            mentions: HashMap::default(),
  79        }
  80    }
  81
  82    pub fn contents(
  83        &self,
  84        full_mention_content: bool,
  85        cx: &mut App,
  86    ) -> Task<Result<HashMap<CreaseId, (MentionUri, Mention)>>> {
  87        let Some(project) = self.project.upgrade() else {
  88            return Task::ready(Err(anyhow!("Project not found")));
  89        };
  90        let mentions = self.mentions.clone();
  91        cx.spawn(async move |cx| {
  92            let mut contents = HashMap::default();
  93            for (crease_id, (mention_uri, task)) in mentions {
  94                let content = if full_mention_content
  95                    && let MentionUri::Directory { abs_path } = &mention_uri
  96                {
  97                    cx.update(|cx| full_mention_for_directory(&project, abs_path, cx))
  98                        .await?
  99                } else {
 100                    task.await.map_err(|e| anyhow!("{e}"))?
 101                };
 102
 103                contents.insert(crease_id, (mention_uri, content));
 104            }
 105            Ok(contents)
 106        })
 107    }
 108
 109    pub fn remove_invalid(&mut self, snapshot: &EditorSnapshot) {
 110        for (crease_id, crease) in snapshot.crease_snapshot.creases() {
 111            if !crease.range().start.is_valid(snapshot.buffer_snapshot()) {
 112                self.mentions.remove(&crease_id);
 113            }
 114        }
 115    }
 116
 117    pub fn insert_mention(&mut self, crease_id: CreaseId, uri: MentionUri, task: MentionTask) {
 118        self.mentions.insert(crease_id, (uri, task));
 119    }
 120
 121    pub fn remove_mention(&mut self, crease_id: &CreaseId) {
 122        self.mentions.remove(crease_id);
 123    }
 124
 125    pub fn creases(&self) -> HashSet<CreaseId> {
 126        self.mentions.keys().cloned().collect()
 127    }
 128
 129    pub fn mentions(&self) -> HashSet<MentionUri> {
 130        self.mentions.values().map(|(uri, _)| uri.clone()).collect()
 131    }
 132
 133    pub fn set_mentions(&mut self, mentions: HashMap<CreaseId, (MentionUri, MentionTask)>) {
 134        self.mentions = mentions;
 135    }
 136
 137    pub fn clear(&mut self) -> impl Iterator<Item = (CreaseId, (MentionUri, MentionTask))> {
 138        self.mentions.drain()
 139    }
 140
 141    pub fn confirm_mention_completion(
 142        &mut self,
 143        crease_text: SharedString,
 144        start: text::Anchor,
 145        content_len: usize,
 146        mention_uri: MentionUri,
 147        supports_images: bool,
 148        editor: Entity<Editor>,
 149        workspace: &Entity<Workspace>,
 150        window: &mut Window,
 151        cx: &mut Context<Self>,
 152    ) -> Task<()> {
 153        let Some(project) = self.project.upgrade() else {
 154            return Task::ready(());
 155        };
 156
 157        let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 158        let Some(start_anchor) = snapshot.buffer_snapshot().as_singleton_anchor(start) else {
 159            return Task::ready(());
 160        };
 161        let excerpt_id = start_anchor.excerpt_id;
 162        let end_anchor = snapshot.buffer_snapshot().anchor_before(
 163            start_anchor.to_offset(&snapshot.buffer_snapshot()) + content_len + 1usize,
 164        );
 165
 166        let crease = if let MentionUri::File { abs_path } = &mention_uri
 167            && let Some(extension) = abs_path.extension()
 168            && let Some(extension) = extension.to_str()
 169            && Img::extensions().contains(&extension)
 170            && !extension.contains("svg")
 171        {
 172            let Some(project_path) = project
 173                .read(cx)
 174                .project_path_for_absolute_path(&abs_path, cx)
 175            else {
 176                log::error!("project path not found");
 177                return Task::ready(());
 178            };
 179            let image_task = project.update(cx, |project, cx| project.open_image(project_path, cx));
 180            let image = cx
 181                .spawn(async move |_, cx| {
 182                    let image = image_task.await.map_err(|e| e.to_string())?;
 183                    let image = image.update(cx, |image, _| image.image.clone());
 184                    Ok(image)
 185                })
 186                .shared();
 187            insert_crease_for_mention(
 188                excerpt_id,
 189                start,
 190                content_len,
 191                mention_uri.name().into(),
 192                IconName::Image.path().into(),
 193                Some(image),
 194                editor.clone(),
 195                window,
 196                cx,
 197            )
 198        } else {
 199            insert_crease_for_mention(
 200                excerpt_id,
 201                start,
 202                content_len,
 203                crease_text,
 204                mention_uri.icon_path(cx),
 205                None,
 206                editor.clone(),
 207                window,
 208                cx,
 209            )
 210        };
 211        let Some((crease_id, tx)) = crease else {
 212            return Task::ready(());
 213        };
 214
 215        let task = match mention_uri.clone() {
 216            MentionUri::Fetch { url } => {
 217                self.confirm_mention_for_fetch(url, workspace.read(cx).client().http_client(), cx)
 218            }
 219            MentionUri::Directory { .. } => Task::ready(Ok(Mention::Link)),
 220            MentionUri::Thread { id, .. } => self.confirm_mention_for_thread(id, cx),
 221            MentionUri::TextThread { .. } => {
 222                Task::ready(Err(anyhow!("Text thread mentions are no longer supported")))
 223            }
 224            MentionUri::File { abs_path } => {
 225                self.confirm_mention_for_file(abs_path, supports_images, cx)
 226            }
 227            MentionUri::Symbol {
 228                abs_path,
 229                line_range,
 230                ..
 231            } => self.confirm_mention_for_symbol(abs_path, line_range, cx),
 232            MentionUri::Rule { id, .. } => self.confirm_mention_for_rule(id, cx),
 233            MentionUri::PastedImage => {
 234                debug_panic!("pasted image URI should not be included in completions");
 235                Task::ready(Err(anyhow!(
 236                    "pasted imaged URI should not be included in completions"
 237                )))
 238            }
 239            MentionUri::Selection { .. } => {
 240                debug_panic!("unexpected selection URI");
 241                Task::ready(Err(anyhow!("unexpected selection URI")))
 242            }
 243        };
 244        let task = cx
 245            .spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
 246            .shared();
 247        self.mentions.insert(crease_id, (mention_uri, task.clone()));
 248
 249        // Notify the user if we failed to load the mentioned context
 250        cx.spawn_in(window, async move |this, cx| {
 251            let result = task.await.notify_async_err(cx);
 252            drop(tx);
 253            if result.is_none() {
 254                this.update(cx, |this, cx| {
 255                    editor.update(cx, |editor, cx| {
 256                        // Remove mention
 257                        editor.edit([(start_anchor..end_anchor, "")], cx);
 258                    });
 259                    this.mentions.remove(&crease_id);
 260                })
 261                .ok();
 262            }
 263        })
 264    }
 265
 266    pub fn confirm_mention_for_file(
 267        &self,
 268        abs_path: PathBuf,
 269        supports_images: bool,
 270        cx: &mut Context<Self>,
 271    ) -> Task<Result<Mention>> {
 272        let Some(project) = self.project.upgrade() else {
 273            return Task::ready(Err(anyhow!("project not found")));
 274        };
 275
 276        let Some(project_path) = project
 277            .read(cx)
 278            .project_path_for_absolute_path(&abs_path, cx)
 279        else {
 280            return Task::ready(Err(anyhow!("project path not found")));
 281        };
 282        let extension = abs_path
 283            .extension()
 284            .and_then(OsStr::to_str)
 285            .unwrap_or_default();
 286
 287        if Img::extensions().contains(&extension) && !extension.contains("svg") {
 288            if !supports_images {
 289                return Task::ready(Err(anyhow!("This model does not support images yet")));
 290            }
 291            let task = project.update(cx, |project, cx| project.open_image(project_path, cx));
 292            return cx.spawn(async move |_, cx| {
 293                let image = task.await?;
 294                let image = image.update(cx, |image, _| image.image.clone());
 295                let format = image.format;
 296                let image = cx
 297                    .update(|cx| LanguageModelImage::from_image(image, cx))
 298                    .await;
 299                if let Some(image) = image {
 300                    Ok(Mention::Image(MentionImage {
 301                        data: image.source,
 302                        format,
 303                    }))
 304                } else {
 305                    Err(anyhow!("Failed to convert image"))
 306                }
 307            });
 308        }
 309
 310        let buffer = project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 311        cx.spawn(async move |_, cx| {
 312            let buffer = buffer.await?;
 313            let buffer_content = outline::get_buffer_content_or_outline(
 314                buffer.clone(),
 315                Some(&abs_path.to_string_lossy()),
 316                &cx,
 317            )
 318            .await?;
 319
 320            Ok(Mention::Text {
 321                content: buffer_content.text,
 322                tracked_buffers: vec![buffer],
 323            })
 324        })
 325    }
 326
 327    fn confirm_mention_for_fetch(
 328        &self,
 329        url: url::Url,
 330        http_client: Arc<HttpClientWithUrl>,
 331        cx: &mut Context<Self>,
 332    ) -> Task<Result<Mention>> {
 333        cx.background_executor().spawn(async move {
 334            let content = fetch_url_content(http_client, url.to_string()).await?;
 335            Ok(Mention::Text {
 336                content,
 337                tracked_buffers: Vec::new(),
 338            })
 339        })
 340    }
 341
 342    fn confirm_mention_for_symbol(
 343        &self,
 344        abs_path: PathBuf,
 345        line_range: RangeInclusive<u32>,
 346        cx: &mut Context<Self>,
 347    ) -> Task<Result<Mention>> {
 348        let Some(project) = self.project.upgrade() else {
 349            return Task::ready(Err(anyhow!("project not found")));
 350        };
 351        let Some(project_path) = project
 352            .read(cx)
 353            .project_path_for_absolute_path(&abs_path, cx)
 354        else {
 355            return Task::ready(Err(anyhow!("project path not found")));
 356        };
 357        let buffer = project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 358        cx.spawn(async move |_, cx| {
 359            let buffer = buffer.await?;
 360            let mention = buffer.update(cx, |buffer, cx| {
 361                let start = Point::new(*line_range.start(), 0).min(buffer.max_point());
 362                let end = Point::new(*line_range.end() + 1, 0).min(buffer.max_point());
 363                let content = buffer.text_for_range(start..end).collect();
 364                Mention::Text {
 365                    content,
 366                    tracked_buffers: vec![cx.entity()],
 367                }
 368            });
 369            Ok(mention)
 370        })
 371    }
 372
 373    fn confirm_mention_for_rule(
 374        &mut self,
 375        id: PromptId,
 376        cx: &mut Context<Self>,
 377    ) -> Task<Result<Mention>> {
 378        let Some(prompt_store) = self.prompt_store.as_ref() else {
 379            return Task::ready(Err(anyhow!("Missing prompt store")));
 380        };
 381        let prompt = prompt_store.read(cx).load(id, cx);
 382        cx.spawn(async move |_, _| {
 383            let prompt = prompt.await?;
 384            Ok(Mention::Text {
 385                content: prompt,
 386                tracked_buffers: Vec::new(),
 387            })
 388        })
 389    }
 390
 391    pub fn confirm_mention_for_selection(
 392        &mut self,
 393        source_range: Range<text::Anchor>,
 394        selections: Vec<(Entity<Buffer>, Range<text::Anchor>, Range<usize>)>,
 395        editor: Entity<Editor>,
 396        window: &mut Window,
 397        cx: &mut Context<Self>,
 398    ) {
 399        let Some(project) = self.project.upgrade() else {
 400            return;
 401        };
 402
 403        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
 404        let Some(start) = snapshot.as_singleton_anchor(source_range.start) else {
 405            return;
 406        };
 407
 408        let offset = start.to_offset(&snapshot);
 409
 410        for (buffer, selection_range, range_to_fold) in selections {
 411            let range = snapshot.anchor_after(offset + range_to_fold.start)
 412                ..snapshot.anchor_after(offset + range_to_fold.end);
 413
 414            let abs_path = buffer
 415                .read(cx)
 416                .project_path(cx)
 417                .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx));
 418            let snapshot = buffer.read(cx).snapshot();
 419
 420            let text = snapshot
 421                .text_for_range(selection_range.clone())
 422                .collect::<String>();
 423            let point_range = selection_range.to_point(&snapshot);
 424            let line_range = point_range.start.row..=point_range.end.row;
 425
 426            let uri = MentionUri::Selection {
 427                abs_path: abs_path.clone(),
 428                line_range: line_range.clone(),
 429            };
 430            let crease = crease_for_mention(
 431                selection_name(abs_path.as_deref(), &line_range).into(),
 432                uri.icon_path(cx),
 433                range,
 434                editor.downgrade(),
 435            );
 436
 437            let crease_id = editor.update(cx, |editor, cx| {
 438                let crease_ids = editor.insert_creases(vec![crease.clone()], cx);
 439                editor.fold_creases(vec![crease], false, window, cx);
 440                crease_ids.first().copied().unwrap()
 441            });
 442
 443            self.mentions.insert(
 444                crease_id,
 445                (
 446                    uri,
 447                    Task::ready(Ok(Mention::Text {
 448                        content: text,
 449                        tracked_buffers: vec![buffer],
 450                    }))
 451                    .shared(),
 452                ),
 453            );
 454        }
 455
 456        // Take this explanation with a grain of salt but, with creases being
 457        // inserted, GPUI's recomputes the editor layout in the next frames, so
 458        // directly calling `editor.request_autoscroll` wouldn't work as
 459        // expected. We're leveraging `cx.on_next_frame` to wait 2 frames and
 460        // ensure that the layout has been recalculated so that the autoscroll
 461        // request actually shows the cursor's new position.
 462        cx.on_next_frame(window, move |_, window, cx| {
 463            cx.on_next_frame(window, move |_, _, cx| {
 464                editor.update(cx, |editor, cx| {
 465                    editor.request_autoscroll(Autoscroll::fit(), cx)
 466                });
 467            });
 468        });
 469    }
 470
 471    fn confirm_mention_for_thread(
 472        &mut self,
 473        id: acp::SessionId,
 474        cx: &mut Context<Self>,
 475    ) -> Task<Result<Mention>> {
 476        let Some(project) = self.project.upgrade() else {
 477            return Task::ready(Err(anyhow!("project not found")));
 478        };
 479
 480        let server = Rc::new(agent::NativeAgentServer::new(
 481            project.read(cx).fs().clone(),
 482            self.thread_store.clone(),
 483        ));
 484        let delegate = AgentServerDelegate::new(
 485            project.read(cx).agent_server_store().clone(),
 486            project.clone(),
 487            None,
 488            None,
 489        );
 490        let connection = server.connect(None, delegate, cx);
 491        cx.spawn(async move |_, cx| {
 492            let (agent, _) = connection.await?;
 493            let agent = agent.downcast::<agent::NativeAgentConnection>().unwrap();
 494            let summary = agent
 495                .0
 496                .update(cx, |agent, cx| agent.thread_summary(id, cx))
 497                .await?;
 498            Ok(Mention::Text {
 499                content: summary.to_string(),
 500                tracked_buffers: Vec::new(),
 501            })
 502        })
 503    }
 504}
 505
 506pub(crate) fn paste_images_as_context(
 507    editor: Entity<Editor>,
 508    mention_set: Entity<MentionSet>,
 509    window: &mut Window,
 510    cx: &mut App,
 511) -> Option<Task<()>> {
 512    let clipboard = cx.read_from_clipboard()?;
 513    Some(window.spawn(cx, async move |cx| {
 514        use itertools::Itertools;
 515        let (mut images, paths) = clipboard
 516            .into_entries()
 517            .filter_map(|entry| match entry {
 518                ClipboardEntry::Image(image) => Some(Either::Left(image)),
 519                ClipboardEntry::ExternalPaths(paths) => Some(Either::Right(paths)),
 520                _ => None,
 521            })
 522            .partition_map::<Vec<_>, Vec<_>, _, _, _>(std::convert::identity);
 523
 524        if !paths.is_empty() {
 525            images.extend(
 526                cx.background_spawn(async move {
 527                    let mut images = vec![];
 528                    for path in paths.into_iter().flat_map(|paths| paths.paths().to_owned()) {
 529                        let Ok(content) = async_fs::read(path).await else {
 530                            continue;
 531                        };
 532                        let Ok(format) = image::guess_format(&content) else {
 533                            continue;
 534                        };
 535                        images.push(gpui::Image::from_bytes(
 536                            match format {
 537                                image::ImageFormat::Png => gpui::ImageFormat::Png,
 538                                image::ImageFormat::Jpeg => gpui::ImageFormat::Jpeg,
 539                                image::ImageFormat::WebP => gpui::ImageFormat::Webp,
 540                                image::ImageFormat::Gif => gpui::ImageFormat::Gif,
 541                                image::ImageFormat::Bmp => gpui::ImageFormat::Bmp,
 542                                image::ImageFormat::Tiff => gpui::ImageFormat::Tiff,
 543                                image::ImageFormat::Ico => gpui::ImageFormat::Ico,
 544                                _ => continue,
 545                            },
 546                            content,
 547                        ));
 548                    }
 549                    images
 550                })
 551                .await,
 552            );
 553        }
 554
 555        if images.is_empty() {
 556            return;
 557        }
 558
 559        let replacement_text = MentionUri::PastedImage.as_link().to_string();
 560        cx.update(|_window, cx| {
 561            cx.stop_propagation();
 562        })
 563        .ok();
 564        for image in images {
 565            let Some((excerpt_id, text_anchor, multibuffer_anchor)) = editor
 566                .update_in(cx, |message_editor, window, cx| {
 567                    let snapshot = message_editor.snapshot(window, cx);
 568                    let (excerpt_id, _, buffer_snapshot) =
 569                        snapshot.buffer_snapshot().as_singleton().unwrap();
 570
 571                    let text_anchor = buffer_snapshot.anchor_before(buffer_snapshot.len());
 572                    let multibuffer_anchor = snapshot
 573                        .buffer_snapshot()
 574                        .anchor_in_excerpt(*excerpt_id, text_anchor);
 575                    message_editor.edit(
 576                        [(
 577                            multi_buffer::Anchor::max()..multi_buffer::Anchor::max(),
 578                            format!("{replacement_text} "),
 579                        )],
 580                        cx,
 581                    );
 582                    (*excerpt_id, text_anchor, multibuffer_anchor)
 583                })
 584                .ok()
 585            else {
 586                break;
 587            };
 588
 589            let content_len = replacement_text.len();
 590            let Some(start_anchor) = multibuffer_anchor else {
 591                continue;
 592            };
 593            let end_anchor = editor.update(cx, |editor, cx| {
 594                let snapshot = editor.buffer().read(cx).snapshot(cx);
 595                snapshot.anchor_before(start_anchor.to_offset(&snapshot) + content_len)
 596            });
 597            let image = Arc::new(image);
 598            let Ok(Some((crease_id, tx))) = cx.update(|window, cx| {
 599                insert_crease_for_mention(
 600                    excerpt_id,
 601                    text_anchor,
 602                    content_len,
 603                    MentionUri::PastedImage.name().into(),
 604                    IconName::Image.path().into(),
 605                    Some(Task::ready(Ok(image.clone())).shared()),
 606                    editor.clone(),
 607                    window,
 608                    cx,
 609                )
 610            }) else {
 611                continue;
 612            };
 613            let task = cx
 614                .spawn(async move |cx| {
 615                    let format = image.format;
 616                    let image = cx
 617                        .update(|_, cx| LanguageModelImage::from_image(image, cx))
 618                        .map_err(|e| e.to_string())?
 619                        .await;
 620                    drop(tx);
 621                    if let Some(image) = image {
 622                        Ok(Mention::Image(MentionImage {
 623                            data: image.source,
 624                            format,
 625                        }))
 626                    } else {
 627                        Err("Failed to convert image".into())
 628                    }
 629                })
 630                .shared();
 631
 632            mention_set.update(cx, |mention_set, _cx| {
 633                mention_set.insert_mention(crease_id, MentionUri::PastedImage, task.clone())
 634            });
 635
 636            if task.await.notify_async_err(cx).is_none() {
 637                editor.update(cx, |editor, cx| {
 638                    editor.edit([(start_anchor..end_anchor, "")], cx);
 639                });
 640                mention_set.update(cx, |mention_set, _cx| {
 641                    mention_set.remove_mention(&crease_id)
 642                });
 643            }
 644        }
 645    }))
 646}
 647
 648pub(crate) fn insert_crease_for_mention(
 649    excerpt_id: ExcerptId,
 650    anchor: text::Anchor,
 651    content_len: usize,
 652    crease_label: SharedString,
 653    crease_icon: SharedString,
 654    // abs_path: Option<Arc<Path>>,
 655    image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
 656    editor: Entity<Editor>,
 657    window: &mut Window,
 658    cx: &mut App,
 659) -> Option<(CreaseId, postage::barrier::Sender)> {
 660    let (tx, rx) = postage::barrier::channel();
 661
 662    let crease_id = editor.update(cx, |editor, cx| {
 663        let snapshot = editor.buffer().read(cx).snapshot(cx);
 664
 665        let start = snapshot.anchor_in_excerpt(excerpt_id, anchor)?;
 666
 667        let start = start.bias_right(&snapshot);
 668        let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
 669
 670        let placeholder = FoldPlaceholder {
 671            render: render_mention_fold_button(
 672                crease_label.clone(),
 673                crease_icon.clone(),
 674                start..end,
 675                rx,
 676                image,
 677                cx.weak_entity(),
 678                cx,
 679            ),
 680            merge_adjacent: false,
 681            ..Default::default()
 682        };
 683
 684        let crease = Crease::Inline {
 685            range: start..end,
 686            placeholder,
 687            render_toggle: None,
 688            render_trailer: None,
 689            metadata: Some(CreaseMetadata {
 690                label: crease_label,
 691                icon_path: crease_icon,
 692            }),
 693        };
 694
 695        let ids = editor.insert_creases(vec![crease.clone()], cx);
 696        editor.fold_creases(vec![crease], false, window, cx);
 697
 698        Some(ids[0])
 699    })?;
 700
 701    Some((crease_id, tx))
 702}
 703
 704pub(crate) fn crease_for_mention(
 705    label: SharedString,
 706    icon_path: SharedString,
 707    range: Range<Anchor>,
 708    editor_entity: WeakEntity<Editor>,
 709) -> Crease<Anchor> {
 710    let placeholder = FoldPlaceholder {
 711        render: render_fold_icon_button(icon_path.clone(), label.clone(), editor_entity),
 712        merge_adjacent: false,
 713        ..Default::default()
 714    };
 715
 716    let render_trailer = move |_row, _unfold, _window: &mut Window, _cx: &mut App| Empty.into_any();
 717
 718    Crease::inline(range, placeholder, fold_toggle("mention"), render_trailer)
 719        .with_metadata(CreaseMetadata { icon_path, label })
 720}
 721
 722fn render_fold_icon_button(
 723    icon_path: SharedString,
 724    label: SharedString,
 725    editor: WeakEntity<Editor>,
 726) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
 727    Arc::new({
 728        move |fold_id, fold_range, cx| {
 729            let is_in_text_selection = editor
 730                .update(cx, |editor, cx| editor.is_range_selected(&fold_range, cx))
 731                .unwrap_or_default();
 732
 733            MentionCrease::new(fold_id, icon_path.clone(), label.clone())
 734                .is_toggled(is_in_text_selection)
 735                .into_any_element()
 736        }
 737    })
 738}
 739
 740fn fold_toggle(
 741    name: &'static str,
 742) -> impl Fn(
 743    MultiBufferRow,
 744    bool,
 745    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
 746    &mut Window,
 747    &mut App,
 748) -> AnyElement {
 749    move |row, is_folded, fold, _window, _cx| {
 750        Disclosure::new((name, row.0 as u64), !is_folded)
 751            .toggle_state(is_folded)
 752            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
 753            .into_any_element()
 754    }
 755}
 756
 757fn full_mention_for_directory(
 758    project: &Entity<Project>,
 759    abs_path: &Path,
 760    cx: &mut App,
 761) -> Task<Result<Mention>> {
 762    fn collect_files_in_path(worktree: &Worktree, path: &RelPath) -> Vec<(Arc<RelPath>, String)> {
 763        let mut files = Vec::new();
 764
 765        for entry in worktree.child_entries(path) {
 766            if entry.is_dir() {
 767                files.extend(collect_files_in_path(worktree, &entry.path));
 768            } else if entry.is_file() {
 769                files.push((
 770                    entry.path.clone(),
 771                    worktree
 772                        .full_path(&entry.path)
 773                        .to_string_lossy()
 774                        .to_string(),
 775                ));
 776            }
 777        }
 778
 779        files
 780    }
 781
 782    let Some(project_path) = project
 783        .read(cx)
 784        .project_path_for_absolute_path(&abs_path, cx)
 785    else {
 786        return Task::ready(Err(anyhow!("project path not found")));
 787    };
 788    let Some(entry) = project.read(cx).entry_for_path(&project_path, cx) else {
 789        return Task::ready(Err(anyhow!("project entry not found")));
 790    };
 791    let directory_path = entry.path.clone();
 792    let worktree_id = project_path.worktree_id;
 793    let Some(worktree) = project.read(cx).worktree_for_id(worktree_id, cx) else {
 794        return Task::ready(Err(anyhow!("worktree not found")));
 795    };
 796    let project = project.clone();
 797    cx.spawn(async move |cx| {
 798        let file_paths = worktree.read_with(cx, |worktree, _cx| {
 799            collect_files_in_path(worktree, &directory_path)
 800        });
 801        let descendants_future = cx.update(|cx| {
 802            futures::future::join_all(file_paths.into_iter().map(
 803                |(worktree_path, full_path): (Arc<RelPath>, String)| {
 804                    let rel_path = worktree_path
 805                        .strip_prefix(&directory_path)
 806                        .log_err()
 807                        .map_or_else(|| worktree_path.clone(), |rel_path| rel_path.into());
 808
 809                    let open_task = project.update(cx, |project, cx| {
 810                        project.buffer_store().update(cx, |buffer_store, cx| {
 811                            let project_path = ProjectPath {
 812                                worktree_id,
 813                                path: worktree_path,
 814                            };
 815                            buffer_store.open_buffer(project_path, cx)
 816                        })
 817                    });
 818
 819                    cx.spawn(async move |cx| {
 820                        let buffer = open_task.await.log_err()?;
 821                        let buffer_content = outline::get_buffer_content_or_outline(
 822                            buffer.clone(),
 823                            Some(&full_path),
 824                            &cx,
 825                        )
 826                        .await
 827                        .ok()?;
 828
 829                        Some((rel_path, full_path, buffer_content.text, buffer))
 830                    })
 831                },
 832            ))
 833        });
 834
 835        let contents = cx
 836            .background_spawn(async move {
 837                let (contents, tracked_buffers): (Vec<_>, Vec<_>) = descendants_future
 838                    .await
 839                    .into_iter()
 840                    .flatten()
 841                    .map(|(rel_path, full_path, rope, buffer)| {
 842                        ((rel_path, full_path, rope), buffer)
 843                    })
 844                    .unzip();
 845                Mention::Text {
 846                    content: render_directory_contents(contents),
 847                    tracked_buffers,
 848                }
 849            })
 850            .await;
 851        anyhow::Ok(contents)
 852    })
 853}
 854
 855fn render_directory_contents(entries: Vec<(Arc<RelPath>, String, String)>) -> String {
 856    let mut output = String::new();
 857    for (_relative_path, full_path, content) in entries {
 858        let fence = codeblock_fence_for_path(Some(&full_path), None);
 859        write!(output, "\n{fence}\n{content}\n```").unwrap();
 860    }
 861    output
 862}
 863
 864fn render_mention_fold_button(
 865    label: SharedString,
 866    icon: SharedString,
 867    range: Range<Anchor>,
 868    mut loading_finished: postage::barrier::Receiver,
 869    image_task: Option<Shared<Task<Result<Arc<Image>, String>>>>,
 870    editor: WeakEntity<Editor>,
 871    cx: &mut App,
 872) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
 873    let loading = cx.new(|cx| {
 874        let loading = cx.spawn(async move |this, cx| {
 875            loading_finished.recv().await;
 876            this.update(cx, |this: &mut LoadingContext, cx| {
 877                this.loading = None;
 878                cx.notify();
 879            })
 880            .ok();
 881        });
 882        LoadingContext {
 883            id: cx.entity_id(),
 884            label,
 885            icon,
 886            range,
 887            editor,
 888            loading: Some(loading),
 889            image: image_task.clone(),
 890        }
 891    });
 892    Arc::new(move |_fold_id, _fold_range, _cx| loading.clone().into_any_element())
 893}
 894
 895struct LoadingContext {
 896    id: EntityId,
 897    label: SharedString,
 898    icon: SharedString,
 899    range: Range<Anchor>,
 900    editor: WeakEntity<Editor>,
 901    loading: Option<Task<()>>,
 902    image: Option<Shared<Task<Result<Arc<Image>, String>>>>,
 903}
 904
 905impl Render for LoadingContext {
 906    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 907        let is_in_text_selection = self
 908            .editor
 909            .update(cx, |editor, cx| editor.is_range_selected(&self.range, cx))
 910            .unwrap_or_default();
 911
 912        let id = ElementId::from(("loading_context", self.id));
 913
 914        MentionCrease::new(id, self.icon.clone(), self.label.clone())
 915            .is_toggled(is_in_text_selection)
 916            .is_loading(self.loading.is_some())
 917            .when_some(self.image.clone(), |this, image_task| {
 918                this.image_preview(move |_, cx| {
 919                    let image = image_task.peek().cloned().transpose().ok().flatten();
 920                    let image_task = image_task.clone();
 921                    cx.new::<ImageHover>(|cx| ImageHover {
 922                        image,
 923                        _task: cx.spawn(async move |this, cx| {
 924                            if let Ok(image) = image_task.clone().await {
 925                                this.update(cx, |this, cx| {
 926                                    if this.image.replace(image).is_none() {
 927                                        cx.notify();
 928                                    }
 929                                })
 930                                .ok();
 931                            }
 932                        }),
 933                    })
 934                    .into()
 935                })
 936            })
 937    }
 938}
 939
 940struct ImageHover {
 941    image: Option<Arc<Image>>,
 942    _task: Task<()>,
 943}
 944
 945impl Render for ImageHover {
 946    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
 947        if let Some(image) = self.image.clone() {
 948            gpui::img(image).max_w_96().max_h_96().into_any_element()
 949        } else {
 950            gpui::Empty.into_any_element()
 951        }
 952    }
 953}
 954
 955async fn fetch_url_content(http_client: Arc<HttpClientWithUrl>, url: String) -> Result<String> {
 956    #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
 957    enum ContentType {
 958        Html,
 959        Plaintext,
 960        Json,
 961    }
 962    use html_to_markdown::{TagHandler, convert_html_to_markdown, markdown};
 963
 964    let url = if !url.starts_with("https://") && !url.starts_with("http://") {
 965        format!("https://{url}")
 966    } else {
 967        url
 968    };
 969
 970    let mut response = http_client.get(&url, AsyncBody::default(), true).await?;
 971    let mut body = Vec::new();
 972    response
 973        .body_mut()
 974        .read_to_end(&mut body)
 975        .await
 976        .context("error reading response body")?;
 977
 978    if response.status().is_client_error() {
 979        let text = String::from_utf8_lossy(body.as_slice());
 980        anyhow::bail!(
 981            "status error {}, response: {text:?}",
 982            response.status().as_u16()
 983        );
 984    }
 985
 986    let Some(content_type) = response.headers().get("content-type") else {
 987        anyhow::bail!("missing Content-Type header");
 988    };
 989    let content_type = content_type
 990        .to_str()
 991        .context("invalid Content-Type header")?;
 992    let content_type = match content_type {
 993        "text/html" => ContentType::Html,
 994        "text/plain" => ContentType::Plaintext,
 995        "application/json" => ContentType::Json,
 996        _ => ContentType::Html,
 997    };
 998
 999    match content_type {
1000        ContentType::Html => {
1001            let mut handlers: Vec<TagHandler> = vec![
1002                Rc::new(RefCell::new(markdown::WebpageChromeRemover)),
1003                Rc::new(RefCell::new(markdown::ParagraphHandler)),
1004                Rc::new(RefCell::new(markdown::HeadingHandler)),
1005                Rc::new(RefCell::new(markdown::ListHandler)),
1006                Rc::new(RefCell::new(markdown::TableHandler::new())),
1007                Rc::new(RefCell::new(markdown::StyledTextHandler)),
1008            ];
1009            if url.contains("wikipedia.org") {
1010                use html_to_markdown::structure::wikipedia;
1011
1012                handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaChromeRemover)));
1013                handlers.push(Rc::new(RefCell::new(wikipedia::WikipediaInfoboxHandler)));
1014                handlers.push(Rc::new(
1015                    RefCell::new(wikipedia::WikipediaCodeHandler::new()),
1016                ));
1017            } else {
1018                handlers.push(Rc::new(RefCell::new(markdown::CodeHandler)));
1019            }
1020            convert_html_to_markdown(&body[..], &mut handlers)
1021        }
1022        ContentType::Plaintext => Ok(std::str::from_utf8(&body)?.to_owned()),
1023        ContentType::Json => {
1024            let json: serde_json::Value = serde_json::from_slice(&body)?;
1025
1026            Ok(format!(
1027                "```json\n{}\n```",
1028                serde_json::to_string_pretty(&json)?
1029            ))
1030        }
1031    }
1032}