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.

Properly replace hints per each chunk (#61562)

Kirill Bulatov90b15493109a
diff --git a/crates/editor/src/inlays/inlay_hints.rs b/crates/editor/src/inlays/inlay_hints.rs
index 56cd3e4fc6e..2a10a78515e 100644
--- a/crates/editor/src/inlays/inlay_hints.rs
+++ b/crates/editor/src/inlays/inlay_hints.rs
@@ -1008,6 +1008,7 @@ pub mod tests {
use crate::scroll::ScrollAmount;
use crate::{Editor, SelectionEffects};
use collections::HashSet;
+ use futures::channel::oneshot;
use futures::{StreamExt, future};
use gpui::{AppContext as _, Context, TestAppContext, WindowHandle};
use itertools::Itertools as _;
@@ -1220,6 +1221,94 @@ pub mod tests {
.unwrap();
}
+ #[gpui::test]
+ async fn test_no_hint_duplication_when_refresh_races_with_fetch(cx: &mut gpui::TestAppContext) {
+ init_test(cx, &|settings| {
+ settings.defaults.inlay_hints = Some(InlayHintSettingsContent {
+ enabled: Some(true),
+ ..InlayHintSettingsContent::default()
+ })
+ });
+ let (first_request_unblock, first_request_gate) = oneshot::channel::<()>();
+ let first_request_gate = Arc::new(Mutex::new(Some(first_request_gate)));
+ let lsp_request_count = Arc::new(AtomicU32::new(0));
+ let (_, editor, fake_server) = prepare_test_objects(cx, {
+ let first_request_gate = first_request_gate.clone();
+ let lsp_request_count = lsp_request_count.clone();
+ move |fake_server, file_with_hints| {
+ let lsp_request_count = lsp_request_count.clone();
+ let first_request_gate = first_request_gate.clone();
+ fake_server.set_request_handler::<lsp::request::InlayHintRequest, _, _>(
+ move |params, _| {
+ let first_request_gate = first_request_gate.lock().take();
+ let i = lsp_request_count.fetch_add(1, Ordering::Release) + 1;
+ async move {
+ if let Some(first_request_gate) = first_request_gate {
+ first_request_gate.await.ok();
+ }
+ assert_eq!(
+ params.text_document.uri,
+ lsp::Uri::from_file_path(file_with_hints).unwrap(),
+ );
+ Ok(Some(vec![lsp::InlayHint {
+ position: lsp::Position::new(0, 1),
+ label: lsp::InlayHintLabel::String(i.to_string()),
+ kind: Some(lsp::InlayHintKind::TYPE),
+ text_edits: None,
+ tooltip: None,
+ padding_left: None,
+ padding_right: None,
+ data: None,
+ }]))
+ }
+ },
+ );
+ }
+ })
+ .await;
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.executor().run_until_parked();
+
+ editor
+ .update(cx, |editor, _window, cx| {
+ assert!(
+ cached_hint_labels(editor, cx).is_empty(),
+ "The initial hint fetch is blocked and should not have populated the cache yet"
+ );
+ })
+ .unwrap();
+
+ // Emulate a server refresh request arriving while the initial fetch is still running.
+ fake_server
+ .request::<lsp::request::InlayHintRefreshRequest>((), lsp::DEFAULT_LSP_REQUEST_TIMEOUT)
+ .await
+ .into_response()
+ .unwrap();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.executor().run_until_parked();
+
+ first_request_unblock.send(()).unwrap();
+ cx.executor().advance_clock(Duration::from_secs(1));
+ cx.executor().run_until_parked();
+ assert_eq!(
+ 2,
+ lsp_request_count.load(Ordering::Acquire),
+ "The refresh should have re-queried the server"
+ );
+
+ editor
+ .update(cx, |editor, _window, cx| {
+ let expected_hints = vec!["2".to_string()];
+ assert_eq!(
+ expected_hints,
+ cached_hint_labels(editor, cx),
+ "A refresh racing with an in-flight fetch should replace its hints, not duplicate them"
+ );
+ assert_eq!(expected_hints, visible_hint_labels(editor, cx));
+ })
+ .unwrap();
+ }
+
#[gpui::test]
async fn test_cache_update_on_lsp_completion_tasks(cx: &mut gpui::TestAppContext) {
init_test(cx, &|settings| {
diff --git a/crates/project/src/lsp_store/inlay_hints.rs b/crates/project/src/lsp_store/inlay_hints.rs
index e7e110a628a..8a48992ee53 100644
--- a/crates/project/src/lsp_store/inlay_hints.rs
+++ b/crates/project/src/lsp_store/inlay_hints.rs
@@ -177,26 +177,28 @@ impl BufferInlayHints {
server_id: LanguageServerId,
new_hints: Vec<(InlayId, InlayHint)>,
) {
- let existing_hints = self.hints_by_chunks[chunk.id]
- .get_or_insert_default()
- .entry(server_id)
- .or_insert_with(Vec::new);
- let existing_count = existing_hints.len();
- existing_hints.extend(new_hints.into_iter().enumerate().filter_map(
- |(i, (id, new_hint))| {
- let new_hint_for_id = HintForId {
+ let chunk_hints = self.hints_by_chunks[chunk.id].get_or_insert_default();
+
+ // A response always covers the entire chunk, so it supersedes the server's previously
+ // cached hints for this chunk: a concurrent fetch for the same chunk and server
+ // (e.g. a server refresh arriving mid-fetch) would otherwise append the same hints
+ // again under fresh ids, duplicating them.
+ for (stale_id, _) in chunk_hints.remove(&server_id).into_iter().flatten() {
+ self.hints_by_id.remove(&stale_id);
+ self.hint_resolves.remove(&stale_id);
+ }
+ let mut inserted_hints = Vec::with_capacity(new_hints.len());
+ for (id, new_hint) in new_hints {
+ if let hash_map::Entry::Vacant(vacant_entry) = self.hints_by_id.entry(id) {
+ vacant_entry.insert(HintForId {
chunk_id: chunk.id,
server_id,
- position: existing_count + i,
- };
- if let hash_map::Entry::Vacant(vacant_entry) = self.hints_by_id.entry(id) {
- vacant_entry.insert(new_hint_for_id);
- Some((id, new_hint))
- } else {
- None
- }
- },
- ));
+ position: inserted_hints.len(),
+ });
+ inserted_hints.push((id, new_hint));
+ }
+ }
+ chunk_hints.insert(server_id, inserted_hints);
*self.fetched_hints(&chunk) = None;
}