дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-21 00:50:47 +02:00
Порівняти коміти
13
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
4867c99734 | ||
|
|
43f7b6db25 | ||
|
|
92fd29707d | ||
|
|
7482b27518 | ||
|
|
a949a93454 | ||
|
|
16cfb63bda | ||
|
|
6b1d5aca50 | ||
|
|
b5bdab0a63 | ||
|
|
c3e19c93d3 | ||
|
|
b33762b4c8 | ||
|
|
41087d074b | ||
|
|
fa8dd2465a | ||
|
|
ea965c7e2d |
No files matched your search
Створено
+47
-46
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4169,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4212,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4226,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4265,7 +4265,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4279,7 +4279,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4308,7 +4308,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4344,7 +4344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4357,7 +4357,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4378,7 +4378,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4390,7 +4390,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4403,7 +4403,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4421,7 +4421,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4495,7 +4495,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4514,7 +4514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4536,7 +4536,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4548,7 +4548,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4565,7 +4565,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4574,7 +4574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4585,7 +4585,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4644,7 +4644,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4672,7 +4672,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4691,7 +4691,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4714,7 +4714,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4737,7 +4737,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4751,7 +4751,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4771,7 +4771,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4795,7 +4795,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4811,7 +4811,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"flate2",
|
||||
@@ -4834,7 +4834,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4855,7 +4855,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4868,7 +4868,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4893,7 +4893,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4906,7 +4906,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4921,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4934,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4947,7 +4947,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4968,7 +4968,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4989,7 +4989,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5015,7 +5015,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5031,7 +5031,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6660,7 +6660,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6734,6 +6734,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.47"
|
||||
version = "0.1.48"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1241,10 +1241,13 @@ fn file_stamp(path: &Path) -> FileStamp {
|
||||
std::fs::metadata(path).ok().map(|m| (m.modified().ok(), m.len()))
|
||||
}
|
||||
|
||||
/// The POM files a reactor walk read or looked for, and the module folders it found outside the root.
|
||||
/// The POM files a reactor walk read or looked for, the module folders it found outside the
|
||||
/// root, and the folders of every project in the reactor (canonical, the root's first).
|
||||
#[derive(Clone)]
|
||||
struct ReactorScan {
|
||||
stamps: Vec<(PathBuf, FileStamp)>,
|
||||
dirs: Vec<PathBuf>,
|
||||
members: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
/// Folders of the modules that the reactor of `root/pom.xml` lists outside `root`
|
||||
@@ -1254,18 +1257,28 @@ struct ReactorScan {
|
||||
/// Callers keep the outermost directory only. Memoized on the POMs' modification times and
|
||||
/// sizes: content roots are read on hot paths (every references search, Find in Files).
|
||||
pub fn reactor_external_dirs(root: &Path, profiles: &[String], unlinked: &[String]) -> Vec<PathBuf> {
|
||||
reactor(root, profiles, unlinked).dirs
|
||||
}
|
||||
|
||||
/// Folders of every project in the reactor of `root/pom.xml` (canonical): `root` itself and its
|
||||
/// modules, theirs in turn, including those of the active `profiles`. A POM elsewhere below `root`
|
||||
/// that no `<module>` reaches is a separate build.
|
||||
pub fn reactor_member_dirs(root: &Path, profiles: &[String]) -> Vec<PathBuf> {
|
||||
reactor(root, profiles, &[]).members
|
||||
}
|
||||
|
||||
fn reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> ReactorScan {
|
||||
type Memo = HashMap<(PathBuf, Vec<String>, Vec<String>), ReactorScan>;
|
||||
static MEMO: std::sync::LazyLock<Mutex<Memo>> = std::sync::LazyLock::new(Default::default);
|
||||
let key = (root.to_path_buf(), profiles.to_vec(), unlinked.to_vec());
|
||||
if let Some(scan) = MEMO.lock().unwrap_or_else(|e| e.into_inner()).get(&key)
|
||||
&& scan.stamps.iter().all(|(path, stamp)| file_stamp(path) == *stamp)
|
||||
{
|
||||
return scan.dirs.clone();
|
||||
return scan.clone();
|
||||
}
|
||||
let scan = scan_reactor(root, profiles, unlinked);
|
||||
let dirs = scan.dirs.clone();
|
||||
MEMO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, scan);
|
||||
dirs
|
||||
MEMO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, scan.clone());
|
||||
scan
|
||||
}
|
||||
|
||||
/// Reads only the POMs the reactor lists (no parent resolution and no directory walk).
|
||||
@@ -1274,7 +1287,8 @@ fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> Reacto
|
||||
let chosen = Resolver::new(None, profiles);
|
||||
let unlinked: HashSet<String> = unlinked.iter().map(|p| normalized_pom(p.trim())).collect();
|
||||
let first = root.join("pom.xml");
|
||||
let mut scan = ReactorScan { stamps: vec![(first.clone(), file_stamp(&first))], dirs: Vec::new() };
|
||||
let mut scan =
|
||||
ReactorScan { stamps: vec![(first.clone(), file_stamp(&first))], dirs: Vec::new(), members: Vec::new() };
|
||||
let mut seen: HashSet<PathBuf> = HashSet::new();
|
||||
let mut pending = vec![first];
|
||||
while let Some(path) = pending.pop() {
|
||||
@@ -1288,6 +1302,7 @@ fn scan_reactor(root: &Path, profiles: &[String], unlinked: &[String]) -> Reacto
|
||||
let Some(pom) = xml::read_text(&path).as_deref().and_then(parse_pom) else { continue };
|
||||
let dir = path.parent().unwrap_or(root).to_path_buf();
|
||||
let dir_canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
scan.members.push(dir_canon.clone());
|
||||
if !dir_canon.starts_with(&canonical_root) {
|
||||
if canonical_root.starts_with(&dir_canon) {
|
||||
continue;
|
||||
|
||||
@@ -1062,11 +1062,13 @@ mod tests {
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_environment() {
|
||||
let root = std::path::Path::new("/openidea-test-process/project");
|
||||
// Absolute on the platform: the search path drops relative entries.
|
||||
let devshell = if cfg!(windows) { r"C:\nix\store\x-devshell\bin" } else { "/nix/store/x-devshell/bin" };
|
||||
crate::project_env::set(
|
||||
root,
|
||||
vec![
|
||||
("OPENIDEA_PROJECT_VAR".into(), Some("devshell".into())),
|
||||
("PATH".into(), Some("/nix/store/x-devshell/bin".into())),
|
||||
("PATH".into(), Some(devshell.into())),
|
||||
("OPENIDEA_PROJECT_UNSET".into(), None),
|
||||
],
|
||||
);
|
||||
@@ -1075,7 +1077,7 @@ mod tests {
|
||||
let mut inside = Command::new("true");
|
||||
inside.current_dir(root.join("src")).env("OPENIDEA_PROJECT_VAR", "call site");
|
||||
host_env(&mut inside);
|
||||
assert_eq!(get(&inside, "PATH"), Some(Some("/nix/store/x-devshell/bin".into())));
|
||||
assert_eq!(get(&inside, "PATH"), Some(Some(devshell.into())));
|
||||
assert_eq!(get(&inside, "OPENIDEA_PROJECT_UNSET"), Some(None));
|
||||
assert_eq!(get(&inside, "OPENIDEA_PROJECT_VAR"), Some(Some("call site".into())), "the call site's value wins");
|
||||
|
||||
@@ -1093,7 +1095,7 @@ mod tests {
|
||||
assert_eq!(host_var_os_in(root, "OPENIDEA_PROJECT_VAR"), Some("devshell".into()));
|
||||
assert_eq!(host_var_os("OPENIDEA_PROJECT_VAR"), None);
|
||||
let search = crate::tool_path::search_path_in(root);
|
||||
assert_eq!(std::env::split_paths(&search).next(), Some("/nix/store/x-devshell/bin".into()));
|
||||
assert_eq!(std::env::split_paths(&search).next(), Some(devshell.into()));
|
||||
crate::project_env::remove(root);
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
@@ -216,7 +216,21 @@ pub(crate) async fn serve(
|
||||
}
|
||||
}
|
||||
if holding {
|
||||
let _ = write.send(call("Fetch.disable", json!({})).1).await;
|
||||
let (disable, command) = call("Fetch.disable", json!({}));
|
||||
if write.send(command).await.is_ok() {
|
||||
// Wait until the proxy has disabled interception before closing the
|
||||
// socket. Dropping it with unread replies can reset the connection.
|
||||
let _ = tokio::time::timeout(REQUEST_TIMEOUT, async {
|
||||
while let Some(Ok(message)) = read.next().await {
|
||||
let Ok(text) = message.to_text() else { continue };
|
||||
let Ok(reply) = serde_json::from_str::<Value>(text) else { continue };
|
||||
if reply.get("id").and_then(Value::as_u64) == Some(disable) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
let _ = write.close().await;
|
||||
}
|
||||
|
||||
@@ -108,27 +108,53 @@ fn detected_and_saved(
|
||||
}
|
||||
|
||||
/// Folders of the Maven / Gradle builds linked explicitly (Add Maven Projects, linked Gradle
|
||||
/// builds) that detection did not reach: deeper than its folder search and outside the builds
|
||||
/// it found, which own their nested folders.
|
||||
/// builds) that detection did not reach: deeper than its folder search, or inside the folder of
|
||||
/// a build it found without being one of that build's projects (a separate build nested there).
|
||||
fn linked_build_dirs(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
gradle: Option<&[ide_build::GradleModel]>,
|
||||
detected: &[RunConfig],
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
let found: Vec<_> = detected
|
||||
.iter()
|
||||
.filter(|c| matches!(c.kind.as_str(), "maven" | "gradle"))
|
||||
.map(|c| ide_core::project_roots::resolve(root, c.cwd.as_deref().unwrap_or(Path::new(""))))
|
||||
.collect();
|
||||
let found = |kind: &str| -> Vec<std::path::PathBuf> {
|
||||
let mut dirs: Vec<_> = detected
|
||||
.iter()
|
||||
.filter(|c| c.kind == kind)
|
||||
.map(|c| ide_core::project_roots::resolve(root, c.cwd.as_deref().unwrap_or(Path::new(""))))
|
||||
.collect();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
};
|
||||
let canonical = |dir: &Path| dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
let profiles = settings.languages.java.maven.profiles(&[]);
|
||||
let maven_builds = found("maven");
|
||||
let poms = settings.languages.java.maven.linked_projects.iter().filter_map(|pom| {
|
||||
let pom = root.join(pom.trim());
|
||||
pom.is_file().then(|| pom.parent().map(Path::to_path_buf)).flatten()
|
||||
});
|
||||
poms.chain(gradle.unwrap_or_default().iter().map(|build| root.join(&build.dir)))
|
||||
.map(|dir| ide_core::project_roots::resolve(root, &dir))
|
||||
.filter(|dir| !found.iter().any(|build| dir.starts_with(build)))
|
||||
.collect()
|
||||
let maven = poms.map(|dir| ide_core::project_roots::resolve(root, &dir)).filter(|dir| {
|
||||
let dir_canon = canonical(dir);
|
||||
!maven_builds.iter().any(|build| {
|
||||
dir.starts_with(build) && ide_build::maven::reactor_member_dirs(build, &profiles).contains(&dir_canon)
|
||||
})
|
||||
});
|
||||
let models = gradle.unwrap_or_default();
|
||||
let gradle_builds = found("gradle");
|
||||
let gradle =
|
||||
models.iter().map(|build| ide_core::project_roots::resolve(root, &root.join(&build.dir))).filter(|dir| {
|
||||
!gradle_builds.iter().any(|build| {
|
||||
dir == build
|
||||
|| (dir.starts_with(build)
|
||||
&& models.iter().filter(|m| root.join(&m.dir) == *build).any(|m| {
|
||||
m.projects
|
||||
.iter()
|
||||
.any(|p| ide_core::project_roots::resolve(root, &root.join(&p.dir)) == *dir)
|
||||
}))
|
||||
})
|
||||
});
|
||||
let mut dirs: Vec<_> = maven.chain(gradle).collect();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
}
|
||||
|
||||
fn linked_config(
|
||||
@@ -672,11 +698,59 @@ mod ownership_tests {
|
||||
),
|
||||
(
|
||||
"linked module inside the root reactor belongs to the reactor",
|
||||
vec![("pom.xml".into(), "<project></project>"), (format!("{deep}/pom.xml"), BOOT_POM)],
|
||||
vec![
|
||||
(
|
||||
"pom.xml".into(),
|
||||
"<project><modules><module>site/service/03_src/demo-monitor</module></modules></project>",
|
||||
),
|
||||
(format!("{deep}/pom.xml"), BOOT_POM),
|
||||
],
|
||||
vec!["site/service/03_src/demo-monitor/pom.xml"],
|
||||
None,
|
||||
vec!["maven:package".into(), "maven:test".into()],
|
||||
),
|
||||
(
|
||||
"a separate Maven build linked inside the root build's folder has its own configurations",
|
||||
vec![("pom.xml".into(), "<project></project>"), (format!("{deep}/pom.xml"), BOOT_POM)],
|
||||
vec!["site/service/03_src/demo-monitor/pom.xml"],
|
||||
None,
|
||||
vec![
|
||||
"maven:package".into(),
|
||||
"maven:test".into(),
|
||||
format!("maven:package:{deep}"),
|
||||
format!("maven:test:{deep}"),
|
||||
format!("maven:spring-boot:run:{deep}"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"a Gradle subproject linked as a build belongs to the root build",
|
||||
vec![
|
||||
("settings.gradle.kts".into(), "rootProject.name = \"root\"\ninclude(\"a:b:c:tool\")\n"),
|
||||
("build.gradle.kts".into(), "plugins {\n java\n}"),
|
||||
(format!("{tool}/build.gradle.kts"), "plugins {\n application\n}"),
|
||||
],
|
||||
vec![],
|
||||
Some(vec![".", tool]),
|
||||
vec!["gradle:build".into(), "gradle:test".into()],
|
||||
),
|
||||
(
|
||||
"a separate Gradle build linked inside the root build's folder has its own configurations",
|
||||
vec![
|
||||
("settings.gradle.kts".into(), "rootProject.name = \"root\"\n"),
|
||||
("build.gradle.kts".into(), "plugins {\n java\n}"),
|
||||
(format!("{tool}/settings.gradle.kts"), "rootProject.name = \"tool\"\n"),
|
||||
(format!("{tool}/build.gradle.kts"), "plugins {\n application\n}"),
|
||||
],
|
||||
vec![],
|
||||
Some(vec![".", tool]),
|
||||
vec![
|
||||
"gradle:build".into(),
|
||||
"gradle:test".into(),
|
||||
format!("gradle:build:{tool}"),
|
||||
format!("gradle:test:{tool}"),
|
||||
format!("gradle:run:{tool}"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"linked module within the search depth is not detected twice",
|
||||
vec![("svc/pom.xml".into(), "<project></project>")],
|
||||
|
||||
@@ -118,6 +118,16 @@ pub(super) fn folding(
|
||||
});
|
||||
return true;
|
||||
}
|
||||
// Some languages write documentation as a string-like node rather than a
|
||||
// lexical comment (Python docstrings, Elixir `@doc` / `@moduledoc`). The
|
||||
// generic comment pass above never sees those, so fold them as documentation.
|
||||
if node.is_named()
|
||||
&& start != end
|
||||
&& let Some(fold) = docstring_fold(spec, &node, kinds, text)
|
||||
{
|
||||
out.push(fold);
|
||||
return false;
|
||||
}
|
||||
if start != end && !spec.imports.is_empty() && node.named_child_count() > 1 {
|
||||
import_runs(kinds, node, text, &mut out);
|
||||
}
|
||||
@@ -206,6 +216,64 @@ pub(crate) fn is_comment(kind: &str) -> bool {
|
||||
kind.contains("comment") || kind == "Comment"
|
||||
}
|
||||
|
||||
/// Folds a documentation string written as a non-comment node. Returns `None`
|
||||
/// for every other node; the caller skips its subtree only on a match.
|
||||
fn docstring_fold(spec: &Spec, node: &Node, kinds: &KindTable, text: &str) -> Option<FoldRange> {
|
||||
let multi_line = |n: &Node| n.start_position().row != n.end_position().row && kinds.has(n, FOLD_NODE);
|
||||
let range = |n: &Node| FoldRange {
|
||||
start_line: n.start_position().row as u32,
|
||||
end_line: last_content_row(n, text) as u32,
|
||||
kind: FoldKind::Comment,
|
||||
};
|
||||
match spec.name {
|
||||
// A bare string as the first statement of a module/class/function body.
|
||||
"python" if node.kind() == "expression_statement" => {
|
||||
let string = node.named_child(0)?;
|
||||
if string.kind() != "string" || !multi_line(&string) {
|
||||
return None;
|
||||
}
|
||||
let parent = node.parent()?;
|
||||
let mut cursor = parent.walk();
|
||||
if parent.named_children(&mut cursor).find(|c| !kinds.has(c, COMMENT)) != Some(*node) {
|
||||
return None;
|
||||
}
|
||||
Some(range(node))
|
||||
}
|
||||
// `@doc """…"""` / `@moduledoc """…"""`: an @-prefixed call whose
|
||||
// argument is a multi-line string (or a sigil like `~S"""`).
|
||||
"elixir" if node.kind() == "unary_operator" => {
|
||||
let operand = node.child_by_field_name("operand")?;
|
||||
if operand.kind() != "call" || !is_elixir_doc_attr(operand, text) {
|
||||
return None;
|
||||
}
|
||||
// The string is the argument of the attribute call: `@doc """…"""`
|
||||
// parses as unary_operator -> call(target: doc) -> arguments -> string.
|
||||
let mut cursor = operand.walk();
|
||||
let doc_string =
|
||||
operand.named_children(&mut cursor).find(|c| c.kind() == "arguments").and_then(|args| {
|
||||
let mut args_cursor = args.walk();
|
||||
args.named_children(&mut args_cursor).find(|c| multi_line(c))
|
||||
})?;
|
||||
if !matches!(doc_string.kind(), "string" | "sigil") {
|
||||
return None;
|
||||
}
|
||||
Some(range(&doc_string))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an Elixir `call` is `@doc` / `@moduledoc` / `@typedoc` (the documented
|
||||
/// attributes that take a string argument).
|
||||
fn is_elixir_doc_attr(call: Node, text: &str) -> bool {
|
||||
let Some(target) = call.child_by_field_name("target") else { return false };
|
||||
let name = text.get(target.byte_range()).unwrap_or_default();
|
||||
if target.kind() != "identifier" {
|
||||
return false;
|
||||
}
|
||||
matches!(name, "doc" | "moduledoc" | "typedoc")
|
||||
}
|
||||
|
||||
/// Row of the closing token when `node` is delimited by a matching bracket pair.
|
||||
pub(crate) fn bracket_pair<'t>(node: &Node<'t>) -> Option<(Node<'t>, Node<'t>)> {
|
||||
let count = node.child_count();
|
||||
|
||||
@@ -1103,6 +1103,77 @@ fn folding_python_bodies_start_at_header() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_python_docstrings_are_comments() {
|
||||
let src = r#""""Module doc.
|
||||
More.
|
||||
"""
|
||||
|
||||
class A:
|
||||
"""Class doc.
|
||||
More.
|
||||
"""
|
||||
def f(self):
|
||||
"""Method doc.
|
||||
More.
|
||||
"""
|
||||
return 1
|
||||
"#;
|
||||
assert_eq!(
|
||||
folds("python", src),
|
||||
vec![
|
||||
(0, 2, FoldKind::Comment),
|
||||
(4, 12, FoldKind::Region),
|
||||
(5, 7, FoldKind::Comment),
|
||||
(8, 12, FoldKind::Region),
|
||||
(9, 11, FoldKind::Comment),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_python_single_line_or_later_strings_are_not_docstrings() {
|
||||
// A one-line docstring has nothing to fold; a multi-line string that is not
|
||||
// the opening statement stays an ordinary string fold, not a doc comment.
|
||||
let src = r#"x = 1
|
||||
"""Later string.
|
||||
Still later.
|
||||
"""
|
||||
|
||||
def f():
|
||||
"""One line."""
|
||||
return 1
|
||||
"#;
|
||||
let found = folds("python", src);
|
||||
assert!(!found.contains(&(1, 3, FoldKind::Comment)), "later string must not be a doc comment: {found:?}");
|
||||
assert!(found.contains(&(1, 3, FoldKind::Region)), "later string still folds as a string: {found:?}");
|
||||
assert!(!found.iter().any(|f| f.2 == FoldKind::Comment), "single-line docstring has no fold: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_elixir_doc_strings_are_comments() {
|
||||
let src = r#"defmodule Foo do
|
||||
@moduledoc """
|
||||
Module doc.
|
||||
More.
|
||||
"""
|
||||
|
||||
@doc ~S"""
|
||||
Function doc.
|
||||
More.
|
||||
"""
|
||||
def bar, do: :ok
|
||||
|
||||
@doc "one line"
|
||||
def baz, do: :ok
|
||||
end
|
||||
"#;
|
||||
assert_eq!(
|
||||
folds("elixir", src),
|
||||
vec![(0, 14, FoldKind::Region), (1, 4, FoldKind::Comment), (6, 9, FoldKind::Comment),]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_data_and_markup() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use crate::LspManager;
|
||||
use crate::server::Server;
|
||||
use ide_core::{CancellationToken, DocId, Pos, Range};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -128,7 +129,7 @@ impl LspManager {
|
||||
let search = crate::launch::server_search_path(&config, &server.root);
|
||||
let Some(dir) = path.parent().map(Path::to_path_buf) else { return };
|
||||
let modules: Vec<String> = required.iter().map(|r| r.path.clone()).collect();
|
||||
let Some(deprecated) = list_deprecations(&dir, &search, &modules, cancel).await else { return };
|
||||
let Some(deprecated) = list_deprecations(&dir, &config, &search, &modules, cancel).await else { return };
|
||||
// The document changed meanwhile: its own save runs again.
|
||||
if cancel.is_cancelled() || self.docs.lock().get(&doc).is_none_or(|d| d.text.as_str() != text) {
|
||||
return;
|
||||
@@ -208,16 +209,15 @@ struct ListedModule {
|
||||
/// `(module, message)` of each deprecated module in `modules`; `None` when `go` failed.
|
||||
async fn list_deprecations(
|
||||
dir: &Path,
|
||||
config: &LanguageServerConfig,
|
||||
search: &std::ffi::OsStr,
|
||||
modules: &[String],
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<Vec<(String, String)>> {
|
||||
let (dir, search, modules) = (dir.to_path_buf(), search.to_owned(), modules.to_vec());
|
||||
let (dir, config, search, modules) = (dir.to_path_buf(), config.clone(), search.to_owned(), modules.to_vec());
|
||||
let command = tokio::task::spawn_blocking(move || {
|
||||
let go: PathBuf = ide_core::tool_path::find_command("go", &search, &dir)?;
|
||||
let mut command = Command::new(go);
|
||||
command.args(["list", "-m", "-u", "-e", "-json"]).args(modules).current_dir(dir).env("PATH", search);
|
||||
Some(command)
|
||||
Some(deprecations_command(&go, &dir, &config, &search, &modules))
|
||||
})
|
||||
.await
|
||||
.ok()??;
|
||||
@@ -228,6 +228,23 @@ async fn list_deprecations(
|
||||
tokio::task::spawn_blocking(move || parse_deprecations(&output)).await.ok()
|
||||
}
|
||||
|
||||
fn deprecations_command(
|
||||
go: &Path,
|
||||
dir: &Path,
|
||||
config: &LanguageServerConfig,
|
||||
search: &std::ffi::OsStr,
|
||||
modules: &[String],
|
||||
) -> Command {
|
||||
let mut command = Command::new(go);
|
||||
command
|
||||
.args(["list", "-m", "-u", "-e", "-json"])
|
||||
.args(modules)
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
.env("PATH", search);
|
||||
command
|
||||
}
|
||||
|
||||
async fn run_query(command: Command, cancel: &CancellationToken, timeout: Duration) -> Option<Vec<u8>> {
|
||||
let cancel = cancel.child_token();
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
@@ -314,6 +331,30 @@ fn parse_deprecations(json: &[u8]) -> Vec<(String, String)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deprecation_command_inherits_server_environment() {
|
||||
let config: LanguageServerConfig = serde_json::from_value(serde_json::json!({
|
||||
"name": "gopls", "command": "gopls", "env": {
|
||||
"PATH": "selected-toolchain", "GOPROXY": "off", "GOPRIVATE": "example.invalid/*",
|
||||
"GOTOOLCHAIN": "local", "GOWORK": "off"
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let command = deprecations_command(
|
||||
Path::new("go"),
|
||||
Path::new("workspace"),
|
||||
&config,
|
||||
&crate::launch::server_search_path(&config, Path::new("workspace")),
|
||||
&["example.invalid/lib".into()],
|
||||
);
|
||||
let env: std::collections::BTreeMap<_, _> = command.get_envs().collect();
|
||||
for (key, value) in &config.env {
|
||||
assert_eq!(env.get(std::ffi::OsStr::new(key)), Some(&Some(std::ffi::OsStr::new(value))), "missing {key}");
|
||||
}
|
||||
assert_eq!(command.get_current_dir(), Some(Path::new("workspace")));
|
||||
assert_eq!(command.get_args().collect::<Vec<_>>(), ["list", "-m", "-u", "-e", "-json", "example.invalid/lib"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queries_cancel_only_the_superseded_document() {
|
||||
let mut queries = Queries::default();
|
||||
|
||||
@@ -3005,13 +3005,13 @@ async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|arg| (arg["path"].as_str().unwrap().to_owned(), arg["test"].as_bool().unwrap()))
|
||||
.map(|arg| (PathBuf::from(arg["path"].as_str().unwrap()), arg["test"].as_bool().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
(h.root.join("target/generated-sources/protobuf/grpc-java").to_string_lossy().into_owned(), false),
|
||||
(h.root.join("target/generated-sources/protobuf/java").to_string_lossy().into_owned(), false),
|
||||
(h.root.join("target/generated-sources/protobuf/grpc-java"), false),
|
||||
(h.root.join("target/generated-sources/protobuf/java"), false),
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -3654,6 +3654,7 @@ async fn a_framework_server_serves_files_spelt_differently_from_the_project() {
|
||||
let range = json!({ "start": { "line": 1, "character": 2 }, "end": { "line": 1, "character": 11 } });
|
||||
framework.respond("textDocument/definition", json!([{ "uri": uri_of(&component), "range": range }]));
|
||||
|
||||
#[cfg(unix)]
|
||||
let links = tempfile::tempdir().unwrap();
|
||||
let mut spellings = Vec::new();
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,7 +25,10 @@ fn root(data_dir: &Path) -> PathBuf {
|
||||
pub fn mark_used(cfg: &LanguageServerConfig) {
|
||||
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
|
||||
let dir = Path::new(dir);
|
||||
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
|
||||
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
|
||||
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
|
||||
marker.set_modified(SystemTime::now())
|
||||
}) {
|
||||
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,6 +277,25 @@ pub fn copy_merge(
|
||||
let target_base = project.filter(|p| to.starts_with(p)).or(Some(roots.1));
|
||||
let rules = Rules::new(from, source_base, excludes);
|
||||
let target_rules = Rules::new(to, target_base, excludes);
|
||||
// Find a conflict before writing anything, so declining to overwrite leaves the
|
||||
// destination untouched. Nothing below a missing destination can conflict.
|
||||
if !overwrite {
|
||||
let mut pending = vec![(from.to_path_buf(), to.to_path_buf())];
|
||||
while let Some((src, dst)) = pending.pop() {
|
||||
let meta = fs::symlink_metadata(&src)?;
|
||||
if rules.excluded(&src, meta.is_dir()) || target_rules.excluded(&dst, meta.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(existing) = fs::symlink_metadata(&dst) else { continue };
|
||||
if !(meta.is_dir() && existing.is_dir()) {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, dst.display().to_string()).into());
|
||||
}
|
||||
for entry in fs::read_dir(&src)? {
|
||||
let entry = entry?;
|
||||
pending.push((entry.path(), dst.join(entry.file_name())));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pending = vec![(from.to_path_buf(), to.to_path_buf())];
|
||||
while let Some((src, dst)) = pending.pop() {
|
||||
let meta = fs::symlink_metadata(&src)?;
|
||||
@@ -494,6 +513,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declined_overwrite_writes_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let left = tmp.path().join("left");
|
||||
let right = tmp.path().join("right");
|
||||
put(&left, "merge/a-clash.txt", b"source");
|
||||
put(&left, "merge/z-new.txt", b"source only");
|
||||
put(&left, "merge/deep/new.txt", b"new");
|
||||
put(&right, "merge/a-clash.txt", b"destination");
|
||||
let error =
|
||||
copy_merge(&left.join("merge"), &right.join("merge"), false, None, &[], (&left, &right)).unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::AlreadyExists);
|
||||
assert_eq!(fs::read(right.join("merge/a-clash.txt")).unwrap(), b"destination");
|
||||
assert!(!right.join("merge/z-new.txt").exists());
|
||||
assert!(!right.join("merge/deep").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtree_copy_keeps_excludes_anchored_to_each_comparison_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.47",
|
||||
"version": "0.1.48",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
|
||||
/// follows its file: the file's own project, or the nearest one when it is outside them all.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
@@ -75,6 +75,21 @@ interface ui {
|
||||
remove-context: func(key: string);
|
||||
/// Copies `text` to the system clipboard. Requires `clipboard`.
|
||||
copy-to-clipboard: func(text: string) -> result<_, error>;
|
||||
/// What `read-clipboard` found (API 1.11). Both `none`: the clipboard holds
|
||||
/// neither text nor an image.
|
||||
record clipboard-content {
|
||||
text: option<string>,
|
||||
/// An image (a screenshot), always as PNG bytes.
|
||||
image: option<list<u8>>,
|
||||
}
|
||||
/// Reads the system clipboard of the user's machine (API 1.11). Requires
|
||||
/// `clipboard.read`. Only in a command the user ran or a view action from
|
||||
/// a window; anywhere else (event handlers, background and scheduled
|
||||
/// work, web view messages, a command run through `command-runner`) it is
|
||||
/// `denied`, so nothing reads the clipboard behind the user's back. Text
|
||||
/// or an image over 16 MiB fails the call. In a remote project the user
|
||||
/// confirms first; refusing is `denied`.
|
||||
read-clipboard: func() -> result<clipboard-content, error>;
|
||||
/// Opens an `http://` or `https://` URL in the user's default browser.
|
||||
open-url: func(url: string) -> result<_, error>;
|
||||
/// Shows a list and waits for the chosen key, or `none` when dismissed.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]0.0;
|
||||
package openidea:[email protected]1.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
|
||||
@@ -97,6 +97,7 @@ objc2-web-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
gtk = "0.18"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
webview2-com = "0.39"
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_EnhancedStorage",
|
||||
|
||||
@@ -43,6 +43,8 @@ mod window_zoom;
|
||||
mod windows;
|
||||
#[cfg(windows)]
|
||||
mod windows_error_mode;
|
||||
#[cfg(windows)]
|
||||
mod windows_webview_recovery;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use state::AppState;
|
||||
@@ -137,6 +139,8 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.plugin(tauri_plugin_dialog::init());
|
||||
#[cfg(windows)]
|
||||
let app = app.plugin(windows_webview_recovery::init());
|
||||
#[cfg(target_os = "linux")]
|
||||
let app = app.plugin(linux_window_state::plugin());
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Native recovery for a WebView2 browser crash. The webview can no longer show its own UI.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use tauri::{AppHandle, Manager, Webview, Wry, plugin};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||
use webview2_com::{
|
||||
Microsoft::Web::WebView2::Win32::{
|
||||
COREWEBVIEW2_PROCESS_FAILED_KIND, COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED, ICoreWebView2,
|
||||
ICoreWebView2ProcessFailedEventArgs2,
|
||||
},
|
||||
ProcessFailedEventHandler,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recovery {
|
||||
announced_browsers: Mutex<HashSet<u32>>,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
fn announce(&self, browser_pid: u32) -> bool {
|
||||
self.announced_browsers.lock().insert(browser_pid)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init() -> plugin::TauriPlugin<Wry> {
|
||||
plugin::Builder::new("webview-recovery")
|
||||
.setup(|app, _| {
|
||||
app.manage(Recovery::default());
|
||||
Ok(())
|
||||
})
|
||||
.on_webview_ready(install)
|
||||
.build()
|
||||
}
|
||||
|
||||
fn install(webview: Webview) {
|
||||
let app = webview.app_handle().clone();
|
||||
let label = webview.label().to_owned();
|
||||
if let Err(error) = webview.with_webview(move |platform| {
|
||||
// SAFETY: with_webview runs on the controller's owning STA thread.
|
||||
let result = unsafe { platform.controller().CoreWebView2() }.and_then(|core| listen(&core, app, label.clone()));
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(window = %label, %error, "cannot monitor WebView2 browser failures");
|
||||
}
|
||||
}) {
|
||||
tracing::warn!(window = webview.label(), %error, "cannot access WebView2 controller");
|
||||
}
|
||||
}
|
||||
|
||||
fn listen(core: &ICoreWebView2, app: AppHandle, label: String) -> windows::core::Result<()> {
|
||||
let mut browser_pid = 0;
|
||||
// SAFETY: the controller is live and this runs on its owning thread.
|
||||
unsafe { core.BrowserProcessId(&mut browser_pid)? };
|
||||
let handler = ProcessFailedEventHandler::create(Box::new(move |_, args| {
|
||||
let Some(args) = args else { return Ok(()) };
|
||||
let mut kind = COREWEBVIEW2_PROCESS_FAILED_KIND::default();
|
||||
// SAFETY: callback arguments are live and used on the controller's thread.
|
||||
unsafe { args.ProcessFailedKind(&mut kind)? };
|
||||
if kind != COREWEBVIEW2_PROCESS_FAILED_KIND_BROWSER_PROCESS_EXITED
|
||||
|| !app.state::<Recovery>().announce(browser_pid)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let exit_code = args.cast::<ICoreWebView2ProcessFailedEventArgs2>().ok().and_then(|args| {
|
||||
let mut code = 0;
|
||||
// SAFETY: queried from the live callback arguments on this thread.
|
||||
unsafe { args.ExitCode(&mut code) }.ok().map(|()| code)
|
||||
});
|
||||
tracing::error!(window = %label, browser_pid, ?exit_code, "WebView2 browser process exited unexpectedly");
|
||||
// Dispatch from a worker so Wry queues the prompt instead of running it
|
||||
// inline inside WebView2's STA callback.
|
||||
let app = app.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let handle = app.clone();
|
||||
if let Err(error) = app.run_on_main_thread(move || show_recovery(handle)) {
|
||||
tracing::error!(%error, "cannot show WebView2 recovery prompt");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}));
|
||||
let mut token = 0;
|
||||
// SAFETY: the controller is live on this thread. WebView2 owns the handler until it closes.
|
||||
unsafe { core.add_ProcessFailed(&handler, &mut token) }
|
||||
}
|
||||
|
||||
fn show_recovery(app: AppHandle) {
|
||||
let mut dialog = app
|
||||
.dialog()
|
||||
.message(
|
||||
"The Windows web engine stopped unexpectedly. Restart OpenIDEA to recover the interface. \
|
||||
This restarts all OpenIDEA windows. Unsaved edits may be lost.",
|
||||
)
|
||||
.title("OpenIDEA")
|
||||
.kind(MessageDialogKind::Error)
|
||||
.buttons(MessageDialogButtons::OkCancelCustom("Restart OpenIDEA".into(), "Cancel".into()));
|
||||
if let Some(window) = crate::windows::target_window(&app).filter(|w| w.is_visible().unwrap_or(false)) {
|
||||
dialog = dialog.parent(&window);
|
||||
}
|
||||
dialog.show(move |restart| {
|
||||
if restart {
|
||||
// The normal quit waits for a response from each webview. The failed browser
|
||||
// cannot answer, so restart through Tauri's native exit path.
|
||||
app.request_restart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Recovery;
|
||||
|
||||
#[test]
|
||||
fn only_one_prompt_for_windows_sharing_a_failed_browser() {
|
||||
let recovery = Recovery::default();
|
||||
assert!(recovery.announce(100));
|
||||
assert!(!recovery.announce(100));
|
||||
assert!(recovery.announce(200));
|
||||
assert!(!recovery.announce(100));
|
||||
assert!(!recovery.announce(200));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.47",
|
||||
"version": "0.1.48",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -65,6 +65,31 @@ import { tx } from "@/platform/i18n";
|
||||
import { logError } from "@/platform/errorLog";
|
||||
import { WorkspaceHistory } from "./workspaceHistory";
|
||||
|
||||
/**
|
||||
* Whether a comment fold is the file header (as opposed to a documentation
|
||||
* comment). Both conditions must hold: the fold sits at the top of the file
|
||||
* (its first line is at or before the first code line) and that line starts
|
||||
* with a comment token. Otherwise ordinary documentation comments further down
|
||||
* would follow the file-header toggle. A Python module docstring opens with
|
||||
* quotes, so it is documentation even though it is the first thing in the file.
|
||||
*
|
||||
* Line numbers are 1-based; `firstCodeLine` is 0 when the file has no code line
|
||||
* (only blanks / shebang), in which case nothing is a header.
|
||||
*/
|
||||
export function isFileHeaderFold(
|
||||
foldLine: number,
|
||||
firstCodeLine: number,
|
||||
line: string,
|
||||
lineComment: string | null | undefined,
|
||||
blockComment: readonly [string, string] | null | undefined,
|
||||
): boolean {
|
||||
if (firstCodeLine === 0 || foldLine > firstCodeLine) return false;
|
||||
const text = line.trimStart();
|
||||
if (lineComment && text.startsWith(lineComment)) return true;
|
||||
if (blockComment && text.startsWith(blockComment[0])) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export type Banner = "binary" | "tooLarge" | "readOnly" | "library" | null;
|
||||
|
||||
/** A view attached to a document outside the tab system (see `attachment.ts`). */
|
||||
@@ -611,17 +636,23 @@ export class DocModel {
|
||||
for (const s of this.slots) {
|
||||
const state = s.currentState();
|
||||
const folds = state.field(backendFolds, false) ?? [];
|
||||
const firstCode = (() => {
|
||||
const info = this.info;
|
||||
const firstCodeLine = (() => {
|
||||
for (let n = 1; n <= state.doc.lines; n++) {
|
||||
const t = state.doc.line(n).text.trim();
|
||||
if (t && !t.startsWith("#!")) return state.doc.line(n).from;
|
||||
if (t && !t.startsWith("#!")) return n;
|
||||
}
|
||||
return 0;
|
||||
})();
|
||||
const chosen = folds.filter((r) => {
|
||||
if (r.kind === "imports") return f.imports;
|
||||
if (r.kind !== "comment") return false;
|
||||
const header = state.doc.lineAt(r.from).from <= firstCode;
|
||||
// A file header must sit at the top AND start with a comment token.
|
||||
// Keeping the position check keeps ordinary doc comments further down
|
||||
// under "documentation comments"; the token check keeps a Python module
|
||||
// docstring (which opens with quotes) out of the file-header toggle.
|
||||
const first = state.doc.lineAt(r.from);
|
||||
const header = isFileHeaderFold(first.number, firstCodeLine, first.text, info?.lineComment, info?.blockComment);
|
||||
return header ? f.fileHeader : f.docComments;
|
||||
});
|
||||
const effects: StateEffect<unknown>[] = chosen.map((r) => foldEffect.of({ from: r.from, to: r.to }));
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isFileHeaderFold } from "./document";
|
||||
|
||||
describe("isFileHeaderFold", () => {
|
||||
it("treats a comment block at the top of the file as the header", () => {
|
||||
// First code line is 3; header comment folds start at lines 1-2.
|
||||
expect(isFileHeaderFold(1, 3, "#!/usr/bin/env python", "#", null)).toBe(true);
|
||||
expect(isFileHeaderFold(2, 3, "# Copyright 2026", "#", null)).toBe(true);
|
||||
expect(isFileHeaderFold(1, 3, " # license", "#", null)).toBe(true);
|
||||
expect(isFileHeaderFold(1, 3, "// license", "//", ["/*", "*/"])).toBe(true);
|
||||
expect(isFileHeaderFold(1, 2, "/* license */", "//", ["/*", "*/"])).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps documentation comments further down under documentation comments", () => {
|
||||
// The reviewer's regression: a doc comment above a function far down the
|
||||
// file starts with the line comment token but is NOT the file header.
|
||||
expect(isFileHeaderFold(20, 1, "// Returns the room", "//", ["/*", "*/"])).toBe(false);
|
||||
expect(isFileHeaderFold(8, 1, "# docs for f", "#", null)).toBe(false);
|
||||
expect(isFileHeaderFold(5, 1, "/** Javadoc */", "//", ["/*", "*/"])).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a Python docstring at the top of the file as documentation, not a header", () => {
|
||||
// Python: lineComment '#', no block comment; a docstring opens with quotes,
|
||||
// so even though it is line 1 it must not be classified as a file header.
|
||||
expect(isFileHeaderFold(1, 1, '"""Module docstring.', "#", null)).toBe(false);
|
||||
expect(isFileHeaderFold(1, 1, "'''Module docstring.", "#", null)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not classify ordinary code or a code-less file as a header", () => {
|
||||
expect(isFileHeaderFold(1, 2, "import os", "#", null)).toBe(false);
|
||||
// firstCodeLine === 0 means no real code line (only blanks / shebang).
|
||||
expect(isFileHeaderFold(1, 0, "# just a comment", "#", null)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -28,17 +28,22 @@ import styles from "./ReferenceChip.module.css";
|
||||
|
||||
export { styles as chipStyles };
|
||||
|
||||
const MAX_EXISTING = 4000;
|
||||
/** Whether a path names an existing file or folder, per path (the same files come up again and again). */
|
||||
const existing = new Map<string, Promise<boolean>>();
|
||||
export function fileExists(path: string): Promise<boolean> {
|
||||
let known = existing.get(path);
|
||||
if (!known) {
|
||||
known = call(commands.fsProbe(path)).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
if (known) {
|
||||
existing.delete(path);
|
||||
existing.set(path, known);
|
||||
return known;
|
||||
}
|
||||
known = call(commands.fsProbe(path)).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
if (existing.size >= MAX_EXISTING) existing.delete(existing.keys().next().value!);
|
||||
existing.set(path, known);
|
||||
return known;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ interface PopupSection {
|
||||
items: PopupItem[];
|
||||
}
|
||||
|
||||
const MAX_GH_META = 500;
|
||||
/** Shared per-process cache so repeated renders/tabs never re-query `gh api` for the same PR or issue. */
|
||||
const ghMetaCache = new Map<string, Promise<RemoteItemMeta | null>>();
|
||||
const ghResolvedMeta = new Map<string, RemoteItemMeta | null>();
|
||||
@@ -117,9 +118,14 @@ function fetchGithubMeta(
|
||||
.then((text) => parseGhItemResponse(text, kind))
|
||||
.catch(() => null)
|
||||
.then((meta) => {
|
||||
ghResolvedMeta.set(cacheKey, meta);
|
||||
if (ghMetaCache.get(cacheKey) === req) ghResolvedMeta.set(cacheKey, meta);
|
||||
return meta;
|
||||
});
|
||||
if (ghMetaCache.size >= MAX_GH_META) {
|
||||
const oldest = ghMetaCache.keys().next().value!;
|
||||
ghMetaCache.delete(oldest);
|
||||
ghResolvedMeta.delete(oldest);
|
||||
}
|
||||
ghMetaCache.set(cacheKey, req);
|
||||
return req;
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
openHome,
|
||||
refreshModels,
|
||||
refreshProviders,
|
||||
releaseClosedTaskCache,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
import { TaskStatusMark } from "./TaskStatusMark";
|
||||
@@ -174,6 +175,10 @@ export function activate(): () => void {
|
||||
// Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`).
|
||||
restorable: true,
|
||||
onTabClose: (tabId) => clearAgentTabFontZoom(tabId),
|
||||
onClose: (input) => {
|
||||
const task = (input.data as { task?: string } | undefined)?.task;
|
||||
if (task) releaseClosedTaskCache(task);
|
||||
},
|
||||
// Rebuilding a long conversation on every switch back is slow.
|
||||
keepAlive: true,
|
||||
}),
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
hideImportSessions,
|
||||
importExternalSessions,
|
||||
refreshExternalSessions,
|
||||
releaseClosedTaskCache,
|
||||
showImportSessions,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
@@ -2115,6 +2116,69 @@ describe("session state across tasks and hosts", () => {
|
||||
act(() => disconnect());
|
||||
expect(useAgents.getState().scrollPositions.size).toBe(0);
|
||||
});
|
||||
|
||||
it("bounds retained entries for closed tabs (including busy and subagent entries) and refreshes MRU order", () => {
|
||||
const entries = new Map<string, AgentEntry[]>();
|
||||
const entryLoads = new Map<string, { error: string | null }>();
|
||||
const changes = new Map<string, AgentChange[]>();
|
||||
const scrollPositions = new Map<string, { top: number; stick: boolean }>();
|
||||
const tasks = new Map<string, AgentTask>();
|
||||
const baseTask = useAgents.getState().tasks.get("A")!;
|
||||
for (let i = 1; i <= 7; i++) {
|
||||
const id = `T${i}`;
|
||||
tasks.set(id, { ...baseTask, id, title: id, status: i === 2 ? "running" : "ready" });
|
||||
entries.set(id, [{ type: "agent", text: `Reply ${id}` }]);
|
||||
entries.set(`${id}/sub`, [{ type: "agent", text: `Sub ${id}` }]);
|
||||
entryLoads.set(id, { error: "err" });
|
||||
changes.set(id, [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]);
|
||||
scrollPositions.set(id, { top: 10, stick: false });
|
||||
}
|
||||
entries.set("gone", [{ type: "agent", text: "Deleted reply" }]);
|
||||
useAgents.setState({ tasks, entries, entryLoads, changes, scrollPositions });
|
||||
for (let i = 1; i <= 5; i++) releaseClosedTaskCache(`T${i}`);
|
||||
// A deleted task's tab closing drops its data without taking one of the cached slots.
|
||||
releaseClosedTaskCache("gone");
|
||||
expect(useAgents.getState().entries.has("gone")).toBe(false);
|
||||
expect(useAgents.getState().entries.has("T1")).toBe(true);
|
||||
// Re-closing T1 refreshes it so T2 (even though running) becomes the oldest and is evicted next.
|
||||
releaseClosedTaskCache("T1");
|
||||
releaseClosedTaskCache("T6");
|
||||
releaseClosedTaskCache("T7");
|
||||
const state = useAgents.getState();
|
||||
expect(state.entries.has("T1")).toBe(true);
|
||||
expect(state.entries.has("T2")).toBe(false);
|
||||
expect(state.entries.has("T2/sub")).toBe(false);
|
||||
expect(state.entryLoads.has("T2")).toBe(false);
|
||||
expect(state.changes.has("T2")).toBe(false);
|
||||
expect(state.scrollPositions.has("T2")).toBe(false);
|
||||
expect(state.entries.has("T3")).toBe(false);
|
||||
expect(state.entries.has("T7")).toBe(true);
|
||||
});
|
||||
|
||||
it("loads an archived task's conversation and changes again when it reopens after its cache was dropped", async () => {
|
||||
backend.changes = [
|
||||
{
|
||||
path: "/project/kept-change.ts",
|
||||
relPath: "kept-change.ts",
|
||||
kind: "modified",
|
||||
added: 1,
|
||||
removed: 0,
|
||||
oldPath: null,
|
||||
},
|
||||
];
|
||||
localStorage.setItem("openidea.agents.changesOpen.v1", JSON.stringify({ A: true }));
|
||||
useAgents.setState((s) => ({
|
||||
tasks: new Map(s.tasks).set("A", { ...s.tasks.get("A")!, status: "archived" }),
|
||||
}));
|
||||
releaseClosedTaskCache("A");
|
||||
expect(useAgents.getState().entries.has("A")).toBe(false);
|
||||
backend.fetched = [];
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
expect(await screen.findByText("Answer A")).toBeInTheDocument();
|
||||
const panel = await screen.findByRole("complementary", { name: "Changes" });
|
||||
expect(await within(panel).findByText("kept-change.ts")).toBeInTheDocument();
|
||||
expect(backend.fetched).toEqual(["A"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("meters in the task header", () => {
|
||||
|
||||
@@ -546,11 +546,117 @@ function onEntryEvent(s: AgentsState, e: EntryEvent) {
|
||||
else if (next !== current) useAgents.setState({ entries: new Map(s.entries).set(key, next) });
|
||||
}
|
||||
|
||||
const CACHED_CLOSED_TASKS = 5;
|
||||
|
||||
/** Recent closed-task ids kept in memory so reopening a just-closed tab avoids refetching. */
|
||||
const closedTaskMru: string[] = [];
|
||||
/** Bumped when a task's cache is dropped, so a fetch started before that doesn't refill it. */
|
||||
const cacheDrops = new Map<string, number>();
|
||||
|
||||
function isTaskKey(key: string, taskId: string): boolean {
|
||||
return key === taskId || key.startsWith(`${taskId}/`);
|
||||
}
|
||||
|
||||
function forgetClosed(taskId: string) {
|
||||
const idx = closedTaskMru.indexOf(taskId);
|
||||
if (idx >= 0) closedTaskMru.splice(idx, 1);
|
||||
}
|
||||
|
||||
function clearTaskMaps(taskId: string, clearStreaming = false) {
|
||||
forgetClosed(taskId);
|
||||
for (const key of [...arrivedWhileLoading.keys()]) {
|
||||
if (isTaskKey(key, taskId)) arrivedWhileLoading.delete(key);
|
||||
}
|
||||
// Mounted streams write into this map directly, so it is pruned in place rather than replaced.
|
||||
const positions = useAgents.getState().scrollPositions;
|
||||
for (const key of [...positions.keys()]) {
|
||||
if (isTaskKey(key, taskId)) positions.delete(key);
|
||||
}
|
||||
if (clearStreaming) streamingReply.delete(taskId);
|
||||
const timer = pendingChanges.get(taskId);
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer);
|
||||
pendingChanges.delete(taskId);
|
||||
}
|
||||
}
|
||||
|
||||
function withoutTaskCache(s: AgentsState, taskId: string): Partial<AgentsState> | null {
|
||||
let entries: Map<string, AgentEntry[]> | undefined;
|
||||
for (const key of s.entries.keys()) {
|
||||
if (isTaskKey(key, taskId)) (entries ??= new Map(s.entries)).delete(key);
|
||||
}
|
||||
let entryLoads: Map<string, { error: string | null }> | undefined;
|
||||
for (const key of s.entryLoads.keys()) {
|
||||
if (isTaskKey(key, taskId)) (entryLoads ??= new Map(s.entryLoads)).delete(key);
|
||||
}
|
||||
let changes: Map<string, AgentChange[]> | undefined;
|
||||
if (s.changes.has(taskId)) {
|
||||
changes = new Map(s.changes);
|
||||
changes.delete(taskId);
|
||||
}
|
||||
let groupedChanges: Map<string, AgentChanges> | undefined;
|
||||
if (s.groupedChanges.has(taskId)) {
|
||||
groupedChanges = new Map(s.groupedChanges);
|
||||
groupedChanges.delete(taskId);
|
||||
}
|
||||
if (!entries && !entryLoads && !changes && !groupedChanges) return null;
|
||||
return {
|
||||
...(entries ? { entries } : {}),
|
||||
...(entryLoads ? { entryLoads } : {}),
|
||||
...(changes ? { changes } : {}),
|
||||
...(groupedChanges ? { groupedChanges } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function dropTaskCache(taskId: string) {
|
||||
clearTaskMaps(taskId);
|
||||
// A deleted task needs no marker: fetches already discard results for tasks that are gone.
|
||||
if (useAgents.getState().tasks.has(taskId)) cacheDrops.set(taskId, (cacheDrops.get(taskId) ?? 0) + 1);
|
||||
useAgents.setState((s) => withoutTaskCache(s, taskId) ?? s);
|
||||
}
|
||||
|
||||
function isTaskOpenInUi(taskId: string): boolean {
|
||||
if (useAgents.getState().docked === taskId) return true;
|
||||
return (editorService().openTabs?.() ?? []).some(
|
||||
(t) => t.input.kind === SESSION_KIND && (t.input.data as { task?: string } | undefined)?.task === taskId,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a background trigger should reload a task's changes: only while they are shown or still cached. */
|
||||
function wantsChanges(taskId: string): boolean {
|
||||
const s = useAgents.getState();
|
||||
return s.changes.has(taskId) || s.groupedChanges.has(taskId) || isTaskOpenInUi(taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases cached conversation data for a closed or un-docked session once more than
|
||||
* `CACHED_CLOSED_TASKS` closed tasks have been retained. Archived and deleted tasks are
|
||||
* dropped immediately; other tasks stay in a small MRU cache so reopening is instant.
|
||||
*/
|
||||
export function releaseClosedTaskCache(taskId: string) {
|
||||
if (!taskId || isTaskOpenInUi(taskId)) return;
|
||||
const task = useAgents.getState().tasks.get(taskId);
|
||||
if (!task || task.status === "archived") {
|
||||
dropTaskCache(taskId);
|
||||
return;
|
||||
}
|
||||
forgetClosed(taskId);
|
||||
closedTaskMru.push(taskId);
|
||||
while (closedTaskMru.length > CACHED_CLOSED_TASKS) {
|
||||
const oldest = closedTaskMru.shift()!;
|
||||
if (!isTaskOpenInUi(oldest)) dropTaskCache(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
export function disconnect() {
|
||||
generation++;
|
||||
arrivedWhileLoading.clear();
|
||||
streamingReply.clear();
|
||||
modelFlights.clear();
|
||||
closedTaskMru.length = 0;
|
||||
cacheDrops.clear();
|
||||
for (const timer of pendingChanges.values()) clearTimeout(timer);
|
||||
pendingChanges.clear();
|
||||
resetAllAgentFontZoom();
|
||||
useAgents.setState({
|
||||
loaded: false,
|
||||
@@ -584,9 +690,12 @@ function onEvent(e: AgentEvent) {
|
||||
const prev = s.tasks.get(e.task.id);
|
||||
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
|
||||
if (prev && (prev.title !== e.task.title || prev.status !== e.task.status)) notifyTabTitlesChanged();
|
||||
if (e.task.status === "archived") setUnread(e.task.id, false);
|
||||
if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
|
||||
void refreshChanges(e.task.id);
|
||||
if (e.task.status === "archived") {
|
||||
setUnread(e.task.id, false);
|
||||
if (prev?.status !== "archived" && !isTaskOpenInUi(e.task.id)) dropTaskCache(e.task.id);
|
||||
}
|
||||
if (prev?.status !== e.task.status && !isBusy(e.task.status) && e.task.status !== "archived") {
|
||||
if (wantsChanges(e.task.id)) void refreshChanges(e.task.id);
|
||||
void refreshProviders();
|
||||
}
|
||||
break;
|
||||
@@ -597,6 +706,8 @@ function onEvent(e: AgentEvent) {
|
||||
break;
|
||||
}
|
||||
case "removed": {
|
||||
clearTaskMaps(e.id, true);
|
||||
cacheDrops.delete(e.id);
|
||||
const tasks = new Map(s.tasks);
|
||||
tasks.delete(e.id);
|
||||
const composers = new Map(s.composers);
|
||||
@@ -610,6 +721,7 @@ function onEvent(e: AgentEvent) {
|
||||
tasks,
|
||||
composers,
|
||||
unread,
|
||||
...withoutTaskCache(s, e.id),
|
||||
organize,
|
||||
...(s.docked === e.id ? { docked: null } : {}),
|
||||
});
|
||||
@@ -734,16 +846,23 @@ export async function loadEntries(task: string, subagent: string | null = null):
|
||||
}
|
||||
|
||||
export async function refreshChanges(task: string): Promise<void> {
|
||||
const gen = generation;
|
||||
const drops = cacheDrops.get(task);
|
||||
// Discard a result that arrives after a project switch, the task's deletion, or its cache being dropped.
|
||||
const stillWanted = () =>
|
||||
gen === generation && useAgents.getState().tasks.has(task) && cacheDrops.get(task) === drops;
|
||||
// Local tasks have no commits of their own to group: the flat list is their only view.
|
||||
const grouped =
|
||||
useChangesOptions.getState().groupByCommit && useAgents.getState().tasks.get(task)?.isolation === "worktree";
|
||||
if (grouped) {
|
||||
try {
|
||||
const review = await call(commands.agentGroupedChanges(task));
|
||||
if (!stillWanted()) return;
|
||||
useAgents.setState((s) => ({
|
||||
groupedChanges: new Map(s.groupedChanges).set(task, review),
|
||||
}));
|
||||
} catch {
|
||||
if (!stillWanted()) return;
|
||||
// The worktree is gone or not a repository: nothing to list.
|
||||
useAgents.setState((s) => ({
|
||||
groupedChanges: new Map(s.groupedChanges).set(task, { uncommitted: [], commits: [] }),
|
||||
@@ -753,10 +872,12 @@ export async function refreshChanges(task: string): Promise<void> {
|
||||
}
|
||||
try {
|
||||
const changes = await call(commands.agentChanges(task));
|
||||
if (!stillWanted()) return;
|
||||
useAgents.setState((s) => ({
|
||||
changes: new Map(s.changes).set(task, changes),
|
||||
}));
|
||||
} catch {
|
||||
if (!stillWanted()) return;
|
||||
// The worktree is gone or not a repository: nothing to list.
|
||||
useAgents.setState((s) => ({ changes: new Map(s.changes).set(task, []) }));
|
||||
}
|
||||
@@ -792,7 +913,7 @@ export function scheduleChanges(task: string) {
|
||||
task,
|
||||
setTimeout(() => {
|
||||
pendingChanges.delete(task);
|
||||
void refreshChanges(task);
|
||||
if (wantsChanges(task)) void refreshChanges(task);
|
||||
}, 500),
|
||||
);
|
||||
}
|
||||
@@ -850,6 +971,7 @@ export function useAgentCommands(
|
||||
}
|
||||
|
||||
export function openTask(task: string) {
|
||||
forgetClosed(task);
|
||||
if (useAgents.getState().sessionLocation === "toolWindow") {
|
||||
showDockedTask(task);
|
||||
return;
|
||||
@@ -865,12 +987,14 @@ function openTaskInEditor(task: string) {
|
||||
}
|
||||
|
||||
function showDockedTask(task: string) {
|
||||
const previousDocked = useAgents.getState().docked;
|
||||
useAgents.setState({
|
||||
docked: task,
|
||||
lastTask: task,
|
||||
homeOpen: false,
|
||||
lastComposer: task,
|
||||
});
|
||||
if (previousDocked && previousDocked !== task) releaseClosedTaskCache(previousDocked);
|
||||
toolWindowService().show(TOOL_WINDOW, true);
|
||||
void editorService().closeInput?.(sessionKey(task));
|
||||
}
|
||||
@@ -899,8 +1023,11 @@ export function setSessionLocation(location: SessionLocation) {
|
||||
[...s.tasks.values()]
|
||||
.filter((t) => t.status !== "archived")
|
||||
.sort((a, b) => (b.updatedMs ?? b.createdMs ?? 0) - (a.updatedMs ?? a.createdMs ?? 0))[0]?.id;
|
||||
const previousDocked = s.docked;
|
||||
saveSessionLocation(location);
|
||||
useAgents.setState({ docked: null, homeOpen: false });
|
||||
// The docked task itself reopens in the new location unless the New Task page takes its place.
|
||||
if (previousDocked && (home || previousDocked !== task)) releaseClosedTaskCache(previousDocked);
|
||||
if (home) {
|
||||
openHome();
|
||||
} else if (task) {
|
||||
@@ -922,8 +1049,10 @@ export function undockTask() {
|
||||
|
||||
/** An explicit editor drop also updates where subsequent sessions open. */
|
||||
export function openTaskInEditorLocation(task: string) {
|
||||
const previousDocked = useAgents.getState().docked;
|
||||
saveSessionLocation("editor");
|
||||
useAgents.setState({ docked: null, homeOpen: false });
|
||||
if (previousDocked && previousDocked !== task) releaseClosedTaskCache(previousDocked);
|
||||
openTask(task);
|
||||
}
|
||||
|
||||
@@ -957,7 +1086,9 @@ export function openHome(prompt?: string) {
|
||||
}
|
||||
if (prompt !== undefined) updateComposer(HOME, { text: prompt });
|
||||
if (useAgents.getState().sessionLocation === "toolWindow") {
|
||||
const previousDocked = useAgents.getState().docked;
|
||||
useAgents.setState({ docked: null, homeOpen: true });
|
||||
if (previousDocked) releaseClosedTaskCache(previousDocked);
|
||||
toolWindowService().show(TOOL_WINDOW, true);
|
||||
void editorService().closeInput?.(HOME_KEY);
|
||||
return;
|
||||
|
||||
@@ -78,4 +78,15 @@ describe("lookupSymbols", () => {
|
||||
await lookupSymbols("/elsewhere", ["load"]).get("load");
|
||||
expect(asked).toEqual([["FooView", "load"], ["BarView"], ["load"]]);
|
||||
});
|
||||
|
||||
it("answers every name of one request even when it exceeds the per-folder limit", async () => {
|
||||
mockIPC((cmd, args) => {
|
||||
if (cmd !== "find_symbols_named") return null;
|
||||
const { names } = args as { names: string[] };
|
||||
return names.map((name) => symbol(name, `/repo/${name}.ts`));
|
||||
});
|
||||
const requested = Array.from({ length: 2001 }, (_, i) => `Name${i}`);
|
||||
const found = lookupSymbols("/large", requested);
|
||||
expect((await found.get("Name0"))!.map((match) => match.name)).toEqual(["Name0"]);
|
||||
});
|
||||
});
|
||||
@@ -8,24 +8,36 @@ import type { SymbolRef } from "./conversation";
|
||||
/** Index answers by the folder they were asked in, then by name. */
|
||||
const answers = new Map<string, Map<string, Promise<SymbolMatch[]>>>();
|
||||
const NAMES_PER_FOLDER = 2000;
|
||||
const MAX_FOLDERS = 16;
|
||||
|
||||
/** The index's symbols named exactly each of `names` inside `within`; one request for the names not asked before. */
|
||||
export function lookupSymbols(within: string, names: Iterable<string>): Map<string, Promise<SymbolMatch[]>> {
|
||||
const known = answers.get(within) ?? new Map<string, Promise<SymbolMatch[]>>();
|
||||
let known = answers.get(within);
|
||||
if (known) {
|
||||
answers.delete(within);
|
||||
} else {
|
||||
if (answers.size >= MAX_FOLDERS) answers.delete(answers.keys().next().value!);
|
||||
known = new Map<string, Promise<SymbolMatch[]>>();
|
||||
}
|
||||
answers.set(within, known);
|
||||
const wanted = new Set(names);
|
||||
const missing = [...wanted].filter((name) => !known.has(name));
|
||||
const result = new Map<string, Promise<SymbolMatch[]>>();
|
||||
const missing: string[] = [];
|
||||
for (const name of wanted) {
|
||||
const hit = known.get(name);
|
||||
if (hit) result.set(name, hit);
|
||||
else missing.push(name);
|
||||
}
|
||||
if (missing.length) {
|
||||
const found = call(commands.findSymbolsNamed(missing, within)).catch(() => []);
|
||||
for (const name of missing) {
|
||||
const promise = found.then((symbols) => symbols.filter((symbol) => symbol.name === name));
|
||||
result.set(name, promise);
|
||||
if (known.size >= NAMES_PER_FOLDER) known.delete(known.keys().next().value!);
|
||||
known.set(
|
||||
name,
|
||||
found.then((symbols) => symbols.filter((symbol) => symbol.name === name)),
|
||||
);
|
||||
known.set(name, promise);
|
||||
}
|
||||
}
|
||||
return new Map([...wanted].map((name) => [name, known.get(name)!]));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Narrows `symbols` by each preference in turn, skipping one that would leave nothing. */
|
||||
|
||||
@@ -13,7 +13,7 @@ import { AgentsStatus } from "./AgentsStatus";
|
||||
import { activate } from "./index";
|
||||
import { openChangeDiff } from "./session/ChangesPane";
|
||||
import * as actions from "@/platform/actions";
|
||||
import { TASK_DRAG } from "./model";
|
||||
import { SESSION_KIND, sessionKey, TASK_DRAG } from "./model";
|
||||
import {
|
||||
connect,
|
||||
disconnect,
|
||||
@@ -265,6 +265,88 @@ describe("agent unread activity", () => {
|
||||
expect(useAgents.getState().unread.size).toBe(0);
|
||||
expect([...useAgents.getState().tasks.keys()]).toEqual(["other"]);
|
||||
});
|
||||
|
||||
it("evicts entries, subagent entries, changes, and scroll positions when a task is removed or archived", () => {
|
||||
backend.tabs = [
|
||||
{
|
||||
input: { kind: SESSION_KIND, key: sessionKey("open"), data: { task: "open" } },
|
||||
title: "open",
|
||||
icon: "toolwindow-agents",
|
||||
lastActive: 1,
|
||||
},
|
||||
];
|
||||
useAgents.setState((s) => ({
|
||||
tasks: new Map(s.tasks).set("two", task("two", "ready")).set("open", task("open", "ready")),
|
||||
entries: new Map(s.entries)
|
||||
.set("one", [{ type: "agent", text: "Answer one" }])
|
||||
.set("one/child", [{ type: "agent", text: "Child one" }])
|
||||
.set("one1", [{ type: "agent", text: "Answer one1" }])
|
||||
.set("two", [{ type: "agent", text: "Answer two" }])
|
||||
.set("open", [{ type: "agent", text: "Answer open" }]),
|
||||
changes: new Map(s.changes)
|
||||
.set("one", [{ path: "a.ts", relPath: "a.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }])
|
||||
.set("two", [{ path: "b.ts", relPath: "b.ts", oldPath: null, kind: "modified", added: 1, removed: 0 }]),
|
||||
groupedChanges: new Map(s.groupedChanges)
|
||||
.set("one", { uncommitted: [], commits: [] })
|
||||
.set("two", { uncommitted: [], commits: [] }),
|
||||
scrollPositions: new Map(s.scrollPositions)
|
||||
.set("one", { top: 100, stick: false })
|
||||
.set("one/child", { top: 50, stick: false }),
|
||||
}));
|
||||
emit({ type: "removed", id: "one" });
|
||||
const afterRemoved = useAgents.getState();
|
||||
expect(afterRemoved.entries.has("one")).toBe(false);
|
||||
expect(afterRemoved.entries.has("one/child")).toBe(false);
|
||||
expect(afterRemoved.changes.has("one")).toBe(false);
|
||||
expect(afterRemoved.groupedChanges.has("one")).toBe(false);
|
||||
expect(afterRemoved.scrollPositions.has("one")).toBe(false);
|
||||
expect(afterRemoved.scrollPositions.has("one/child")).toBe(false);
|
||||
expect(afterRemoved.entries.has("one1")).toBe(true);
|
||||
expect(afterRemoved.entries.has("two")).toBe(true);
|
||||
|
||||
emit({ type: "task", task: task("two", "archived") });
|
||||
const afterArchived = useAgents.getState();
|
||||
expect(afterArchived.entries.has("two")).toBe(false);
|
||||
expect(afterArchived.changes.has("two")).toBe(false);
|
||||
expect(afterArchived.groupedChanges.has("two")).toBe(false);
|
||||
|
||||
// An archived task that is still open in a tab keeps its entries until closed.
|
||||
emit({ type: "task", task: task("open", "archived") });
|
||||
expect(useAgents.getState().entries.has("open")).toBe(true);
|
||||
backend.tabs = [];
|
||||
const dispose = activate();
|
||||
try {
|
||||
const sessionKind = useContributions.getState().editorKinds.get(SESSION_KIND);
|
||||
sessionKind?.onClose?.({ kind: SESSION_KIND, key: sessionKey("open"), data: { task: "open" } });
|
||||
expect(useAgents.getState().entries.has("open")).toBe(false);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"releases the previously docked task when another task or New Task replaces it (via New Task: %s)",
|
||||
(viaHome) => {
|
||||
setSessionLocation("toolWindow");
|
||||
const tasks = new Map<string, AgentTask>();
|
||||
const entries = new Map<string, AgentEntry[]>();
|
||||
for (let i = 1; i <= 7; i++) {
|
||||
const id = `D${i}`;
|
||||
tasks.set(id, task(id, "ready"));
|
||||
entries.set(id, [{ type: "agent", text: `Reply ${id}` }]);
|
||||
}
|
||||
useAgents.setState({ tasks, entries });
|
||||
for (let i = 1; i <= 7; i++) {
|
||||
if (viaHome) openHome();
|
||||
openTask(`D${i}`);
|
||||
}
|
||||
const state = useAgents.getState();
|
||||
expect(state.docked).toBe("D7");
|
||||
expect(state.entries.has("D1")).toBe(false);
|
||||
expect(state.entries.has("D7")).toBe(true);
|
||||
expect(state.entries.size).toBe(6); // D7 docked + 5 most recently un-docked (D2..D6)
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("agent unread indicators", () => {
|
||||
|
||||
@@ -115,7 +115,8 @@ export function declaredCatalogs(settings: string): DeclaredCatalog[] {
|
||||
}
|
||||
|
||||
const readText = (path: string) => call(commands.fsReadText(path)).catch(() => null);
|
||||
const join = (dir: string, rel: string) => (rel.startsWith("/") ? rel : `${dir}/${rel.replace(/^\.\//, "")}`);
|
||||
const join = (dir: string, rel: string) =>
|
||||
rel.startsWith("/") || /^[A-Za-z]:[\\/]/.test(rel) ? rel : `${dir}/${rel.replace(/^\.\//, "")}`;
|
||||
|
||||
/**
|
||||
* The catalogs a build script sees: those of the nearest enclosing build (its settings file).
|
||||
|
||||
@@ -512,7 +512,7 @@
|
||||
}
|
||||
|
||||
.detailsNotice {
|
||||
margin: 0 0 12px;
|
||||
margin: 12px 0 0;
|
||||
}
|
||||
|
||||
.marketOverview {
|
||||
|
||||
@@ -8,40 +8,45 @@ import { PluginView } from "../views/PluginView";
|
||||
vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), isTauri: () => true }));
|
||||
|
||||
describe("html bodies in the app", () => {
|
||||
it("writes the document into the plugin scheme's host page, not a srcdoc that inherits the workbench CSP", async () => {
|
||||
const view: View = {
|
||||
toolbar: [],
|
||||
body: { kind: "html", value: "<p>chart</p><script>draw()</script>" },
|
||||
status: null,
|
||||
};
|
||||
setPluginsBackend({ ...createMemoryPluginsBackend([]), renderView: vi.fn(async () => view) });
|
||||
const { container } = render(<PluginView pluginId="charts" view="chart" />);
|
||||
await waitFor(() => expect(container.querySelector("iframe")).not.toBeNull());
|
||||
const frame = container.querySelector("iframe")!;
|
||||
expect(frame.hasAttribute("srcdoc")).toBe(false);
|
||||
expect(frame.getAttribute("src")).toMatch(
|
||||
/^(openidea-plugin:\/\/localhost|http:\/\/openidea-plugin\.localhost)\/\.frame$/,
|
||||
);
|
||||
expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
|
||||
|
||||
const post = vi.spyOn(frame.contentWindow!, "postMessage");
|
||||
const ready = (source: Window | null) =>
|
||||
window.dispatchEvent(new MessageEvent("message", { data: { tag: FRAME_TAG, ready: true }, source }));
|
||||
// The listener is added in an effect that can run after the frame is in the DOM.
|
||||
await waitFor(() => {
|
||||
ready(frame.contentWindow);
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
{ tag: FRAME_TAG, document: expect.stringContaining("<p>chart</p><script>draw()</script>") },
|
||||
"*",
|
||||
it.each([false, true])(
|
||||
"writes the document into the plugin host page with an earlier theme message: %s",
|
||||
async (themeFirst) => {
|
||||
const view: View = {
|
||||
toolbar: [],
|
||||
body: { kind: "html", value: "<p>chart</p><script>draw()</script>" },
|
||||
status: null,
|
||||
};
|
||||
setPluginsBackend({ ...createMemoryPluginsBackend([]), renderView: vi.fn(async () => view) });
|
||||
const { container } = render(<PluginView pluginId="charts" view="chart" />);
|
||||
await waitFor(() => expect(container.querySelector("iframe")).not.toBeNull());
|
||||
const frame = container.querySelector("iframe")!;
|
||||
expect(frame.hasAttribute("srcdoc")).toBe(false);
|
||||
expect(frame.getAttribute("src")).toMatch(
|
||||
/^(openidea-plugin:\/\/localhost|http:\/\/openidea-plugin\.localhost)\/\.frame$/,
|
||||
);
|
||||
});
|
||||
const doc = (post.mock.calls[0]![0] as { document: string }).document;
|
||||
expect(doc).toContain('<meta http-equiv="Content-Security-Policy"');
|
||||
expect(doc).toContain("window.openidea");
|
||||
expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
|
||||
|
||||
// Not from the frame: ignored.
|
||||
post.mockClear();
|
||||
ready(window);
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
const post = vi.spyOn(frame.contentWindow!, "postMessage");
|
||||
if (themeFirst) frame.contentWindow!.postMessage({ tag: FRAME_TAG, theme: { dark: true, vars: {} } }, "*");
|
||||
const ready = (source: Window | null) =>
|
||||
window.dispatchEvent(new MessageEvent("message", { data: { tag: FRAME_TAG, ready: true }, source }));
|
||||
// The listener is added in an effect that can run after the frame is in the DOM.
|
||||
await waitFor(() => {
|
||||
ready(frame.contentWindow);
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
{ tag: FRAME_TAG, document: expect.stringContaining("<p>chart</p><script>draw()</script>") },
|
||||
"*",
|
||||
);
|
||||
});
|
||||
const documentCall = post.mock.calls.find(([message]) => typeof message?.document === "string")!;
|
||||
const doc = (documentCall[0] as { document: string }).document;
|
||||
expect(doc).toContain('<meta http-equiv="Content-Security-Policy"');
|
||||
expect(doc).toContain("window.openidea");
|
||||
|
||||
// Not from the frame: ignored.
|
||||
post.mockClear();
|
||||
ready(window);
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -41,6 +41,12 @@ describe("Find in Files module and custom scopes", () => {
|
||||
path: "/p/web",
|
||||
});
|
||||
expect(resolveFindScope({ ...base, scopeTab: "module", module: "" }, inputs)).toEqual({ kind: "project" });
|
||||
// A Windows workspace member is a drive-letter path, not one under the first project (#4069).
|
||||
const windows = { ...inputs, root: "C:/tmp/alpha" };
|
||||
expect(resolveFindScope({ ...base, scopeTab: "module", module: "C:/tmp/beta" }, windows)).toEqual({
|
||||
kind: "directory",
|
||||
path: "C:/tmp/beta",
|
||||
});
|
||||
});
|
||||
|
||||
it("named scopes resolve to file sets, files and custom patterns", () => {
|
||||
|
||||
@@ -35,6 +35,8 @@ describe("parseLocationQuery", () => {
|
||||
expect(parseLocationQuery('"src/a.ts"').text).toBe("src/a.ts");
|
||||
expect(parseLocationQuery("file:///dev/acme/My%20File.kt", "/dev/acme").text).toBe("My File.kt");
|
||||
expect(parseLocationQuery("src\\main\\App.kt").text).toBe("src/main/App.kt");
|
||||
// Windows file URLs, with a space and an encoded `#` in the name (#4079).
|
||||
expect(parseLocationQuery("file:///C:/work/sample/src/a%20b%23c.txt", "C:/work/sample").text).toBe("src/a b#c.txt");
|
||||
});
|
||||
|
||||
it("selectionOf maps to an editor selection", () => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
countUsages,
|
||||
groupState,
|
||||
markDone,
|
||||
mayMatchLineBreak,
|
||||
nextPending,
|
||||
pendingUsages,
|
||||
replacePreviewLines,
|
||||
@@ -217,3 +218,14 @@ describe("replace previews", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mayMatchLineBreak", () => {
|
||||
it("tells patterns whose matches can span lines (#4082)", () => {
|
||||
expect(mayMatchLineBreak("JOIN\\nTARGET", true)).toBe(true);
|
||||
expect(mayMatchLineBreak("a\\s+b", true)).toBe(true);
|
||||
expect(mayMatchLineBreak("[^x]", true)).toBe(true);
|
||||
expect(mayMatchLineBreak("JOIN.TARGET", true)).toBe(false);
|
||||
expect(mayMatchLineBreak("JOIN\nTARGET", false)).toBe(true);
|
||||
expect(mayMatchLineBreak("a\\nb", false)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -23,10 +23,13 @@ export function parseLocationQuery(raw: string, root?: string | null): ParsedQue
|
||||
if (/^file:\/\//i.test(text)) {
|
||||
text = text.replace(/^file:\/\//i, "");
|
||||
try {
|
||||
text = decodeURI(text);
|
||||
// Component decoding: `%23` in a file name is a `#`, not a fragment.
|
||||
text = decodeURIComponent(text);
|
||||
} catch {
|
||||
/* keep as is */
|
||||
}
|
||||
// `file:///C:/x` names `C:/x` on Windows.
|
||||
if (/^\/[a-zA-Z]:\//.test(text)) text = text.slice(1);
|
||||
}
|
||||
if (/^[a-zA-Z]:\\/.test(text) || (text.includes("\\") && !text.includes("/"))) text = text.replace(/\\/g, "/");
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
groupState,
|
||||
loadReplacePreview,
|
||||
markDone,
|
||||
mayMatchLineBreak,
|
||||
nextPending,
|
||||
pendingUsages,
|
||||
replacePreviewLines,
|
||||
@@ -362,8 +363,14 @@ function FindInFilesDialog() {
|
||||
});
|
||||
clearPreviewCache();
|
||||
setPreviewVersion((v) => v + 1);
|
||||
// Replacements that add or remove lines (or a stopped run) invalidate the positions found.
|
||||
if (summary.cancelled || /\n|\\n/.test(s.replacement)) {
|
||||
// Positions found are stale when lines were added or removed (a multi-line replacement or
|
||||
// match), the run stopped, or a target no longer matched (#4082): search again.
|
||||
if (
|
||||
summary.cancelled ||
|
||||
/\n|\\n/.test(s.replacement) ||
|
||||
mayMatchLineBreak(s.pattern, s.isRegex) ||
|
||||
summary.replacements < usages.length
|
||||
) {
|
||||
setRerun((r) => r + 1);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -300,3 +300,9 @@ export function replacePreviewLines(before: string, edits: readonly TextEdit[]):
|
||||
for (let l = next; l < lines.length; l++) out.push({ kind: "same", line: l, text: lines[l] ?? "" });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a match of `pattern` can span lines, so replacing it may remove line breaks. */
|
||||
export function mayMatchLineBreak(pattern: string, regex: boolean): boolean {
|
||||
if (!regex) return pattern.includes("\n");
|
||||
return /\n|\\[nrsSWD]|\[\^/.test(pattern);
|
||||
}
|
||||
@@ -255,9 +255,7 @@ export function resolveFindScope(o: FindOptions, inputs: ScopeInputs): SearchSco
|
||||
if (o.scopeTab === "directory" && o.directory.trim())
|
||||
return { kind: "directory", path: resolveDirectory(o.directory, root) };
|
||||
if (o.scopeTab === "module")
|
||||
return o.module && root
|
||||
? { kind: "directory", path: o.module.startsWith("/") ? o.module : `${root}/${o.module}` }
|
||||
: { kind: "project" };
|
||||
return o.module && root ? { kind: "directory", path: resolveDirectory(o.module, root) } : { kind: "project" };
|
||||
if (o.scopeTab !== "scope") return { kind: "project" };
|
||||
const custom = customScopeName(o.namedScope);
|
||||
if (custom !== null) {
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
background: var(--bg-editor);
|
||||
--compare-side: minmax(0, 1fr) 72px 132px;
|
||||
/* Names keep a readable width; size and date give way first in a narrow tab. */
|
||||
--compare-side: minmax(96px, 1fr) minmax(0, 72px) minmax(0, 132px);
|
||||
--compare-columns: var(--compare-side) 28px var(--compare-side);
|
||||
}
|
||||
.paths {
|
||||
@@ -118,15 +119,19 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.num {
|
||||
justify-content: flex-end;
|
||||
text-align: right;
|
||||
/* Plain text cells: a narrow column ends in an ellipsis instead of clipping both edges. */
|
||||
.num,
|
||||
.date {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.num {
|
||||
text-align: right;
|
||||
}
|
||||
.date {
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.marker {
|
||||
justify-content: center;
|
||||
|
||||
@@ -96,9 +96,11 @@ export function directoryRows(
|
||||
const both = (e: DirectoryCompareEntry) => e.leftKind === "dir" && e.rightKind === "dir";
|
||||
const byPath = new Map(entries.map((e) => [e.path, e]));
|
||||
const oneSided = new Set(entries.filter((e) => directory(e) && (!e.leftKind || !e.rightKind)).map((e) => e.path));
|
||||
// The outermost one-sided folder: the only row shown for its whole subtree.
|
||||
const owner = (path: string) => {
|
||||
for (let p = parentOf(path); p; p = parentOf(p)) if (oneSided.has(p)) return p;
|
||||
return null;
|
||||
let found: string | null = null;
|
||||
for (let p = parentOf(path); p; p = parentOf(p)) if (oneSided.has(p)) found = p;
|
||||
return found;
|
||||
};
|
||||
const matched = new Set<string>();
|
||||
for (const e of entries) if (q && e.path.toLocaleLowerCase().includes(q)) matched.add(owner(e.path) ?? e.path);
|
||||
@@ -132,7 +134,7 @@ function Side({ entry, side, folder }: { entry: DirectoryCompareEntry; side: "le
|
||||
const name = folder ? entry.path : nameOf(entry.path);
|
||||
return (
|
||||
<>
|
||||
<span role="gridcell" className={clsx(styles.cell, styles.name)}>
|
||||
<span role="gridcell" className={styles.cell}>
|
||||
{kind && (
|
||||
<>
|
||||
<Icon name={kind === "dir" ? "folder" : fileIconName(name)} size={14} />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Chunk, MergeView } from "@codemirror/merge";
|
||||
import { Chunk, MergeView, unifiedMergeView } from "@codemirror/merge";
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { applyChunk, arrowControls } from "../diffControls";
|
||||
import {
|
||||
DEFAULT_DIFF_OPTIONS,
|
||||
@@ -363,6 +363,35 @@ describe("diff options", () => {
|
||||
parent.remove();
|
||||
});
|
||||
|
||||
it("paints whole inserted and deleted blocks of the unified viewer as blocks, without word marks", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
doc: "keep\nvalue = new\nmid\n first();\n second();\nend\n",
|
||||
parent,
|
||||
extensions: [
|
||||
viewerBase({ readOnly: true }),
|
||||
diffWords,
|
||||
unifiedMergeView({
|
||||
original: "dropped\nkeep\nvalue = old\nmid\nend\n gone();\n away();\n",
|
||||
highlightChanges: true,
|
||||
mergeControls: false,
|
||||
diffConfig: ideaDiffConfig("none", "words"),
|
||||
}),
|
||||
],
|
||||
});
|
||||
const texts = (selector: string) => [...view.dom.querySelectorAll(selector)].map((e) => e.textContent);
|
||||
// A whole block (IDEA's fragment without inner ones) has no words to compare: a full-width line tint only.
|
||||
expect(texts(".cm-diffLine-inserted:not(.cm-diffLine-fine)")).toEqual([" first();", " second();"]);
|
||||
expect(texts(".cm-changedText")).toEqual(["new"]);
|
||||
expect(texts(".cm-deletedChunk .cm-deletedLine")).toEqual(["dropped", "value = old", " gone();", " away();"]);
|
||||
expect(texts(".cm-deletedText")).toEqual(["old"]);
|
||||
// The old lines of the compared chunk take its lighter colour, whole deleted blocks the full one.
|
||||
expect(texts(".cm-diffWords .cm-deletedChunk:has(+ .cm-diffLine-fine)")).toEqual(["value = old"]);
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
|
||||
it("gives a read-only side a tab stop and leaves an editable side alone", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
@@ -467,6 +496,8 @@ describe("oversized line comparison", () => {
|
||||
[updatedA, nextA, b],
|
||||
] as const) {
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
// No words compared: the unified viewer paints whole blocks, as for IDEA's own chunks.
|
||||
expect(chunks.every((chunk) => chunk.changes.length === 0)).toBe(true);
|
||||
let restored = target;
|
||||
for (const chunk of [...chunks].reverse()) {
|
||||
const edit = transferChunk(chunk, "a", source, restored);
|
||||
|
||||
@@ -126,6 +126,20 @@ describe("Diff toolbar", () => {
|
||||
mounted.unmount();
|
||||
localStorage.removeItem("openidea.vcs.diffOptions");
|
||||
});
|
||||
it("shows lines added to two texts as one block in the unified viewer, as a plugin's diff", async () => {
|
||||
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "unified", highlight: "words" }));
|
||||
const data = {
|
||||
path: "plugin-diff:/Rules.java",
|
||||
left: { type: "text", text: "class Rules {\n int a;\n}\n", label: "Before" },
|
||||
right: { type: "text", text: "class Rules {\n int a;\n void check() {\n run();\n }\n}\n", label: "After" },
|
||||
};
|
||||
const mounted = render(<DiffEditor input={{ ...input, data } as EditorInput} />);
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-diffLine-inserted")).toHaveLength(3));
|
||||
expect(mounted.container.querySelector(".cm-mergeView")).toBeNull();
|
||||
expect(mounted.container.querySelector(".cm-changedText, .cm-deletedText, .cm-diffWord")).toBeNull();
|
||||
mounted.unmount();
|
||||
localStorage.removeItem("openidea.vcs.diffOptions");
|
||||
});
|
||||
it("shows a binary notice for disk comparisons instead of identical empty text", async () => {
|
||||
probe.mockResolvedValue({ status: "ok", data: { size: 3, binary: true, tooLarge: false } });
|
||||
const binaryInput = {
|
||||
|
||||
@@ -116,6 +116,13 @@ describe("disk directory comparison", () => {
|
||||
"dir/sub/c.txt",
|
||||
]);
|
||||
expect(directoryRows(entries, all, "inside").map(label)).toEqual(["gone"]);
|
||||
// A match nested deeper inside a one-sided folder still shows that folder's row (#4085).
|
||||
const nested = [
|
||||
row("only-left", "leftOnly", "dir", null),
|
||||
row("only-left/sub", "leftOnly", "dir", null),
|
||||
row("only-left/sub/nested.txt", "leftOnly", "file", null),
|
||||
];
|
||||
expect(directoryRows(nested, new Set(["leftOnly"]), "nested.txt").map(label)).toEqual(["only-left"]);
|
||||
expect(directoryRows(entries, new Set(["rightOnly"]), "").map(label)).toEqual(["<dir/sub>", "dir/sub/c.txt"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -377,12 +377,14 @@ export const viewerTheme = EditorView.theme(
|
||||
margin: "0 -1px",
|
||||
verticalAlign: "top",
|
||||
},
|
||||
// The unified view: old lines deleted, new lines inserted.
|
||||
// The unified view: old lines deleted, new lines inserted. The old lines of a chunk whose words
|
||||
// were compared sit right above its first new line and take the lighter colour too.
|
||||
".cm-deletedChunk": { backgroundColor: diffTint("deleted", 70) },
|
||||
"&.cm-diffWords .cm-deletedChunk": { backgroundColor: diffTint("deleted", 28) },
|
||||
".cm-deletedChunk .cm-deletedText": { background: diffTint("deleted", 85) },
|
||||
"&.cm-diffWords .cm-deletedChunk:has(+ .cm-diffLine-fine)": { backgroundColor: diffTint("deleted", 28) },
|
||||
// Full line height, as `.cm-diffWord`.
|
||||
".cm-deletedChunk .cm-deletedText": { display: "inline-block", background: diffTint("deleted", 85) },
|
||||
"&.cm-merge-a .cm-changedText": { background: diffTint("deleted", 85) },
|
||||
"&.cm-merge-b .cm-changedText": { background: diffTint("inserted", 85) },
|
||||
"&.cm-merge-b .cm-changedText": { display: "inline-block", background: diffTint("inserted", 85) },
|
||||
".cm-changeGutter": { width: "3px", paddingLeft: "0" },
|
||||
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": { background: "var(--gutter-deleted)" },
|
||||
"&.cm-merge-b .cm-changedLineGutter": { background: "var(--gutter-modified)" },
|
||||
|
||||
@@ -140,7 +140,7 @@ export const getDiffInsights = (chunks: readonly Chunk[]): DiffInsights => insig
|
||||
*/
|
||||
export const hasInnerFragments = (chunk: Chunk) => !!fragments.get(chunk)?.inner;
|
||||
|
||||
/** IDEA's line fragments as chunks; `changes` hold the inner fragments, or the whole block. */
|
||||
/** IDEA's line fragments as chunks; `changes` hold the inner fragments, if any. */
|
||||
export function ideaChunks(a: Text, b: Text, ignore: IgnorePolicy, highlight: HighlightPolicy): readonly Chunk[] {
|
||||
return toChunks(a, b, ideaOf(ideaDiffConfig(ignore, highlight))!);
|
||||
}
|
||||
@@ -160,16 +160,18 @@ function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
|
||||
compared = compareTexts(textA, textB, idea);
|
||||
} catch (error) {
|
||||
if (!(error instanceof DiffTooBigError)) throw error;
|
||||
// Repeated lines can exhaust IDEA's search. Keep the viewer usable with a bounded, coarser diff.
|
||||
return remember(build.call(Chunk, a, b, { scanLimit: 500 }));
|
||||
// Repeated lines can exhaust IDEA's search. Keep the viewer usable with a bounded, coarser diff,
|
||||
// its blocks without words as IDEA's own.
|
||||
const coarse = build.call(Chunk, a, b, { scanLimit: 500 });
|
||||
return remember(coarse.map((c) => new Chunk([], c.fromA, c.toA, c.fromB, c.toB, c.precise)));
|
||||
}
|
||||
const chunks = compared.map((f) => {
|
||||
// `to` is one past the last line's end, past the document for its last line.
|
||||
const toA = f.startLine1 === f.endLine1 ? f.startOffset1 : f.endLine1 === a.lines ? a.length + 1 : f.endOffset1;
|
||||
const toB = f.startLine2 === f.endLine2 ? f.startOffset2 : f.endLine2 === b.lines ? b.length + 1 : f.endOffset2;
|
||||
const changes = f.inner
|
||||
? f.inner.map((r) => new Change(r.start1, r.end1, r.start2, r.end2))
|
||||
: [new Change(0, f.endOffset1 - f.startOffset1, 0, f.endOffset2 - f.startOffset2)];
|
||||
// A block without inner fragments has no words to mark (the unified viewer marks `changes`).
|
||||
// A fresh array each: @codemirror/merge caches deleted-line widgets by it.
|
||||
const changes = f.inner ? f.inner.map((r) => new Change(r.start1, r.end1, r.start2, r.end2)) : [];
|
||||
const chunk = new Chunk(changes, f.startOffset1, toA, f.startOffset2, toB);
|
||||
fragments.set(chunk, f);
|
||||
return chunk;
|
||||
|
||||
@@ -231,6 +231,7 @@ describe("markdown preview rendering", () => {
|
||||
});
|
||||
expect(resolveLink(file, "javascript:alert(1)")).toBeNull();
|
||||
expect(joinPath("C:/repo/docs", "../a.md")).toBe("C:/repo/a.md");
|
||||
expect(joinPath("C:/repo/docs", "D:/shared/a.md")).toBe("D:/shared/a.md");
|
||||
expect(joinPath("/repo", "../../a.md")).toBe("/a.md");
|
||||
});
|
||||
|
||||
|
||||
@@ -192,9 +192,9 @@ export type LinkTarget =
|
||||
/** Directory of `file` (forward slashes). */
|
||||
const dirOf = (file: string) => file.slice(0, Math.max(0, file.lastIndexOf("/")));
|
||||
|
||||
/** Joins `rel` onto `dir`, resolving `.` / `..`. Absolute `rel` (leading `/`) is kept. */
|
||||
/** Joins `rel` onto `dir`, resolving `.` / `..`. Absolute `rel` (`/…` or `C:/…`) is kept. */
|
||||
export function joinPath(dir: string, rel: string): string {
|
||||
const parts = (rel.startsWith("/") ? rel : `${dir}/${rel}`).split("/");
|
||||
const parts = (rel.startsWith("/") || /^[A-Za-z]:\//.test(rel) ? rel : `${dir}/${rel}`).split("/");
|
||||
const out: string[] = [];
|
||||
for (const p of parts) {
|
||||
if (p === "..") {
|
||||
|
||||
Reference in new issue
Заблокувати користувача