Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

agent_ui: Add mention disambiguation (#56926)

Danilo Lealb9ba43c9c1f9
diff --git a/crates/acp_thread/src/mention.rs b/crates/acp_thread/src/mention.rs
index 6fc2cc50c1f..67c1ddb9416 100644
--- a/crates/acp_thread/src/mention.rs
+++ b/crates/acp_thread/src/mention.rs
@@ -342,6 +342,21 @@ impl MentionUri {
..
} => selection_name(path.as_deref(), line_range),
MentionUri::Fetch { url } => url.to_string(),
+ MentionUri::Skill { name, .. } => name.clone(),
+ }
+ }
+
+ /// Returns a label for this mention at the given disambiguation `detail`
+ /// level. `detail == 0` is the base name returned by [`Self::name`]; higher
+ /// levels include progressively more context (e.g. additional parent path
+ /// components for files, or the source for skills) until a fixed point is
+ /// reached. Intended to be driven by [`util::disambiguate::compute_disambiguation_details`].
+ pub fn disambiguated_name(&self, detail: usize) -> String {
+ if detail == 0 {
+ return self.name();
+ }
+
+ match self {
MentionUri::Skill { name, source, .. } => {
if source.is_empty() {
format!("{} (global)", name)
@@ -349,6 +364,10 @@ impl MentionUri {
format!("{} ({})", name, source)
}
}
+ MentionUri::File { abs_path, .. } | MentionUri::Directory { abs_path, .. } => {
+ project::path_suffix(abs_path, detail)
+ }
+ _ => self.name(),
}
}
@@ -1070,4 +1089,68 @@ mod tests {
let parsed_single = MentionUri::parse(single_line_uri, PathStyle::local()).unwrap();
assert_eq!(parsed_single.name(), "Terminal (1 line)");
}
+
+ #[test]
+ fn test_disambiguated_name() {
+ // Two files with the same name — should disambiguate with parent dir
+ let file_a = MentionUri::File {
+ abs_path: PathBuf::from(path!("/project/src/README.md")),
+ };
+ let file_b = MentionUri::File {
+ abs_path: PathBuf::from(path!("/project/docs/README.md")),
+ };
+ assert_eq!(file_a.name(), "README.md");
+ assert_eq!(file_b.name(), "README.md");
+ assert_eq!(file_a.disambiguated_name(0), "README.md");
+ assert_eq!(file_a.disambiguated_name(1), "src/README.md");
+ assert_eq!(file_b.disambiguated_name(1), "docs/README.md");
+
+ // Files that still collide at one parent should grow further.
+ let deep_a = MentionUri::File {
+ abs_path: PathBuf::from(path!("/a/src/foo.rs")),
+ };
+ let deep_b = MentionUri::File {
+ abs_path: PathBuf::from(path!("/b/src/foo.rs")),
+ };
+ assert_eq!(deep_a.disambiguated_name(1), "src/foo.rs");
+ assert_eq!(deep_b.disambiguated_name(1), "src/foo.rs");
+ assert_eq!(deep_a.disambiguated_name(2), "a/src/foo.rs");
+ assert_eq!(deep_b.disambiguated_name(2), "b/src/foo.rs");
+
+ // Two skills with the same name — should disambiguate with source
+ let global_skill = MentionUri::Skill {
+ name: "create-skill".into(),
+ source: "".into(),
+ skill_file_path: PathBuf::from("/global/create-skill/SKILL.md"),
+ };
+ let project_skill = MentionUri::Skill {
+ name: "create-skill".into(),
+ source: "my-project".into(),
+ skill_file_path: PathBuf::from("/project/create-skill/SKILL.md"),
+ };
+ assert_eq!(global_skill.name(), "create-skill");
+ assert_eq!(global_skill.disambiguated_name(0), "create-skill");
+ assert_eq!(global_skill.disambiguated_name(1), "create-skill (global)");
+ assert_eq!(
+ project_skill.disambiguated_name(1),
+ "create-skill (my-project)"
+ );
+
+ // A type without special disambiguation (Thread) — detail has no effect
+ // (the value is a fixed point so the disambiguation loop terminates).
+ let thread = MentionUri::Thread {
+ id: acp::SessionId::new("123"),
+ name: "My Thread".into(),
+ };
+ assert_eq!(thread.disambiguated_name(0), "My Thread");
+ assert_eq!(thread.disambiguated_name(1), "My Thread");
+ assert_eq!(thread.disambiguated_name(5), "My Thread");
+
+ // Edge case: file at filesystem root has no parent to show
+ let root_file = MentionUri::File {
+ abs_path: PathBuf::from(path!("/README.md")),
+ };
+ assert_eq!(root_file.disambiguated_name(1), "README.md");
+ assert_eq!(root_file.disambiguated_name(5), "README.md");
+ }
}
diff --git a/crates/agent_ui/src/completion_provider.rs b/crates/agent_ui/src/completion_provider.rs
index 37074aa35a2..3a4ae6ecc2b 100644
--- a/crates/agent_ui/src/completion_provider.rs
+++ b/crates/agent_ui/src/completion_provider.rs
@@ -2603,7 +2603,7 @@ fn completion_text_for_terminal_selections(
};
mention_set
- .update(cx, |mention_set, _| {
+ .update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri.clone(),
@@ -2612,6 +2612,8 @@ fn completion_text_for_terminal_selections(
tracked_buffers: vec![],
}))
.shared(),
+ None,
+ cx,
);
})
.ok();
diff --git a/crates/agent_ui/src/mention_set.rs b/crates/agent_ui/src/mention_set.rs
index 17ad11d3288..31bb31c046c 100644
--- a/crates/agent_ui/src/mention_set.rs
+++ b/crates/agent_ui/src/mention_set.rs
@@ -63,6 +63,7 @@ pub struct MentionSet {
thread_store: Option<Entity<ThreadStore>>,
prompt_store: Option<Entity<PromptStore>>,
mentions: HashMap<CreaseId, (MentionUri, MentionTask)>,
+ crease_entities: HashMap<CreaseId, Entity<LoadingContext>>,
}
impl MentionSet {
@@ -76,6 +77,7 @@ impl MentionSet {
thread_store,
prompt_store,
mentions: HashMap::default(),
+ crease_entities: HashMap::default(),
}
}
@@ -110,12 +112,24 @@ impl MentionSet {
for (crease_id, crease) in snapshot.crease_snapshot.creases() {
if !crease.range().start.is_valid(snapshot.buffer_snapshot()) {
self.mentions.remove(&crease_id);
+ self.crease_entities.remove(&crease_id);
}
}
}
- pub fn insert_mention(&mut self, crease_id: CreaseId, uri: MentionUri, task: MentionTask) {
+ pub fn insert_mention(
+ &mut self,
+ crease_id: CreaseId,
+ uri: MentionUri,
+ task: MentionTask,
+ crease_entity: Option<Entity<LoadingContext>>,
+ cx: &mut App,
+ ) {
self.mentions.insert(crease_id, (uri, task));
+ if let Some(entity) = crease_entity {
+ self.crease_entities.insert(crease_id, entity);
+ }
+ self.recompute_disambiguation(cx);
}
/// Creates the appropriate confirmation task for a mention based on its URI type.
@@ -165,8 +179,10 @@ impl MentionSet {
}
}
- pub fn remove_mention(&mut self, crease_id: &CreaseId) {
+ pub fn remove_mention(&mut self, crease_id: &CreaseId, cx: &mut App) {
self.mentions.remove(crease_id);
+ self.crease_entities.remove(crease_id);
+ self.recompute_disambiguation(cx);
}
pub fn creases(&self) -> HashSet<CreaseId> {
@@ -196,13 +212,32 @@ impl MentionSet {
}
pub fn set_mentions(&mut self, mentions: HashMap<CreaseId, (MentionUri, MentionTask)>) {
+ self.crease_entities
+ .retain(|id, _| mentions.contains_key(id));
self.mentions = mentions;
}
pub fn clear(&mut self) -> impl Iterator<Item = (CreaseId, (MentionUri, MentionTask))> {
+ self.crease_entities.clear();
self.mentions.drain()
}
+ fn recompute_disambiguation(&self, cx: &mut App) {
+ let labels =
+ compute_disambiguated_labels(self.mentions.iter().map(|(id, (uri, _))| (*id, uri)));
+
+ for (crease_id, new_label) in labels {
+ if let Some(entity) = self.crease_entities.get(&crease_id) {
+ entity.update(cx, |loading_ctx, cx| {
+ if loading_ctx.label != new_label {
+ loading_ctx.label = new_label;
+ cx.notify();
+ }
+ });
+ }
+ }
+ }
+
pub fn confirm_mention_completion(
&mut self,
crease_text: SharedString,
@@ -273,7 +308,7 @@ impl MentionSet {
cx,
)
};
- let Some((crease_id, tx)) = crease else {
+ let Some((crease_id, tx, crease_entity)) = crease else {
return Task::ready(());
};
@@ -325,6 +360,10 @@ impl MentionSet {
.spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
.shared();
self.mentions.insert(crease_id, (mention_uri, task.clone()));
+ if let Some(entity) = crease_entity {
+ self.crease_entities.insert(crease_id, entity);
+ }
+ self.recompute_disambiguation(cx);
// Notify the user if we failed to load the mentioned context
let workspace = workspace.downgrade();
@@ -338,6 +377,7 @@ impl MentionSet {
editor.edit([(start_anchor..end_anchor, "")], cx);
});
this.mentions.remove(&crease_id);
+ this.crease_entities.remove(&crease_id);
})
.ok();
}
@@ -669,6 +709,26 @@ impl MentionSet {
}
}
+/// Computes disambiguated labels for a set of mentions. When multiple mentions
+/// share the same base name, their labels include extra context (additional
+/// parent path components for files/directories, source for skills) so the user
+/// can tell them apart. Driven by [`util::disambiguate::compute_disambiguation_details`],
+/// which is the same utility used for buffer tab titles and the sidebar.
+fn compute_disambiguated_labels<'a>(
+ mentions: impl Iterator<Item = (CreaseId, &'a MentionUri)>,
+) -> HashMap<CreaseId, SharedString> {
+ let mentions: Vec<_> = mentions.collect();
+ let details =
+ util::disambiguate::compute_disambiguation_details(&mentions, |(_, uri), detail| {
+ uri.disambiguated_name(detail)
+ });
+ mentions
+ .into_iter()
+ .zip(details)
+ .map(|((id, uri), detail)| (id, uri.disambiguated_name(detail).into()))
+ .collect()
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -821,7 +881,7 @@ pub(crate) async fn insert_images_as_context(
snapshot.anchor_before(start_anchor.to_offset(&snapshot) + content_len)
});
let image = Arc::new(image);
- let Ok(Some((crease_id, tx))) = cx.update(|window, cx| {
+ let Ok(Some((crease_id, tx, crease_entity))) = cx.update(|window, cx| {
insert_crease_for_mention(
text_anchor,
content_len,
@@ -856,13 +916,15 @@ pub(crate) async fn insert_images_as_context(
})
.shared();
- mention_set.update(cx, |mention_set, _cx| {
+ mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
MentionUri::PastedImage {
name: name.to_string(),
},
task.clone(),
+ crease_entity,
+ cx,
)
});
@@ -874,8 +936,8 @@ pub(crate) async fn insert_images_as_context(
editor.update(cx, |editor, cx| {
editor.edit([(start_anchor..end_anchor, "")], cx);
});
- mention_set.update(cx, |mention_set, _cx| {
- mention_set.remove_mention(&crease_id)
+ mention_set.update(cx, |mention_set, cx| {
+ mention_set.remove_mention(&crease_id, cx)
});
}
}
@@ -991,7 +1053,11 @@ pub(crate) fn insert_crease_for_mention(
editor: Entity<Editor>,
window: &mut Window,
cx: &mut App,
-) -> Option<(CreaseId, postage::barrier::Sender)> {
+) -> Option<(
+ CreaseId,
+ postage::barrier::Sender,
+ Option<Entity<LoadingContext>>,
+)> {
let (tx, rx) = postage::barrier::channel();
let crease_id = editor.update(cx, |editor, cx| {
@@ -1002,19 +1068,20 @@ pub(crate) fn insert_crease_for_mention(
let start = start.bias_right(&snapshot);
let end = snapshot.anchor_before(start.to_offset(&snapshot) + content_len);
+ let (render, crease_entity) = render_mention_fold_button(
+ crease_label.clone(),
+ crease_icon.clone(),
+ crease_tooltip,
+ mention_uri.clone(),
+ workspace.clone(),
+ start..end,
+ rx,
+ image,
+ cx.weak_entity(),
+ cx,
+ );
let placeholder = FoldPlaceholder {
- render: render_mention_fold_button(
- crease_label.clone(),
- crease_icon.clone(),
- crease_tooltip,
- mention_uri.clone(),
- workspace.clone(),
- start..end,
- rx,
- image,
- cx.weak_entity(),
- cx,
- ),
+ render,
merge_adjacent: false,
..Default::default()
};
@@ -1033,10 +1100,11 @@ pub(crate) fn insert_crease_for_mention(
let ids = editor.insert_creases(vec![crease.clone()], cx);
editor.fold_creases(vec![crease], false, window, cx);
- Some(ids[0])
+ Some((ids[0], crease_entity))
})?;
- Some((crease_id, tx))
+ let (crease_id, crease_entity) = crease_id;
+ Some((crease_id, tx, Some(crease_entity)))
}
pub(crate) fn crease_for_mention(
@@ -1215,7 +1283,10 @@ fn render_mention_fold_button(
image_task: Option<Shared<Task<Result<Arc<Image>, String>>>>,
editor: WeakEntity<Editor>,
cx: &mut App,
-) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
+) -> (
+ Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement>,
+ Entity<LoadingContext>,
+) {
let loading = cx.new(|cx| {
let loading = cx.spawn(async move |this, cx| {
loading_finished.recv().await;
@@ -1238,10 +1309,13 @@ fn render_mention_fold_button(
image: image_task.clone(),
}
});
- Arc::new(move |_fold_id, _fold_range, _cx| loading.clone().into_any_element())
+ let loading_clone = loading.clone();
+ let render: Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> =
+ Arc::new(move |_fold_id, _fold_range, _cx| loading_clone.clone().into_any_element());
+ (render, loading)
}
-struct LoadingContext {
+pub struct LoadingContext {
id: EntityId,
label: SharedString,
icon: SharedString,
diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs
index 8a152239c14..ecd1febba72 100644
--- a/crates/agent_ui/src/message_editor.rs
+++ b/crates/agent_ui/src/message_editor.rs
@@ -1134,7 +1134,7 @@ impl MessageEditor {
(text_anchor, mention_text.len())
});
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
text_anchor,
content_len,
crease_text.into(),
@@ -1181,8 +1181,14 @@ impl MessageEditor {
})
.shared();
- self.mention_set.update(cx, |mention_set, _cx| {
- mention_set.insert_mention(crease_id, mention_uri.clone(), mention_task)
+ self.mention_set.update(cx, |mention_set, cx| {
+ mention_set.insert_mention(
+ crease_id,
+ mention_uri.clone(),
+ mention_task,
+ crease_entity,
+ cx,
+ )
});
}
}
@@ -1241,7 +1247,7 @@ impl MessageEditor {
let http_client = workspace.read(cx).client().http_client();
for (anchor, content_len, mention_uri) in all_mentions {
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
snapshot.anchor_to_buffer_anchor(anchor).unwrap().0,
content_len,
mention_uri.name().into(),
@@ -1271,8 +1277,14 @@ impl MessageEditor {
.spawn(async move |_, _| task.await.map_err(|e| e.to_string()))
.shared();
- self.mention_set.update(cx, |mention_set, _cx| {
- mention_set.insert_mention(crease_id, mention_uri.clone(), task.clone())
+ self.mention_set.update(cx, |mention_set, cx| {
+ mention_set.insert_mention(
+ crease_id,
+ mention_uri.clone(),
+ task.clone(),
+ crease_entity,
+ cx,
+ )
});
// Drop the tx after inserting to signal the crease is ready
@@ -1463,7 +1475,7 @@ impl MessageEditor {
(text_anchor, mention_text.len())
});
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
text_anchor,
content_len,
mention_uri.name().into(),
@@ -1488,8 +1500,14 @@ impl MessageEditor {
.spawn(async move |_cx| confirm_task.await.map_err(|e| e.to_string()))
.shared();
- mention_set.update(cx, |mention_set, _| {
- mention_set.insert_mention(crease_id, mention_uri, mention_task);
+ mention_set.update(cx, |mention_set, cx| {
+ mention_set.insert_mention(
+ crease_id,
+ mention_uri,
+ mention_task,
+ crease_entity,
+ cx,
+ );
});
})
})
@@ -1744,7 +1762,7 @@ impl MessageEditor {
for (range, mention_uri, mention) in mentions {
let adjusted_start = insertion_start + range.start;
let anchor = snapshot.anchor_before(MultiBufferOffset(adjusted_start));
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, crease_entity)) = insert_crease_for_mention(
snapshot.anchor_to_buffer_anchor(anchor).unwrap().0,
range.end - range.start,
mention_uri.name().into(),
@@ -1761,11 +1779,13 @@ impl MessageEditor {
};
drop(tx);
- self.mention_set.update(cx, |mention_set, _cx| {
+ self.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
mention_uri.clone(),
Task::ready(Ok(mention)).shared(),
+ crease_entity,
+ cx,
)
});
}
@@ -4349,7 +4369,7 @@ mod tests {
"line 3\nline 4\n".to_string(),
),
] {
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, _crease_entity)) = insert_crease_for_mention(
snapshot
.anchor_to_buffer_anchor(
snapshot.anchor_before(MultiBufferOffset(range.start)),
@@ -4371,7 +4391,7 @@ mod tests {
};
drop(tx);
- message_editor.mention_set.update(cx, |mention_set, _cx| {
+ message_editor.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
uri,
@@ -4380,6 +4400,8 @@ mod tests {
tracked_buffers: Vec::new(),
}))
.shared(),
+ None,
+ cx,
);
});
}
@@ -4508,7 +4530,7 @@ mod tests {
"line 3\nline 4\n".to_string(),
),
] {
- let Some((crease_id, tx)) = insert_crease_for_mention(
+ let Some((crease_id, tx, _crease_entity)) = insert_crease_for_mention(
snapshot
.anchor_to_buffer_anchor(
snapshot.anchor_before(MultiBufferOffset(range.start)),
@@ -4530,7 +4552,7 @@ mod tests {
};
drop(tx);
- message_editor.mention_set.update(cx, |mention_set, _cx| {
+ message_editor.mention_set.update(cx, |mention_set, cx| {
mention_set.insert_mention(
crease_id,
uri,
@@ -4539,6 +4561,8 @@ mod tests {
tracked_buffers: Vec::new(),
}))
.shared(),
+ None,
+ cx,
);
});
}