message_editor.rs

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