дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 22:32:35 +02:00
Порівняти коміти
12
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c00016db8a | ||
|
|
88b463d888 | ||
|
|
ac88059d0f | ||
|
|
a09c9aa9ad | ||
|
|
7fef1e10a8 | ||
|
|
1748c98ac8 | ||
|
|
399ae25ab6 | ||
|
|
f28dd8125b | ||
|
|
d5f7e0a99b | ||
|
|
a66c9e6d05 | ||
|
|
59bcf7eac5 | ||
|
|
fe21c67537 |
No files matched your search
Створено
+2
-2
@@ -252,9 +252,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
version = "1.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
|
||||
@@ -614,6 +614,15 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
|
||||
Ok(Some(DebugServer { host, port }))
|
||||
}
|
||||
|
||||
/// A source served only through the `source` request whose `path` is no file, such as
|
||||
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
|
||||
/// debug info. Opening it would show an error tab; without a path the stop selects the
|
||||
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
|
||||
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
|
||||
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
|
||||
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
|
||||
}
|
||||
|
||||
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
|
||||
pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
let source = f.get("source");
|
||||
@@ -626,7 +635,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
StackFrame {
|
||||
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
|
||||
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
|
||||
path: source
|
||||
.and_then(|s| s.get("path"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !is_pseudo_path(source, p))
|
||||
.map(Into::into),
|
||||
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
presentation_hint: hint,
|
||||
|
||||
@@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() {
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_drop_pseudo_paths_of_referenced_sources() {
|
||||
let frame = |path: &str, reference: i64| {
|
||||
frame_from(&json!({"id": 1, "name": "f", "line": 1,
|
||||
"source": {"path": path, "sourceReference": reference}}))
|
||||
.path
|
||||
};
|
||||
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
|
||||
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
|
||||
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
|
||||
let here = env!("CARGO_MANIFEST_DIR");
|
||||
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
|
||||
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -544,38 +544,24 @@ async fn resolve_launch_without_jdtls(
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
}
|
||||
None if by_service => {}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
if !is_maven_module(root, &model, &module) {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven;
|
||||
apply_without_jdtls_classpath(
|
||||
&mut class_paths,
|
||||
&mut info,
|
||||
from_server,
|
||||
by_service,
|
||||
is_maven,
|
||||
delegated_maven,
|
||||
|| {
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
|
||||
if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)
|
||||
} else {
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
|
||||
};
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)
|
||||
}
|
||||
},
|
||||
)?;
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
@@ -825,6 +811,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
a == b || entry_key(a, windows) == entry_key(b, windows)
|
||||
}
|
||||
|
||||
/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or
|
||||
/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven
|
||||
/// module), delegates classpath resolution to Maven itself (falling back to the language server's
|
||||
/// classpath on error, matching the jdtls path) so child POM `<exclusions>` and Maven dependency
|
||||
/// mediation are respected (#5586).
|
||||
fn apply_without_jdtls_classpath(
|
||||
class_paths: &mut Vec<String>,
|
||||
info: &mut JavaLaunchInfo,
|
||||
from_server: Option<ide_lsp::java_project::ServerClasspath>,
|
||||
by_service: bool,
|
||||
is_maven: bool,
|
||||
delegated_maven: bool,
|
||||
probe_maven: impl FnOnce() -> IdeResult<String>,
|
||||
) -> IdeResult<()> {
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
Ok(())
|
||||
}
|
||||
None if by_service => Ok(()),
|
||||
Some(server) if delegated_maven => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
info.class_paths = server.classpath.class_paths;
|
||||
merge_maven_launch_classpath(class_paths, info, probe_maven(), &[])
|
||||
}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
append_unique_class_paths(class_paths, server.classpath.class_paths);
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
if !is_maven {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let classpath = probe_maven()?;
|
||||
append_unique_class_paths(
|
||||
class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
|
||||
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
|
||||
/// and leave the reason in the run console. Maven lists the module's and its reactor
|
||||
@@ -1259,6 +1298,55 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() {
|
||||
let server = ide_lsp::java_project::ServerClasspath {
|
||||
classpath: ide_lsp::jdtls::JavaClasspath {
|
||||
project_root: Some(PathBuf::from("/work/child").into()),
|
||||
// Static server resolver kept an excluded parent transitive jar (#5586).
|
||||
class_paths: vec![
|
||||
"/work/child/target/classes".into(),
|
||||
"/m2/log4j-slf4j-impl-2.12.1.jar".into(),
|
||||
"/m2/logback-classic.jar".into(),
|
||||
],
|
||||
module_paths: vec![],
|
||||
},
|
||||
jdk_home: Some(PathBuf::from("/jdk8")),
|
||||
};
|
||||
let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"])
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven))
|
||||
.unwrap();
|
||||
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]);
|
||||
assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into()));
|
||||
assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into()));
|
||||
assert!(info.hints.is_empty(), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() {
|
||||
let server = ide_lsp::java_project::ServerClasspath {
|
||||
classpath: ide_lsp::jdtls::JavaClasspath {
|
||||
project_root: Some(PathBuf::from("/work/child").into()),
|
||||
class_paths: vec!["/m2/server-fallback.jar".into()],
|
||||
module_paths: vec![],
|
||||
},
|
||||
jdk_home: None,
|
||||
};
|
||||
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || {
|
||||
Err(IdeError::internal("maven offline"))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]);
|
||||
assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
|
||||
let mut class_paths = vec!["snapshot.jar".to_owned()];
|
||||
|
||||
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
|
||||
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
|
||||
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
|
||||
let cancel = cancel.clone();
|
||||
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
|
||||
plugin_call(move || {
|
||||
let offered = plugins.offers_inline_completion(&d.language);
|
||||
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
|
||||
})
|
||||
.await
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
host.end_request(request);
|
||||
inline_items(result, plugin)
|
||||
}
|
||||
|
||||
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
|
||||
/// for the document, "no server supports inline completion" is not returned:
|
||||
/// the editor would stop asking while typing for 30 s, and a plugin that had
|
||||
/// nothing this time (cancelled by the next keystroke) may have some next time.
|
||||
fn inline_items(
|
||||
servers: IdeResult<Vec<InlineCompletionItem>>,
|
||||
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
|
||||
) -> IdeResult<Vec<InlineCompletionItem>> {
|
||||
match plugin {
|
||||
Some((_, s)) => Ok(vec![InlineCompletionItem {
|
||||
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
|
||||
insert_text: s.insert_text,
|
||||
range: s.replace,
|
||||
filter_text: None,
|
||||
command: None,
|
||||
server: PLUGIN_SERVER,
|
||||
}]),
|
||||
None => result,
|
||||
Some((true, None)) => provider_server(servers),
|
||||
_ => servers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2429,6 +2445,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
|
||||
use super::*;
|
||||
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
|
||||
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
|
||||
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
|
||||
// No plugin for this language: the servers' answer as it is.
|
||||
assert!(inline_items(none(), Some((false, None))).is_err());
|
||||
assert!(inline_items(none(), None).is_err());
|
||||
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
|
||||
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completion_word_is_its_line_and_what_precedes_it() {
|
||||
use super::*;
|
||||
|
||||
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
|
||||
pub paths: Vec<ide_core::IpcPath>,
|
||||
pub indexing: bool,
|
||||
pub extensions: Vec<String>,
|
||||
/// In-scope files matching `extensions`; `paths` holds the first
|
||||
/// `MAX_NAVIGATION_FILES` of them.
|
||||
pub total: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Discovery offers at most this many files; larger projects get navigation
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
|
||||
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
|
||||
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
|
||||
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
|
||||
let total = files.len();
|
||||
files.truncate(limit);
|
||||
(files, total)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
|
||||
blocking(move || {
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
if extensions.is_empty() {
|
||||
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
|
||||
return Ok(NavigationFiles {
|
||||
paths: vec![],
|
||||
indexing: false,
|
||||
extensions: vec![],
|
||||
total: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
let indexing = project.index.status().indexing;
|
||||
let files = project.index.files_with_extensions(&extensions, 20_001);
|
||||
if files.len() > 20_000 {
|
||||
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
|
||||
}
|
||||
let files = project.index.files_with_extensions(&extensions, usize::MAX);
|
||||
// A project window group's members are project scope: their files are
|
||||
// in the group's index (the group root holds none of them).
|
||||
let members = crate::project::workspace_member_roots(&project.root);
|
||||
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
|
||||
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
|
||||
Ok(NavigationFiles {
|
||||
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
|
||||
truncated: total > files.len(),
|
||||
total: u32::try_from(total).unwrap_or(u32::MAX),
|
||||
paths: files.into_iter().map(Into::into).collect(),
|
||||
indexing,
|
||||
extensions,
|
||||
})
|
||||
@@ -210,3 +232,19 @@ ide_command::domain!(
|
||||
plugin_navigation_invalidate,
|
||||
plugin_navigation_markers,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
|
||||
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
|
||||
// Out-of-scope files neither take a slot nor count toward the total.
|
||||
assert_eq!(total, 4);
|
||||
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
|
||||
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
|
||||
assert_eq!((kept.len(), total), (3, 3));
|
||||
}
|
||||
}
|
||||
@@ -653,6 +653,11 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a usable plugin offers ghost text for `language`.
|
||||
pub fn offers_inline_completion(&self, language: &str) -> bool {
|
||||
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
|
||||
}
|
||||
|
||||
/// Ghost text from the first plugin that has some. Not bound by the
|
||||
/// edit-path soft deadline (it may need the network) but by `cancel`:
|
||||
/// the editor cancels a request as soon as the user types on.
|
||||
|
||||
@@ -3027,6 +3027,38 @@ fn official_ai_completion_cancels_superseded_requests() {
|
||||
assert!(times[9] < Duration::from_millis(500), "{times:?}");
|
||||
}
|
||||
|
||||
/// Installed with the optional network permission refused (it is not ticked by
|
||||
/// default), a suggestion request says so in the window instead of failing silently.
|
||||
#[test]
|
||||
fn official_ai_completion_explains_a_refused_network_permission() {
|
||||
let f = fixture(Limits::default());
|
||||
f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap();
|
||||
let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO);
|
||||
f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap();
|
||||
f.take_events();
|
||||
let doc = ide_plugin::ProviderDocument {
|
||||
path: f.project.join("src/a.rs"),
|
||||
language: "rust".into(),
|
||||
version: 1,
|
||||
text: "let x = ".into(),
|
||||
};
|
||||
for _ in 0..2 {
|
||||
assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none());
|
||||
}
|
||||
assert!(seen.lock().is_empty(), "denied before connecting");
|
||||
let notices: Vec<String> = f
|
||||
.take_events()
|
||||
.into_iter()
|
||||
.filter_map(|(_, e)| match e {
|
||||
PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(notices.len(), 1, "once: {notices:?}");
|
||||
assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}");
|
||||
assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash");
|
||||
}
|
||||
|
||||
/// Checkstyle: a save runs the approved `checkstyle` and publishes
|
||||
/// diagnostics; quick fixes come through the code-action provider; saving
|
||||
/// again cancels the check still running.
|
||||
|
||||
@@ -258,7 +258,8 @@ impl ProjectIndex {
|
||||
}
|
||||
|
||||
/// Bounded file inventory for background plugin indexers; honors the same
|
||||
/// project/exclude scope as search and never walks the filesystem.
|
||||
/// project/exclude scope as search, leaves VCS-ignored files out and never
|
||||
/// walks the filesystem.
|
||||
pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec<PathBuf> {
|
||||
self.shared
|
||||
.data
|
||||
@@ -266,6 +267,7 @@ impl ProjectIndex {
|
||||
.files
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|f| !f.ignored)
|
||||
.filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)))
|
||||
.take(limit)
|
||||
.map(|f| f.path.clone())
|
||||
|
||||
@@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() {
|
||||
fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() {
|
||||
let java = "package demo; interface UserMapper { void find(); }";
|
||||
let f = Fixture::new(&[
|
||||
("src/UserMapper.java", java),
|
||||
("src/mapper.xml", "<mapper/>"),
|
||||
("target/Generated.java", "class Generated {}"),
|
||||
("other.txt", "ignored"),
|
||||
(".gitignore", "gen/\n"),
|
||||
("gen/Ignored.java", "class Ignored {}"),
|
||||
]);
|
||||
let index = f.open();
|
||||
// Go to File lists the git-ignored file; plugin navigation leaves it out.
|
||||
assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]);
|
||||
let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100);
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert!(paths.iter().all(|p| p.starts_with(f.root.join("src"))));
|
||||
|
||||
@@ -9,7 +9,8 @@ use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::error::{ErrorData, ErrorKind};
|
||||
use ide_core::event::LspRefreshKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos};
|
||||
use lsp_types as lsp;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
@@ -20,6 +21,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
pub(crate) const SERVER: &str = "jdtls";
|
||||
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
|
||||
const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
pub(crate) mod exception_breakpoints;
|
||||
@@ -771,6 +773,19 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`.
|
||||
/// JDT's selection-based definition can return the functional interface method when the
|
||||
/// referenced method is inherited; the extension resolves the AST binding instead.
|
||||
pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult<Vec<Location>> {
|
||||
let uri = crate::path_to_uri_string(path);
|
||||
let value = self
|
||||
.jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)])
|
||||
.await?;
|
||||
let locations: Vec<lsp::Location> = serde_json::from_value(value).unwrap_or_default();
|
||||
let conv = self.conv(crate::text::Encoding::Utf16);
|
||||
Ok(locations.iter().filter_map(|location| conv.location(location)).collect())
|
||||
}
|
||||
|
||||
/// The jdtls instance serving `path` (a module directory or source file),
|
||||
/// started if needed and waited for.
|
||||
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
|
||||
|
||||
@@ -327,6 +327,25 @@ fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the caret is on the method name of a Java method reference (`Type::method`).
|
||||
/// A method reference can name a functional interface's method through JDT's selection-based
|
||||
/// definition when the referenced method is inherited, so ask the AST binding command instead.
|
||||
fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
|
||||
let line = text.line(pos.line as usize);
|
||||
let mut utf16 = 0u32;
|
||||
let mut at = line.len();
|
||||
for (i, c) in line.char_indices() {
|
||||
if utf16 >= pos.col {
|
||||
at = i;
|
||||
break;
|
||||
}
|
||||
utf16 += c.len_utf16() as u32;
|
||||
}
|
||||
let before = line[..at].trim_end();
|
||||
let Some(colon) = before.rfind("::") else { return false };
|
||||
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
}
|
||||
|
||||
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
|
||||
match e {
|
||||
RpcError::Cancelled => IdeError::cancelled(),
|
||||
@@ -1793,7 +1812,31 @@ impl LspManager {
|
||||
}
|
||||
let (method, cap, feature) = goto_method(kind);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
self.goto_in(&snap, &targets, method, pos, None, None).await
|
||||
let result = self.goto_in(&snap, &targets, method, pos, None, None).await;
|
||||
// JDT's selection-based definition can name the functional interface method for an
|
||||
// inherited method reference. Ask the Java binding command when that is what came back,
|
||||
// when the caret is on a method reference, or when the server found no target at all.
|
||||
let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos);
|
||||
if kind == GotoKind::Definition
|
||||
&& snap.language.as_str() == "java"
|
||||
&& (method_reference
|
||||
|| result.as_ref().is_ok_and(|locs| {
|
||||
locs.is_empty()
|
||||
|| locs.iter().any(|l| {
|
||||
let path = l.path.to_string_lossy().replace('\\', "/");
|
||||
let uri = l.uri.as_deref().unwrap_or_default();
|
||||
path.contains("java/util/function")
|
||||
|| path.contains("java.util.function")
|
||||
|| uri.contains("java/util/function")
|
||||
|| uri.contains("java.util.function")
|
||||
})
|
||||
}))
|
||||
&& let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await
|
||||
&& !found.is_empty()
|
||||
{
|
||||
return Ok(found);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Implementation, with the implementations found first passed to `partial` while
|
||||
@@ -4677,6 +4720,36 @@ mod code_action_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod java_method_reference_tests {
|
||||
use super::java_method_reference_at;
|
||||
use crate::text::DocText;
|
||||
use ide_core::Pos;
|
||||
|
||||
#[test]
|
||||
fn finds_the_method_name_of_a_method_reference() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
|
||||
let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32;
|
||||
assert!(java_method_reference_at(&text, Pos::new(0, col)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_whitespace_around_the_method_reference_operator() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);");
|
||||
let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32;
|
||||
assert!(java_method_reference_at(&text, Pos::new(0, col)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_regular_calls_and_the_referenced_type() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
|
||||
let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32;
|
||||
assert!(!java_method_reference_at(&text, Pos::new(0, type_col)));
|
||||
let call = DocText::new("wrapper.set(getUpdateTime(), now);");
|
||||
assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod did_change_content_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -613,11 +613,14 @@ impl PluginEngine {
|
||||
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
|
||||
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
|
||||
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
|
||||
if file.is_file() {
|
||||
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
|
||||
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
|
||||
// memory executable"), so the cache never hit and every activation compiled again.
|
||||
if let Ok(precompiled) = std::fs::read(&file) {
|
||||
// SAFETY: the cache directory belongs to the IDE (inside its plugins
|
||||
// directory) and is written only by `store_precompiled` below from
|
||||
// components this engine compiled; a corrupt file fails validation.
|
||||
match unsafe { Component::deserialize_file(&self.engine, &file) } {
|
||||
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
|
||||
Ok(component) => return Ok(component),
|
||||
Err(e) => {
|
||||
tracing::info!("discarding precompiled {}: {e}", file.display());
|
||||
@@ -3035,6 +3038,26 @@ impl Runtime {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The second compile of the same component loads the cached one instead of compiling and
|
||||
/// writing it again (a failed load deletes and rewrites the file).
|
||||
#[test]
|
||||
fn a_precompiled_component_is_loaded_from_the_cache() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
|
||||
let cache = tempfile::tempdir().unwrap();
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
let cached = || {
|
||||
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
|
||||
assert_eq!(entries.len(), 1, "{entries:?}");
|
||||
let file = entries[0].clone();
|
||||
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
|
||||
};
|
||||
let before = cached();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
assert_eq!(cached(), before, "loaded, not compiled and stored again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
|
||||
let fields = [
|
||||
|
||||
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.19.0",
|
||||
"1.20.1",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -311,6 +311,22 @@ fn network_args(r: &Repo) -> Vec<String> {
|
||||
NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect()
|
||||
}
|
||||
|
||||
/// Runs `git status`; when rename detection needs a blob that cannot be fetched (Restricted Mode
|
||||
/// sets `GIT_NO_LAZY_FETCH`, or the promisor remote is unreachable), retries once without it.
|
||||
/// The message is stable because `cli::command` pins `LC_ALL=C`.
|
||||
fn run_status(r: &Repo, mut args: Vec<&str>) -> IdeResult<crate::cli::Output> {
|
||||
let out = crate::cli::run_raw_env(r.root(), &args, None, &read_only())?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(out);
|
||||
}
|
||||
if String::from_utf8_lossy(&out.stderr).contains("promisor remote") {
|
||||
let at = args.iter().position(|a| *a == "status").map_or(args.len(), |i| i + 1);
|
||||
args.insert(at, "--no-renames");
|
||||
return crate::cli::run_env(r.root(), &args, None, &read_only());
|
||||
}
|
||||
Err(crate::cli::failure(&args, &out.stderr, &out.stdout, out.code))
|
||||
}
|
||||
|
||||
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
|
||||
/// In Restricted Mode git compares content without the repository's clean/process
|
||||
/// filters and doesn't ask submodules for their own status (which runs their config).
|
||||
@@ -323,7 +339,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
}
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = run_status(r, args)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -340,7 +356,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
|
||||
}
|
||||
args.push("--");
|
||||
args.extend(paths.iter().map(String::as_str));
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = run_status(r, args)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Partial clones (`--filter=blob:none`) with a sparse checkout: blobs outside the
|
||||
//! checkout are never fetched, and gitoxide's status cannot read them.
|
||||
|
||||
use ide_vcs::{ChangeKind, LogQuery, Repos};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false", "-c", "protocol.file.allow=always"])
|
||||
.args(args)
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn git_available() -> bool {
|
||||
Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
fn file_url(path: &Path) -> String {
|
||||
let path = path.to_string_lossy().replace('\\', "/");
|
||||
format!("file:///{}", path.trim_start_matches('/'))
|
||||
}
|
||||
|
||||
/// A blobless, cone-mode sparse clone of a small source repository; `docs/` and `app/` blobs stay remote.
|
||||
fn blobless_clone(base: &Path) -> std::path::PathBuf {
|
||||
let source = base.join("source");
|
||||
std::fs::create_dir_all(source.join("docs")).unwrap();
|
||||
std::fs::create_dir_all(source.join("app")).unwrap();
|
||||
git(&source, &["init", "-q"]);
|
||||
git(&source, &["config", "user.name", "Test User"]);
|
||||
git(&source, &["config", "user.email", "[email protected]"]);
|
||||
git(&source, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(source.join("README.md"), "hello\n").unwrap();
|
||||
let guide: String = (1..=200).map(|i| format!("line {i}\n")).collect();
|
||||
std::fs::write(source.join("docs/guide.txt"), &guide).unwrap();
|
||||
std::fs::write(source.join("app/main.rs"), "fn main() {}\n").unwrap();
|
||||
git(&source, &["add", "-A"]);
|
||||
git(&source, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let bare = base.join("bare.git");
|
||||
git(base, &["clone", "-q", "--bare", "source", "bare.git"]);
|
||||
git(&bare, &["config", "uploadpack.allowFilter", "true"]);
|
||||
git(&bare, &["config", "uploadpack.allowAnySHA1InWant", "true"]);
|
||||
|
||||
let work = base.join("work");
|
||||
git(base, &["clone", "-q", "--filter=blob:none", "--sparse", &file_url(&bare), "work"]);
|
||||
git(&work, &["config", "user.name", "Test User"]);
|
||||
git(&work, &["config", "user.email", "[email protected]"]);
|
||||
// A global `status.renames=false` would make the baseline pass without the fix.
|
||||
git(&work, &["config", "status.renames", "true"]);
|
||||
assert!(!work.join("app/main.rs").exists(), "app/ is outside the sparse checkout");
|
||||
work
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blobless_sparse_clone_keeps_its_repository_and_status() {
|
||||
if !git_available() {
|
||||
eprintln!("git is not available; skipping");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let work = blobless_clone(&base);
|
||||
let bare = base.join("bare.git");
|
||||
|
||||
std::fs::write(work.join("README.md"), "hello\nchanged\n").unwrap();
|
||||
std::fs::write(work.join("new.txt"), "new\n").unwrap();
|
||||
// A staged deletion of a never-fetched blob plus a near-identical addition: rename
|
||||
// detection would have to fetch the missing blob (`git rm --sparse` needs git 2.35+).
|
||||
git(&work, &["rm", "-q", "--sparse", "docs/guide.txt"]);
|
||||
let renamed: String = (1..=199).map(|i| format!("line {i}\n")).collect();
|
||||
std::fs::write(work.join("guide2.txt"), renamed).unwrap();
|
||||
git(&work, &["add", "guide2.txt"]);
|
||||
|
||||
// The promisor remote is gone: status must not need it.
|
||||
std::fs::rename(&bare, base.join("gone.git")).unwrap();
|
||||
|
||||
let repos = Repos::discover(&work, &|_| false).unwrap();
|
||||
let repo = repos.primary().expect("the partial clone is a repository");
|
||||
assert_eq!(repo.root(), work);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(repo.log(&LogQuery::default()).unwrap().len(), 1);
|
||||
|
||||
let status = repos.status().expect("status of a partial clone");
|
||||
let find = |rel: &str| status.iter().find(|f| f.rel_path == rel);
|
||||
let readme = find("README.md").expect("README.md listed");
|
||||
assert_eq!((readme.staged, readme.unstaged), (None, Some(ChangeKind::Modified)));
|
||||
let new = find("new.txt").expect("new.txt listed");
|
||||
assert_eq!(new.unstaged, Some(ChangeKind::Untracked));
|
||||
// Rename detection needs the never-fetched blob, so the retry without it lists an addition.
|
||||
let moved = find("guide2.txt").expect("guide2.txt listed");
|
||||
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
|
||||
let removed = find("docs/guide.txt").expect("docs/guide.txt listed");
|
||||
assert_eq!(removed.staged, Some(ChangeKind::Deleted));
|
||||
// Skip-worktree entries outside the checkout are not missing files.
|
||||
assert!(find("app/main.rs").is_none(), "{status:?}");
|
||||
assert_eq!(status.len(), 4, "{status:?}");
|
||||
|
||||
// The watcher's scoped refresh (a trusted project's `git status` with a pathspec) retries the
|
||||
// same way.
|
||||
repo.set_execution_allowed(true);
|
||||
let scoped = repo.status_paths(&[work.join("guide2.txt"), work.join("docs/guide.txt")]).expect("scoped status");
|
||||
let find = |rel: &str| scoped.iter().find(|f| f.rel_path == rel);
|
||||
let moved = find("guide2.txt").expect("guide2.txt listed");
|
||||
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
|
||||
assert_eq!(find("docs/guide.txt").expect("docs/guide.txt listed").staged, Some(ChangeKind::Deleted));
|
||||
assert_eq!(scoped.len(), 2, "{scoped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blobless_clone_still_detects_a_rename_between_local_blobs() {
|
||||
if !git_available() {
|
||||
eprintln!("git is not available; skipping");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let work = blobless_clone(&base);
|
||||
// README.md is inside the cone, so both sides of the rename are local blobs.
|
||||
git(&work, &["mv", "README.md", "README2.md"]);
|
||||
|
||||
let repos = Repos::discover(&work, &|_| false).unwrap();
|
||||
let repo = repos.primary().expect("the partial clone is a repository");
|
||||
let status = repos.status().expect("status of a partial clone");
|
||||
let moved = status.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
|
||||
assert_eq!(
|
||||
(moved.staged, moved.renamed_from.as_deref()),
|
||||
(Some(ChangeKind::Renamed), Some("README.md")),
|
||||
"{status:?}"
|
||||
);
|
||||
|
||||
repo.set_execution_allowed(true);
|
||||
let scoped = repo.status_paths(&[work.join("README2.md"), work.join("README.md")]).expect("scoped status");
|
||||
let moved = scoped.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
|
||||
assert_eq!(
|
||||
(moved.staged, moved.renamed_from.as_deref()),
|
||||
(Some(ChangeKind::Renamed), Some("README.md")),
|
||||
"{scoped:?}"
|
||||
);
|
||||
}
|
||||
@@ -99,7 +99,9 @@ impl FileMoves {
|
||||
|
||||
/// Applies `edit` (paths as before the move, as `workspace/willRenameFiles`
|
||||
/// returns them), then performs `moves`. Edited files are snapshotted in
|
||||
/// Local History first. On failure everything done so far is rolled back.
|
||||
/// Local History first. `apply_edit` must be transactional: on error it leaves none of
|
||||
/// its own changes behind, so a rejected edit keeps external changes. A failed
|
||||
/// file move rolls back the applied edits.
|
||||
/// Returns the id for [`undo`](Self::undo).
|
||||
pub fn perform(
|
||||
&self,
|
||||
@@ -134,11 +136,8 @@ impl FileMoves {
|
||||
}
|
||||
before.push(text);
|
||||
}
|
||||
if !paths.is_empty()
|
||||
&& let Err(e) = apply_edit(edit)
|
||||
{
|
||||
restore(documents, &paths, &before);
|
||||
return Err(e);
|
||||
if !paths.is_empty() {
|
||||
apply_edit(edit)?;
|
||||
}
|
||||
if let Err(e) = crate::file_ops::move_files(moves) {
|
||||
restore(documents, &paths, &before);
|
||||
@@ -305,6 +304,37 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_reference_edits_preserve_changes_after_the_snapshot() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
fs::write(root.join("source.ts"), "source\n").unwrap();
|
||||
fs::write(root.join("main.ts"), "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit {
|
||||
path: root.join("main.ts").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
let apply_edit = |edit: &WorkspaceEdit| {
|
||||
// An external writer lands after perform captured its rollback text.
|
||||
fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap();
|
||||
docs.apply_file_move_edits(edit)
|
||||
};
|
||||
let moves = FileMoves::new();
|
||||
let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }];
|
||||
let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync);
|
||||
assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n");
|
||||
assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n");
|
||||
assert!(!root.join("renamed.ts").exists());
|
||||
assert_eq!(moves.last(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moved_paths() {
|
||||
let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }];
|
||||
|
||||
@@ -242,3 +242,51 @@ for (const theme of ["dark", "light"] as const) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("a long agent form scrolls above the composer instead of being cut off", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1000, height: 520 });
|
||||
const fields = Array.from({ length: 5 }, (_, q) => ({
|
||||
name: `q${q + 1}`,
|
||||
title: `Question ${q + 1}`,
|
||||
kind: "choice" as const,
|
||||
required: true,
|
||||
options: Array.from({ length: 4 }, (_, o) => ({ value: `a${o + 1}`, label: `Answer ${q + 1}.${o + 1}` })),
|
||||
}));
|
||||
await page.evaluate(
|
||||
async ({ task, fields }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store: typeof AgentStore = await import(storePath);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[{ type: "permission", id: 1, title: "Plan the change", options: [], chosen: null, form: { fields } }],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, fields },
|
||||
);
|
||||
const card = page.getByRole("form", { name: "Plan the change" });
|
||||
await expect(card).toBeVisible();
|
||||
const composer = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await expect(composer).toBeInViewport();
|
||||
for (let q = 1; q <= 5; q++) {
|
||||
const last = card.getByRole("radio", { name: `Answer ${q}.4` });
|
||||
await last.scrollIntoViewIfNeeded();
|
||||
const box = (await last.boundingBox())!;
|
||||
const hit = await page.evaluate(
|
||||
({ x, y }) => document.elementFromPoint(x, y)?.closest("label")?.textContent ?? null,
|
||||
{ x: box.x + box.width / 2, y: box.y + box.height / 2 },
|
||||
);
|
||||
expect(hit).toContain(`Answer ${q}.4`);
|
||||
await last.check();
|
||||
}
|
||||
const submit = card.getByRole("button", { name: "Submit", exact: true });
|
||||
await submit.scrollIntoViewIfNeeded();
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeEnabled();
|
||||
});
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.19.0
|
||||
Bundle-Version: 1.20.1
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce
|
||||
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
|
||||
`access` is read/write/readWrite/unknown. Missing access metadata is unknown;
|
||||
old servers and ordinary LSP locations remain visible under either filter.
|
||||
`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name
|
||||
of a `Type::method` or `expr::method` reference through its AST binding and returns the
|
||||
declaring method's location. This keeps inherited methods on their parent declaration
|
||||
where JDT's selection-based definition may return the functional interface method.
|
||||
An absent or failing extension command uses standard LSP references, without access
|
||||
classification or toolbar controls. This includes errors during scope widening.
|
||||
The Rust bridge logs the failure once per project session. Cancelled requests and
|
||||
@@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.20.1.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
|
||||
Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception
|
||||
breakpoint intention; its reproducible SHA-256 is
|
||||
`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`.
|
||||
Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method
|
||||
references from their AST binding instead of JDT's selection result. Lombok-generated accessors
|
||||
without a source range fall back to their field or declaring type; its reproducible SHA-256 is
|
||||
`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
@@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat
|
||||
python3 java/java-usages/tests/hierarchy.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/implementations.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/exception-type.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/method-reference.py /path/to/jdtls
|
||||
```
|
||||
|
||||
The harnesses select the JDT LS configuration for the current platform. The first
|
||||
|
||||
Бінарний файл не відображається.
@@ -27,6 +27,9 @@
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.navigation.MethodReferenceDefinitionCommand">
|
||||
<command id="openidea.java.methodReferenceDefinition"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
|
||||
<command id="openidea.java.hierarchy.members"/>
|
||||
<command id="openidea.java.hierarchy.refactor"/>
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package ai.openidea.navigation;
|
||||
|
||||
import ai.openidea.Documents;
|
||||
import java.util.List;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.jdt.core.IField;
|
||||
import org.eclipse.jdt.core.IMember;
|
||||
import org.eclipse.jdt.core.IMethod;
|
||||
import org.eclipse.jdt.core.IType;
|
||||
import org.eclipse.jdt.core.ITypeRoot;
|
||||
import org.eclipse.jdt.core.dom.ASTNode;
|
||||
import org.eclipse.jdt.core.dom.CompilationUnit;
|
||||
import org.eclipse.jdt.core.dom.ExpressionMethodReference;
|
||||
import org.eclipse.jdt.core.dom.IMethodBinding;
|
||||
import org.eclipse.jdt.core.dom.ITypeBinding;
|
||||
import org.eclipse.jdt.core.dom.MethodReference;
|
||||
import org.eclipse.jdt.core.dom.NodeFinder;
|
||||
import org.eclipse.jdt.core.dom.SimpleName;
|
||||
import org.eclipse.jdt.core.dom.SuperMethodReference;
|
||||
import org.eclipse.jdt.core.dom.TypeMethodReference;
|
||||
import org.eclipse.jdt.core.manipulation.CoreASTProvider;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/**
|
||||
* Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration
|
||||
* of the referenced method. JDT's selection-based definition request can return the
|
||||
* functional interface method ({@code Function.apply}) when the method is inherited;
|
||||
* bindings retain the actual method identity instead.
|
||||
*/
|
||||
public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
Documents.awaitChanges(monitor);
|
||||
String uri = (String) arguments.get(0);
|
||||
int line = ((Number) arguments.get(1)).intValue();
|
||||
int column = ((Number) arguments.get(2)).intValue();
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
|
||||
if (root == null || !root.exists()) return List.of();
|
||||
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
|
||||
if (ast == null) return List.of();
|
||||
int offset = JsonRpcHelpers.toOffset(root, line, column);
|
||||
if (offset < 0) return List.of();
|
||||
|
||||
MethodReference reference = enclosingReference(ast, offset);
|
||||
if (reference == null) return List.of();
|
||||
SimpleName name = methodName(reference);
|
||||
if (name == null) return List.of();
|
||||
int start = name.getStartPosition();
|
||||
if (offset < start || offset > start + name.getLength()) return List.of();
|
||||
|
||||
IMethodBinding binding = reference.resolveMethodBinding();
|
||||
if (binding == null) return List.of();
|
||||
IMethodBinding declaration = binding.getMethodDeclaration();
|
||||
if (declaration == null) return List.of();
|
||||
Location location = locationOf(declaration);
|
||||
return location == null ? List.of() : List.of(location);
|
||||
}
|
||||
|
||||
/**
|
||||
* The declaration's source location. Lombok-generated accessors have a binding and a Java
|
||||
* element but no source range; then the field the accessor reads (or the declaring type)
|
||||
* is the closest source declaration. Without this fallback the standard definition request
|
||||
* stays at the functional interface method.
|
||||
*/
|
||||
private static Location locationOf(IMethodBinding declaration) throws Exception {
|
||||
var element = declaration.getJavaElement();
|
||||
Location location = element == null ? null : JDTUtils.toLocation(element);
|
||||
if (location != null) return location;
|
||||
if (element instanceof IMember member && member.getClassFile() != null)
|
||||
return JDTUtils.toLocation(member.getClassFile());
|
||||
|
||||
ITypeBinding owner = declaration.getDeclaringClass();
|
||||
if (owner == null) return null;
|
||||
var ownerElement = owner.getJavaElement();
|
||||
if (!(ownerElement instanceof IType type) || !type.exists()) return null;
|
||||
|
||||
for (IMethod method : type.getMethods()) {
|
||||
if (!method.getElementName().equals(declaration.getName())) continue;
|
||||
if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue;
|
||||
location = JDTUtils.toLocation(method);
|
||||
if (location != null) return location;
|
||||
}
|
||||
|
||||
String fieldName = propertyName(declaration.getName());
|
||||
if (fieldName != null) {
|
||||
IField field = type.getField(fieldName);
|
||||
if (field.exists()) {
|
||||
location = JDTUtils.toLocation(field);
|
||||
if (location != null) return location;
|
||||
}
|
||||
}
|
||||
return JDTUtils.toLocation(type);
|
||||
}
|
||||
|
||||
/** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */
|
||||
private static String propertyName(String methodName) {
|
||||
String rest;
|
||||
if (methodName.startsWith("get") || methodName.startsWith("set")) {
|
||||
rest = methodName.substring(3);
|
||||
} else if (methodName.startsWith("is")) {
|
||||
rest = methodName.substring(2);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (rest.isEmpty()) return null;
|
||||
if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) {
|
||||
return rest;
|
||||
}
|
||||
return Character.toLowerCase(rest.charAt(0)) + rest.substring(1);
|
||||
}
|
||||
|
||||
private static MethodReference enclosingReference(CompilationUnit ast, int offset) {
|
||||
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
|
||||
for (ASTNode node = leaf; node != null; node = node.getParent()) {
|
||||
if (node instanceof MethodReference reference) return reference;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static SimpleName methodName(MethodReference reference) {
|
||||
return switch (reference) {
|
||||
case TypeMethodReference type -> type.getName();
|
||||
case ExpressionMethodReference expression -> expression.getName();
|
||||
case SuperMethodReference superReference -> superReference.getName();
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
|
||||
|
||||
Each case puts the caret on a method reference's name and checks that
|
||||
`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited
|
||||
method on its parent, not the functional interface method), and nothing elsewhere.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
home = pathlib.Path(sys.argv[1]).resolve()
|
||||
bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-'))
|
||||
config = work / 'config'
|
||||
config.mkdir()
|
||||
system, machine = platform.system(), platform.machine().lower()
|
||||
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
|
||||
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
|
||||
config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file())
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
(project / 'src/app').mkdir(parents=True)
|
||||
(project / '.project').write_text('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
sources = {
|
||||
'Parent.java': '''package app;
|
||||
|
||||
public class Parent {
|
||||
public String getGoodsSpace() {
|
||||
return "space";
|
||||
}
|
||||
|
||||
public static String describe(Object o) {
|
||||
return String.valueOf(o);
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Child.java': '''package app;
|
||||
|
||||
public class Child extends Parent {
|
||||
public int own() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Main.java': '''package app;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Main {
|
||||
void run(List<Child> children) {
|
||||
Function<Child, String> inherited = Child::getGoodsSpace;
|
||||
Function<Child, Integer> own = Child::own;
|
||||
Function<Object, String> statics = Child::describe;
|
||||
children.forEach(System.out::println);
|
||||
String plain = new Child().getGoodsSpace();
|
||||
}
|
||||
}
|
||||
''',
|
||||
}
|
||||
for name, text in sources.items():
|
||||
(project / 'src/app' / name).write_text(text)
|
||||
uri = lambda name: (project / 'src/app' / name).as_uri()
|
||||
|
||||
log = (work / 'stderr.log').open('w')
|
||||
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
|
||||
messages = queue.Queue()
|
||||
lock = threading.Lock()
|
||||
|
||||
|
||||
def send(message):
|
||||
data = json.dumps(message).encode()
|
||||
with lock:
|
||||
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
|
||||
proc.stdin.flush()
|
||||
|
||||
|
||||
def read():
|
||||
while True:
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if not line:
|
||||
return
|
||||
if line == b'\r\n':
|
||||
break
|
||||
k, v = line.decode().split(':', 1)
|
||||
headers[k.lower()] = v.strip()
|
||||
message = json.loads(proc.stdout.read(int(headers['content-length'])))
|
||||
if 'method' in message and 'id' in message:
|
||||
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
|
||||
else:
|
||||
messages.put(message)
|
||||
|
||||
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
seq = 0
|
||||
|
||||
|
||||
def request(method, params):
|
||||
global seq
|
||||
seq += 1
|
||||
send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params})
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
|
||||
if msg.get('id') == seq:
|
||||
if 'error' in msg:
|
||||
raise RuntimeError(msg['error'])
|
||||
return msg.get('result')
|
||||
raise TimeoutError(method)
|
||||
|
||||
|
||||
|
||||
|
||||
def where(loc):
|
||||
return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line'])
|
||||
|
||||
|
||||
def line_of(file, needle):
|
||||
return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t)
|
||||
|
||||
|
||||
CASES = [
|
||||
('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]),
|
||||
('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]),
|
||||
('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]),
|
||||
('Child::getGoodsSpace', 'Child', 2, []),
|
||||
('new Child().getGoodsSpace', 'getGoodsSpace', 2, []),
|
||||
]
|
||||
|
||||
try:
|
||||
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
|
||||
commands = init['capabilities']['executeCommandProvider']['commands']
|
||||
assert 'openidea.java.methodReferenceDefinition' in commands, commands
|
||||
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
|
||||
for name, text in sources.items():
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}})
|
||||
request('java/buildWorkspace', True)
|
||||
failed = []
|
||||
lines = sources['Main.java'].splitlines()
|
||||
for line_needle, needle, at, expected in CASES:
|
||||
line = next(i for i, t in enumerate(lines) if line_needle in t)
|
||||
column = lines[line].index(needle, lines[line].index(line_needle)) + at
|
||||
got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]})
|
||||
got = [where(l) for l in got or []]
|
||||
ok = got == expected
|
||||
if not ok:
|
||||
failed.append((line_needle, needle))
|
||||
print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got)
|
||||
# The functional interface's method is what the standard request answers for the inherited case.
|
||||
line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t)
|
||||
std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}})
|
||||
print('standard definition:', std)
|
||||
assert not failed, failed
|
||||
print('method-reference: all cases passed')
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=20)
|
||||
print('Evidence:', work, file=sys.stderr)
|
||||
+1
-1
@@ -105,7 +105,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-openidea-ai-completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "openidea-plugin-openidea-ai-completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
fbaa75cf43cf1188b6b5f7621a94739a0f91ba4c8bd13b94fe78a2e8aa17bcc9
|
||||
385b624ee9593d759a2ce22d4427edc0f06954d0e98f458a77d780e5a3dbe92a
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "openidea.ai-completion"
|
||||
name = "AI Completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
description = "Inline code suggestions (ghost text) from a local model (Ollama) or OpenAI, as you type."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
change-notes = "0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
|
||||
change-notes = "0.1.1 — say why no suggestions appear (network access, missing model, Ollama not running) and choose the model with AI Completion: Set Model. 0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
|
||||
categories = ["ai"]
|
||||
engines.openidea = "^1.0"
|
||||
wasm = "dist/plugin.wasm"
|
||||
@@ -43,3 +43,8 @@ category = "AI Completion"
|
||||
id = "set-endpoint"
|
||||
title = "AI Completion: Set Endpoint URL"
|
||||
category = "AI Completion"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "set-model"
|
||||
title = "AI Completion: Set Model"
|
||||
category = "AI Completion"
|
||||
@@ -22,6 +22,8 @@ const SUFFIX_CHARS: usize = 1000;
|
||||
pub struct AiCompletion {
|
||||
/// Why the last request failed, so it is logged once rather than per keystroke.
|
||||
last_error: Option<String>,
|
||||
/// The last failure shown to the user, so a notice is not repeated.
|
||||
last_notice: Option<String>,
|
||||
}
|
||||
|
||||
struct Config {
|
||||
@@ -48,6 +50,34 @@ fn config() -> Config {
|
||||
Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") }
|
||||
}
|
||||
|
||||
/// What to tell the user about a failed request: why, and what to do.
|
||||
pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result<String, Error>) -> String {
|
||||
match failure {
|
||||
Err(Error::Denied(_)) => format!(
|
||||
"AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion."
|
||||
),
|
||||
Ok(text) if !openai && text.starts_with("HTTP 404") => format!(
|
||||
"The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model."
|
||||
),
|
||||
Err(Error::Failed(e)) if e.contains("timed out") => format!(
|
||||
"{endpoint} took too long to answer; the model may still be loading, or be too large for this machine."
|
||||
),
|
||||
Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"),
|
||||
Ok(text) => format!("{endpoint} answered {text}"),
|
||||
Err(e) => format!("Could not reach {endpoint}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The command's argument, or what the user types (pre-filled with `current`);
|
||||
/// `None` when dismissed.
|
||||
fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result<Option<String>, Error> {
|
||||
let value = match arg {
|
||||
Some(a) => Some(a.to_owned()),
|
||||
None => host::input(prompt, Some(current))?,
|
||||
};
|
||||
Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()))
|
||||
}
|
||||
|
||||
/// The last `max` characters of `s` (on a char boundary).
|
||||
fn tail(s: &str, max: usize) -> &str {
|
||||
match s.char_indices().rev().nth(max.saturating_sub(1)) {
|
||||
@@ -112,14 +142,21 @@ impl Providers for AiCompletion {
|
||||
// Superseded by the next keystroke: nothing to report.
|
||||
Err(Error::Cancelled) => None,
|
||||
other => {
|
||||
let msg = match other {
|
||||
Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)),
|
||||
let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200)));
|
||||
let msg = match &failure {
|
||||
Ok(m) => m.clone(),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
if self.last_error.as_ref() != Some(&msg) {
|
||||
host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint));
|
||||
self.last_error = Some(msg);
|
||||
}
|
||||
// Otherwise a failure only shows in the IDE log, where nobody looks.
|
||||
let notice = advice(&c.endpoint, &c.model, c.openai, &failure);
|
||||
if self.last_notice.as_ref() != Some(¬ice) {
|
||||
host::notify(NotificationLevel::Warning, "AI Completion", ¬ice);
|
||||
self.last_notice = Some(notice);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -144,11 +181,23 @@ impl Plugin for AiCompletion {
|
||||
}
|
||||
}
|
||||
"set-endpoint" => {
|
||||
let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://"));
|
||||
let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?;
|
||||
storage::set("endpoint", url)?;
|
||||
let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err("give the endpoint URL, e.g. http://localhost:11434".into());
|
||||
}
|
||||
storage::set("endpoint", &url)?;
|
||||
format!("Using {url}.")
|
||||
}
|
||||
"set-model" => {
|
||||
let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
storage::set("model", &model)?;
|
||||
format!("Using the model {model}.")
|
||||
}
|
||||
"toggle" => {
|
||||
let enabled = !config().enabled;
|
||||
storage::set("enabled", if enabled { "true" } else { "false" })?;
|
||||
@@ -156,6 +205,8 @@ impl Plugin for AiCompletion {
|
||||
}
|
||||
_ => return Err(Error::NotFound(format!("command {id}"))),
|
||||
};
|
||||
// A new setting may fix (or change) the failure: tell again.
|
||||
self.last_notice = None;
|
||||
host::notify(NotificationLevel::Info, "AI Completion", &msg);
|
||||
Ok(Some(msg))
|
||||
}
|
||||
@@ -228,7 +279,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_when_cancelled_denied_or_mid_word() {
|
||||
fn quiet_when_cancelled_or_mid_word() {
|
||||
let host = MockHost::install().with_capabilities(&["storage"]);
|
||||
let mut p = AiCompletion::default();
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied");
|
||||
@@ -243,4 +294,61 @@ mod tests {
|
||||
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
|
||||
assert_eq!(host2.requests().len(), 1, "disabled: no request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tells_the_user_why_once_and_what_to_do() {
|
||||
// Installed without the optional network permission (the default for it).
|
||||
let host = MockHost::install().with_capabilities(&["storage"]);
|
||||
let mut p = AiCompletion::default();
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none());
|
||||
let notes = host.notifications();
|
||||
assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}");
|
||||
assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body);
|
||||
|
||||
// A model that is not pulled: Ollama answers 404.
|
||||
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
|
||||
host.on_fetch(|_| {
|
||||
Ok(HttpResponse {
|
||||
status: 404,
|
||||
headers: vec![],
|
||||
body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"#
|
||||
.to_vec(),
|
||||
})
|
||||
});
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
let body = &host.notifications()[0].body;
|
||||
assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}");
|
||||
|
||||
// Ollama not running.
|
||||
host.on_fetch(|_| Err(Error::Failed("connection refused".into())));
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(host.notifications()[1].body.contains("Is it running?"));
|
||||
host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into())));
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(host.notifications()[2].body.contains("took too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_model_takes_an_argument_or_asks() {
|
||||
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
|
||||
host.on_fetch(|_| {
|
||||
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
|
||||
});
|
||||
let mut p = AiCompletion::default();
|
||||
p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap();
|
||||
assert_eq!(config().model, "qwen2.5-coder:7b");
|
||||
// From the command palette: no argument, so it asks.
|
||||
host.answer_next_prompt(Some(&["codellama:7b-code"]));
|
||||
p.run_command("set-model", &host.invocation(), None).unwrap();
|
||||
p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap();
|
||||
let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(body["model"], "codellama:7b-code");
|
||||
// Dismissed: nothing changes.
|
||||
assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None);
|
||||
assert_eq!(config().model, "codellama:7b-code");
|
||||
host.answer_next_prompt(Some(&["http://127.0.0.1:11434"]));
|
||||
p.run_command("set-endpoint", &host.invocation(), None).unwrap();
|
||||
assert_eq!(config().endpoint, "http://127.0.0.1:11434");
|
||||
}
|
||||
}
|
||||
@@ -11748,6 +11748,12 @@ export type NavigationFiles = {
|
||||
paths: IpcPath[],
|
||||
indexing: boolean,
|
||||
extensions: string[],
|
||||
/**
|
||||
* In-scope files matching `extensions`; `paths` holds the first
|
||||
* `MAX_NAVIGATION_FILES` of them.
|
||||
*/
|
||||
total: number,
|
||||
truncated: boolean,
|
||||
};
|
||||
|
||||
export type NavigationResult = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useId, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { AgentForm, AgentFormField, AgentTask } from "@/bindings";
|
||||
import { Button, Checkbox, Input, Radio, T } from "@/ui";
|
||||
import type { PermissionEntry } from "./permission";
|
||||
@@ -48,7 +49,7 @@ export function FormCard({ task, entry, form }: { task: AgentTask; entry: Permis
|
||||
};
|
||||
return (
|
||||
<form
|
||||
className={styles.questionCard}
|
||||
className={clsx(styles.questionCard, styles.questionCardPinned)}
|
||||
aria-label={entry.title}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1632,9 +1632,11 @@
|
||||
font-size: var(--agent-fs-ui, var(--fs-ui));
|
||||
container: question-card / inline-size;
|
||||
}
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. */
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. It scrolls within at most
|
||||
half the window, and less when the session is shorter, so the composer and the card's buttons stay in view. */
|
||||
.questionCardPinned {
|
||||
flex: none;
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
width: 100%;
|
||||
|
||||
@@ -245,7 +245,11 @@ describe("remote attach requests", () => {
|
||||
port: 9229,
|
||||
localRoot: "/p",
|
||||
remoteRoot: "/usr/src/app",
|
||||
autoAttachChildProcesses: false,
|
||||
});
|
||||
// Without a remote root the program may be local, and its child processes are followed.
|
||||
const local = JSON.parse(remoteAttachConfig(configOf(nodeRemoteType), "/p")!.extraJson!);
|
||||
expect(local).not.toHaveProperty("autoAttachChildProcesses");
|
||||
});
|
||||
|
||||
it("Attach to Node.js reconnects automatically only when the option is on", () => {
|
||||
|
||||
@@ -502,7 +502,11 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
|
||||
type: "pwa-node",
|
||||
address: host,
|
||||
port: portOf(p, 9229),
|
||||
...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}),
|
||||
// On a loopback address (a published container port, an SSH tunnel) js-debug makes the
|
||||
// program require its child-process bootloader by a path on this machine. Behind a
|
||||
// remote root that path is missing: tsx's esbuild worker dies of it and the program
|
||||
// waits for that worker forever.
|
||||
...(map ? { localRoot: map.local, remoteRoot: map.remote, autoAttachChildProcesses: false } : {}),
|
||||
skipFiles: skip ? ["<node_internals>/**", "**/node_modules/**"] : [],
|
||||
...(p.restart === "true" ? { restart: true } : {}),
|
||||
});
|
||||
|
||||
@@ -5,7 +5,8 @@ import { useProject } from "@/platform/project";
|
||||
import { usePlugins } from "./store";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { lspDoc } from "@/editor/lsp/lsp";
|
||||
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
|
||||
import { notifications, provideNotificationService, synchronizeDocumentIndexes } from "@/workbench/contributions";
|
||||
import { setLocale, txTemplate, useI18n } from "@/platform/i18n";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
files: vi.fn(),
|
||||
@@ -215,3 +216,29 @@ it("keeps unrelated language-server queries available when plugin discovery fail
|
||||
await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true);
|
||||
expect(mocks.index).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("indexes the first files of a large project and says how many it covers, in one sentence", async () => {
|
||||
mocks.files.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { paths: ["/project/A.java"], indexing: false, extensions: ["java"], total: 28684, truncated: true },
|
||||
});
|
||||
useProject.setState({ project: { root: "/project", name: "big-demo", trusted: true } as never });
|
||||
const notify = vi.fn();
|
||||
const previous = notifications();
|
||||
const locale = useI18n.getState().locale;
|
||||
provideNotificationService({ notify } as never);
|
||||
try {
|
||||
await setLocale("zh");
|
||||
off = startPluginNavigation();
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
expect(mocks.index.mock.calls[0]?.[0]).toEqual(["/project/A.java"]);
|
||||
expect(notify).toHaveBeenCalledTimes(1);
|
||||
const body = notify.mock.calls[0]![0].body;
|
||||
expect(body).toBe("插件导航仅覆盖 big-demo 中 28,684 个文件里的 1 个;可排除文件夹以缩小范围");
|
||||
// The balloon and the OS toast look the text up again: it stays whole.
|
||||
expect(txTemplate(body)).toBe(body);
|
||||
} finally {
|
||||
provideNotificationService(previous);
|
||||
await setLocale(locale);
|
||||
}
|
||||
});
|
||||
@@ -47,6 +47,19 @@ export function startPluginNavigation(): () => void {
|
||||
body: String(error),
|
||||
});
|
||||
}
|
||||
let reportedTruncated = false;
|
||||
function reportTruncated(count: number, total: number) {
|
||||
if (reportedTruncated) return;
|
||||
reportedTruncated = true;
|
||||
const project = useProject.getState().project;
|
||||
const name = project?.displayName || project?.name || "";
|
||||
notifications().notify({
|
||||
group: "plugins",
|
||||
level: "warning",
|
||||
title: "Plugin navigation indexing incomplete",
|
||||
body: tx`Plugin navigation covers ${count.toLocaleString()} of ${total.toLocaleString()} files in ${name}; exclude folders to narrow it`,
|
||||
});
|
||||
}
|
||||
let fileExtensions = new Set<string>();
|
||||
const extensions = () => fileExtensions;
|
||||
const eligible = (path: string) => extensions().has(path.split(".").pop() ?? "");
|
||||
@@ -142,6 +155,7 @@ export function startPluginNavigation(): () => void {
|
||||
inventory.paths.forEach((p) => known.add(p));
|
||||
queue(fresh);
|
||||
queue([...views.values()], true);
|
||||
if (inventory.truncated) reportTruncated(inventory.paths.length, inventory.total);
|
||||
} catch (error) {
|
||||
discovered = false;
|
||||
discoveryFailed = true;
|
||||
@@ -165,6 +179,7 @@ export function startPluginNavigation(): () => void {
|
||||
discoveryFailed = false;
|
||||
discovery = null;
|
||||
reportedError = false;
|
||||
reportedTruncated = false;
|
||||
notify();
|
||||
if (ready())
|
||||
void call(commands.pluginNavigationInvalidate(null))
|
||||
|
||||
@@ -4810,5 +4810,6 @@
|
||||
"{count} files aren't in the Xcode project": "{count} files aren't in the Xcode project",
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
|
||||
"Open in Xcode": "Open in Xcode"
|
||||
"Open in Xcode": "Open in Xcode",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
|
||||
}
|
||||
@@ -11463,5 +11463,6 @@
|
||||
"{count} files aren't in the Xcode project": "{count} 个文件不在 Xcode 项目中",
|
||||
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
|
||||
"Open in Xcode": "在 Xcode 中打开"
|
||||
"Open in Xcode": "在 Xcode 中打开",
|
||||
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача