дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 05:22:23 +02:00
Порівняти коміти
37
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
85ab17b710 | ||
|
|
19d6eab21a | ||
|
|
5c0befeff0 | ||
|
|
07bd8ded5e | ||
|
|
4ab85d5f49 | ||
|
|
3c91adfae2 | ||
|
|
5cfa6614a1 | ||
|
|
e875d97f7c | ||
|
|
31016ee684 | ||
|
|
6a93f1cce6 | ||
|
|
2b4e3c79f8 | ||
|
|
4e90d9fd5c | ||
|
|
ffc2f75d3b | ||
|
|
19587af8b1 | ||
|
|
b2c22ccec6 | ||
|
|
f795aa3232 | ||
|
|
9239b99f3a | ||
|
|
c5be2998ec | ||
|
|
b83df2dbda | ||
|
|
9f7a35f170 | ||
|
|
52b3e14a8c | ||
|
|
934e4ca0e7 | ||
|
|
a2809bda80 | ||
|
|
0fd8389b33 | ||
|
|
19c0ae07f2 | ||
|
|
5a5b53d86b | ||
|
|
ac7a81db1c | ||
|
|
9681e1a118 | ||
|
|
293972baaa | ||
|
|
b173a53004 | ||
|
|
f6e54f581b | ||
|
|
276a30849c | ||
|
|
63abedaadd | ||
|
|
c22a7fa112 | ||
|
|
a46f187428 | ||
|
|
ff826279f2 | ||
|
|
759fb3278d |
No files matched your search
Створено
+44
-44
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4168,7 +4168,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4193,7 +4193,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4211,7 +4211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4225,7 +4225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4235,7 +4235,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4252,7 +4252,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4266,7 +4266,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4293,7 +4293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4329,7 +4329,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4342,7 +4342,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4363,7 +4363,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4388,7 +4388,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4406,7 +4406,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4477,7 +4477,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4496,7 +4496,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4518,7 +4518,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4530,7 +4530,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4547,7 +4547,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4556,7 +4556,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4567,7 +4567,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4624,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4652,7 +4652,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4671,7 +4671,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4694,7 +4694,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4717,7 +4717,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4731,7 +4731,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4751,7 +4751,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4775,7 +4775,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4791,7 +4791,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4812,7 +4812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4833,7 +4833,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4846,7 +4846,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4871,7 +4871,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4886,7 +4886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4899,7 +4899,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4912,7 +4912,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4933,7 +4933,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4954,7 +4954,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4978,7 +4978,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -4994,7 +4994,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6595,7 +6595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.44"
|
||||
version = "0.1.45"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -12,6 +12,7 @@ use ide_db::{
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// One statement of a console run.
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -179,6 +180,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
apply_edits(&c.host, &c.window, &id, &schema, &table, edits).await
|
||||
});
|
||||
d.add("db_console_path", |c| async move { console_path(&c.host, &c.arg::<String>("id")?) });
|
||||
d.add("db_consoles", |c| async move { consoles(&c.host, &c.arg::<String>("id")?, c.arg("create")?) });
|
||||
}
|
||||
|
||||
/// The data sources configured for the project (the tree's roots).
|
||||
@@ -472,11 +474,52 @@ pub async fn apply_edits(
|
||||
/// created on first use. Consoles are files of the project, so a remote
|
||||
/// window resolves it on the host the project runs on.
|
||||
pub fn console_path(host: &Host, id: &str) -> IdeResult<IpcPath> {
|
||||
let file = console_dir(host, id)?.join("console.sql");
|
||||
if !file.exists() {
|
||||
std::fs::write(&file, "")?;
|
||||
}
|
||||
Ok(file.into())
|
||||
}
|
||||
|
||||
/// The query consoles of data source `id`: the default `console.sql`, then
|
||||
/// `console_1.sql`, `console_2.sql`… in order. `create` adds the next one first
|
||||
/// (DataGrip's New › Query Console).
|
||||
pub fn consoles(host: &Host, id: &str, create: bool) -> IdeResult<Vec<IpcPath>> {
|
||||
let dir = console_dir(host, id)?;
|
||||
let default = dir.join("console.sql");
|
||||
let mut numbered: Vec<(u32, PathBuf)> = std::fs::read_dir(&dir)?
|
||||
.filter_map(|e| {
|
||||
let path = e.ok()?.path();
|
||||
let n = path.file_name()?.to_str()?.strip_prefix("console_")?.strip_suffix(".sql")?.parse().ok()?;
|
||||
Some((n, path))
|
||||
})
|
||||
.collect();
|
||||
numbered.sort();
|
||||
if create {
|
||||
// The default console comes first; once it exists, the next number.
|
||||
if !default.exists() {
|
||||
std::fs::write(&default, "")?;
|
||||
} else {
|
||||
let n = numbered.last().map_or(1, |(n, _)| n + 1);
|
||||
let file = dir.join(format!("console_{n}.sql"));
|
||||
std::fs::write(&file, "")?;
|
||||
numbered.push((n, file));
|
||||
}
|
||||
}
|
||||
let mut out: Vec<IpcPath> = Vec::new();
|
||||
if default.exists() {
|
||||
out.push(default.into());
|
||||
}
|
||||
out.extend(numbered.into_iter().map(|(_, p)| p.into()));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
let (source, database) = ide_db::split_target(id);
|
||||
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
return Err(IdeError::invalid("invalid data source id"));
|
||||
}
|
||||
// One console per database: `<id>` for the default one, `<id>.<database>` for the others.
|
||||
let name = match database {
|
||||
Some(db) => {
|
||||
let safe: String =
|
||||
@@ -487,9 +530,5 @@ pub fn console_path(host: &Host, id: &str) -> IdeResult<IpcPath> {
|
||||
};
|
||||
let dir = host.data_dir.join("consoles").join("db").join(&name);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let file = dir.join("console.sql");
|
||||
if !file.exists() {
|
||||
std::fs::write(&file, "")?;
|
||||
}
|
||||
Ok(file.into())
|
||||
Ok(dir)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::doc::blocking;
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use crate::rpc::Dispatcher;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, Location, Pos};
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -22,6 +22,23 @@ pub struct WebGoto {
|
||||
|
||||
const MAX_WEB_TARGETS: usize = 200;
|
||||
|
||||
/// A Python class definition and the base names written in its source. The UI builds a
|
||||
/// name → locations index from every class in the project (attached dependency roots
|
||||
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
|
||||
/// server's type-hierarchy provider.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClassInheritance {
|
||||
/// Start of the class definition's selection range (0-based line, UTF-16 column).
|
||||
pub path: IpcPath,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
pub name: String,
|
||||
/// Base names as written in source (bare name, e.g. `AllToAllTokenDispatcher`; a
|
||||
/// qualified name keeps only its last segment).
|
||||
pub bases: Vec<String>,
|
||||
}
|
||||
|
||||
/// The project root and its resource roots (served at `/`), for file references.
|
||||
fn reference_roots(project: &Project) -> (PathBuf, Vec<PathBuf>) {
|
||||
let resources = project.roots().resource_dirs().iter().map(|d| project.root.join(d)).collect();
|
||||
@@ -174,6 +191,74 @@ pub async fn nav_index_definitions(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Every Python class in the project (attached dependency roots included) and its base
|
||||
/// names. The index covers content roots, so this is the whole-project answer the UI uses
|
||||
/// for inheritance gutter markers when no type-hierarchy provider exists.
|
||||
pub async fn nav_inheritance(host: &Host, window: &str) -> IdeResult<Vec<ClassInheritance>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let python = LanguageId::new("python");
|
||||
let files = project.index.files_with_extensions(&["py".into(), "pyi".into()], 20_000);
|
||||
let mut cache = CLASS_BASES.lock();
|
||||
let mut out = Vec::new();
|
||||
for path in files {
|
||||
// The open (possibly unsaved) buffer is keyed by its text, a file on disk by its
|
||||
// size and modification time, so only changed files are parsed again.
|
||||
let open = project.documents.text_of(&path);
|
||||
let stamp = match &open {
|
||||
Some(text) => Stamp::Text(text_hash(text)),
|
||||
None => match std::fs::metadata(&path) {
|
||||
Ok(m) => Stamp::Disk(m.len(), m.modified().ok()),
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
let classes = match cache.get(&path) {
|
||||
Some((cached, classes)) if *cached == stamp => classes,
|
||||
_ => {
|
||||
let text = match open {
|
||||
Some(text) => text,
|
||||
None => match project.text_of(&path) {
|
||||
Ok(text) => text,
|
||||
Err(_) => continue,
|
||||
},
|
||||
};
|
||||
let classes = syntax.class_bases(&python, &text);
|
||||
&cache.entry(path.clone()).insert_entry((stamp, classes)).into_mut().1
|
||||
}
|
||||
};
|
||||
out.extend(classes.iter().map(|class| ClassInheritance {
|
||||
path: IpcPath::from(path.clone()),
|
||||
line: class.line,
|
||||
col: class.col,
|
||||
name: class.name.clone(),
|
||||
bases: class.bases.clone(),
|
||||
}));
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum Stamp {
|
||||
Text(u64),
|
||||
Disk(u64, Option<std::time::SystemTime>),
|
||||
}
|
||||
|
||||
fn text_hash(text: &str) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
text.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
type ClassBasesCache = std::collections::HashMap<PathBuf, (Stamp, Vec<ide_language::ClassBases>)>;
|
||||
|
||||
/// Class bases per Python file, reused while the file is unchanged.
|
||||
static CLASS_BASES: std::sync::LazyLock<parking_lot::Mutex<ClassBasesCache>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
|
||||
pub async fn fs_resolve_reference(
|
||||
host: &Host,
|
||||
@@ -249,6 +334,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("nav_index_definitions", |c| async move {
|
||||
nav_index_definitions(&c.host, &c.window, c.arg("name")?, c.arg("from")?).await
|
||||
});
|
||||
d.add("nav_inheritance", |c| async move { nav_inheritance(&c.host, &c.window).await });
|
||||
d.add("fs_resolve_reference", |c| async move {
|
||||
fs_resolve_reference(&c.host, &c.window, c.arg("from")?, c.arg("value")?).await
|
||||
});
|
||||
|
||||
@@ -357,6 +357,7 @@ pub fn restricted_command_allowed(cmd: &str) -> bool {
|
||||
| "docker_set_registry_password"
|
||||
| "docker_run_env"
|
||||
| "db_console_path"
|
||||
| "db_consoles"
|
||||
| "db_export_file"
|
||||
| "vcs_write_patch"
|
||||
| "app_metrics"
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
use ide_core::NullSink;
|
||||
use ide_host::ops::db;
|
||||
use ide_host::{Host, HostConfig};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
|
||||
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
|
||||
};
|
||||
assert!(db::consoles(&host, "pg", false).unwrap().is_empty());
|
||||
// The first new console is the default one, then console_1, console_2…
|
||||
assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql"]);
|
||||
assert_eq!(names(db::consoles(&host, "pg", true).unwrap()), ["console.sql", "console_1.sql"]);
|
||||
let all = db::consoles(&host, "pg", true).unwrap();
|
||||
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
|
||||
// Numbers sort numerically, and the default console path is the first one.
|
||||
std::fs::write(all[0].0.with_file_name("console_10.sql"), "").unwrap();
|
||||
assert_eq!(names(db::consoles(&host, "pg", false).unwrap())[3], "console_10.sql");
|
||||
assert_eq!(db::console_path(&host, "pg").unwrap().0, all[0].0);
|
||||
// Each database of a source has its own consoles.
|
||||
assert!(db::consoles(&host, "pg:other", false).unwrap().is_empty());
|
||||
assert!(db::consoles(&host, "../x", true).is_err());
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The native `nav_inheritance` command: it must return every Python class definition
|
||||
//! in the project — attached dependency roots included — together with the base names
|
||||
//! written in its source, so the UI can compute inheritance gutter markers without a
|
||||
//! language server's type-hierarchy provider.
|
||||
|
||||
use ide_host::{Host, HostConfig, ops};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const WINDOW: &str = "main";
|
||||
|
||||
struct Opened {
|
||||
host: Arc<Host>,
|
||||
root: PathBuf,
|
||||
_tmp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
/// Opens a synthetic project whose Python files carry known class / base shapes, then
|
||||
/// waits for the index to settle (it walks content roots, so dependency roots are covered).
|
||||
async fn open() -> Opened {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("proj");
|
||||
let src = root.join("src");
|
||||
let dep = root.join("vendor");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
std::fs::create_dir_all(&dep).unwrap();
|
||||
|
||||
// Own root: a plain class, a class with two bases + a keyword arg, a qualified base,
|
||||
// and a subscripted generic base. A comment / docstring that mentions `class X(Y)`
|
||||
// must not be reported.
|
||||
std::fs::write(
|
||||
src.join("app.py"),
|
||||
concat!(
|
||||
"class Base:\n",
|
||||
" pass\n",
|
||||
"\n",
|
||||
"class Mixin:\n",
|
||||
" pass\n",
|
||||
"\n",
|
||||
"class Child(Base, Mixin, metaclass=Meta):\n",
|
||||
" # class Ghost(Spook): must be ignored\n",
|
||||
" \"\"\"class Phantom(Apparition): must be ignored\"\"\"\n",
|
||||
" pass\n",
|
||||
"\n",
|
||||
"class Qualified(pkg.mod.Base):\n",
|
||||
" pass\n",
|
||||
"\n",
|
||||
"class Generic(Generic[T]):\n",
|
||||
" pass\n",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
// A second own-root file to prove the command scans more than one file.
|
||||
std::fs::write(src.join("extra.pyi"), "class Stub(Base):\n ...\n").unwrap();
|
||||
// An attached dependency root (content root) — must be covered by the index.
|
||||
std::fs::write(dep.join("dep.py"), "class DepBase:\n pass\n").unwrap();
|
||||
|
||||
let app = tmp.path().join("app");
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: app.join("config"),
|
||||
data_dir: app.join("data"),
|
||||
local_data_dir: app.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
ops::project::open(&host, WINDOW, &root).await.unwrap();
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
let s = ops::nav::index_status(&host, WINDOW).unwrap();
|
||||
if !s.indexing && s.files > 0 {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "indexing timed out; status: {s:?}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Opened { host, root, _tmp: tmp }
|
||||
}
|
||||
|
||||
fn find<'a>(all: &'a [ide_host::ops::nav::ClassInheritance], name: &str) -> &'a ide_host::ops::nav::ClassInheritance {
|
||||
all.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name:?} in {all:#?}"))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn returns_all_python_classes_and_bases() {
|
||||
let p = open().await;
|
||||
let all = ops::nav::nav_inheritance(&p.host, WINDOW).await.unwrap();
|
||||
|
||||
// Both own-root Python files are scanned (src/app.py + src/extra.pyi).
|
||||
let base = find(&all, "Base");
|
||||
assert!(base.path.0.ends_with("src/app.py"), "Base path: {:?}", base.path);
|
||||
// The location is the class name identifier (selection-range start), i.e. after `class `.
|
||||
assert_eq!(base.line, 0);
|
||||
assert_eq!(base.col, 6);
|
||||
assert!(base.bases.is_empty(), "a bare class has no bases: {:?}", base.bases);
|
||||
|
||||
let child = find(&all, "Child");
|
||||
assert_eq!(child.line, 6);
|
||||
assert_eq!(child.col, 6);
|
||||
// The `metaclass=Meta` keyword argument is not a base.
|
||||
assert!(child.bases.contains(&"Base".to_string()), "Child bases: {:?}", child.bases);
|
||||
assert!(child.bases.contains(&"Mixin".to_string()), "Child bases: {:?}", child.bases);
|
||||
assert!(!child.bases.iter().any(|b| b == "Meta"), "metaclass must be skipped: {:?}", child.bases);
|
||||
|
||||
// A qualified base keeps only its last segment.
|
||||
let qualified = find(&all, "Qualified");
|
||||
assert_eq!(qualified.bases, vec!["Base".to_string()], "qualified base: {:?}", qualified.bases);
|
||||
|
||||
// A subscripted generic base keeps the identifier.
|
||||
let generic = find(&all, "Generic");
|
||||
assert_eq!(generic.bases, vec!["Generic".to_string()], "generic base: {:?}", generic.bases);
|
||||
|
||||
// Comments / docstrings are not mistaken for class definitions.
|
||||
assert!(!all.iter().any(|c| c.name == "Ghost" || c.name == "Phantom"), "parsed a comment: {all:#?}");
|
||||
|
||||
// The .pyi stub in the second own-root file is included.
|
||||
let stub = find(&all, "Stub");
|
||||
assert!(stub.path.0.ends_with("src/extra.pyi"), "Stub path: {:?}", stub.path);
|
||||
assert_eq!(stub.bases, vec!["Base".to_string()]);
|
||||
|
||||
// The attached dependency root is covered by the project index.
|
||||
let dep = find(&all, "DepBase");
|
||||
assert!(dep.path.0.starts_with(&p.root), "DepBase path: {:?}", dep.path);
|
||||
|
||||
// Every returned entry is a Python file.
|
||||
assert!(all.iter().all(|c| { matches!(c.path.0.extension().and_then(|e| e.to_str()), Some("py" | "pyi")) }));
|
||||
|
||||
// A file changed on disk is parsed again; the others come from the cache.
|
||||
let extra = p.root.join("src/extra.pyi");
|
||||
std::fs::write(&extra, "class Stub(Child): ...\nclass Added(Base): ...\n").unwrap();
|
||||
let again = ops::nav::nav_inheritance(&p.host, WINDOW).await.unwrap();
|
||||
assert_eq!(find(&again, "Stub").bases, vec!["Child".to_string()]);
|
||||
assert_eq!(find(&again, "Added").bases, vec!["Base".to_string()]);
|
||||
assert_eq!(find(&again, "Child").bases, child.bases);
|
||||
}
|
||||
@@ -821,8 +821,10 @@ fn a_reporting_task_outlives_its_background_budget() {
|
||||
|
||||
#[test]
|
||||
fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
// Room for activation (about 3_100 on macOS, more on Windows) but not for `patient`'s
|
||||
// whole run (about 9_000) without the refill on each report.
|
||||
let f = fixture(Limits {
|
||||
fuel: 3_500,
|
||||
fuel: 6_000,
|
||||
timeout: Duration::from_millis(500),
|
||||
background: Duration::from_millis(5_000),
|
||||
..Limits::default()
|
||||
@@ -831,14 +833,14 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
if f.host.set_capability("misbehave", "process:git", true).is_err() {
|
||||
return;
|
||||
}
|
||||
// Warm up activation in its own call so `patient` starts with a fresh 3_500-fuel budget.
|
||||
// Warm up activation in its own call so `patient` starts with a fresh budget.
|
||||
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
|
||||
|
||||
let out = f.run("misbehave", "patient", None).expect("background task succeeds").expect("output");
|
||||
assert_eq!(out, "still here");
|
||||
|
||||
let err = f.run("misbehave", "spin", None).unwrap_err();
|
||||
assert!(err.contains("exceeded its CPU budget (3500 fuel per call)"), "{err}");
|
||||
assert!(err.contains("exceeded its CPU budget (6000 fuel per call)"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -365,6 +365,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_table_page",
|
||||
"db_apply_edits",
|
||||
"db_console_path",
|
||||
"db_consoles",
|
||||
"ssh_test",
|
||||
"ssh_set_secret",
|
||||
"ssh_password_saved",
|
||||
|
||||
@@ -66,6 +66,7 @@ async fn application_commands_work_in_restricted_projects_and_without_a_project(
|
||||
"docker_set_registry_password",
|
||||
"docker_run_env",
|
||||
"db_console_path",
|
||||
"db_consoles",
|
||||
"db_export_file",
|
||||
"vcs_write_patch",
|
||||
"remote_bootstrap_list",
|
||||
|
||||
@@ -27,17 +27,38 @@ fn git_dir(root: &Path) -> Option<std::path::PathBuf> {
|
||||
Some(if path.is_absolute() { path.to_owned() } else { root.join(path) })
|
||||
}
|
||||
|
||||
/// The config and exclude file of the Git directory `git`; a linked worktree's directory
|
||||
/// (`.git/worktrees/<name>`) reads the shared ones its `commondir` names as well.
|
||||
fn insert_git_inputs(out: &mut std::collections::BTreeSet<std::path::PathBuf>, git: &Path) {
|
||||
out.insert(git.join("config"));
|
||||
out.insert(git.join("info/exclude"));
|
||||
if let Ok(common) = std::fs::read_to_string(git.join("commondir")) {
|
||||
let common = Path::new(common.trim());
|
||||
let common = if common.is_absolute() { common.to_owned() } else { git.join(common) };
|
||||
out.insert(common.join("config"));
|
||||
out.insert(common.join("info/exclude"));
|
||||
}
|
||||
}
|
||||
|
||||
/// External ignore/config inputs, including candidates that do not exist yet.
|
||||
/// These are outside the directory manifest (`.git` is skipped), so the full
|
||||
/// path set must match at warm start.
|
||||
pub(crate) fn external_ignore_candidates(root: &Path) -> Vec<std::path::PathBuf> {
|
||||
let mut out = std::collections::BTreeSet::new();
|
||||
if let Some(git) = git_dir(root) {
|
||||
out.insert(git.join("config"));
|
||||
out.insert(git.join("info/exclude"));
|
||||
insert_git_inputs(&mut out, &git);
|
||||
}
|
||||
out.insert(root.join(".git/config"));
|
||||
out.insert(root.join(".git/info/exclude"));
|
||||
// The walker also reads the ignore files above the root (`parents`), and a project nested
|
||||
// in a repository uses that repository's exclude file and config.
|
||||
for dir in root.ancestors().skip(1) {
|
||||
out.insert(dir.join(".gitignore"));
|
||||
out.insert(dir.join(".ignore"));
|
||||
if let Some(git) = git_dir(dir) {
|
||||
insert_git_inputs(&mut out, &git);
|
||||
}
|
||||
}
|
||||
if let Some(path) = ignore::gitignore::gitconfig_excludes_path() {
|
||||
out.insert(path);
|
||||
}
|
||||
|
||||
@@ -797,6 +797,52 @@ fn warm_start_detects_changed_ignore_rules() {
|
||||
assert_eq!(idx.status().files, 1, "an updated ignore rule invalidates the warm snapshot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_start_detects_changed_ignore_rules_above_the_project() {
|
||||
// The project is a folder of a repository whose ignore files sit above it.
|
||||
let f = Fixture::new(&[("generated/a.rs", "fn a() {}\n"), ("src/b.rs", "fn b() {}\n")]);
|
||||
let repo = f.root.parent().unwrap().to_owned();
|
||||
std::fs::create_dir_all(repo.join(".git/info")).unwrap();
|
||||
std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 2);
|
||||
drop(idx);
|
||||
|
||||
std::fs::write(repo.join(".gitignore"), "proj/generated/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "a new ignore file above the project invalidates the warm snapshot");
|
||||
drop(idx);
|
||||
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
std::fs::write(repo.join(".gitignore"), "").unwrap();
|
||||
std::fs::write(repo.join(".git/info/exclude"), "proj/src/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "so do the enclosing repository's changed rules");
|
||||
assert!(!symbols(&idx, "a", SymbolFilter::All).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_start_detects_a_changed_exclude_file_of_a_linked_worktree() {
|
||||
// The project is a linked worktree: its `.git` file points into the main repository,
|
||||
// whose shared `info/exclude` the walker reads through `commondir`.
|
||||
let f = Fixture::new(&[("generated/a.rs", "fn a() {}\n"), ("src/b.rs", "fn b() {}\n")]);
|
||||
let main = f.root.parent().unwrap().join("main/.git");
|
||||
let worktree = main.join("worktrees/proj");
|
||||
std::fs::create_dir_all(main.join("info")).unwrap();
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
std::fs::write(main.join("HEAD"), "ref: refs/heads/main\n").unwrap();
|
||||
std::fs::write(worktree.join("HEAD"), "ref: refs/heads/wt\n").unwrap();
|
||||
std::fs::write(worktree.join("commondir"), "../..\n").unwrap();
|
||||
std::fs::write(f.root.join(".git"), format!("gitdir: {}\n", worktree.display())).unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 2);
|
||||
drop(idx);
|
||||
|
||||
std::fs::write(main.join("info/exclude"), "generated/\n").unwrap();
|
||||
let idx = f.open();
|
||||
assert_eq!(idx.status().files, 1, "the shared exclude file invalidates the warm snapshot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_start_detects_a_new_file_in_an_existing_empty_directory() {
|
||||
let f = Fixture::new(&[("src/a.rs", "fn a() {}\n")]);
|
||||
|
||||
@@ -22,11 +22,11 @@ pub use markers::{arduino_sketch_root, is_arduino_sketch_dir, marked_root};
|
||||
pub use plugin_point::PluginLanguages;
|
||||
pub use registry::{FileTypes, LanguageRegistry};
|
||||
pub use syntax::{
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken,
|
||||
FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind, SpellingRegion,
|
||||
Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError, VueComponentImport,
|
||||
VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility, set_external_syntax, shift_pos,
|
||||
shift_range,
|
||||
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
|
||||
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
|
||||
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Extraction of Python class base names, used to build an inheritance graph
|
||||
//! without an LSP `typeHierarchyProvider`.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use crate::{LanguageId, Syntax};
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
/// A Python class definition and the base names written in its source.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ClassBases {
|
||||
/// The class name (bare identifier).
|
||||
pub name: String,
|
||||
/// 0-based line of the class name (selection-range start).
|
||||
pub line: u32,
|
||||
/// 0-based UTF-16 column of the class name (selection-range start).
|
||||
pub col: u32,
|
||||
/// Source-written base names (last segment of a qualified name).
|
||||
pub bases: Vec<String>,
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// Class definitions of `text` with their base names, in source order.
|
||||
/// Only Python is supported; every other language returns an empty vector.
|
||||
pub fn class_bases(&self, lang: &LanguageId, text: &str) -> Vec<ClassBases> {
|
||||
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
fn extract(tree: &Tree, text: &str) -> Vec<ClassBases> {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
visit(&mut cursor, &mut |node| {
|
||||
if node.kind() != "class_definition" {
|
||||
return;
|
||||
}
|
||||
let Some(name_node) = node.child_by_field_name("name") else { return };
|
||||
let name = text.get(name_node.byte_range()).unwrap_or_default().to_owned();
|
||||
if name.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Selection-range start of the class: its name identifier (`class Foo`
|
||||
// -> `Foo`), matching `outline.rs` and the gutter marker candidates.
|
||||
let range = idx.range(name_node.start_byte(), name_node.end_byte());
|
||||
let bases = node.child_by_field_name("superclasses").map(|args| base_names(args, text)).unwrap_or_default();
|
||||
out.push(ClassBases { name, line: range.start.line, col: range.start.col, bases });
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Depth-first pre-order traversal of all descendants of `cursor`'s node.
|
||||
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
|
||||
loop {
|
||||
f(cursor.node());
|
||||
if cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn base_names(args: Node, text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = args.walk();
|
||||
for arg in args.named_children(&mut cursor) {
|
||||
if let Some(name) = base_name(arg, text) {
|
||||
out.push(name);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Bare name of one base expression, or `None` for keyword arguments and
|
||||
/// expressions that are not a (possibly qualified) name.
|
||||
fn base_name(arg: Node, text: &str) -> Option<String> {
|
||||
match arg.kind() {
|
||||
"identifier" => text.get(arg.byte_range()).map(str::to_owned),
|
||||
// `pkg.mod.Base` -> `Base`.
|
||||
"attribute" => {
|
||||
let attr = arg.child_by_field_name("attribute")?;
|
||||
(attr.kind() == "identifier").then(|| text.get(attr.byte_range()).unwrap_or_default().to_owned())
|
||||
}
|
||||
// `Generic[T]` -> `Generic`.
|
||||
"subscript" => {
|
||||
let value = arg.child_by_field_name("value")?;
|
||||
(value.kind() == "identifier").then(|| text.get(value.byte_range()).unwrap_or_default().to_owned())
|
||||
}
|
||||
// `metaclass=Meta`, `**kwargs`, `*bases` and other expressions.
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn bases(src: &str) -> Vec<ClassBases> {
|
||||
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
|
||||
S.get_or_init(Syntax::new).class_bases(&LanguageId::new("python"), src)
|
||||
}
|
||||
|
||||
fn shape(src: &str) -> Vec<(String, u32, u32, Vec<String>)> {
|
||||
bases(src).into_iter().map(|c| (c.name, c.line, c.col, c.bases)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_bases() {
|
||||
assert_eq!(shape("class A: pass"), vec![("A".to_owned(), 0, 6, vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_bases_skips_metaclass() {
|
||||
assert_eq!(
|
||||
shape("class B(A, C, metaclass=Meta): pass"),
|
||||
vec![("B".to_owned(), 0, 6, vec!["A".to_owned(), "C".to_owned()])]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qualified_name_takes_last_segment() {
|
||||
assert_eq!(shape("class D(pkg.mod.Base): pass"), vec![("D".to_owned(), 0, 6, vec!["Base".to_owned()])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscript_takes_value() {
|
||||
assert_eq!(shape("class E(Generic[T]): pass"), vec![("E".to_owned(), 0, 6, vec!["Generic".to_owned()])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiline_bases() {
|
||||
let src = "class F(\n A,\n B,\n):\n pass";
|
||||
assert_eq!(shape(src), vec![("F".to_owned(), 0, 6, vec!["A".to_owned(), "B".to_owned()])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_classes() {
|
||||
let src = "class Outer:\n class Inner(Y):\n pass";
|
||||
assert_eq!(
|
||||
shape(src),
|
||||
vec![("Outer".to_owned(), 0, 6, vec![]), ("Inner".to_owned(), 1, 10, vec!["Y".to_owned()]),]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_and_strings_are_ignored() {
|
||||
let src = r#"
|
||||
# class Fake(Nope): pass
|
||||
doc = """
|
||||
class InDocstring(X): pass
|
||||
"""
|
||||
s = 'class InString(Y): pass'
|
||||
class Real(Base): pass
|
||||
"#;
|
||||
assert_eq!(shape(src), vec![("Real".to_owned(), 6, 6, vec!["Base".to_owned()])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_languages_are_empty() {
|
||||
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
|
||||
let s = S.get_or_init(Syntax::new);
|
||||
assert!(s.class_bases(&LanguageId::new("rust"), "struct A;").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod external;
|
||||
mod folding;
|
||||
mod grammars;
|
||||
mod highlight;
|
||||
mod inheritance;
|
||||
pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
@@ -22,6 +23,7 @@ pub use external::{ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken,
|
||||
use grammars::{SPECS, Spec};
|
||||
pub use highlight::{SyntaxHighlightKind, SyntaxHighlights};
|
||||
use ide_core::{LanguageId, OutlineItem, Pos, Range};
|
||||
pub use inheritance::ClassBases;
|
||||
pub use lines::{shift_pos, shift_range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::merge_visibility;
|
||||
|
||||
@@ -482,7 +482,8 @@ mod tests {
|
||||
std::fs::create_dir_all(output.join("test001")).unwrap();
|
||||
// As jdtls writes it: the class's source file name in the path, the library's
|
||||
// classpath attributes after the folder.
|
||||
let escaped = output.to_string_lossy().replace('/', "\\/");
|
||||
// JDT writes the folder as a portable path, `/` on Windows too, each `/` escaped.
|
||||
let escaped = output.to_string_lossy().replace('\\', "/").replace('/', "\\/");
|
||||
let handle = format!("=demo/{escaped}=/ai.openidea.kotlin=/true=/<test001(Db.class");
|
||||
let uri = format!("jdt://contents/main-0/test001/Db.kt?{}", utf8_percent_encode(&handle, PATH));
|
||||
assert_eq!(folder_class(&uri), Some(("test001".into(), "Db".into())));
|
||||
|
||||
@@ -40,22 +40,37 @@ const LOOSE: &AsciiSet = &CONTROLS
|
||||
.add(b'|')
|
||||
.add(b'}');
|
||||
|
||||
/// Percent-encodes the characters URIs don't allow in every `file:` URI in `value`, string
|
||||
/// values and object keys alike (a workspace edit's `changes`). Eclipse's jdtls sends a path
|
||||
/// as is (`file:///H:/项目/…`), which `lsp_types::Uri` rejects, failing the whole response.
|
||||
/// Fields of LSP messages whose value is a URI.
|
||||
const URI_FIELDS: [&str; 9] =
|
||||
["uri", "targetUri", "newUri", "oldUri", "baseUri", "scopeUri", "rootUri", "target", "href"];
|
||||
|
||||
/// Percent-encodes the characters URIs don't allow in the `file:` URIs of `value`: the URI
|
||||
/// fields and the keys of a workspace edit's `changes`. Eclipse's jdtls sends a path as is
|
||||
/// (`file:///H:/项目/…`), which `lsp_types::Uri` rejects, failing the whole response. Other
|
||||
/// strings stay as sent: an edit's `newText` may well start with `file:` (YAML, `.env`).
|
||||
pub fn encode_loose_file_uris(value: &mut Value) {
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
if let Some(encoded) = encode_loose(s) {
|
||||
*s = encoded;
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(encode_loose_file_uris),
|
||||
Value::Object(map) => {
|
||||
if map.keys().any(|k| encode_loose(k).is_some()) {
|
||||
*map = std::mem::take(map).into_iter().map(|(k, v)| (encode_loose(&k).unwrap_or(k), v)).collect();
|
||||
for (key, value) in map.iter_mut() {
|
||||
match value {
|
||||
Value::String(s) if URI_FIELDS.contains(&key.as_str()) => {
|
||||
if let Some(encoded) = encode_loose(s) {
|
||||
*s = encoded;
|
||||
}
|
||||
}
|
||||
Value::Object(changes) if key == "changes" => {
|
||||
if changes.keys().any(|k| encode_loose(k).is_some()) {
|
||||
*changes = std::mem::take(changes)
|
||||
.into_iter()
|
||||
.map(|(k, v)| (encode_loose(&k).unwrap_or(k), v))
|
||||
.collect();
|
||||
}
|
||||
changes.values_mut().for_each(encode_loose_file_uris);
|
||||
}
|
||||
_ => encode_loose_file_uris(value),
|
||||
}
|
||||
}
|
||||
map.values_mut().for_each(encode_loose_file_uris);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -161,9 +176,28 @@ mod tests {
|
||||
assert!(v["edit"]["changes"].get("file:///tmp/%E7%9B%AE%E5%BD%95/b.java").is_some());
|
||||
assert_eq!(v["text"], "项目", "only file: URIs change");
|
||||
// Already encoded: untouched.
|
||||
let mut encoded = serde_json::json!("file:///a%20b/%E9%A1%B9.java");
|
||||
let mut encoded = serde_json::json!({ "uri": "file:///a%20b/%E9%A1%B9.java" });
|
||||
encode_loose_file_uris(&mut encoded);
|
||||
assert_eq!(encoded, "file:///a%20b/%E9%A1%B9.java");
|
||||
assert_eq!(encoded["uri"], "file:///a%20b/%E9%A1%B9.java");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_that_starts_with_file_is_not_a_uri() {
|
||||
// A YAML formatting edit and a completion whose text begins with `file:`.
|
||||
let mut v = serde_json::json!({ "result": [
|
||||
{ "range": { "start": { "line": 0, "character": 0 }, "end": { "line": 1, "character": 0 } }, "newText": "file: a b\n - c\n" },
|
||||
{ "label": "file:", "insertText": "file: ${1:path}", "documentation": "file: the input" }
|
||||
], "edit": { "changes": { "file:///tmp/a b.yaml": [{ "newText": "file: x y" }] } } });
|
||||
encode_loose_file_uris(&mut v);
|
||||
assert_eq!(v["result"][0]["newText"], "file: a b\n - c\n");
|
||||
assert_eq!(v["result"][1]["insertText"], "file: ${1:path}");
|
||||
assert_eq!(v["result"][1]["documentation"], "file: the input");
|
||||
let changes = &v["edit"]["changes"]["file:///tmp/a%20b.yaml"];
|
||||
assert_eq!(changes[0]["newText"], "file: x y");
|
||||
// A diagnostic's help link is a URI too.
|
||||
let mut d = serde_json::json!({ "codeDescription": { "href": "file:///tmp/help files/rule.html" } });
|
||||
encode_loose_file_uris(&mut d);
|
||||
assert_eq!(d["codeDescription"]["href"], "file:///tmp/help%20files/rule.html");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -403,7 +403,7 @@ async fn download_into_copies_only_the_selected_items() {
|
||||
assert!(std::fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing written through the links");
|
||||
}
|
||||
|
||||
let missing = [server.join("gone").to_str().unwrap().to_owned()];
|
||||
let missing = [server.join("gone").to_str().unwrap().replace('\\', "/")];
|
||||
let report = service
|
||||
.download_into(&FsConnection::Local, &missing, &project, &CancellationToken::new(), &mut |_, _, _| {})
|
||||
.await
|
||||
|
||||
@@ -1830,10 +1830,17 @@ pub fn without_derived_in(config: &RunConfig, root: &Path, fallback: Option<&Pat
|
||||
if path.is_absolute()
|
||||
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
{
|
||||
let mut probe = out.clone();
|
||||
probe.command = name.clone();
|
||||
if applied(&probe).command == config.command {
|
||||
out.command = name;
|
||||
// Generated configurations name the bare program (`java`), also on Windows where the
|
||||
// derived path ends in `java.exe`.
|
||||
let bare =
|
||||
name.len().checked_sub(4).filter(|&at| name[at..].eq_ignore_ascii_case(".exe")).map(|at| &name[..at]);
|
||||
for candidate in bare.into_iter().chain([name.as_str()]) {
|
||||
let mut probe = out.clone();
|
||||
probe.command = candidate.to_owned();
|
||||
if applied(&probe).command == config.command {
|
||||
out.command = candidate.to_owned();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -1136,7 +1136,10 @@ pub(crate) fn stash_push(
|
||||
paths: &[PathBuf],
|
||||
) -> IdeResult<()> {
|
||||
let rel = r.rel_paths(paths)?;
|
||||
let mut args = vec!["--literal-pathspecs", "stash", "push", "-q"];
|
||||
// Literal pathspecs only for the chosen files: git's whole-tree stash passes itself `:/`,
|
||||
// which a literal pathspec turns into a file of that name.
|
||||
let mut args = if rel.is_empty() { vec![] } else { vec!["--literal-pathspecs"] };
|
||||
args.extend(["stash", "push", "-q"]);
|
||||
if include_untracked {
|
||||
args.push("--include-untracked");
|
||||
}
|
||||
|
||||
@@ -769,11 +769,11 @@ fn stash_push_list_apply_pop() {
|
||||
let repo = fx.repo();
|
||||
|
||||
fx.write("s.txt", "change 1\n");
|
||||
repo.stash_push(Some("first stash"), false, false).unwrap();
|
||||
repo.stash_push(Some("first stash"), false, false, &[]).unwrap();
|
||||
assert_eq!(fx.read("s.txt"), "base\n");
|
||||
fx.write("s.txt", "change 2\n");
|
||||
fx.write("u.txt", "untracked\n");
|
||||
repo.stash_push(None, true, false).unwrap();
|
||||
repo.stash_push(None, true, false, &[]).unwrap();
|
||||
assert!(!fx.path("u.txt").exists());
|
||||
|
||||
let stashes = repo.stashes().unwrap();
|
||||
@@ -808,7 +808,7 @@ fn stash_keep_index_reinstate_index_and_branch() {
|
||||
fx.write("a.txt", "a staged\n");
|
||||
fx.git(&["add", "a.txt"]);
|
||||
fx.write("b.txt", "b unstaged\n");
|
||||
repo.stash_push(Some("keep"), false, true).unwrap();
|
||||
repo.stash_push(Some("keep"), false, true, &[]).unwrap();
|
||||
// Keep index: the staged change stays, the unstaged one is stashed.
|
||||
assert_eq!(fx.read("a.txt"), "a staged\n");
|
||||
assert_eq!(fx.read("b.txt"), "b\n");
|
||||
|
||||
@@ -67,6 +67,8 @@ The task tab shows the conversation: your messages, the agent's replies, its rea
|
||||
|
||||
On your own messages you can **Edit** (the messages after it are replaced; files already changed stay as they are) or **Retract Message**. On replies you can **Copy Markdown**, **Quote Reply**, **Regenerate Response** and **Branch Conversation from Here**, which starts a new task from that point.
|
||||
|
||||
Right-click a link and choose **Copy Link Address** to copy its URL; **Copy** copies the selected text.
|
||||
|
||||
### Permissions
|
||||
|
||||
When an agent wants to run a command or call a tool that needs approval, the task shows the request and is listed as **Needs Input**. Choose one of the options the agent offers, such as **Allow Once**, **Allow for This Session**, **Always Allow**, **Decline**, **Always Decline** or **Decline and Stop**. Many agents also have a mode picker that approves edits or everything automatically; use it with care.
|
||||
|
||||
@@ -107,6 +107,8 @@ To format on every save, enable **Reformat code** (and optionally **Optimize imp
|
||||
|
||||
Tab placement, the tab limit and what happens when it is reached, the preview tab, sorting, and which tab is activated after one closes are set in **Settings › Editor › General › Editor Tabs**.
|
||||
|
||||
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
|
||||
|
||||
## Split editors
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
|
||||
@@ -75,7 +75,7 @@ Pick **VS Code (macOS)** or **VS Code (Windows)** as the keymap; then `⇧⌘P`
|
||||
| Extensions | **Settings › Plugins** |
|
||||
| `settings.json` | **Settings** (`⌘,` / `Ctrl+Alt+S`), stored in `settings.toml`; per-project values in `.openidea/settings.toml` |
|
||||
| `launch.json` | Run configurations: **Import Run Configurations from .vscode/launch.json** |
|
||||
| Multi-root workspace | **File › New Workspace…** and **Attach Project…** |
|
||||
| Multi-root workspace | **File › New › Workspace…** and **Attach Project…** |
|
||||
|
||||
`.editorconfig` files are applied. VS Code settings and extensions are not imported.
|
||||
|
||||
@@ -84,7 +84,7 @@ Pick **VS Code (macOS)** or **VS Code (Windows)** as the keymap; then `⇧⌘P`
|
||||
Pick **Eclipse (macOS)** or **Eclipse** as the keymap.
|
||||
|
||||
- **Formatter.** To keep using an Eclipse formatter profile for Java, open **Settings › Editor › Code Style › Java**, set **Formatting profile** to **Custom Eclipse formatter XML** and choose the exported XML file.
|
||||
- **Workspaces and projects.** Eclipse opens many projects in one workspace. OpenIDEA opens one project per window; to work on several folders together, create a workspace with **File › New Workspace…** or add folders with **Attach Project…**.
|
||||
- **Workspaces and projects.** Eclipse opens many projects in one workspace. OpenIDEA opens one project per window; to work on several folders together, create a workspace with **File › New › Workspace…** or add folders with **Attach Project…**.
|
||||
- **Perspectives.** OpenIDEA has no perspectives. Arrange tool windows the way you like and save the arrangement with **Window › Tool Window Layouts › Save Current Layout as…**.
|
||||
|
||||
## Concepts at a glance
|
||||
|
||||
@@ -13,7 +13,7 @@ A scratch file is a throwaway file in any language: a place to try a snippet, ke
|
||||
|
||||
<Steps>
|
||||
<Step title="Create one">
|
||||
Choose **File › New Scratch File…** (or **Scratch File** at the top of the Project view's **New** menu).
|
||||
Choose **File › New › Scratch File** (or **Scratch File** at the top of the Project view's **New** menu).
|
||||
</Step>
|
||||
<Step title="Pick a language">
|
||||
Type to filter the language list and press `↵` / `Enter`.
|
||||
|
||||
@@ -73,7 +73,7 @@ The page also has **Expand abbreviations with Tab** and **Show live templates in
|
||||
|
||||
Live templates, postfix settings and macros are stored per user on this machine, not in the project.
|
||||
|
||||
For new-file templates (what **File › New…** creates), see **Settings › Editor › File and Code Templates**.
|
||||
For new-file templates (what **File › New › File…** creates), see **Settings › Editor › File and Code Templates**.
|
||||
|
||||
## Macros
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ This page covers how a plugin works with files:
|
||||
projects.
|
||||
- **Other files** (`fs.wit`, API 1.3): files outside the projects, under explicit grants,
|
||||
and the plugin's own private directory.
|
||||
- **File templates**: entries of the **File › New…** menu, no code needed.
|
||||
- **File templates**: entries of the **File › New › File…** menu, no code needed.
|
||||
|
||||
## File actions
|
||||
|
||||
@@ -180,7 +180,7 @@ as an argument to an approved process.
|
||||
|
||||
## File templates
|
||||
|
||||
`[[contributes.fileTemplates]]` adds entries to the **File › New…** menu. They need no code and grant
|
||||
`[[contributes.fileTemplates]]` adds entries to the **File › New › File…** menu. They need no code and grant
|
||||
no file access: files are created only when the user invokes a template, through the IDE's
|
||||
normal New File flow.
|
||||
|
||||
|
||||
@@ -67,6 +67,8 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
|
||||
在你自己的消息上可以 **编辑**(其后的消息会被替换,已经改动的文件保持不变)或 **撤回消息**。在回复上可以 **复制 Markdown**、**引用回复**、**重新生成回复**,以及 **从此处创建分支对话**,从这一点开始一个新任务。
|
||||
|
||||
右键点击链接并选择 **复制链接地址** 可复制它的 URL;**复制** 复制选中的文字。
|
||||
|
||||
### 权限
|
||||
|
||||
agent 要运行命令或调用需要授权的工具时,任务中会显示请求,并归入 **等待输入**。从 agent 提供的选项中选择,例如 **允许一次**、**在此会话中允许**、**始终允许**、**拒绝**、**始终拒绝** 或 **拒绝并停止**。很多 agent 还有模式选择器,可以自动批准编辑甚至所有操作,请谨慎使用。
|
||||
|
||||
@@ -107,6 +107,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
标签页的位置、数量上限以及达到上限后的处理方式、预览标签页、排序方式,以及关闭标签页后激活哪一个,都在 **设置 › 编辑器 › 常规 › 编辑器标签页** 中设置。
|
||||
|
||||
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
|
||||
|
||||
## 拆分编辑器
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
|
||||
@@ -75,7 +75,7 @@ Vim 模式会读取 `~/.ideavimrc`(或 `~/.openideavimrc`)。通过 **工具
|
||||
| 扩展 | **设置 › 插件** |
|
||||
| `settings.json` | **设置**(`⌘,` / `Ctrl+Alt+S`),保存在 `settings.toml`;项目级的值保存在 `.openidea/settings.toml` |
|
||||
| `launch.json` | 运行配置:**从 .vscode/launch.json 导入运行配置** |
|
||||
| 多根工作区 | **文件 › 新建工作区…** 和 **附加项目…** |
|
||||
| 多根工作区 | **文件 › 新建 › 工作区…** 和 **附加项目…** |
|
||||
|
||||
项目中的 `.editorconfig` 会生效。VS Code 的设置和扩展不会导入。
|
||||
|
||||
@@ -84,7 +84,7 @@ Vim 模式会读取 `~/.ideavimrc`(或 `~/.openideavimrc`)。通过 **工具
|
||||
把快捷键方案切换为 **Eclipse (macOS)** 或 **Eclipse**。
|
||||
|
||||
- **格式化器。** 想继续用 Eclipse 的 Java 格式化配置,打开 **设置 › 编辑器 › 代码样式 › Java**,把 **格式化方案** 设为 **自定义 Eclipse 格式化 XML**,然后选择导出的 XML 文件。
|
||||
- **工作空间与项目。** Eclipse 在一个工作空间里打开多个项目;OpenIDEA 每个窗口打开一个项目。需要同时处理多个文件夹时,用 **文件 › 新建工作区…** 创建工作区,或用 **附加项目…** 添加文件夹。
|
||||
- **工作空间与项目。** Eclipse 在一个工作空间里打开多个项目;OpenIDEA 每个窗口打开一个项目。需要同时处理多个文件夹时,用 **文件 › 新建 › 工作区…** 创建工作区,或用 **附加项目…** 添加文件夹。
|
||||
- **透视图。** OpenIDEA 没有透视图。按自己的习惯摆放工具窗口,再用 **窗口 › 工具窗口布局 › 将当前布局另存为…** 保存。
|
||||
|
||||
## 概念对照
|
||||
|
||||
@@ -13,7 +13,7 @@ description: "在项目之外保留临时文件,并在 TODO 工具窗口中汇
|
||||
|
||||
<Steps>
|
||||
<Step title="新建">
|
||||
选择 **文件 › 新建临时文件…**(或项目视图 **新建** 菜单最上面的 **临时文件**)。
|
||||
选择 **文件 › 新建 › 临时文件**(或项目视图 **新建** 菜单最上面的 **临时文件**)。
|
||||
</Step>
|
||||
<Step title="选择语言">
|
||||
输入文字过滤语言列表,按 `↵` / `Enter` 确认。
|
||||
|
||||
@@ -67,7 +67,7 @@ items.for → for (var item : items) { … }
|
||||
|
||||
实时模板、后缀补全设置和宏都按用户保存在本机,不保存在项目里。
|
||||
|
||||
新建文件用的模板(**文件 › 新建…** 创建的内容)在 **设置 › 编辑器 › 文件和代码模板** 中设置。
|
||||
新建文件用的模板(**文件 › 新建 › 文件…** 创建的内容)在 **设置 › 编辑器 › 文件和代码模板** 中设置。
|
||||
|
||||
## 宏
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ description: "创建、重命名或删除文件的快速修复,读写项目文
|
||||
- **文件操作**(`file-actions.wit`,API 1.3):创建、重命名或删除文件的快速修复和重构,作为一次可撤销的工作区编辑应用。
|
||||
- **项目文件**(`workspace.wit`):读取、写入、查找和搜索打开项目中的文件。
|
||||
- **其他文件**(`fs.wit`,API 1.3):在明确授权下访问项目之外的文件,以及插件自己的私有目录。
|
||||
- **文件模板**:**文件 › 新建…** 菜单中的条目,不需要代码。
|
||||
- **文件模板**:**文件 › 新建 › 文件…** 菜单中的条目,不需要代码。
|
||||
|
||||
## 文件操作
|
||||
|
||||
@@ -162,7 +162,7 @@ fs::write_file("~/.config/mytool/state.json", "{}")?;
|
||||
|
||||
## 文件模板
|
||||
|
||||
`[[contributes.fileTemplates]]` 在 **文件 › 新建…** 菜单中添加条目。不需要代码,也不授予任何文件访问权限:
|
||||
`[[contributes.fileTemplates]]` 在 **文件 › 新建 › 文件…** 菜单中添加条目。不需要代码,也不授予任何文件访问权限:
|
||||
只有用户调用模板时,才通过 IDE 正常的新建文件流程创建文件。
|
||||
|
||||
```toml
|
||||
|
||||
@@ -198,6 +198,37 @@ test("copies reply Markdown with the keyboard and keeps code copying separate",
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("const a = 1;");
|
||||
});
|
||||
|
||||
test("copies a reply link's address from its context menu and keeps Copy for the selected text", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const url = "https://example.com/pull/42?tab=files#diff";
|
||||
const reply = await openReply(page, `[**Review changes**](${url})\n\nOrdinary reply text`);
|
||||
const link = reply.getByRole("link", { name: "Review changes" });
|
||||
await link.locator("strong").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Copy Link Address" }).click();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(url);
|
||||
|
||||
await link.evaluate((el) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
window.getSelection()!.removeAllRanges();
|
||||
window.getSelection()!.addRange(range);
|
||||
});
|
||||
await link.click({ button: "right" });
|
||||
await page
|
||||
.getByRole("menuitem", { name: /^Copy\b/ })
|
||||
.first()
|
||||
.click();
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("Review changes");
|
||||
|
||||
const paragraph = reply.getByText("Ordinary reply text", { exact: true });
|
||||
await paragraph.click({ button: "right" });
|
||||
await expect(page.getByRole("menuitem", { name: "Copy Link Address" })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
|
||||
test("keeps latest reply actions visible and quotes into the draft without shifting content", async ({ page }) => {
|
||||
const reply = await openReply(page, REPLY);
|
||||
const copy = page.getByRole("button", { name: "Copy Markdown", exact: true });
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "source-a",
|
||||
title: "Source task in A",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
capabilities: { fork: true },
|
||||
};
|
||||
|
||||
async function prepare(page: Page, kind: "create" | "fork", failure: boolean, holdClose = false, closeFailure = false) {
|
||||
await page.evaluate(
|
||||
async ({ task, kind, failure, holdClose, closeFailure }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const trustPath = "/src/platform/projectTrust.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
const project = await import(projectPath);
|
||||
const initial = project.useProject.getState().project;
|
||||
(await import(trustPath)).provideProjectTrustPrompt(async () => true);
|
||||
commands.openProject = async (root: string) => ({
|
||||
status: "ok",
|
||||
data: {
|
||||
...initial,
|
||||
root,
|
||||
name: root === task.cwd ? "acme-api" : "project-b",
|
||||
trusted: true,
|
||||
},
|
||||
});
|
||||
commands.closeProject = async () => {};
|
||||
const provider = {
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
command: "codex",
|
||||
program: "codex",
|
||||
args: [],
|
||||
defaultProgram: null,
|
||||
defaultArgs: [],
|
||||
loginHint: null,
|
||||
commandOverridden: false,
|
||||
commandEditable: true,
|
||||
commandReadOnlyReason: null,
|
||||
installed: true,
|
||||
env: {},
|
||||
commands: [],
|
||||
source: { kind: "custom" },
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
};
|
||||
commands.agentProviders = async () => ({ status: "ok", data: [provider] });
|
||||
commands.agentProbe = async () => ({ status: "ok", data: null });
|
||||
commands.agentEntries = async () => ({ status: "ok", data: [] });
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
const complete = () => {
|
||||
document.documentElement.dataset.taskRequest = "pending";
|
||||
return new Promise((resolve) =>
|
||||
document.addEventListener(
|
||||
"test:task-complete",
|
||||
() => {
|
||||
resolve(
|
||||
failure
|
||||
? { status: "error", error: { kind: "internal", message: "Local operation failed" } }
|
||||
: { status: "ok", data: { ...task, id: "completed-a", title: "Task from project A" } },
|
||||
);
|
||||
setTimeout(() => {
|
||||
document.documentElement.dataset.taskRequest = "settled";
|
||||
}, 0);
|
||||
},
|
||||
{ once: true },
|
||||
),
|
||||
);
|
||||
};
|
||||
commands.agentCreate = complete;
|
||||
commands.agentFork = complete;
|
||||
if (holdClose) {
|
||||
const editors = (await import(contributionsPath)).editorService();
|
||||
const close = editors.closeInput;
|
||||
editors.closeInput = async (key: string) => {
|
||||
const closed = await close(key);
|
||||
if (key !== "agent:new") return closed;
|
||||
document.documentElement.dataset.homeClosing = "pending";
|
||||
await new Promise((resolve, reject) =>
|
||||
document.addEventListener(
|
||||
"test:close-complete",
|
||||
() => {
|
||||
if (closeFailure) reject(new Error("Local close failed"));
|
||||
else resolve(null);
|
||||
setTimeout(() => {
|
||||
document.documentElement.dataset.homeClosing = "settled";
|
||||
}, 0);
|
||||
},
|
||||
{ once: true },
|
||||
),
|
||||
);
|
||||
return closed;
|
||||
};
|
||||
}
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
providers: [provider],
|
||||
composers: new Map(),
|
||||
history: [],
|
||||
entries: new Map([[task.id, [{ type: "user", text: "Existing prompt in A", attachments: [] }]]]),
|
||||
draft: { provider: "codex", config: {}, isolation: "local", base: null },
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
if (kind === "create") store.openHome("Submitted task in A");
|
||||
else store.openTask(task.id);
|
||||
},
|
||||
{ task, kind, failure, holdClose, closeFailure },
|
||||
);
|
||||
if (kind === "create") await page.getByRole("button", { name: "Start", exact: true }).click();
|
||||
else {
|
||||
await page.getByText("Existing prompt in A", { exact: true }).hover();
|
||||
await page.getByRole("button", { name: "Fork", exact: true }).click();
|
||||
}
|
||||
await expect(page.locator("html")).toHaveAttribute("data-task-request", "pending");
|
||||
}
|
||||
|
||||
async function changeProject(page: Page, change: "A to B" | "A to B to A" | "reopen A") {
|
||||
await page.evaluate(
|
||||
async ({ change, task }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const store = await import(storePath);
|
||||
const project = await import(projectPath);
|
||||
if (change === "reopen A") await project.closeProject();
|
||||
else await project.openProject("/dev/project-b");
|
||||
if (change !== "A to B") await project.openProject(task.cwd);
|
||||
const root = project.useProject.getState().project.root;
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([
|
||||
["current-project", { ...task, id: "current-project", title: "Current project's task", cwd: root }],
|
||||
]),
|
||||
entries: new Map(),
|
||||
history: ["Current project history"],
|
||||
});
|
||||
store.openHome("Current project draft");
|
||||
},
|
||||
{ change, task },
|
||||
);
|
||||
await expect(page.getByRole("textbox", { name: "Message", exact: true })).toHaveText("Current project draft");
|
||||
}
|
||||
|
||||
async function expectCurrentProject(page: Page) {
|
||||
await expect(page.getByRole("textbox", { name: "Message", exact: true })).toHaveText("Current project draft");
|
||||
await expect(page.getByRole("tab", { name: "New Agent Task" })).toBeVisible();
|
||||
await expect(page.getByRole("tab", { name: "Task from project A" })).toHaveCount(0);
|
||||
await expect(page.getByText(/Local (operation|close) failed/)).toHaveCount(0);
|
||||
expect(
|
||||
await page.evaluate(async () => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store = await import(storePath);
|
||||
return { tasks: [...store.useAgents.getState().tasks.keys()], history: store.useAgents.getState().history };
|
||||
}),
|
||||
).toEqual({ tasks: ["current-project"], history: ["Current project history"] });
|
||||
}
|
||||
|
||||
for (const kind of ["create", "fork"] as const) {
|
||||
for (const failure of [false, true]) {
|
||||
for (const change of ["A to B", "A to B to A", "reopen A"] as const) {
|
||||
test(`${kind}: old ${failure ? "failure" : "success"} after ${change}`, async ({ workbench: page }) => {
|
||||
await prepare(page, kind, failure);
|
||||
await changeProject(page, change);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:task-complete")));
|
||||
await expect(page.locator("html")).toHaveAttribute("data-task-request", "settled");
|
||||
await expectCurrentProject(page);
|
||||
});
|
||||
}
|
||||
test(`${kind}: ${failure ? "failure" : "success"} in the current project`, async ({ workbench: page }) => {
|
||||
await prepare(page, kind, failure);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:task-complete")));
|
||||
await expect(page.locator("html")).toHaveAttribute("data-task-request", "settled");
|
||||
if (failure) await expect(page.getByText(/Local operation failed/).first()).toBeVisible();
|
||||
else await expect(page.getByRole("tab", { name: "Task from project A" })).toBeVisible();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const closeFailure of [false, true]) {
|
||||
test(`create: project changes while Home closes (${closeFailure ? "failure" : "success"})`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await prepare(page, "create", false, true, closeFailure);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:task-complete")));
|
||||
await expect(page.locator("html")).toHaveAttribute("data-home-closing", "pending");
|
||||
await changeProject(page, "A to B to A");
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:close-complete")));
|
||||
await expect(page.locator("html")).toHaveAttribute("data-home-closing", "settled");
|
||||
await expectCurrentProject(page);
|
||||
});
|
||||
}
|
||||
@@ -19,9 +19,9 @@ test("an unresolved module gets a startup timeout", async ({ page }) => {
|
||||
);
|
||||
await page.goto("/", { waitUntil: "commit" });
|
||||
await page.locator("#splash").waitFor({ state: "attached" });
|
||||
await page.clock.runFor(30_000);
|
||||
await page.clock.runFor(60_000);
|
||||
await expect(page.getByRole("textbox", { name: "Startup error details" })).toHaveValue(
|
||||
/Startup did not finish within 30 seconds/,
|
||||
/Startup did not finish within 60 seconds/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -83,7 +83,7 @@ test("a slow module load succeeds before the deadline and cancels the startup ti
|
||||
await expect(page.locator("#root")).not.toBeEmpty();
|
||||
await page.clock.runFor(4000);
|
||||
await expect(page.locator("#splash")).toHaveCount(0);
|
||||
await page.clock.runFor(35_000);
|
||||
await page.clock.runFor(50_000);
|
||||
await expect(page.locator("#boot-error")).toHaveCount(0);
|
||||
expect(await page.evaluate(() => sessionStorage.getItem("boot-error-seen"))).toBeNull();
|
||||
});
|
||||
@@ -285,3 +285,38 @@ test("vertical tabs leave a narrow editor group most of its width", async ({ wor
|
||||
expect(contentBox!.width).toBeGreaterThanOrEqual(paneBox!.width * 0.6 - 1);
|
||||
}
|
||||
});
|
||||
|
||||
test("dragging the vertical tab column's edge resizes it and the width is kept", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
const placeLeft = () =>
|
||||
page.evaluate(async () => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const schemaModule = "/src/features/settings/model/schema.ts";
|
||||
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
|
||||
import(/* @vite-ignore */ projectModule),
|
||||
import(/* @vite-ignore */ schemaModule),
|
||||
]);
|
||||
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
|
||||
useProject.setState({
|
||||
settings: { ...base, editor: { ...base.editor, tabs: { ...base.editor.tabs, placement: "left" } } },
|
||||
});
|
||||
});
|
||||
await placeLeft();
|
||||
|
||||
const strip = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const handle = page.getByRole("separator", { name: "Resize editor tabs" });
|
||||
const before = (await strip.boundingBox())!.width;
|
||||
const box = (await handle.boundingBox())!;
|
||||
await page.mouse.move(box.x, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x - 60, box.y + box.height / 2, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await strip.boundingBox())!.width).toBeLessThan(before - 40);
|
||||
const narrowed = (await strip.boundingBox())!.width;
|
||||
|
||||
// The next session starts with the dragged width.
|
||||
await page.reload();
|
||||
await openFromTree(page, "settings.gradle.kts");
|
||||
await placeLeft();
|
||||
await expect.poll(async () => Math.round((await strip.boundingBox())!.width)).toBe(Math.round(narrowed));
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test.use({ video: "on" });
|
||||
|
||||
test("offers file templates for the selected workspace member", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const markers: Record<string, string> = {
|
||||
"/work/api": "go.mod",
|
||||
"/work/web": "pom.xml",
|
||||
"/work/library": "pom.xml",
|
||||
};
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) => {
|
||||
const name = markers[String(path)];
|
||||
return name ? [{ name, path: `${path}/${name}`, kind: "file", size: 0, mtimeMs: 0 }] : [];
|
||||
};
|
||||
window.__ipc.handlers.run_configs = () => [
|
||||
{
|
||||
id: "workspace:web:tomcat",
|
||||
name: "Web / Tomcat",
|
||||
kind: "tomcat",
|
||||
command: "catalina",
|
||||
args: ["run"],
|
||||
cwd: "/work/web",
|
||||
module: "/work/web",
|
||||
env: {},
|
||||
detected: true,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
},
|
||||
];
|
||||
window.__ipc.handlers.project_roots = () => ({ folders: [] });
|
||||
const module = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ module);
|
||||
const current = useProject.getState().project;
|
||||
useProject.setState({
|
||||
project: {
|
||||
...current,
|
||||
name: "Workspace",
|
||||
root: "/workspace",
|
||||
workspace: { version: 1, name: "Workspace", projects: Object.keys(markers) },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const newMenu = async (path: string) => {
|
||||
await page.locator(`[data-project-path="${path}"]`).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "New", exact: true }).hover();
|
||||
await expect(page.getByRole("menuitem", { name: "From Template…", exact: true })).toBeVisible();
|
||||
};
|
||||
await newMenu("/work/api");
|
||||
await expect(page.getByRole("menuitem", { name: "Go File", exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: test.info().outputPath("go-new-menu.png"), animations: "disabled" });
|
||||
await expect(page.getByRole("menuitem", { name: "Go Module", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "JSON File", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await newMenu("/work/web");
|
||||
await expect(page.getByRole("menuitem", { name: "Java Class", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Tomcat Context Descriptor", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Go File", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole("menuitem", { name: "TypeScript File", exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: test.info().outputPath("tomcat-new-menu.png"), animations: "disabled" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await page.locator('[data-project-path="/work/library"]').click();
|
||||
await page.keyboard.press("Meta+n");
|
||||
const popup = page.getByRole("dialog", { name: "New", exact: true });
|
||||
await expect(popup.getByText("Java Class", { exact: true })).toBeVisible();
|
||||
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
|
||||
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("uses the single project's type in the keyboard New popup", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
path === "/work/script" ? [{ name: "pyproject.toml", path: "/work/script/pyproject.toml", kind: "file" }] : [];
|
||||
window.__ipc.handlers.run_configs = () => [];
|
||||
window.__ipc.handlers.project_roots = () => ({ folders: [] });
|
||||
const module = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ module);
|
||||
useProject.setState({
|
||||
project: { ...useProject.getState().project, name: "script", root: "/work/script" },
|
||||
});
|
||||
});
|
||||
await page.locator('[data-project-path="/work/script"]').click();
|
||||
await page.keyboard.press("Meta+n");
|
||||
const popup = page.getByRole("dialog", { name: "New", exact: true });
|
||||
await expect(popup.getByText("Python File", { exact: true })).toBeVisible();
|
||||
await expect(popup.getByText("Go File", { exact: true })).toHaveCount(0);
|
||||
await expect(popup.getByText("Tomcat Context Descriptor", { exact: true })).toHaveCount(0);
|
||||
await popup.getByRole("textbox", { name: "Search for file type" }).fill("from template");
|
||||
await popup.getByText("From Template…", { exact: true }).click();
|
||||
await expect(
|
||||
page.getByRole("dialog", { name: "New File from Template" }).getByText("Go File", { exact: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
@@ -20,7 +20,9 @@ test("Search Everywhere finds and runs an action", async ({ workbench: page }) =
|
||||
await expect(option).toBeVisible();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("dialog", { name: "Settings" })).toBeVisible();
|
||||
await expect(page.getByRole("list", { name: /language servers/i })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("dialog", { name: "Settings" }).getByRole("list", { name: "Languages", exact: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
const ROOT = "/dev/acme-api";
|
||||
|
||||
@@ -86,20 +86,20 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
|
||||
// The page tree is virtualized; search brings the page into view.
|
||||
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Language Servers");
|
||||
await dialog.getByRole("treeitem", { name: "Language Servers", exact: true }).click();
|
||||
const list = dialog.getByRole("list", { name: /language servers/i });
|
||||
await expect(list).toBeVisible();
|
||||
|
||||
await list.locator('[data-tool="gopls"]').click();
|
||||
const languages = dialog.getByRole("list", { name: "Languages", exact: true });
|
||||
await languages.getByRole("button", { name: /^Go\b/ }).click();
|
||||
const gopls = dialog.getByLabel("Go tools").locator('[data-tool="gopls"]');
|
||||
await gopls.click();
|
||||
await expect(gopls).toContainText("Missing");
|
||||
const details = dialog.getByLabel("gopls details");
|
||||
await expect(details).toContainText("Missing");
|
||||
await details.getByRole("button", { name: "Install gopls" }).click();
|
||||
await expect(details.getByRole("progressbar", { name: "Installing gopls" })).toBeVisible();
|
||||
await expect(details).toContainText("Installed");
|
||||
await expect(details).toContainText("1.0.0");
|
||||
await expect(gopls).toContainText("Installed");
|
||||
await expect(gopls).toContainText("1.0.0");
|
||||
await expect(details.getByRole("button", { name: "Uninstall" })).toBeVisible();
|
||||
|
||||
// Tools without an installer explain how to get them.
|
||||
await list.locator('[data-tool="solargraph"]').click();
|
||||
await languages.getByRole("button", { name: /^Ruby\b/ }).click();
|
||||
await expect(dialog.getByLabel("solargraph details")).toContainText("gem install solargraph");
|
||||
});
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { expect, test } from "./fixtures";
|
||||
for (const [id, selector] of [
|
||||
["build.deployment", "[class*='layout'] > [class*='note']"],
|
||||
["editor.inspections", "[class*='split'] > [class*='details']"],
|
||||
["languages.servers", "[class*='body'] > [class*='details']"],
|
||||
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
|
||||
["plugins", "[class*='body'] > [class*='details']"],
|
||||
["agents.list", "section[aria-label='Codex']"],
|
||||
]) {
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.44",
|
||||
"version": "0.1.45",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
copied: "已复制",
|
||||
manual: "无法复制。请选择下方详情并手动复制。",
|
||||
details: "启动错误详情",
|
||||
timeout: "启动未在 30 秒内完成。",
|
||||
timeout: "启动未在 60 秒内完成。",
|
||||
outdatedMac:
|
||||
"这台 Mac 的系统网页引擎过旧:OpenIDEA 的界面运行在 macOS 自带的 WebKit 引擎上,需要 macOS 13 Ventura 或更高版本。在 macOS 11、12 上更新 Safari 不会更新其他应用使用的引擎,需要升级 macOS。",
|
||||
outdated:
|
||||
@@ -25,7 +25,7 @@
|
||||
copied: "Copied",
|
||||
manual: "Could not copy. Select the details below and copy them.",
|
||||
details: "Startup error details",
|
||||
timeout: "Startup did not finish within 30 seconds.",
|
||||
timeout: "Startup did not finish within 60 seconds.",
|
||||
outdatedMac:
|
||||
"The system web engine on this Mac is too old: OpenIDEA's interface runs on macOS's built-in WebKit and needs macOS 13 Ventura or later. On macOS 11 and 12 a Safari update doesn't update the engine other apps use, so macOS itself needs upgrading.",
|
||||
outdated:
|
||||
@@ -146,7 +146,7 @@
|
||||
};
|
||||
// The timeout counts only while the window shows: a hidden or covered window gets no
|
||||
// animation frames, and the splash waits for those to finish startup.
|
||||
let remaining = 30_000;
|
||||
let remaining = 60_000;
|
||||
let armedAt = 0;
|
||||
let timer;
|
||||
const arm = () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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,9 +1,10 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Project-scoped decorations (API 1.4). Requires project.read; paths must be inside
|
||||
/// an open project. Sets belong to the plugin and disappear when it stops.
|
||||
/// 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.
|
||||
/// Tree sets are rooted in an open project. Sets belong to the plugin and disappear when it stops.
|
||||
/// Styles: highlight, search, added, modified, removed, warning, error, info,
|
||||
/// underline, strikethrough, muted. Unknown styles are ignored. Theme tokens only.
|
||||
/// typo, weak, underline, strikethrough, muted. Unknown styles are ignored. Theme tokens only.
|
||||
interface decorations {
|
||||
use types.{error, range};
|
||||
/// An editor annotation; after is plain text shown after the range.
|
||||
@@ -22,4 +23,9 @@ interface decorations {
|
||||
/// Replace this set's tree annotation for a file with a note shown after its name (API 1.7):
|
||||
/// one line of at most 200 characters, with an optional tooltip.
|
||||
set-file-note: func(path: string, set-id: string, note: string, tooltip: option<string>) -> result<_, error>;
|
||||
/// Replace this set's tree icon for a file or folder with an id declared under
|
||||
/// `[[contributes.fileIcons]]` (API 1.8), with an optional tooltip.
|
||||
set-file-icon: func(path: string, set-id: string, icon: string, tooltip: option<string>) -> result<_, error>;
|
||||
/// Replace all `(path, icon)` entries of a tree set at once (API 1.8; at most 10,000 entries).
|
||||
set-file-icons: func(set-id: string, items: list<tuple<string, string>>) -> result<_, error>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
use types.{error, range, location};
|
||||
/// Problems reported by a source for a file in this window's project.
|
||||
/// Problems one producer reported for a file, wherever the file is: the host records every
|
||||
/// diagnostics event it emits, so this follows the file, not the invoking window.
|
||||
record file-problems { path: string, source: string, diagnostics: list<diagnostic> }
|
||||
/// Current Problems view snapshot, optionally filtered to a project file.
|
||||
/// The diagnostics the host recorded, one entry per producer, optionally
|
||||
/// filtered to a file: language servers, builds, spelling and plugin
|
||||
/// providers alike, whatever window or project opened the file.
|
||||
/// Requires project.read and an invoking window. Empty for remote projects.
|
||||
problems: func(path: option<string>) -> result<list<file-problems>, error>;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.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:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.7.0;
|
||||
package openidea:plugin@1.8.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -135,7 +135,9 @@ interface editor {
|
||||
|
||||
/// Applies versioned edits to an open project document from a background
|
||||
/// event. The path is project-relative and requires `project.read` and
|
||||
/// `editor.write`. Stale versions are rejected without changing text.
|
||||
/// `editor.write`. The host refuses VCS/IDE control directories and every
|
||||
/// symlink, junction or reparse-point component before it finds the open
|
||||
/// document. Stale versions are rejected without changing text.
|
||||
/// These background edits are non-undoable and are not re-emitted as
|
||||
/// `document-changed` events.
|
||||
apply-edits-at: func(project: borrow<project>, path: string, version: u64, edits: list<text-edit>) -> result<u64, error>;
|
||||
|
||||
@@ -362,3 +362,10 @@ pub async fn db_apply_edits(
|
||||
pub fn db_console_path(state: State<'_, AppState>, id: String) -> IdeResult<IpcPath> {
|
||||
ide_host::ops::db::console_path(&state.host, &id)
|
||||
}
|
||||
|
||||
/// The query consoles of data source `id`; `create` adds the next one first.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn db_consoles(state: State<'_, AppState>, id: String, create: bool) -> IdeResult<Vec<IpcPath>> {
|
||||
ide_host::ops::db::consoles(&state.host, &id, create)
|
||||
}
|
||||
@@ -65,8 +65,9 @@ pub fn apply(state: &AppState) {
|
||||
}
|
||||
// Another address, port or token: clients connect anew.
|
||||
if let Some(running) = server.take() {
|
||||
let held = (running.address(), running.port());
|
||||
running.stop();
|
||||
if let Some(port) = wanted.port {
|
||||
if let Some(port) = port_to_wait_for(held, wanted.port) {
|
||||
wait_until_free(address, port);
|
||||
}
|
||||
}
|
||||
@@ -104,6 +105,14 @@ pub fn apply(state: &AppState) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The port a restart listening on `wanted` waits for after stopping the server that listened
|
||||
/// on `held`: only its own, at any address (`127.0.0.1` and `0.0.0.0` overlap). A port another
|
||||
/// program holds (the run fell back to a free one) stays taken, and waiting for it would block
|
||||
/// the window.
|
||||
fn port_to_wait_for(held: (IpAddr, u16), wanted: Option<u16>) -> Option<u16> {
|
||||
wanted.filter(|port| held.1 == *port)
|
||||
}
|
||||
|
||||
/// Waits briefly for a stopped server's port to close, so the restart gets it again.
|
||||
fn wait_until_free(address: IpAddr, port: u16) {
|
||||
for _ in 0..100 {
|
||||
@@ -243,3 +252,21 @@ pub fn mcp_respond(
|
||||
) -> IdeResult<()> {
|
||||
state.host.mcp_requests.answer(window.label(), id, allow, error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
#[test]
|
||||
fn a_restart_waits_only_for_the_port_the_stopped_server_held() {
|
||||
let local = IpAddr::V4(Ipv4Addr::LOCALHOST);
|
||||
let any = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
|
||||
assert_eq!(port_to_wait_for((local, 64342), Some(64342)), Some(64342));
|
||||
// Another address on the same port overlaps the old listener: wait for it too.
|
||||
assert_eq!(port_to_wait_for((any, 64342), Some(64342)), Some(64342));
|
||||
// The fixed port was taken by another program: the server ran on a free one.
|
||||
assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None);
|
||||
assert_eq!(port_to_wait_for((local, 64342), None), None);
|
||||
}
|
||||
}
|
||||
@@ -248,6 +248,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
nav::web_goto,
|
||||
nav::nav_resolve_module,
|
||||
nav::nav_index_definitions,
|
||||
nav::nav_inheritance,
|
||||
nav::fs_resolve_reference,
|
||||
nav::path_completions,
|
||||
nav::web_unresolved_references,
|
||||
@@ -746,5 +747,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
db::db_table_page,
|
||||
db::db_apply_edits,
|
||||
db::db_console_path,
|
||||
db::db_consoles,
|
||||
])
|
||||
}
|
||||
@@ -115,6 +115,14 @@ pub async fn nav_index_definitions(
|
||||
ide_host::ops::nav::nav_index_definitions(&state.host, window.label(), name, from).await
|
||||
}
|
||||
|
||||
/// Every Python class in the project (attached dependency roots included) and its base names,
|
||||
/// for native inheritance gutter markers.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn nav_inheritance(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<ClassInheritance>> {
|
||||
ide_host::ops::nav::nav_inheritance(&state.host, window.label()).await
|
||||
}
|
||||
|
||||
/// The existing file or directory a path written in `from` names (`href`, `url()`, a string literal).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
|
||||
@@ -217,14 +217,18 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
}
|
||||
|
||||
let mut file = vec![
|
||||
act("file.newProject", "New Project…"),
|
||||
act("workspace.create", "New Workspace…"),
|
||||
act("workspace.open", "Open Workspace…"),
|
||||
act("workspace.manage", "Manage Workspace…"),
|
||||
act("file.new", "New…"),
|
||||
act("file.newScratchFile", "New Scratch File…"),
|
||||
sub(
|
||||
"new",
|
||||
"New",
|
||||
vec![
|
||||
act("file.newProject", "Project…"),
|
||||
act("workspace.create", "Workspace…"),
|
||||
SEP,
|
||||
act("file.new", "File…"),
|
||||
act("file.newScratchFile", "Scratch File"),
|
||||
],
|
||||
),
|
||||
act("file.openProject", "Open…"),
|
||||
act("project.attach", "Attach Project…"),
|
||||
act("file.openFile", "Open File…"),
|
||||
act("file.openInNewWindow", "Open in New Window…"),
|
||||
sub(
|
||||
@@ -232,6 +236,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Open Recent",
|
||||
vec![Entry::RecentProjects, SEP, act("welcome.recentProjects", "Manage Projects…")],
|
||||
),
|
||||
act("project.attach", "Attach Project…"),
|
||||
SEP,
|
||||
act("workspace.open", "Open Workspace…"),
|
||||
act("workspace.manage", "Manage Workspace…"),
|
||||
SEP,
|
||||
act("file.closeProject", "Close Project"),
|
||||
act("file.renameProject", "Rename Project…"),
|
||||
SEP,
|
||||
@@ -1612,7 +1621,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
const ALL_OS: [Os; 3] = [Os::Mac, Os::Windows, Os::Linux];
|
||||
|
||||
@@ -1972,6 +1981,56 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_menu_starts_with_a_new_submenu() {
|
||||
for os in ALL_OS {
|
||||
let menus = spec(os);
|
||||
let Some(Entry::Submenu { children: file, .. }) =
|
||||
menus.iter().find(|e| matches!(e, Entry::Submenu { id: "file", .. }))
|
||||
else {
|
||||
panic!("File menu missing on {os:?}")
|
||||
};
|
||||
let Some(Entry::Submenu { id: "new", children: new, .. }) = file.first() else {
|
||||
panic!("File menu does not start with New on {os:?}")
|
||||
};
|
||||
assert_eq!(
|
||||
action_ids(new),
|
||||
["file.newProject", "workspace.create", "file.new", "file.newScratchFile"],
|
||||
"{os:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_menu_item_has_a_catalog_label() {
|
||||
fn walk(entries: &[Entry], out: &mut BTreeSet<&'static str>) {
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry::Submenu { id, children, .. } => {
|
||||
out.insert(id);
|
||||
walk(children, out);
|
||||
}
|
||||
Entry::Action { id, .. } => {
|
||||
out.insert(id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for os in ALL_OS {
|
||||
walk(&spec(os), &mut ids);
|
||||
}
|
||||
for (locale, catalog) in [
|
||||
("en", include_str!("../../src/platform/locales/en.json")),
|
||||
("zh", include_str!("../../src/platform/locales/zh.json")),
|
||||
] {
|
||||
let catalog: serde_json::Map<String, serde_json::Value> = serde_json::from_str(catalog).unwrap();
|
||||
let missing: Vec<_> = ids.iter().filter(|id| !catalog.contains_key(&format!("menu.{id}"))).collect();
|
||||
assert!(missing.is_empty(), "{locale}.json lacks menu labels for {missing:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_labels_tildify_home() {
|
||||
let recent = vec![ide_workspace::RecentProject {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.44",
|
||||
"version": "0.1.45",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -475,6 +475,11 @@ export const commands = {
|
||||
* plus its configured dependencies).
|
||||
*/
|
||||
navIndexDefinitions: (name: string, from: IpcPath) => typedError<SymbolMatch[], IdeError>(__TAURI_INVOKE("nav_index_definitions", { name, from })),
|
||||
/**
|
||||
* Every Python class in the project (attached dependency roots included) and its base names,
|
||||
* for native inheritance gutter markers.
|
||||
*/
|
||||
navInheritance: () => typedError<ClassInheritance[], IdeError>(__TAURI_INVOKE("nav_inheritance")),
|
||||
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
|
||||
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
|
||||
/** Files and folders that continue `prefix`, a path being typed in `from`. */
|
||||
@@ -1726,6 +1731,8 @@ export const commands = {
|
||||
dbTablePage: (request: RequestId, id: string, schema: string, table: string, filter: string | null, sort: DbSortKey[], offset: number, limit: number) => typedError<DbTablePage, IdeError>(__TAURI_INVOKE("db_table_page", { request, id, schema, table, filter, sort, offset, limit })),
|
||||
dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })),
|
||||
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
|
||||
/** The query consoles of data source `id`; `create` adds the next one first. */
|
||||
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
|
||||
};
|
||||
|
||||
/* Types */
|
||||
@@ -2889,6 +2896,25 @@ export type ChoiceOption = {
|
||||
label: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* A Python class definition and the base names written in its source. The UI builds a
|
||||
* name → locations index from every class in the project (attached dependency roots
|
||||
* included) to compute ↑ overrides / ↓ overridden gutter markers without a language
|
||||
* server's type-hierarchy provider.
|
||||
*/
|
||||
export type ClassInheritance = {
|
||||
/** Start of the class definition's selection range (0-based line, UTF-16 column). */
|
||||
path: IpcPath,
|
||||
line: number,
|
||||
col: number,
|
||||
name: string,
|
||||
/**
|
||||
* Base names as written in source (bare name, e.g. `AllToAllTokenDispatcher`; a
|
||||
* qualified name keeps only its last segment).
|
||||
*/
|
||||
bases: string[],
|
||||
};
|
||||
|
||||
export type ClassifiedReference = {
|
||||
/** Optional for older Java extensions; missing means unclassified. */
|
||||
access?: ReferenceAccess | null,
|
||||
|
||||
@@ -682,6 +682,10 @@ export function setShownLine(path: string, line: number | null) {
|
||||
}, true);
|
||||
}
|
||||
|
||||
export function shownLine(path: string): number | null {
|
||||
return useShownLines.getState()[path] ?? null;
|
||||
}
|
||||
|
||||
export function useShownLine(path: string | null): number | null {
|
||||
return useShownLines((s) => (path ? (s[path] ?? null) : null));
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { evaluateWhen, getContext, setContext } from "@/platform/context";
|
||||
import { installKeyboardDispatcher } from "@/platform/keymap";
|
||||
import { TEXT_WHEN } from "./actions";
|
||||
import { EDITOR_WHEN } from "@/editor/lsp/actions";
|
||||
import { setShownLine } from "@/editor/api";
|
||||
|
||||
let ctrl: EditorController | null = null;
|
||||
|
||||
@@ -33,6 +34,24 @@ describe("EditorController", () => {
|
||||
expect(useProjectViewLead.getState().lead).toBeNull();
|
||||
});
|
||||
|
||||
it("goes back to the line a stand-in view shows (Markdown Preview only), not the hidden caret", async () => {
|
||||
const text = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.md": text, "/p/b.md": "b\n" }));
|
||||
ctrl.start();
|
||||
await ctrl.openFile("/p/a.md", { selection: { line: 45, col: 0 }, focus: false });
|
||||
// The preview was scrolled after the file opened; then a link opens another file.
|
||||
setShownLine("/p/a.md", 20);
|
||||
try {
|
||||
await ctrl.openFile("/p/b.md", { focus: false });
|
||||
await ctrl.back();
|
||||
const slot = ctrl.activeSlot!;
|
||||
expect(slot.model.path).toBe("/p/a.md");
|
||||
expect(slot.caret().line).toBe(20);
|
||||
} finally {
|
||||
setShownLine("/p/a.md", null);
|
||||
}
|
||||
});
|
||||
|
||||
it("autosaves on blur, but not while focus is in a popup over the editor", async () => {
|
||||
const backend = createMemoryBackend({ "/p/a.c": "int main() {\n \n}\n" });
|
||||
const save = vi.spyOn(backend, "save");
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
_provideNavigationHistory,
|
||||
_provideOpenEditorPaths,
|
||||
_setActiveEditor,
|
||||
shownLine,
|
||||
type NavigationLocation,
|
||||
} from "@/editor/api";
|
||||
import {
|
||||
@@ -972,7 +973,10 @@ export class EditorController implements SlotHost {
|
||||
private recordNav(slot: EditorSlot, navigation = false) {
|
||||
if (this.navSuppress > 0 || slot.disposed) return;
|
||||
const c = slot.caret();
|
||||
this.nav.update({ path: slot.model.path, line: c.line, col: c.col }, navigation);
|
||||
// A view standing in for the editor (Markdown Preview only) is where the reader is.
|
||||
const shown = shownLine(slot.model.path);
|
||||
const loc = shown === null || shown === c.line ? { line: c.line, col: c.col } : { line: shown, col: 0 };
|
||||
this.nav.update({ path: slot.model.path, ...loc }, navigation);
|
||||
}
|
||||
|
||||
async navigateTo(loc: NavigationLocation | null) {
|
||||
@@ -1055,6 +1059,8 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
|
||||
async openFile(path: string, o: OpenOptions = {}): Promise<void> {
|
||||
// The place left behind, as it is now (a preview may have scrolled since it was recorded).
|
||||
if (this.navSuppress === 0 && this.activeSlot) this.recordNav(this.activeSlot);
|
||||
return this.openFileRequest(path, o, this.openingGeneration(o));
|
||||
}
|
||||
|
||||
@@ -1335,7 +1341,10 @@ export class EditorController implements SlotHost {
|
||||
* (`EditorKindContribution.isBusy`): asks before ending what runs in them,
|
||||
* like closing a busy terminal session. Resolves false to keep the tabs.
|
||||
*/
|
||||
private async confirmBusyClose(removal: (s: TabsState) => TabsState): Promise<boolean> {
|
||||
private async confirmBusyClose(
|
||||
removal: (s: TabsState) => TabsState,
|
||||
confirmed: Set<string> = new Set(),
|
||||
): Promise<boolean> {
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
const current = useTabs.getState();
|
||||
const remaining = openKeys(removal(current));
|
||||
@@ -1343,15 +1352,19 @@ export class EditorController implements SlotHost {
|
||||
for (const pane of Object.values(current.panes))
|
||||
for (const tab of pane.tabs)
|
||||
if (!remaining.has(tab.input.key) && kinds.get(tab.input.kind)?.isBusy) closing.set(tab.input.key, tab.input);
|
||||
const busy: string[] = [];
|
||||
for (const input of closing.values()) if (await inputBusy(input, kinds)) busy.push(tabTitle(input, kinds));
|
||||
// Tabs whose ending was confirmed earlier in this close aren't asked about again.
|
||||
const busy: EditorInput[] = [];
|
||||
for (const input of closing.values())
|
||||
if (!confirmed.has(input.key) && (await inputBusy(input, kinds))) busy.push(input);
|
||||
if (!busy.length) return true;
|
||||
const name = busy.join(", ");
|
||||
return confirm({
|
||||
const name = busy.map((input) => tabTitle(input, kinds)).join(", ");
|
||||
const ok = await confirm({
|
||||
title: t("editor.closeBusy.title", { name }),
|
||||
message: t("editor.closeBusy.message", { name }),
|
||||
ok: t("editor.closeBusy.terminate"),
|
||||
});
|
||||
if (ok) for (const input of busy) confirmed.add(input.key);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Close exactly the originally selected tabs, evaluating references after every await. */
|
||||
@@ -1388,6 +1401,8 @@ export class EditorController implements SlotHost {
|
||||
try {
|
||||
const authorized = new Set<string>();
|
||||
const discards = new Map<string, CustomDocument>();
|
||||
const confirmedBusy = new Set<string>();
|
||||
let busyAsked = false;
|
||||
for (;;) {
|
||||
const current = useTabs.getState();
|
||||
const d = closedDocuments(current, currentRemoval(current), useContributions.getState().editorKinds).find(
|
||||
@@ -1397,6 +1412,13 @@ export class EditorController implements SlotHost {
|
||||
// A later Cancel/save failure must not discard earlier documents.
|
||||
const discard = [...discards.values()].find(stillLast);
|
||||
if (!discard) break;
|
||||
// Nor may a Cancel on ending a busy tab's session: ask before discarding anything.
|
||||
if (!busyAsked) {
|
||||
if (!(await this.confirmBusyClose(currentRemoval, confirmedBusy))) return false;
|
||||
if (generation !== this.projectGeneration) return false;
|
||||
busyAsked = true;
|
||||
continue;
|
||||
}
|
||||
discards.delete(discard.input.key);
|
||||
await discard.lifecycle.discard(discard.input);
|
||||
// The await may have changed which documents lose their last tab.
|
||||
@@ -1427,7 +1449,8 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
authorized.add(d.input.key);
|
||||
}
|
||||
if (!(await this.confirmBusyClose(currentRemoval))) return false;
|
||||
// Again after the discards: a tab may have become busy while they ran.
|
||||
if (!(await this.confirmBusyClose(currentRemoval, confirmedBusy))) return false;
|
||||
if (generation !== this.projectGeneration) return false;
|
||||
if (options.beforeRemove && !(await options.beforeRemove())) return false;
|
||||
// Commit only the original target ids against the latest tab state.
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createMemoryBackend } from "./backend";
|
||||
import { findTab, initialTabsState, paneIds } from "./model/tabs";
|
||||
import { useDocMeta } from "./model/document";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { ask, confirm } from "@/workbench/messages";
|
||||
import type * as Messages from "@/workbench/messages";
|
||||
import * as virtualDocs from "@/platform/virtualDocs";
|
||||
import type { VirtualDocument } from "@/platform/ipc";
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
vi.mock("@/workbench/messages", async (original) => ({
|
||||
...(await original<typeof Messages>()),
|
||||
ask: vi.fn(),
|
||||
confirm: vi.fn(),
|
||||
}));
|
||||
|
||||
class TestDocument implements EditorDocumentLifecycle {
|
||||
@@ -248,6 +249,57 @@ describe("custom editor document lifetime", () => {
|
||||
expect(findTab(useTabs.getState(), input().key)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps discarded changes when ending a busy tab's session is cancelled", async () => {
|
||||
const busy = registerEditorKind({
|
||||
kind: "busy-test",
|
||||
component: () => null,
|
||||
title: (i) => i.key,
|
||||
isBusy: () => true,
|
||||
});
|
||||
try {
|
||||
const doc = await open();
|
||||
await ctrl.openInput({ kind: "busy-test", key: "busy:1" }, { focus: false });
|
||||
vi.mocked(ask).mockResolvedValue({ button: "discard", checked: false });
|
||||
vi.mocked(confirm).mockResolvedValue(false);
|
||||
const pane = useTabs.getState().activePane;
|
||||
expect(await ctrl.closeAll(pane)).toBe(false);
|
||||
expect(confirm).toHaveBeenCalledOnce();
|
||||
expect(doc.text).toBe("edited");
|
||||
expect(useTabs.getState().panes[pane]!.tabs.map((tab) => tab.input.key)).toEqual(["custom:a", "busy:1"]);
|
||||
} finally {
|
||||
busy();
|
||||
vi.mocked(confirm).mockReset();
|
||||
}
|
||||
});
|
||||
|
||||
it("asks about a tab that becomes busy while changes are discarded", async () => {
|
||||
let busyNow = false;
|
||||
const busy = registerEditorKind({
|
||||
kind: "busy-test",
|
||||
component: () => null,
|
||||
title: (i) => i.key,
|
||||
isBusy: () => busyNow,
|
||||
});
|
||||
try {
|
||||
const doc = await open();
|
||||
doc.discard = async () => {
|
||||
busyNow = true;
|
||||
doc.pending = "";
|
||||
doc.text = doc.saved;
|
||||
};
|
||||
await ctrl.openInput({ kind: "busy-test", key: "busy:1" }, { focus: false });
|
||||
vi.mocked(ask).mockResolvedValue({ button: "discard", checked: false });
|
||||
vi.mocked(confirm).mockResolvedValue(false);
|
||||
const pane = useTabs.getState().activePane;
|
||||
expect(await ctrl.closeAll(pane)).toBe(false);
|
||||
expect(confirm).toHaveBeenCalledOnce();
|
||||
expect(useTabs.getState().panes[pane]!.tabs.map((tab) => tab.input.key)).toContain("busy:1");
|
||||
} finally {
|
||||
busy();
|
||||
vi.mocked(confirm).mockReset();
|
||||
}
|
||||
});
|
||||
|
||||
it("discards without a removal-triggered autosave", async () => {
|
||||
const doc = await open();
|
||||
useProject.setState({ settings: { files: { autoSave: true } } as never });
|
||||
|
||||
@@ -270,13 +270,29 @@
|
||||
}
|
||||
.tabsVertical > .tabs,
|
||||
.tabsVertical > .tabRows {
|
||||
/* Fits the labels up to the draggable limit (SideTabsResizer); the editor keeps at least 60%. */
|
||||
width: max-content;
|
||||
/* A narrow editor group keeps most of its width for the editor; labels truncate. */
|
||||
min-width: min(140px, 40%);
|
||||
max-width: min(260px, 40%);
|
||||
max-width: min(var(--side-tabs-limit, 260px), 40%);
|
||||
border-bottom: none;
|
||||
border-right: 1px solid var(--border-editor-tabs, var(--border));
|
||||
}
|
||||
/* A zero-width handle on the column's inner border, with a wider hit area. */
|
||||
.sideTabsResizer {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: none;
|
||||
width: 0;
|
||||
outline: none;
|
||||
}
|
||||
.sideTabsResizer::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
}
|
||||
.sideTabsResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
}
|
||||
.tabsVertical .tabRows > .tabs {
|
||||
min-height: 0;
|
||||
border-bottom: none;
|
||||
@@ -285,9 +301,12 @@
|
||||
flex: 1 1 auto;
|
||||
border-top: 1px solid var(--border-editor-tabs, var(--border));
|
||||
}
|
||||
.tabsRight > .sideTabsResizer {
|
||||
order: 1;
|
||||
}
|
||||
.tabsRight > .tabs,
|
||||
.tabsRight > .tabRows {
|
||||
order: 1;
|
||||
order: 2;
|
||||
border-right: none;
|
||||
border-left: 1px solid var(--border-editor-tabs, var(--border));
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ import { TextEditorHost } from "./TextEditorHost";
|
||||
import { FindBar } from "./FindBar";
|
||||
import { EditorBanners, VirtualBanner } from "./Banner";
|
||||
import { CodeBreadcrumbs } from "./StatusItems";
|
||||
import { SideTabsResizer, useSideTabsStyle } from "./SideTabsResizer";
|
||||
import styles from "./EditorArea.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -252,6 +253,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
const pinnedCount = tabs.filter((t) => t.pinned).length;
|
||||
// Settings › Editor Tabs › Tab placement Left / Right: a vertical, scrolling column.
|
||||
const vertical = tabPrefs.placement === "left" || tabPrefs.placement === "right";
|
||||
const sideTabsStyle = useSideTabsStyle();
|
||||
const pinnedRow = tabPrefs.pinnedSeparateRow && pinnedCount > 0 && pinnedCount < tabs.length;
|
||||
const dnd = useMemo(() => {
|
||||
// A tab released outside the window detaches into a forced new window.
|
||||
@@ -366,6 +368,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
vertical && styles.tabsVertical,
|
||||
tabPrefs.placement === "right" && styles.tabsRight,
|
||||
)}
|
||||
style={vertical ? sideTabsStyle : undefined}
|
||||
data-pane-id={paneId}
|
||||
data-focus-scope=""
|
||||
aria-label={tx("Editor")}
|
||||
@@ -381,6 +384,7 @@ function PaneView({ paneId }: { paneId: string }) {
|
||||
) : (
|
||||
strip(items, dnd.all, actions)
|
||||
)}
|
||||
{vertical && !hidden && <SideTabsResizer side={tabPrefs.placement === "left" ? "left" : "right"} />}
|
||||
<div
|
||||
className={styles.content}
|
||||
role="tabpanel"
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Width limit of editor tabs placed left / right, as in IDEA: the column fits its
|
||||
* labels up to this limit, and dragging its inner edge sets the limit for every
|
||||
* editor group. Remembered across sessions.
|
||||
*/
|
||||
import type { CSSProperties, KeyboardEvent, PointerEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import { lockDragCursor } from "@/ui";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import styles from "./EditorArea.module.css";
|
||||
|
||||
const KEY = "openidea.editor.sideTabsWidth";
|
||||
const MIN_WIDTH = 80;
|
||||
const MAX_WIDTH = 800;
|
||||
const KEY_STEP = 16;
|
||||
/** CSS custom property read by `.tabsVertical` in EditorArea.module.css. */
|
||||
const LIMIT_VAR = "--side-tabs-limit";
|
||||
|
||||
function load(): number | null {
|
||||
try {
|
||||
const v: unknown = JSON.parse(localStorage.getItem(KEY) ?? "null");
|
||||
return typeof v === "number" && Number.isFinite(v) ? clamp(v) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function clamp(px: number) {
|
||||
return Math.round(Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, px)));
|
||||
}
|
||||
|
||||
/** `null`: the default limit from the stylesheet. */
|
||||
const useSideTabsWidth = create<{ width: number | null }>(() => ({ width: load() }));
|
||||
|
||||
function setSideTabsWidth(px: number) {
|
||||
const width = clamp(px);
|
||||
useSideTabsWidth.setState({ width });
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(width));
|
||||
} catch {
|
||||
// Storage unavailable: the width lasts for this session.
|
||||
}
|
||||
}
|
||||
|
||||
/** Style for the editor pane that holds a vertical tab column. */
|
||||
export function useSideTabsStyle(): CSSProperties | undefined {
|
||||
const width = useSideTabsWidth((s) => s.width);
|
||||
return width == null ? undefined : ({ [LIMIT_VAR]: `${width}px` } as CSSProperties);
|
||||
}
|
||||
|
||||
/** The drag handle on the editor side of the tab column; render it right after the column. */
|
||||
export function SideTabsResizer({ side }: { side: "left" | "right" }) {
|
||||
const sign = side === "left" ? 1 : -1;
|
||||
|
||||
const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {
|
||||
const handle = e.currentTarget;
|
||||
const pane = handle.parentElement;
|
||||
const start = handle.previousElementSibling?.getBoundingClientRect().width;
|
||||
if (e.button !== 0 || !pane || start == null) return;
|
||||
// No focus ring or text selection from a mouse drag.
|
||||
e.preventDefault();
|
||||
handle.setPointerCapture(e.pointerId);
|
||||
const origin = e.clientX;
|
||||
const previous = pane.style.getPropertyValue(LIMIT_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
let next: number | null = null;
|
||||
// Only this pane follows the pointer; every group takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
next = clamp(start + sign * (ev.clientX - origin));
|
||||
pane.style.setProperty(LIMIT_VAR, `${next}px`);
|
||||
};
|
||||
const end = () => {
|
||||
handle.removeEventListener("pointermove", move);
|
||||
handle.removeEventListener("pointerup", end);
|
||||
handle.removeEventListener("pointercancel", end);
|
||||
releaseCursor();
|
||||
if (next != null) setSideTabsWidth(next);
|
||||
else if (previous) pane.style.setProperty(LIMIT_VAR, previous);
|
||||
else pane.style.removeProperty(LIMIT_VAR);
|
||||
};
|
||||
handle.addEventListener("pointermove", move);
|
||||
handle.addEventListener("pointerup", end);
|
||||
handle.addEventListener("pointercancel", end);
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const dir = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
|
||||
const width = e.currentTarget.previousElementSibling?.getBoundingClientRect().width;
|
||||
if (!dir || width == null) return;
|
||||
e.preventDefault();
|
||||
setSideTabsWidth(width + sign * dir * KEY_STEP);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label={tx("Resize editor tabs")}
|
||||
tabIndex={0}
|
||||
className={styles.sideTabsResizer}
|
||||
onPointerDown={onPointerDown}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -27,12 +27,14 @@ import {
|
||||
isCancelled,
|
||||
nextRequestId,
|
||||
onIdeEvent,
|
||||
type ClassInheritance,
|
||||
type HierarchyItem,
|
||||
type Location,
|
||||
type OutlineItem,
|
||||
type Pos,
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { editorPrefs, type EditorExtras } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { gutterIconMarkup } from "@/ui";
|
||||
@@ -48,7 +50,7 @@ import {
|
||||
type MarkerCandidate,
|
||||
type MarkerGroup,
|
||||
} from "./lineMarkers";
|
||||
import { overridersInType, superMethodTargets, type SuperDeps, type SuperMethod } from "./structureNav";
|
||||
import { baseName, overridersInType, superMethodTargets, type SuperDeps, type SuperMethod } from "./structureNav";
|
||||
import styles from "./LineMarkers.module.css";
|
||||
|
||||
/** Lines above / below the viewport that are asked with it. */
|
||||
@@ -85,16 +87,49 @@ export function affectsMarkers(paths: readonly string[]): boolean {
|
||||
return paths.some((p) => !OUTPUT_PATH.test(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* The Python inheritance graph of the open project, shared by every document and kept
|
||||
* across edits: it is a whole-project index answer, not a per-document one, so scanning
|
||||
* it again for each edit would walk every Python file again. Dropped when other files
|
||||
* change or a server settles (the index may have moved on).
|
||||
*/
|
||||
let inheritanceGraphCache: { root: string; promise: Promise<ClassInheritance[]> } | null = null;
|
||||
|
||||
/** The project whose graph is cached; `""` for no project (a loose file). */
|
||||
function projectRoot(): string {
|
||||
return useProject.getState().project?.root ?? "";
|
||||
}
|
||||
|
||||
/** Forgets the cached graph (files changed, a server settled, or tests). */
|
||||
export function forgetInheritanceGraph() {
|
||||
inheritanceGraphCache = null;
|
||||
}
|
||||
|
||||
function inheritanceGraph(): Promise<ClassInheritance[]> {
|
||||
const root = projectRoot();
|
||||
if (!inheritanceGraphCache || inheritanceGraphCache.root !== root) {
|
||||
inheritanceGraphCache = { root, promise: lspRequest(() => commands.navInheritance()) };
|
||||
// A failed request must not stick: the next pass retries it.
|
||||
inheritanceGraphCache.promise.catch(() => {
|
||||
if (inheritanceGraphCache?.root === root) inheritanceGraphCache = null;
|
||||
});
|
||||
}
|
||||
return inheritanceGraphCache.promise;
|
||||
}
|
||||
|
||||
/** Subscribes once per window and stays subscribed, so the settle echo guard survives remounts. */
|
||||
function watchChanges() {
|
||||
if (watching) return;
|
||||
watching = true;
|
||||
onIdeEvent("fsChanged", (e) => {
|
||||
if (affectsMarkers([...e.created, ...e.modified, ...e.removed])) changes++;
|
||||
if (!affectsMarkers([...e.created, ...e.modified, ...e.removed])) return;
|
||||
changes++;
|
||||
forgetInheritanceGraph();
|
||||
});
|
||||
// Answers (outlines too) given while a server was starting or indexing may be incomplete.
|
||||
onServerSettled(() => {
|
||||
docMarkers.clear();
|
||||
forgetInheritanceGraph();
|
||||
for (const plugin of live) plugin.refreshSoon();
|
||||
});
|
||||
}
|
||||
@@ -131,6 +166,13 @@ export interface MarkerDeps {
|
||||
implementations: (positions: Pos[]) => Promise<Location[][]>;
|
||||
supers: SuperDeps;
|
||||
readFiles: (paths: readonly string[]) => Promise<Map<string, string[] | null>>;
|
||||
/**
|
||||
* Every Python class of the project and its base names (the IDE index, attached
|
||||
* dependency roots included). Some servers (basedpyright, pyrefly) answer no
|
||||
* `typeHierarchyProvider`, so ↑/↓ are computed from this graph instead.
|
||||
* Absent for languages whose servers do provide one (Java, Go, ...).
|
||||
*/
|
||||
inheritance?: () => Promise<ClassInheritance[]>;
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
@@ -142,6 +184,8 @@ interface CacheEntry {
|
||||
export interface MarkerCache {
|
||||
entries: Map<string, CacheEntry>;
|
||||
unsupported: Set<MarkerGroup>;
|
||||
/** The Python inheritance graph for this document version, fetched once per cache. */
|
||||
inheritance?: Promise<ClassInheritance[] | null>;
|
||||
}
|
||||
|
||||
export const emptyCache = (): MarkerCache => ({ entries: new Map(), unsupported: new Set() });
|
||||
@@ -164,11 +208,16 @@ export async function fillMarkers(
|
||||
if (!e) cache.entries.set(key, (e = {}));
|
||||
return e;
|
||||
};
|
||||
// A Python inheritance graph answers both groups even when the language server
|
||||
// has no type hierarchy: it must keep the candidates alive through the LSP
|
||||
// "unsupported" bookkeeping, or the fallback would never get to run.
|
||||
const graph = deps.inheritance ? await (cache.inheritance ??= deps.inheritance().catch(() => null)) : null;
|
||||
const fallback = (graph?.length ?? 0) > 0;
|
||||
const down =
|
||||
groups.has("inheritors") && !cache.unsupported.has("inheritors")
|
||||
groups.has("inheritors") && (fallback || !cache.unsupported.has("inheritors"))
|
||||
? candidates.filter((c) => c.inheritable && cache.entries.get(candidateKey(c))?.inheritors === undefined)
|
||||
: [];
|
||||
const askSupers = groups.has("supers") && !cache.unsupported.has("supers");
|
||||
const askSupers = groups.has("supers") && (fallback || !cache.unsupported.has("supers"));
|
||||
const up = askSupers
|
||||
? candidates.filter((c) => c.overriding && c.owner && cache.entries.get(candidateKey(c))?.supers === undefined)
|
||||
: [];
|
||||
@@ -186,8 +235,11 @@ export async function fillMarkers(
|
||||
asked = await deps.implementations(ask.map((c) => ({ line: c.line, col: c.col })));
|
||||
} catch (e) {
|
||||
if (isCancelled(e)) throw e;
|
||||
if (isUnavailable(e)) cache.unsupported.add("inheritors");
|
||||
for (let i = down.length - 1; i >= 0; i--) if (!known.has(down[i]!)) down.splice(i, 1);
|
||||
// With a fallback the candidates stay: the graph may still answer them.
|
||||
if (!fallback) {
|
||||
if (isUnavailable(e)) cache.unsupported.add("inheritors");
|
||||
for (let i = down.length - 1; i >= 0; i--) if (!known.has(down[i]!)) down.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
implementations = down.map((c) => withoutSelf(path, c, known.get(c) ?? asked[ask.indexOf(c)] ?? []));
|
||||
@@ -208,8 +260,79 @@ export async function fillMarkers(
|
||||
}),
|
||||
);
|
||||
}
|
||||
// Python without a type-hierarchy provider: the IDE's inheritance graph holds every
|
||||
// `class X(A)` of the project, so ↑/↓ are computed from it instead.
|
||||
const byName = new Map<string, ClassInheritance[]>();
|
||||
if (graph) for (const cls of graph) byName.set(cls.name, [...(byName.get(cls.name) ?? []), cls]);
|
||||
// The inheritance graph's direct subclasses, keyed by the *declaration* each base
|
||||
// resolves to (path + position), so classes sharing a bare name never mix up.
|
||||
const subclassesOf = new Map<string, ClassInheritance[]>();
|
||||
for (const cls of graph ?? []) {
|
||||
for (const base of new Set(cls.bases)) {
|
||||
for (const decl of resolveBase(byName, base, cls.path)) {
|
||||
const key = declarationKey(decl);
|
||||
subclassesOf.set(key, [...(subclassesOf.get(key) ?? []), cls]);
|
||||
}
|
||||
}
|
||||
}
|
||||
const classOf = (c: MarkerCandidate): ClassInheritance | null => {
|
||||
// A class candidate is its own declaration; a method's is the `owner` it records.
|
||||
const at = c.method ? c.owner : { line: c.line, col: c.col };
|
||||
if (!at) return null;
|
||||
const cls = candidates.find((k) => !k.method && k.line === at.line && k.col === at.col) ?? (c.method ? null : c);
|
||||
if (!cls) return null;
|
||||
return byName.get(cls.name)?.find((x) => x.path === path && x.line === cls.line && x.col === cls.col) ?? null;
|
||||
};
|
||||
/** The declarations a subclass overrides: the subclass itself, or its same-named method. */
|
||||
const subclassDeclarations = async (c: MarkerCandidate, owner: ClassInheritance): Promise<Location[]> => {
|
||||
const subs = subclassesOf.get(declarationKey(owner)) ?? [];
|
||||
if (!c.method) return subs.map(classLocation);
|
||||
const bare = c.symbol.replace(/\s*[(<].*$/, "");
|
||||
const targets: Location[] = [];
|
||||
for (const sub of subs) {
|
||||
const outline = await deps.supers.outline(sub.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, sub, bare);
|
||||
if (m) targets.push({ path: sub.path, range: m.selection_range });
|
||||
}
|
||||
return targets;
|
||||
};
|
||||
if (byName.size) {
|
||||
for (let i = 0; i < down.length; i++) {
|
||||
const c = down[i]!;
|
||||
const owner = classOf(c);
|
||||
if (!owner) continue;
|
||||
// Merge, never replace: a server that answers sees one root, so its list can miss
|
||||
// the subclasses living in an attached project while still being non-empty.
|
||||
implementations[i] = withoutSelf(
|
||||
path,
|
||||
c,
|
||||
mergeLocations(implementations[i] ?? [], await subclassDeclarations(c, owner)),
|
||||
);
|
||||
}
|
||||
}
|
||||
const supers: SuperMethod[][] = [];
|
||||
for (const c of up) supers.push(await superMethodTargets(path, c.owner!, c.symbol, deps.supers));
|
||||
if (byName.size) {
|
||||
for (let i = 0; i < up.length; i++) {
|
||||
const c = up[i]!;
|
||||
const self = classOf(c);
|
||||
if (!self) continue;
|
||||
const found = await superMethodsFrom(byName, self.name, c.symbol, deps);
|
||||
if (!found.length) continue;
|
||||
const known = supers[i]!;
|
||||
// Same merge rule as ↓: add the graph's super methods to what the server answered.
|
||||
const extra = found.map((f) => f.location).filter((l) => !known.some((s) => sameLocation(s.location, l)));
|
||||
const owners = [...new Set(found.map((f) => f.owner))].sort((a, b) => a.localeCompare(b));
|
||||
entry(c).supers = {
|
||||
kind: "overriding",
|
||||
line: c.line,
|
||||
name: c.name,
|
||||
targets: [...known.map((s) => s.location), ...extra],
|
||||
tooltip: tx`Overrides method in ${owners.join(", ")}`,
|
||||
chooserTitle: tx`Choose Super Method of ${c.name} (${known.length + extra.length} found)`,
|
||||
};
|
||||
}
|
||||
}
|
||||
// Go: an implementation request on a type or method answers the interfaces it satisfies.
|
||||
let satisfied: Location[][] = [];
|
||||
if (implicit.length) {
|
||||
@@ -228,10 +351,103 @@ export async function fillMarkers(
|
||||
...satisfied.flat().map((l) => l.path),
|
||||
]);
|
||||
down.forEach((c, i) => (entry(c).inheritors = inheritorsMarker(c, implementations[i] ?? [], files)));
|
||||
up.forEach((c, i) => (entry(c).supers = supersMarker(c, supers[i]!, files)));
|
||||
// A candidate the graph answered already has its marker: don't null it out here.
|
||||
up.forEach((c, i) => {
|
||||
if (supers[i]!.length) entry(c).supers = supersMarker(c, supers[i]!, files);
|
||||
});
|
||||
implicit.forEach((c, i) => (entry(c).supers = implementsMarker(c, withoutSelf(path, c, satisfied[i] ?? []), files)));
|
||||
}
|
||||
|
||||
// One entry per declaration line: the server and the graph may point at the same
|
||||
// declaration with different columns (the name vs the whole statement).
|
||||
const sameLocation = (a: Location, b: Location) => a.path === b.path && a.range.start.line === b.range.start.line;
|
||||
|
||||
/** `first`, then the locations of `more` not already in it. */
|
||||
function mergeLocations(first: readonly Location[], more: readonly Location[]): Location[] {
|
||||
return [...first, ...more.filter((l) => !first.some((f) => sameLocation(f, l)))];
|
||||
}
|
||||
|
||||
/** Identifies one class declaration in the inheritance graph. */
|
||||
function declarationKey(cls: ClassInheritance): string {
|
||||
return `${cls.path}:${cls.line}:${cls.col}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The classes a base name names. A bare name is only trusted when it is unique in the
|
||||
* project, or names a class in the subclass's own file: a `Config` declared in hundreds
|
||||
* of modules must not make every one of them a subclass of every other.
|
||||
*/
|
||||
function resolveBase(byName: ReadonlyMap<string, ClassInheritance[]>, name: string, from: string): ClassInheritance[] {
|
||||
const found = byName.get(name) ?? [];
|
||||
if (found.length <= 1) return found;
|
||||
return found.filter((c) => c.path === from);
|
||||
}
|
||||
|
||||
/** The class declaration itself as a navigation target (its name identifier). */
|
||||
function classLocation(cls: ClassInheritance): Location {
|
||||
const start = { line: cls.line, col: cls.col };
|
||||
return { path: cls.path, range: { start, end: start } };
|
||||
}
|
||||
|
||||
/** The method `method` (bare name) directly inside the class at `cls`'s position. */
|
||||
function methodInOutline(outline: readonly OutlineItem[], cls: ClassInheritance, method: string): OutlineItem | null {
|
||||
const at = cls;
|
||||
const find = (items: readonly OutlineItem[]): OutlineItem | null => {
|
||||
for (const it of items) {
|
||||
if (it.kind === "class" && it.selection_range.start.line === at.line && it.selection_range.start.col === at.col) {
|
||||
return it.children.find((ch) => ch.kind === "method" && baseName(ch.name) === method) ?? null;
|
||||
}
|
||||
const deeper = find(it.children);
|
||||
if (deeper) return deeper;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return find(outline);
|
||||
}
|
||||
|
||||
/**
|
||||
* Super methods of `method` declared by a class in `byName`, walking the inheritance
|
||||
* graph's bases up to a few levels. Empty when no base declares the method.
|
||||
*/
|
||||
async function superMethodsFrom(
|
||||
byName: ReadonlyMap<string, ClassInheritance[]>,
|
||||
start: string,
|
||||
method: string,
|
||||
deps: MarkerDeps,
|
||||
depth = 3,
|
||||
): Promise<{ location: Location; owner: string }[]> {
|
||||
const bare = method.replace(/\s*[(<].*$/, "");
|
||||
const seen = new Set<string>([start]);
|
||||
let level = [start];
|
||||
for (let d = 0; d < depth && level.length; d++) {
|
||||
const next: string[] = [];
|
||||
const found: { location: Location; owner: string }[] = [];
|
||||
for (const name of level) {
|
||||
for (const cls of byName.get(name) ?? []) {
|
||||
for (const base of cls.bases) {
|
||||
if (!seen.add(base)) continue;
|
||||
// Same rule as the graph: only a base that names one class is followed.
|
||||
const declarations = resolveBase(byName, base, cls.path);
|
||||
let answered = false;
|
||||
for (const baseCls of declarations) {
|
||||
const outline = await deps.supers.outline(baseCls.path).catch(() => [] as OutlineItem[]);
|
||||
const m = methodInOutline(outline, baseCls, bare);
|
||||
if (m) {
|
||||
found.push({ location: { path: baseCls.path, range: m.selection_range }, owner: base });
|
||||
answered = true;
|
||||
}
|
||||
}
|
||||
// Not found in a base that declares nothing: keep walking its own bases.
|
||||
if (!answered) next.push(base);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (found.length) return found;
|
||||
level = next;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Overriders of a type's methods from one walk of its subtypes and their outlines, instead of one
|
||||
* implementation request per method: jdtls builds the type hierarchy again for every implementation
|
||||
@@ -575,6 +791,9 @@ function markerDeps(ctx: EditorDocContext, items: OutlineItem[], request: Reques
|
||||
},
|
||||
},
|
||||
readFiles: readManyFileLines,
|
||||
// Python servers answer no type hierarchy (basedpyright, pyrefly): the IDE's
|
||||
// own index knows every `class X(Base)` of the project, attached roots included.
|
||||
inheritance: ctx.language === "python" ? inheritanceGraph : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
IpcError,
|
||||
type ClassInheritance,
|
||||
type HierarchyItem,
|
||||
type Location,
|
||||
type OutlineItem,
|
||||
@@ -208,8 +209,9 @@ function server(
|
||||
impls: Record<string, Location[]>,
|
||||
supers: Record<string, HierarchyItem[]>,
|
||||
subtypes: Record<string, HierarchyItem[]> = {},
|
||||
inheritance?: ClassInheritance[],
|
||||
) {
|
||||
const calls = { implementations: [] as Pos[][], supertypes: 0, subtypes: 0 };
|
||||
const calls = { implementations: [] as Pos[][], supertypes: 0, subtypes: 0, inheritance: 0 };
|
||||
const outlines: Record<string, OutlineItem[]> = {
|
||||
[SHAPE_PATH]: SHAPE_OUTLINE,
|
||||
"/p/Circle.java": CIRCLE_OUTLINE,
|
||||
@@ -234,6 +236,35 @@ function server(
|
||||
outline: async (p) => outlines[p] ?? [],
|
||||
},
|
||||
readFiles: async (paths) => new Map(paths.map((p) => [p, FILES[p] ?? null])),
|
||||
inheritance: inheritance
|
||||
? async () => {
|
||||
calls.inheritance++;
|
||||
return inheritance;
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
return { calls, deps };
|
||||
}
|
||||
|
||||
/** A Python project: the server answers neither implementations nor a type hierarchy. */
|
||||
function pythonServer(inheritance: ClassInheritance[], outlines: Record<string, OutlineItem[]>) {
|
||||
const calls = { implementations: 0, inheritance: 0 };
|
||||
const deps = (): MarkerDeps => ({
|
||||
implementations: async () => {
|
||||
calls.implementations++;
|
||||
throw new IpcError({ kind: "unavailable", message: "basedpyright doesn't support implementation" });
|
||||
},
|
||||
supers: {
|
||||
supertypes: async () => {
|
||||
throw new IpcError({ kind: "unavailable", message: "basedpyright doesn't support type hierarchy" });
|
||||
},
|
||||
outline: async (p) => outlines[p] ?? [],
|
||||
},
|
||||
readFiles: async () => new Map(),
|
||||
inheritance: async () => {
|
||||
calls.inheritance++;
|
||||
return inheritance;
|
||||
},
|
||||
});
|
||||
return { calls, deps };
|
||||
}
|
||||
@@ -637,3 +668,98 @@ describe("overriders of a type's methods from its subtypes", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("python inheritance fallback", () => {
|
||||
// a.py: `class A` (line 0) with `m` (line 1), then `class B(A)` (line 3) with `m` (line 4).
|
||||
const outline = [
|
||||
item("A", "class", 0, 2, [item("m", "method", 1, 1)], 6),
|
||||
item("B", "class", 3, 5, [item("m", "method", 4, 4)], 6),
|
||||
];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/a.py", line: 0, col: 6, name: "A", bases: [] },
|
||||
{ path: "/p/a.py", line: 3, col: 6, name: "B", bases: ["A"] },
|
||||
];
|
||||
|
||||
it("marks the subclass and the overridden method with no type hierarchy", async () => {
|
||||
const { deps, calls } = pythonServer(graph, { "/p/a.py": outline });
|
||||
const candidates = markerCandidates(outline, () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
|
||||
const markers = cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.targets.map((t) => t.path)]);
|
||||
expect(markers).toEqual([
|
||||
// The class B subclasses A...
|
||||
[0, "overridden", ["/p/a.py"]],
|
||||
// ...and its `m` overrides A's `m`.
|
||||
[1, "overridden", ["/p/a.py"]],
|
||||
[4, "overriding", ["/p/a.py"]],
|
||||
]);
|
||||
// The graph is asked once per cache, not once per candidate.
|
||||
expect(calls.inheritance).toBe(1);
|
||||
});
|
||||
|
||||
it("survives an unavailable implementation provider (the fallback keeps its candidates)", async () => {
|
||||
const { deps, calls } = pythonServer(graph, { "/p/a.py": outline });
|
||||
const candidates = markerCandidates(outline, () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps(), cache);
|
||||
// The server said "unavailable", but the graph still answered ↓ and ↑.
|
||||
expect(calls.implementations).toBeGreaterThan(0);
|
||||
expect(cache.unsupported.size).toBe(0);
|
||||
});
|
||||
|
||||
it("adds the graph's cross-project subclasses to a non-empty server answer", async () => {
|
||||
// The server (single root) answers the local subclass only; the attached-project
|
||||
// subclass is known to the IDE's graph and must join the list.
|
||||
const outline = [item("A", "class", 0, 2, [], 6), item("B", "class", 3, 5, [], 6)];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/a.py", line: 0, col: 6, name: "A", bases: [] },
|
||||
{ path: "/p/a.py", line: 3, col: 6, name: "B", bases: ["A"] },
|
||||
{ path: "/p/attached/a.py", line: 0, col: 6, name: "C", bases: ["A"] },
|
||||
];
|
||||
const { deps } = server({ "/p/a.py:0": [loc("/p/a.py", 3)] }, {}, {}, graph);
|
||||
const candidates = markerCandidates(outline, () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps("/p/a.py"), cache);
|
||||
const targets = cachedMarkers(candidates, ALL, cache)
|
||||
.filter((m) => m.line === 0)
|
||||
.flatMap((m) => m.targets.map((t) => t.path));
|
||||
expect(targets).toEqual(["/p/a.py", "/p/attached/a.py"]);
|
||||
});
|
||||
|
||||
it("ignores a bare base name that many classes in the project share", async () => {
|
||||
// `Config` is declared in hundreds of modules: no edge, so no marker.
|
||||
const outline = [item("Child", "class", 0, 2, [], 6)];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/a.py", line: 0, col: 6, name: "Config", bases: [] },
|
||||
{ path: "/p/b.py", line: 0, col: 6, name: "Config", bases: [] },
|
||||
{ path: "/p/c.py", line: 0, col: 6, name: "Child", bases: ["Config"] },
|
||||
];
|
||||
const { deps } = pythonServer(graph, { "/p/c.py": outline });
|
||||
const candidates = markerCandidates(outline, () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/c.py", candidates, ALL, deps(), cache);
|
||||
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
|
||||
});
|
||||
|
||||
it("trusts a shared base name when the subclass's own file declares it", async () => {
|
||||
const outline = [item("Config", "class", 0, 1, [], 6), item("Child", "class", 3, 5, [], 6)];
|
||||
const graph: ClassInheritance[] = [
|
||||
{ path: "/p/c.py", line: 0, col: 6, name: "Config", bases: [] },
|
||||
{ path: "/p/other.py", line: 0, col: 6, name: "Config", bases: [] },
|
||||
{ path: "/p/c.py", line: 3, col: 6, name: "Child", bases: ["Config"] },
|
||||
];
|
||||
const { deps } = pythonServer(graph, { "/p/c.py": outline });
|
||||
const candidates = markerCandidates(outline, () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/c.py", candidates, ALL, deps(), cache);
|
||||
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind])).toEqual([[0, "overridden"]]);
|
||||
});
|
||||
|
||||
it("keeps the existing server path when no inheritance graph is injected", async () => {
|
||||
const { deps } = server({}, {});
|
||||
const candidates = markerCandidates([item("Foo", "class", 0, 2, [item("m", "method", 1, 1)], 6)], () => "");
|
||||
const cache = emptyCache();
|
||||
await fillMarkers("/p/a.py", candidates, ALL, deps("/p/a.py"), cache);
|
||||
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -438,7 +438,10 @@
|
||||
.suggestion:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
}
|
||||
/* The file name truncates first; the hint stays on one line. */
|
||||
.suggestionHint {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.removeChip {
|
||||
@@ -458,6 +461,7 @@
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.attachmentName {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -88,3 +88,16 @@
|
||||
max-width: 45%;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.notes {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
height: 0;
|
||||
}
|
||||
.docked .notes {
|
||||
height: auto;
|
||||
}
|
||||
.docked .notes:empty {
|
||||
display: none;
|
||||
}
|
||||
@@ -221,26 +221,29 @@ export function HomeEditor({ docked = false }: { docked?: boolean; input?: Edito
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{probe && (!docked || probe.error) && (
|
||||
<p className={probe.error ? styles.warning : styles.note}>
|
||||
{probe.error
|
||||
? txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)
|
||||
: [probe.name, probe.version, probe.protocol].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
)}
|
||||
{(error || (provider && !provider.installed) || (provider && !provider.config.length)) && (
|
||||
<p
|
||||
className={error || !provider?.installed ? styles.warning : styles.note}
|
||||
role={error ? "alert" : undefined}
|
||||
>
|
||||
{error ??
|
||||
(provider && !provider.installed ? (
|
||||
txTemplate(`${provider.command} was not found on PATH`)
|
||||
) : (
|
||||
<T>Models and modes appear after this agent's first task.</T>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
{/* Notes under the box don't take part in centring, so the box stays put as they come and go. */}
|
||||
<div className={styles.notes}>
|
||||
{probe && (!docked || probe.error) && (
|
||||
<p className={probe.error ? styles.warning : styles.note}>
|
||||
{probe.error
|
||||
? txTemplate(`${provider?.name ?? probe.provider} didn't start: ${probe.error}`)
|
||||
: [probe.name, probe.version, probe.protocol].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
)}
|
||||
{(error || (provider && !provider.installed) || (provider && !provider.config.length)) && (
|
||||
<p
|
||||
className={error || !provider?.installed ? styles.warning : styles.note}
|
||||
role={error ? "alert" : undefined}
|
||||
>
|
||||
{error ??
|
||||
(provider && !provider.installed ? (
|
||||
txTemplate(`${provider.command} was not found on PATH`)
|
||||
) : (
|
||||
<T>Models and modes appear after this agent's first task.</T>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -43,6 +43,27 @@
|
||||
color: var(--fg-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
/* In the composer: a × at the end removes the reference, as on the attached blocks. */
|
||||
.removable {
|
||||
padding-right: 2px;
|
||||
}
|
||||
.chipRemove {
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius-small);
|
||||
background: none;
|
||||
color: var(--fg-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.chipRemove:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
/* The file is gone (renamed or deleted since it was referenced). */
|
||||
.missing {
|
||||
color: var(--fg-muted);
|
||||
|
||||
@@ -55,8 +55,8 @@ export function openReference(path: string, mention: Mention) {
|
||||
const nameOf = (m: Mention) => basename(m.rel.replace(/\/$/, "")) || m.rel;
|
||||
const iconOf = (m: Mention) => (m.dir ? "folder" : fileIconName(nameOf(m), m.rel));
|
||||
|
||||
/** The chip as DOM, for the composer's editor. */
|
||||
export function chipElement(path: string, mention: Mention): HTMLElement {
|
||||
/** The chip as DOM, for the composer's editor; `onRemove` adds its × button. */
|
||||
export function chipElement(path: string, mention: Mention, onRemove?: () => void): HTMLElement {
|
||||
const chip = document.createElement("span");
|
||||
chip.className = styles.chip!;
|
||||
chip.dataset.refPath = path;
|
||||
@@ -74,6 +74,20 @@ export function chipElement(path: string, mention: Mention): HTMLElement {
|
||||
lines.textContent = linesLabel(mention.lines);
|
||||
chip.append(lines);
|
||||
}
|
||||
if (onRemove) {
|
||||
chip.classList.add(styles.removable!);
|
||||
const remove = document.createElement("button");
|
||||
remove.type = "button";
|
||||
remove.className = styles.chipRemove!;
|
||||
remove.setAttribute("aria-label", tx("Remove"));
|
||||
remove.append(iconNode("close", 10));
|
||||
remove.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
remove.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
});
|
||||
chip.append(remove);
|
||||
}
|
||||
if (!mention.dir)
|
||||
void fileExists(path).then((exists) => {
|
||||
if (!exists) chip.classList.add(styles.missing!);
|
||||
|
||||
@@ -41,9 +41,11 @@
|
||||
/* The task's state and its terminal and changes, just above the composer. */
|
||||
.statusBar {
|
||||
display: flex;
|
||||
/* What doesn't fit moves to the next line whole, instead of every fact shrinking to a letter. */
|
||||
flex-wrap: wrap;
|
||||
/* The changes chip sits above the line; the facts stay on that line's baseline. */
|
||||
align-items: flex-end;
|
||||
gap: 6px;
|
||||
gap: 2px 6px;
|
||||
min-width: 0;
|
||||
padding: 0 2px;
|
||||
overflow: hidden;
|
||||
@@ -54,6 +56,7 @@
|
||||
.agent {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
@@ -70,6 +73,7 @@
|
||||
.where {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
/* The chips' own padding spaces them. */
|
||||
gap: 2px;
|
||||
@@ -87,20 +91,21 @@
|
||||
height: 22px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* The changes sit above the meter, time and terminal; those keep their one row at the right. */
|
||||
/* The rest of the line: the changes at its start, the meter, time and terminal at its end.
|
||||
On a line of its own (a narrow session) the changes line up with the facts above. */
|
||||
.statusEnd {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 2px;
|
||||
flex: 1 1 auto;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 2px 8px;
|
||||
min-width: 0;
|
||||
margin-left: auto;
|
||||
}
|
||||
/* Shrinks before the terminal buttons do: in a narrow docked session the meters clip, not the controls. */
|
||||
.statusMeters {
|
||||
display: inline-flex;
|
||||
flex: 0 1 auto;
|
||||
margin-left: auto;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
gap: 8px;
|
||||
|
||||
@@ -387,7 +387,7 @@ function SessionStatus({
|
||||
<T>{statusLabel(task.status)}</T>
|
||||
{task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`}
|
||||
</span>
|
||||
{/* What changed sits above the meter, time and terminal; those keep their one row at the right. */}
|
||||
{/* What changed sits before the meter, time and terminal, or above them when the row is full. */}
|
||||
<span className={styles.statusEnd}>
|
||||
{(!!changes?.length || !!commits.length) && (
|
||||
<span className={styles.statusChips}>
|
||||
|
||||
@@ -79,8 +79,16 @@ class ChipWidget extends WidgetType {
|
||||
eq(other: ChipWidget) {
|
||||
return other.path === this.path && other.text === this.text;
|
||||
}
|
||||
toDOM() {
|
||||
const chip = chipElement(this.path, this.mention);
|
||||
toDOM(view: EditorView) {
|
||||
const chip = chipElement(this.path, this.mention, () => {
|
||||
const from = view.posAtDOM(chip);
|
||||
const at = view.state.field(painted).chips.find((c) => c.from === from);
|
||||
if (!at) return;
|
||||
// The space typed after the reference goes with it.
|
||||
const end = view.state.sliceDoc(at.to, at.to + 1) === " " ? at.to + 1 : at.to;
|
||||
view.dispatch({ changes: { from: at.from, to: end }, userEvent: "delete" });
|
||||
view.focus();
|
||||
});
|
||||
// Keep the editor's focus and caret; a click opens the file.
|
||||
chip.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
chip.addEventListener("click", (e) => {
|
||||
|
||||
@@ -814,25 +814,31 @@ export async function startTask(
|
||||
: (draft.config[o.id] ?? defaults[o.id] ?? null);
|
||||
return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : [];
|
||||
});
|
||||
const task = await call(
|
||||
commands.agentCreate({
|
||||
projectRoot,
|
||||
prompt: toPrompt(composer),
|
||||
provider: draft.provider,
|
||||
config,
|
||||
isolation,
|
||||
base: isolation === "worktree" ? draft.base : null,
|
||||
}),
|
||||
);
|
||||
// Its events can arrive before this reply: keep the newer state they carried.
|
||||
useAgents.setState((s) => ({
|
||||
tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task),
|
||||
entries: new Map(s.entries).set(task.id, s.entries.get(task.id) ?? []),
|
||||
}));
|
||||
updateDraft({ projectRoot });
|
||||
remember(composer.text.trim());
|
||||
clearSubmittedComposer(HOME, composer, started);
|
||||
if ((await editorService().closeInput?.(HOME_KEY)) !== false) openTask(task.id);
|
||||
try {
|
||||
const task = await call(
|
||||
commands.agentCreate({
|
||||
projectRoot,
|
||||
prompt: toPrompt(composer),
|
||||
provider: draft.provider,
|
||||
config,
|
||||
isolation,
|
||||
base: isolation === "worktree" ? draft.base : null,
|
||||
}),
|
||||
);
|
||||
if (generation !== started) return;
|
||||
// Its events can arrive before this reply: keep the newer state they carried.
|
||||
useAgents.setState((s) => ({
|
||||
tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task),
|
||||
entries: new Map(s.entries).set(task.id, s.entries.get(task.id) ?? []),
|
||||
}));
|
||||
updateDraft({ projectRoot });
|
||||
remember(composer.text.trim());
|
||||
clearSubmittedComposer(HOME, composer, started);
|
||||
const closed = await editorService().closeInput?.(HOME_KEY);
|
||||
if (generation === started && closed !== false) openTask(task.id);
|
||||
} catch (e) {
|
||||
if (generation === started) throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sessions on this machine that no task holds yet (a terminal, another editor: #312). */
|
||||
@@ -955,11 +961,17 @@ export function quoteInComposer(task: string, text: string) {
|
||||
|
||||
/** Copies the task's conversation into a new task (up to its first `turns` turns) and opens it. */
|
||||
export async function forkTask(task: string, turns: number | null): Promise<void> {
|
||||
const copy = await call(commands.agentFork(task, turns));
|
||||
useAgents.setState((s) => ({
|
||||
tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
|
||||
}));
|
||||
openTask(copy.id);
|
||||
const started = generation;
|
||||
try {
|
||||
const copy = await call(commands.agentFork(task, turns));
|
||||
if (generation !== started) return;
|
||||
useAgents.setState((s) => ({
|
||||
tasks: s.tasks.has(copy.id) ? s.tasks : new Map(s.tasks).set(copy.id, copy),
|
||||
}));
|
||||
openTask(copy.id);
|
||||
} catch (e) {
|
||||
if (generation === started) throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts a message back in the task's composer, above anything typed meanwhile. */
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AgentTask, ProjectInfo } from "@/bindings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { HOME_KEY, SESSION_KIND, TOOL_WINDOW, sessionKey } from "./model";
|
||||
import {
|
||||
HOME,
|
||||
composerDraft,
|
||||
connect,
|
||||
disconnect,
|
||||
forkTask,
|
||||
startTask,
|
||||
updateComposer,
|
||||
updateDraft,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
fork: vi.fn(),
|
||||
subscribe: vi.fn(),
|
||||
open: vi.fn(),
|
||||
close: vi.fn(),
|
||||
show: vi.fn(),
|
||||
closeAvailable: true,
|
||||
tasks: [] as AgentTask[],
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (original) => ({
|
||||
...(await original<typeof import("@/platform/ipc")>()),
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
agentCreate: backend.create,
|
||||
agentFork: backend.fork,
|
||||
agentSubscribe: backend.subscribe,
|
||||
agentProviders: async () => ({ status: "ok", data: [] }),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
editorService: () => ({
|
||||
openInput: backend.open,
|
||||
closeInput: backend.closeAvailable ? backend.close : undefined,
|
||||
openTabs: () => [],
|
||||
}),
|
||||
toolWindowService: () => ({ show: backend.show }),
|
||||
}));
|
||||
|
||||
const ok = <T>(data: T) => ({ status: "ok" as const, data });
|
||||
function deferred() {
|
||||
let resolve!: (value: unknown) => void;
|
||||
let reject!: (reason: Error) => void;
|
||||
const promise = new Promise((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
const task = (id: string, cwd = "/project-a"): AgentTask => ({
|
||||
id,
|
||||
cwd,
|
||||
title: id,
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
});
|
||||
const setProject = (root: string | null) =>
|
||||
useProject.setState({
|
||||
project: root === null ? null : ({ root, trusted: true } as ProjectInfo),
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
disconnect();
|
||||
vi.resetAllMocks();
|
||||
backend.closeAvailable = true;
|
||||
backend.close.mockResolvedValue(true);
|
||||
backend.tasks = [task("source")];
|
||||
backend.subscribe.mockImplementation(async () => ok(backend.tasks));
|
||||
setProject("/project-a");
|
||||
useProject.setState({ settings: null });
|
||||
useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([["source", task("source")]]),
|
||||
entries: new Map(),
|
||||
providers: [],
|
||||
draft: { provider: "codex", config: {}, isolation: "local", base: "main" },
|
||||
history: [],
|
||||
composers: new Map(),
|
||||
lastComposer: HOME,
|
||||
focus: null,
|
||||
sessionLocation: "editor",
|
||||
docked: null,
|
||||
lastTask: null,
|
||||
homeOpen: true,
|
||||
});
|
||||
updateComposer(HOME, { text: "submitted in A" });
|
||||
});
|
||||
afterEach(() => disconnect());
|
||||
|
||||
const transitions = [
|
||||
"disconnect",
|
||||
"reconnect",
|
||||
"replace connection",
|
||||
"trust change",
|
||||
"A to B",
|
||||
"A to B to A",
|
||||
"A to B to C",
|
||||
"close project",
|
||||
] as const;
|
||||
async function transition(change: (typeof transitions)[number]) {
|
||||
if (change !== "replace connection") disconnect();
|
||||
if (change.startsWith("A to B")) setProject("/project-b");
|
||||
if (change === "trust change")
|
||||
useProject.setState({ project: { root: "/project-a", trusted: false } as ProjectInfo });
|
||||
if (change === "close project") setProject(null);
|
||||
backend.tasks = [task("current", useProject.getState().project?.root ?? "")];
|
||||
if (change !== "disconnect" && change !== "close project") await connect();
|
||||
if (change === "A to B to A" || change === "A to B to C") {
|
||||
disconnect();
|
||||
setProject(change === "A to B to A" ? "/project-a" : "/project-c");
|
||||
backend.tasks = [task("current", useProject.getState().project!.root)];
|
||||
await connect();
|
||||
}
|
||||
updateDraft({ projectRoot: "/current/member", provider: "current-agent", config: { model: "current-model" } });
|
||||
updateComposer(HOME, {
|
||||
text: "current project draft",
|
||||
files: [{ path: "/current/next.ts", rel: "next.ts", attached: true }],
|
||||
images: [{ mimeType: "image/png", data: "next", name: "next.png" }],
|
||||
});
|
||||
useAgents.setState({ history: ["current history"], docked: "current", homeOpen: true, lastTask: "current" });
|
||||
}
|
||||
|
||||
const paths = [
|
||||
{ name: "create local task", create: true, run: () => startTask("local"), mock: backend.create, turns: null },
|
||||
{ name: "create worktree task", create: true, run: () => startTask("worktree"), mock: backend.create, turns: null },
|
||||
{ name: "fork entire task", create: false, run: () => forkTask("source", null), mock: backend.fork, turns: null },
|
||||
{ name: "fork selected turns", create: false, run: () => forkTask("source", 2), mock: backend.fork, turns: 2 },
|
||||
];
|
||||
|
||||
describe.each(paths)("$name project ownership", (path) => {
|
||||
function begin() {
|
||||
const response = deferred();
|
||||
path.mock.mockReturnValueOnce(response.promise);
|
||||
return { ...response, pending: path.run() };
|
||||
}
|
||||
|
||||
it.each(["editor", "toolWindow"] as const)("opens a successful task in the current %s", async (location) => {
|
||||
useAgents.setState({ sessionLocation: location });
|
||||
const response = begin();
|
||||
expect(path.mock).toHaveBeenCalledTimes(1);
|
||||
if (path.create)
|
||||
expect(backend.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
prompt: { text: "submitted in A", files: [], images: [] },
|
||||
}),
|
||||
);
|
||||
else expect(backend.fork).toHaveBeenCalledWith("source", path.turns);
|
||||
response.resolve(ok(task("completed")));
|
||||
await response.pending;
|
||||
expect(useAgents.getState().tasks.get("completed")).toEqual(task("completed"));
|
||||
if (location === "editor") {
|
||||
expect(backend.open).toHaveBeenCalledWith(
|
||||
{ kind: SESSION_KIND, key: sessionKey("completed"), data: { task: "completed", title: "completed" } },
|
||||
{ focus: true },
|
||||
);
|
||||
} else {
|
||||
expect(useAgents.getState().docked).toBe("completed");
|
||||
expect(backend.show).toHaveBeenCalledWith(TOOL_WINDOW, true);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
}
|
||||
expect(composerDraft(HOME).text).toBe(path.create ? "" : "submitted in A");
|
||||
expect(useAgents.getState().history).toEqual(path.create ? ["submitted in A"] : []);
|
||||
});
|
||||
|
||||
it.each(transitions)("ignores a successful reply after %s", async (change) => {
|
||||
const response = begin();
|
||||
await transition(change);
|
||||
const current = useAgents.getState();
|
||||
response.resolve(ok(task("old-task")));
|
||||
await response.pending;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(backend.close).not.toHaveBeenCalled();
|
||||
expect(backend.show).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves a current task with a colliding id and its conversation untouched", async () => {
|
||||
const response = begin();
|
||||
await transition("A to B");
|
||||
const currentTask = { ...task("completed", "/project-b"), title: "B's task" };
|
||||
useAgents.setState({
|
||||
tasks: new Map([[currentTask.id, currentTask]]),
|
||||
entries: new Map([[currentTask.id, [{ type: "agent", text: "B's conversation" }]]]),
|
||||
});
|
||||
const current = useAgents.getState();
|
||||
response.resolve(ok(task("completed")));
|
||||
await response.pending;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves state on command failure (switched project=%s)", async (switched) => {
|
||||
const response = begin();
|
||||
if (switched) await transition("A to B");
|
||||
const current = useAgents.getState();
|
||||
const failure = switched
|
||||
? expect(response.pending).resolves.toBeUndefined()
|
||||
: expect(response.pending).rejects.toThrow("operation failed");
|
||||
response.resolve({ status: "error", error: { kind: "internal", message: "operation failed" } });
|
||||
await failure;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(backend.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves state on transport failure (switched project=%s)", async (switched) => {
|
||||
const response = begin();
|
||||
if (switched) await transition("A to B");
|
||||
const current = useAgents.getState();
|
||||
const failure = switched
|
||||
? expect(response.pending).resolves.toBeUndefined()
|
||||
: expect(response.pending).rejects.toThrow("connection lost");
|
||||
response.reject(new Error("connection lost"));
|
||||
await failure;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(backend.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps task and conversation events that arrived before the same-project reply", async () => {
|
||||
const response = begin();
|
||||
const newer = { ...task("completed"), title: "Newer title", status: "running" as const };
|
||||
useAgents.setState({
|
||||
tasks: new Map([[newer.id, newer]]),
|
||||
entries: new Map([[newer.id, [{ type: "agent", text: "new entry" }]]]),
|
||||
});
|
||||
response.resolve(ok(task("completed")));
|
||||
await response.pending;
|
||||
expect(useAgents.getState().tasks.get(newer.id)).toBe(newer);
|
||||
expect(useAgents.getState().entries.get(newer.id)).toEqual([{ type: "agent", text: "new entry" }]);
|
||||
});
|
||||
|
||||
it.each(["old first", "new first"])(
|
||||
"accepts only the new project's request when acknowledgements arrive %s",
|
||||
async (order) => {
|
||||
const old = begin();
|
||||
await transition("A to B");
|
||||
const current = begin();
|
||||
const finishOld = async () => {
|
||||
old.resolve(ok(task("old-task")));
|
||||
await old.pending;
|
||||
};
|
||||
const finishCurrent = async () => {
|
||||
current.resolve(ok(task("new-task", "/project-b")));
|
||||
await current.pending;
|
||||
};
|
||||
if (order === "old first") {
|
||||
await finishOld();
|
||||
await finishCurrent();
|
||||
} else {
|
||||
await finishCurrent();
|
||||
await finishOld();
|
||||
}
|
||||
expect([...useAgents.getState().tasks.keys()]).toEqual(["current", "new-task"]);
|
||||
expect(useAgents.getState().lastTask).toBe("new-task");
|
||||
expect(backend.open).toHaveBeenCalledTimes(1);
|
||||
expect(backend.open).toHaveBeenCalledWith(expect.objectContaining({ key: sessionKey("new-task") }), {
|
||||
focus: true,
|
||||
});
|
||||
expect(useAgents.getState().history).toEqual(
|
||||
path.create ? ["current project draft", "current history"] : ["current history"],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["first then second", "second then first"])(
|
||||
"keeps both legitimate same-project requests (%s)",
|
||||
async (order) => {
|
||||
const first = begin();
|
||||
const second = begin();
|
||||
const finishFirst = async () => {
|
||||
first.resolve(ok(task("first")));
|
||||
await first.pending;
|
||||
};
|
||||
const finishSecond = async () => {
|
||||
second.resolve(ok(task("second")));
|
||||
await second.pending;
|
||||
};
|
||||
if (order === "first then second") {
|
||||
await finishFirst();
|
||||
await finishSecond();
|
||||
} else {
|
||||
await finishSecond();
|
||||
await finishFirst();
|
||||
}
|
||||
expect(useAgents.getState().tasks.has("first")).toBe(true);
|
||||
expect(useAgents.getState().tasks.has("second")).toBe(true);
|
||||
expect(backend.open).toHaveBeenCalledTimes(2);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe.each(paths.filter((path) => path.create))("$name after closing Home", (path) => {
|
||||
async function waitingForClose() {
|
||||
const closing = deferred();
|
||||
backend.close.mockReturnValueOnce(closing.promise);
|
||||
backend.create.mockResolvedValueOnce(ok(task("completed")));
|
||||
const pending = path.run();
|
||||
await vi.waitFor(() => expect(backend.close).toHaveBeenCalledWith(HOME_KEY));
|
||||
return { ...closing, pending };
|
||||
}
|
||||
|
||||
it.each(transitions)("does not navigate after %s while the page is closing", async (change) => {
|
||||
const closing = await waitingForClose();
|
||||
await transition(change);
|
||||
const current = useAgents.getState();
|
||||
closing.resolve(true);
|
||||
await closing.pending;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(backend.show).not.toHaveBeenCalled();
|
||||
expect(backend.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(transitions)("does not surface an old close failure after %s", async (change) => {
|
||||
const closing = await waitingForClose();
|
||||
await transition(change);
|
||||
const current = useAgents.getState();
|
||||
const done = expect(closing.pending).resolves.toBeUndefined();
|
||||
closing.reject(new Error("old close failed"));
|
||||
await done;
|
||||
expect(useAgents.getState()).toBe(current);
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(backend.show).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still navigates after closing when only settings or another composer changed", async () => {
|
||||
const closing = await waitingForClose();
|
||||
updateDraft({ config: { model: "different" } });
|
||||
updateComposer("other", { text: "another conversation" });
|
||||
closing.resolve(true);
|
||||
await closing.pending;
|
||||
expect(backend.open).toHaveBeenCalledWith(expect.objectContaining({ key: sessionKey("completed") }), {
|
||||
focus: true,
|
||||
});
|
||||
expect(composerDraft("other").text).toBe("another conversation");
|
||||
});
|
||||
|
||||
it("respects a cancelled close", async () => {
|
||||
const closing = await waitingForClose();
|
||||
closing.resolve(false);
|
||||
await closing.pending;
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(useAgents.getState().tasks.has("completed")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not navigate when closing fails", async () => {
|
||||
const closing = await waitingForClose();
|
||||
const failure = expect(closing.pending).rejects.toThrow("could not close");
|
||||
closing.reject(new Error("could not close"));
|
||||
await failure;
|
||||
expect(backend.open).not.toHaveBeenCalled();
|
||||
expect(useAgents.getState().tasks.has("completed")).toBe(true);
|
||||
});
|
||||
|
||||
it("opens the task when the editor service has no close operation", async () => {
|
||||
backend.closeAvailable = false;
|
||||
backend.create.mockResolvedValueOnce(ok(task("completed")));
|
||||
await path.run();
|
||||
expect(backend.open).toHaveBeenCalledWith(expect.objectContaining({ key: sessionKey("completed") }), {
|
||||
focus: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the workspace member selected for the request", async () => {
|
||||
const root = "/workspace/member-a";
|
||||
const result = task("completed", root);
|
||||
backend.create.mockResolvedValueOnce(ok(result));
|
||||
await startTask(path.name === "create worktree task" ? "worktree" : "local", root);
|
||||
expect(backend.create).toHaveBeenCalledWith(expect.objectContaining({ projectRoot: root }));
|
||||
expect(useAgents.getState().tasks.get(result.id)).toEqual(result);
|
||||
expect(backend.open).toHaveBeenCalledWith(expect.objectContaining({ key: sessionKey(result.id) }), { focus: true });
|
||||
});
|
||||
});
|
||||
@@ -246,12 +246,6 @@
|
||||
margin: 0 4px;
|
||||
background: var(--border);
|
||||
}
|
||||
.treeFilter {
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
max-width: 280px;
|
||||
margin-left: 4px;
|
||||
}
|
||||
.treeHost {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -41,7 +41,6 @@ beforeEach(() => {
|
||||
sequences: [],
|
||||
},
|
||||
},
|
||||
treeFilter: "",
|
||||
separateProceduresAndFunctions: false,
|
||||
treeExpanded: new Set(["pg", "pg/public", "pg/public/routines"]),
|
||||
});
|
||||
@@ -60,9 +59,6 @@ describe("routine grouping", () => {
|
||||
expect(tree.queryByText("functions")).toBeNull();
|
||||
fireEvent.mouseDown(tree.getAllByText("calculate")[1]!, { button: 0 });
|
||||
expect(useDatabase.getState().selectedNode?.key).toBe("pg/public/routines/calculate(text)");
|
||||
act(() => useDatabase.setState({ treeFilter: "refresh" }));
|
||||
expect(tree.queryAllByText("calculate")).toHaveLength(0);
|
||||
expect(tree.getByText("refresh_data")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles through the action, persists the option, and restores the old expansion", async () => {
|
||||
@@ -91,7 +87,7 @@ describe("routine grouping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([false, true])("applies object and quick filters before grouping (separate: %s)", (separate) => {
|
||||
it.each([false, true])("applies the object filter before grouping (separate: %s)", (separate) => {
|
||||
const source = useDatabase.getState().sources[0]!;
|
||||
useDatabase.setState({
|
||||
separateProceduresAndFunctions: separate,
|
||||
@@ -105,10 +101,6 @@ describe("routine grouping", () => {
|
||||
expect(tree.getAllByText("calculate")).toHaveLength(2);
|
||||
const folder = tree.getByText(separate ? "functions" : "routines").closest('[role="treeitem"]')!;
|
||||
expect(within(folder as HTMLElement).getByText("2")).toBeInTheDocument();
|
||||
act(() => useDatabase.setState({ treeFilter: "refresh" }));
|
||||
expect(tree.queryByText("public")).toBeNull();
|
||||
expect(tree.queryByText("routines")).toBeNull();
|
||||
expect(tree.queryByText("functions")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -12,25 +12,17 @@ import { shortcutLabel } from "@/platform/keymap";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
HighlightedText,
|
||||
Icon,
|
||||
IconButton,
|
||||
Menu,
|
||||
SearchField,
|
||||
Tree,
|
||||
showContextMenu,
|
||||
tooltipAttrs,
|
||||
type TreeHandle,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import {
|
||||
databaseKey,
|
||||
passesObjectFilter,
|
||||
passesTreeFilter,
|
||||
shownNames,
|
||||
sourceIcon,
|
||||
splitTarget,
|
||||
targetOf,
|
||||
} from "./model";
|
||||
import { databaseKey, passesObjectFilter, shownNames, sourceIcon, splitTarget, targetOf } from "./model";
|
||||
import {
|
||||
nodeTarget,
|
||||
isOtherFolder,
|
||||
@@ -168,25 +160,10 @@ export function DatabaseView() {
|
||||
[st.sources],
|
||||
);
|
||||
|
||||
// While a quick filter is on, the schemas of expanded sources load their objects, so
|
||||
// tables / routines matching the filter show up without expanding every schema node.
|
||||
useEffect(() => {
|
||||
if (!st.treeFilter.trim()) return;
|
||||
const s = useDatabase.getState();
|
||||
for (const [target, list] of Object.entries(s.schemas)) {
|
||||
if (list.status !== "ok") continue;
|
||||
const { id, database } = splitTarget(target);
|
||||
if (!s.treeExpanded.has(database ? databaseKey(id, database) : id)) continue;
|
||||
for (const schema of list.value) {
|
||||
if (!s.tables[tablesKey(target, schema)]) void loadTables(target, schema);
|
||||
}
|
||||
}
|
||||
}, [st.treeFilter, st.treeExpanded, st.schemas]);
|
||||
|
||||
/** Schemas tab › Object filter, plus the toolbar's quick filter, of the data source of target `id`. */
|
||||
/** Schemas tab › Object filter of the data source of target `id`. */
|
||||
const shown = (id: string) => {
|
||||
const filter = sourceOf(id)?.introspection?.objectFilter;
|
||||
return (o: { name: string }) => passesObjectFilter(o.name, filter) && passesTreeFilter(o.name, st.treeFilter);
|
||||
return (o: { name: string }) => passesObjectFilter(o.name, filter);
|
||||
};
|
||||
const tablesOf = (id: string, schema: string) => {
|
||||
const t = st.tables[tablesKey(id, schema)];
|
||||
@@ -200,7 +177,7 @@ export function DatabaseView() {
|
||||
(st.objects[tablesKey(id, schema)]?.packages ?? []).filter(shown(id));
|
||||
const othersOf = (id: string, schema: string, folder: Folder) =>
|
||||
(st.objects[tablesKey(id, schema)]?.others ?? []).filter((o) => otherFolder(o.kind) === folder).filter(shown(id));
|
||||
/** Members of a schema folder, after object and quick filtering. */
|
||||
/** Members of a schema folder, after object filtering. */
|
||||
const folderSize = (id: string, schema: string, folder: Folder): number => {
|
||||
if (isOtherFolder(folder)) return othersOf(id, schema, folder).length;
|
||||
if (folder === "routines" || folder === "procedures" || folder === "functions")
|
||||
@@ -227,19 +204,9 @@ export function DatabaseView() {
|
||||
return shownNames(v.names, i?.allDatabases, i?.databases, v.current);
|
||||
};
|
||||
|
||||
/** Under a quick filter a schema shows when its name matches, or its loaded objects do. */
|
||||
const schemaVisible = (id: string, schema: string) =>
|
||||
passesTreeFilter(schema, st.treeFilter) ||
|
||||
!!tablesOf(id, schema)?.length ||
|
||||
routinesOf(id, schema).length > 0 ||
|
||||
packagesOf(id, schema).length > 0 ||
|
||||
sequencesOf(id, schema).length > 0;
|
||||
|
||||
const schemasOf = (key: string, id: string) =>
|
||||
status(key, st.schemas[id], (v) =>
|
||||
shownSchemas(id, v)
|
||||
.filter((schema) => schemaVisible(id, schema))
|
||||
.map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node),
|
||||
shownSchemas(id, v).map((schema) => ({ kind: "schema", key: `${id}/${schema}`, id, schema }) as Node),
|
||||
);
|
||||
|
||||
const children = (n: Node): readonly Node[] | undefined => {
|
||||
@@ -563,7 +530,8 @@ export function DatabaseView() {
|
||||
const color = target ? sourceOf(target)?.color : null;
|
||||
return color ? `${styles.tintedRow} ${ROW_TINTS[color]}` : undefined;
|
||||
}}
|
||||
renderNode={(n: Node) => {
|
||||
speedSearchField
|
||||
renderNode={(n: Node, state) => {
|
||||
const i = icon(n);
|
||||
const d = detail(n);
|
||||
const counted = n.kind === "source" || n.kind === "database" || n.kind === "folder" || n.kind === "group";
|
||||
@@ -586,7 +554,7 @@ export function DatabaseView() {
|
||||
{live && <span className={styles.connectedDot} title={tx("Connected")} />}
|
||||
</span>
|
||||
)}
|
||||
<span className={labelClass}>{label(n)}</span>
|
||||
<HighlightedText className={labelClass} text={label(n)} indices={state.matches} />
|
||||
{n.kind === "source" && n.source.global && (
|
||||
<span className={styles.treeDetail} title={tx("Available in all projects")}>
|
||||
{tx("global")}
|
||||
@@ -643,7 +611,6 @@ function DatabaseToolbar() {
|
||||
const node = useDatabase((s) => s.selectedNode);
|
||||
const connected = useDatabase((s) => s.connected);
|
||||
const sources = useDatabase((s) => s.sources);
|
||||
const treeFilter = useDatabase((s) => s.treeFilter);
|
||||
const plus = useRef<HTMLButtonElement>(null);
|
||||
const newOpen = useDatabase((s) => s.newMenuOpen);
|
||||
const setNewOpen = (v: boolean) => useDatabase.setState({ newMenuOpen: v });
|
||||
@@ -689,13 +656,6 @@ function DatabaseToolbar() {
|
||||
>
|
||||
<T>DDL</T>
|
||||
</button>
|
||||
<SearchField
|
||||
className={styles.treeFilter}
|
||||
value={treeFilter}
|
||||
onChange={(treeFilter) => useDatabase.setState({ treeFilter })}
|
||||
placeholder={tx("Filter objects")}
|
||||
aria-label={tx("Filter objects")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,16 @@
|
||||
* a toolbar (re-run, export / copy as CSV, JSON, SQL…), the grid and a floating row count.
|
||||
*/
|
||||
import { copySelectionOnKeyDown } from "@/ui/selectableText";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
@@ -198,8 +207,32 @@ function Pager({ tab }: { tab: ResultTab }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Unsubmitted edits by the rows they were made on, kept while another result tab is shown. */
|
||||
/**
|
||||
* Unsubmitted edits by the rows they were made on, and the results whose edits are being
|
||||
* submitted. They live outside the pane, which remounts when another result tab is selected,
|
||||
* so a submit that ends while its pane is unmounted still clears what the remounted one shows.
|
||||
*/
|
||||
const keptEdits = new WeakMap<DbQueryResult, PendingEdits>();
|
||||
const submittingResults = new Set<DbQueryResult>();
|
||||
const NO_EDITS = emptyEdits();
|
||||
const resultListeners = new Set<() => void>();
|
||||
function notifyResults() {
|
||||
for (const listener of resultListeners) listener();
|
||||
}
|
||||
function subscribeResults(listener: () => void) {
|
||||
resultListeners.add(listener);
|
||||
return () => void resultListeners.delete(listener);
|
||||
}
|
||||
function setKeptEdits(result: DbQueryResult, edits: PendingEdits) {
|
||||
if (hasEdits(edits)) keptEdits.set(result, edits);
|
||||
else keptEdits.delete(result);
|
||||
notifyResults();
|
||||
}
|
||||
function setSubmittingResult(result: DbQueryResult, on: boolean) {
|
||||
if (on) submittingResults.add(result);
|
||||
else submittingResults.delete(result);
|
||||
notifyResults();
|
||||
}
|
||||
|
||||
function Result({ tab }: { tab: ResultTab }) {
|
||||
const [view, setView] = useState<"table" | "chart">("table");
|
||||
@@ -275,20 +308,12 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
driver !== "clickhouse" &&
|
||||
sources.some((s) => s !== null);
|
||||
|
||||
// The pending edits belong to the result they were made on: fresh rows (a
|
||||
// re-run, another page) start over, without an effect. They outlive the pane,
|
||||
// which remounts when another result tab is selected.
|
||||
const [pending, setPending] = useState<{ outcome: DbQueryResult | null; edits: PendingEdits }>(() => ({
|
||||
outcome: r ?? null,
|
||||
edits: (r && keptEdits.get(r)) ?? emptyEdits(),
|
||||
}));
|
||||
const edits = pending.outcome === r ? pending.edits : emptyEdits();
|
||||
const setEdits = (f: (e: PendingEdits) => PendingEdits) =>
|
||||
setPending((previous) => {
|
||||
const next = f(previous.outcome === r ? previous.edits : emptyEdits());
|
||||
if (r) keptEdits.set(r, next);
|
||||
return { outcome: r ?? null, edits: next };
|
||||
});
|
||||
// The pending edits belong to the result they were made on: fresh rows (a re-run,
|
||||
// another page) start over.
|
||||
const edits = useSyncExternalStore(subscribeResults, () => (r && keptEdits.get(r)) ?? NO_EDITS);
|
||||
const setEdits = (f: (e: PendingEdits) => PendingEdits) => {
|
||||
if (r) setKeptEdits(r, f(keptEdits.get(r) ?? NO_EDITS));
|
||||
};
|
||||
const loaded = r?.rows.length ?? 0;
|
||||
const rowCount = loaded + edits.inserts.length;
|
||||
const value = useCallback(
|
||||
@@ -341,14 +366,12 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
});
|
||||
|
||||
const dirty = hasEdits(edits);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const submitGuard = useRef(false);
|
||||
const submitting = useSyncExternalStore(subscribeResults, () => !!r && submittingResults.has(r));
|
||||
const busy = submitting || !!tab.busy;
|
||||
|
||||
const submit = async () => {
|
||||
if (!r || !target || !pk || !editable || busy || submitGuard.current) return;
|
||||
submitGuard.current = true;
|
||||
setSubmitting(true);
|
||||
if (!r || !target || !pk || !editable || busy || submittingResults.has(r)) return;
|
||||
setSubmittingResult(r, true);
|
||||
const list = buildRowEdits(resultNames, r.rows, pk, edits);
|
||||
try {
|
||||
// The Output log shows what the submit is about to change.
|
||||
@@ -358,7 +381,8 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
);
|
||||
log("result", `${target.table}: ${n} row(s) changed`);
|
||||
notifications().notify({ level: "info", title: `${target.table}: ${n} row(s) changed`, key: "db-submit" });
|
||||
setEdits(() => emptyEdits());
|
||||
// Also when this pane was unmounted meanwhile: the applied edits must not come back.
|
||||
setKeptEdits(r, NO_EDITS);
|
||||
await rerunResult(tab.id);
|
||||
} catch (e) {
|
||||
log("error", e instanceof Error ? e.message : String(e));
|
||||
@@ -369,8 +393,7 @@ function Result({ tab }: { tab: ResultTab }) {
|
||||
key: "db-submit",
|
||||
});
|
||||
} finally {
|
||||
submitGuard.current = false;
|
||||
setSubmitting(false);
|
||||
setSubmittingResult(r, false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача