Порівняти коміти

...
Автор SHA1 Повідомлення Дата
lleviathe 3c3d02d7be feat(mcp): list tools on a connection without a project of its own (#7103)
An MCP client started in a folder no project serves got -32001 for tools/list and registered no tools, so it couldn't reach the projects inside even with projectPath. Such a connection (and one naming no folder with zero or several windows open) now lists the tools a trusted project gets; each call still resolves its project, and a tool that writes or runs refuses an untrusted project with the Restricted Mode error before the project loads. initialize tells the agent to pass projectPath in every call.

The stdio bridge picks its IDE process with a new openidea/servesFolder method (falling back to the tools/list probe for older IDEs), keeps the process initialize picked, picks again when processes stop or start, and sends cancellations to every process. Plugin tools list projectPath in their schema and get the call without it when their own schema refuses it.

Closes #7039

Co-authored-by: lleviathe <[email protected]>

Co-authored-by: lleviathe <[email protected]>
2026-12-01 03:53:20 +08:00
NK StudioтаNK-Studio 2f66eb0503 fix(editor): recognize C# using fixes in auto import and imports on paste (#7100)
Add unambiguous imports on the fly and Insert imports on paste pick the import quick fix by its title, but Roslyn (csharp-ls) titles it with the directive itself (using UnityEngine.SceneManagement;), so C# never got a missing using added. Both now also accept a whole using [static] directive title; fully-qualify and Remove unnecessary usings fixes stay ignored.

Co-authored-by: NK-Studio <[email protected]>

Co-authored-by: NK-Studio <[email protected]>
2026-12-01 03:48:45 +08:00
l0ng-ai 63db10a688 fix(vcs): reuse one diff tab with the preview tab turned off (#7108)
Diffs from the version control views reused one tab only through the preview tab, so turning off Opening Policy > Enable preview tab opened every diff in a new tab. Editor kinds can now have their previews granted regardless of that setting (reusesPreviewTab); the diff, combined diff and merge commit diff kinds do, so Commit / Local Changes, the Git Log, shelves and stashes keep one diff tab while project files still open as regular tabs. Pinned and kept diff tabs stay, and activeInput({ previewOnly }) uses the same check so the Git Log's selection-following preview works too.

Fixes #7096
2026-12-01 03:47:32 +08:00
l0ng-ai 1dd3d64781 feat(freemarker): HTML, script and style languages and completion in FreeMarker templates (#7104)
FreeMarker files were highlighted by a stream mode, so markup had no HTML completion and script/style content was plain text. A Lezer grammar now parses the template layer (directives, user-defined directive calls, interpolations, comments, noparse), the first directive fixing the angle or square syntax, and the text between them is mounted as one HTML document: markup nests across directives and <script>/<style> get JavaScript and CSS.

Block directives fold, indent, match their end tags and get their end tag when > is typed; completion offers directives after <#, the open blocks' end tags after </, and built-ins after ?. Comment Block uses <#-- --> ([#-- --] in the square syntax).

Fixes #6906
2026-12-01 03:44:08 +08:00
l0ng-ai 8ac194cf50 fix(plugins): let capabilities.reasons explain capabilities a contribution brings (#7101)
A plugin with [[contributes.javaAgents]] gets java.agent without listing it under [capabilities], so the manifest check rejected a reason for it and the install dialog and Permissions showed only the IDE's description. Manifest::derived_capabilities names the capabilities contributions bring (java.agent from javaAgents, project.read from documentIndexers) and reasons may use those keys too; docs updated.

Fixes #7088
2026-12-01 03:26:09 +08:00
Ivan 3b488a7824 fix(macos): let background project tabs give their web content memory back (#7060)
A background project tab of a native tab group detaches its WKWebView from the window 30 s after it leaves the front, so WebKit frees the hidden page's graphics and caches. The view comes back when the tab is selected through our tab bar, when its window becomes key (Window menu, Close Project) or when AppKit makes it visible by itself; an inactive app's full-screen group waits for activation (#6937).

Every macOS with_webview caller goes through macos::with_web_view, which hands the retained view to a detached tab instead of panicking in wry; titlebar::set_height uses the NSWindow directly. clippy.toml disallows the raw with_webview calls. Covered by BackgroundTabs unit tests and an AppKit test of the synchronous re-attach on the key notification (it no longer asks a never-loaded web view for its process ids, which WebKit asserts on).

Fixes #6938

Co-authored-by: Pecnikas <[email protected]>

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 03:20:08 +08:00
l0ng-ai b5e89aace0 feat(run): show each invocation of a parameterized test in the Run window (#7099)
The JUnit runner and the Gradle test init script report an invocation of a parameterized, repeated or dynamic test with its display name, and the JVM parser puts it under its method node with its own status, output and stack trace; the method shows the aggregate. Rerunning a failed invocation reruns its method.

Fixes #7046
2026-12-01 03:06:11 +08:00
Akbar Husain 81c95b2ab7 perf(lint): clear remaining non-e2e React perf violations (#7093)
Clears the remaining non-e2e React perf lint violations and turns the three rules on outside e2e/ so they can't come back: data-derived keys for diagram edges and deadlock cycles (index keys stay, with a documented suppression, where position is the identity), context values in tests hoisted to constants or memoized, and array/JSX default props replaced with module-level constants.

Co-authored-by: akbar1214 <[email protected]>
2026-12-01 02:59:24 +08:00
LU XIANGRUIтаwildcatDownstairs f7b5cc388c feat(run): debug Python on a WSL run target (#6777)
A Python run configuration on a WSL target can now be debugged: the program starts under the container debugger's bootstrap in the distribution, which waits for the IDE on the distribution's loopback (WSL forwards it), finding the IDE's debugpy and bootstrap through wslpath when the distro has none. Stop ends the debugged process in the distribution, with pkill or, where it is missing, a /proc scan. Other kinds say they can't be debugged in WSL.

Also carries the WSL run target review fixes that neither #6764 nor #6770 included: Maven options naming this machine's files are dropped from remote runs, a failed wsl.exe listing is reported in Run Targets and retried on focus, an unsafe distribution name is cleared and asked for again, a printed path whose .. climbs above its root is refused, and prepare_wsl is built only on Windows.

Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04): a breakpoint is hit and Stop leaves no debug process.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:54:14 +08:00
LU XIANGRUIтаwildcatDownstairs 277d0e9d1e feat(python): a Python in WSL as the project interpreter (#6770)
Python > Add Interpreter gets a WSL tab: pick a distribution and a Python in it (a bare python3 is looked up on the distribution's PATH; Windows paths are refused). The project interpreter then runs in the distribution: packages are listed from there, the project's virtualenv inside the distro is read, the language server resolves imports from the distro's site-packages through \\wsl.localhost, and runs go through the WSL run target. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04).

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:38:34 +08:00
LU XIANGRUIтаwildcatDownstairs d6adb7aa40 feat(run): run configurations in a WSL distribution from a Windows project (#6764)
Settings > Run Targets gets a WSL target that lists the installed distributions. A run configuration on it starts locally as wsl.exe -d <distro> --cd <dir> --exec ..., with the project's Windows paths mapped to /mnt/<drive>/..., arguments passed unchanged, environment variables forwarded through WSLENV, and Stop ending the Linux process. Verified by the contributor on Windows 11 with WSL 2 (Ubuntu 24.04), including quoted arguments and Emulate terminal.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 02:21:28 +08:00
l0ng-ai 6e5e482410 test(memory): make the debounce test tolerate a loaded machine (#7098)
memory::tests::a_burst_of_calls_runs_once_after_the_delay failed on a loaded macOS runner: with a 100 ms delay and 20 ms gaps, oversleeping let the debounced call fire before the burst ended. The test now uses a 500 ms delay, checks "nothing ran yet" only when less than the delay has passed since the last call, waits for the run, and asserts exactly one run only when no gap in the burst reached the delay.
2026-12-01 02:20:22 +08:00
solhovoy cc02c2fe40 feat(vcs): show shelved files under their shelf with grouping and diff preview (#7090)
The Shelf tab now lists each shelf's files beneath it in one tree instead of a separate files pane. View Options groups the files by Directory or Module and toggles Show Diff Preview (a side-by-side diff of the selected file, hidden in non-modal commit mode); Expand All / Collapse All work on the groups. File paths show inline, Delete and Cmd+Backspace delete the selected shelf or file, and the Shelve button, already in Local Changes, is gone from this toolbar.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 02:16:33 +08:00
Игорь Тихомиров 74a3f6470a feat(php): add PHPantom as a built-in language server (#7052)
PHPantom (MIT) joins the selectable PHP language servers, with a tools-registry entry for installing it.

textDocument/implementation now sends a client-created workDoneToken for any server; its progress shows as a cancellable task and is retired when the request ends (response, cancel or timeout). A server's TOML can list server-created progress-token prefixes to ignore (ignored-progress-token-prefixes); php.toml uses it for PHPantom 1.1.0, which can leave find_references/goto_implementation progress open after a cancel (PHPantom-dev/phpantom_lsp#603).

Co-authored-by: fenndooscar <[email protected]>
2026-12-01 02:04:13 +08:00
Ivan 4c8c078666 perf(lsp): bound the cache of virtual document text (#7082)
The window-wide cache of lspVirtualDocument results (decompiled classes, library sources, jdt:// documents) kept one entry per document ever shown, hover previews and go-to-definition included, for the window's lifetime. It now keeps the 32 most recently used; an evicted document is fetched again on next use, and a failed fetch is dropped only while it is still the cached one.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 02:00:34 +08:00
Ivan e672b14d52 fix(plugins,mcp): stop idle IPC loops in Restricted Mode windows (#7091)
Idle Restricted Mode windows called the backend over 100 times a second. PluginHost::restrict_project announced CommandsChanged even when the project had no plugins to restrict; every window answered with plugin_list, which restricted the untrusted root again. Separately, the MCP editor and problems reporters retried every 300 ms on commands Restricted Mode refuses.

restrict_project now announces only when it restricted something, and the reporters skip untrusted projects and report once trust is granted. Measured over 4 idle windows: invoke calls 115/s -> 0.7/s, CPU per idle minute 12.3 s -> 1.1 s.

Refs #6938

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 01:59:18 +08:00
audichuang c0300f8959 fix(vcs): find a worktree added below the project when its HEAD lands after the watcher's rescan (#7086)
git worktree add writes the worktree's .git file before its gitdir's commondir and HEAD, so a watcher rescan in between found no repository there, and the later .git/worktrees/<id>/HEAD write never triggered another rescan. That HEAD now rescans too while its worktree is unknown and is one a scan would find (Repos::searched, sharing discover's depth, hidden, vendor and skip rules, plus Directory Mappings exclusions).

Co-authored-by: audichuang <[email protected]>
2026-12-01 01:57:06 +08:00
l0ng-ai 11cf9864a1 fix(vcs): guide GitHub HTTPS failures to project account settings (#7061)
A Git Update, Fetch, Push or branch update that fails on an https://github.com remote with "repository not found" or "Authentication failed" now checks the GitHub CLI accounts. When several are signed in, the original Git error is kept and a hint says the effective account may lack access, with a GitHub Settings action that opens the project-scoped account selector. Nothing switches gh's global account, rewrites remotes or retries the operation; other hosts, SSH remotes and network errors are left as they were.
2026-12-01 01:52:43 +08:00
141 змінених файлів з 5253 додано та 535 видалено

No files matched your search

+1
Переглянути файл
@@ -15,6 +15,7 @@
"src/editor/core/cm/jsp/parser*.ts",
"src/editor/core/cm/astro/parser*.ts",
"src/editor/core/cm/django/parser*.ts",
"src/editor/core/cm/freemarker/parser*.ts",
"plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
+4 -1
Переглянути файл
@@ -152,7 +152,10 @@
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"excludeFiles": ["e2e/**"],
"rules": {
"no-await-in-loop": "error"
"no-await-in-loop": "error",
"react/no-array-index-key": "error",
"react/jsx-no-constructed-context-values": "error",
"react/no-object-type-as-default-prop": "error"
}
}
]
+21 -4
Переглянути файл
@@ -63,13 +63,30 @@ mod tests {
#[test]
fn a_burst_of_calls_runs_once_after_the_delay() {
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
let delay = Duration::from_millis(500);
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
for _ in 0..5 {
debounce(&DUE, Duration::from_millis(100), count);
debounce(&DUE, delay, count);
let now = Instant::now();
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
last = Some(now);
std::thread::sleep(Duration::from_millis(20));
}
assert_eq!(RUNS.load(SeqCst), 0);
std::thread::sleep(Duration::from_millis(400));
assert_eq!(RUNS.load(SeqCst), 1);
if last.unwrap().elapsed() < delay {
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
}
let deadline = Instant::now() + Duration::from_secs(10);
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
// A second run would come within another delay.
std::thread::sleep(delay);
if widest_gap < delay {
assert_eq!(RUNS.load(SeqCst), 1);
} else {
assert!(RUNS.load(SeqCst) >= 1);
}
release_free_pages_soon();
}
}
+7 -1
Переглянути файл
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
Docker,
/// A new container of a Compose service (`docker compose run --rm`).
Compose,
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
/// through `/mnt/<drive>`.
Wsl,
}
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
@@ -215,7 +218,8 @@ pub struct RunTarget {
pub name: String,
/// [`SshConfiguration::id`] (SSH).
pub ssh_config: String,
/// Remote folder the project is synchronised to and run from (SSH).
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
/// path, empty = its `/mnt/<drive>` path (WSL).
pub project_root: String,
/// Upload changed project files before each run (SSH).
pub sync_before_run: bool,
@@ -241,6 +245,8 @@ pub struct RunTarget {
pub run_options: String,
/// Run as the image's user instead of the project folder's owner (Linux).
pub image_user: bool,
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
pub distro: String,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
+92
Переглянути файл
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
}
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
/// other network shares and relative paths.
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
if let Some(w) = parse(path) {
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
}
let s = path.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").unwrap_or(&s);
let mut chars = s.chars();
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
let rest = chars.as_str().strip_prefix(':')?;
if !(rest.is_empty() || rest.starts_with('/')) {
return None;
}
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
}
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
pub fn is_valid_distro(name: &str) -> bool {
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
Vec::new()
}
/// Where this machine reads `distro`'s file system.
pub fn share_root(distro: &str) -> std::path::PathBuf {
format!(r"\\wsl.localhost\{distro}").into()
}
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
pub fn path_parts(linux: &str) -> Vec<&str> {
let mut parts: Vec<&str> = Vec::new();
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
if c == ".." {
parts.pop();
} else {
parts.push(c);
}
}
parts
}
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
/// within `linux`, never above the drive or the share.
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
let parts = path_parts(linux);
let base = match parts.as_slice() {
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
return parts[2..].iter().fold(base, |p, c| p.join(c));
}
_ => share_root(distro),
};
parts.iter().fold(base, |p, c| p.join(c))
}
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
use crate::cli_process::{CliTool, Decoding};
if !is_valid_distro(distro) {
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
}
let mut cmd = std::process::Command::new(EXE);
cmd.args(["-d", distro, "--exec"]).args(args);
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
if out.success {
return Ok(stdout);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -103,6 +172,21 @@ mod tests {
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
}
#[test]
fn windows_paths_map_onto_the_distro() {
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
assert_eq!(l(r"\\server\share\a"), None);
assert_eq!(l(r"C:relative"), None);
assert_eq!(l("app"), None);
assert_eq!(l("/home/me"), None);
}
#[test]
fn distro_root_and_foreign_paths() {
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
@@ -127,6 +211,14 @@ mod tests {
assert!(parse_distro_list(b"").is_empty());
}
#[test]
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
use std::path::PathBuf;
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
}
#[test]
fn distro_names_cannot_smuggle_options_or_paths() {
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
+27 -2
Переглянути файл
@@ -391,9 +391,12 @@ impl Manifest {
if !self.capabilities.reasons.is_empty() {
self.needs_api("`capabilities.reasons`", 19)?;
}
let derived = self.derived_capabilities();
for (key, text) in &self.capabilities.reasons {
if !self.capabilities.all().any(|c| c.to_string() == *key) {
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
return Err(format!(
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
));
}
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
return Err(format!(
@@ -522,6 +525,17 @@ impl Manifest {
Ok(())
}
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
pub fn derived_capabilities(&self) -> Vec<Capability> {
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
.into_iter()
.filter(|(point, _)| self.contributes.contains_key(*point))
.map(|(_, cap)| cap)
.collect()
}
/// The declarations of one extension point: `[[contributes.x]]` gives
/// several, `[contributes.x]` one.
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
assert!(err(&src(&long)).contains("1 to 500 characters"));
}
#[test]
fn capability_reasons_explain_capabilities_that_contributions_bring() {
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
}
#[test]
fn the_clipboard_read_capability_needs_api_1_11() {
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
+60 -12
Переглянути файл
@@ -18,7 +18,7 @@ pub mod service;
mod symbols;
mod tool;
pub(crate) use tool::trusted_attachments;
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
mod util;
use crate::Host;
@@ -28,6 +28,7 @@ pub use reports::{
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
};
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
use serde_json::json;
pub use service::{McpServerStatus, McpService};
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
tools
}
// Checked both when listing and calling, so a later trust change takes effect immediately.
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
// trust change takes effect immediately.
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
trusted || tool.read_only
}
@@ -63,11 +65,36 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
if let Some(plugins) = host.plugin_host() {
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
}
all.into_iter().filter(|t| allowed(t, trusted)).collect()
}
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
if let Some(schema) = tool.input_schema.as_object_mut()
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
{
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
}
tool
}
/// The tool a call runs: a plugin's or a built-in one.
enum Found {
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
Builtin(tool::Tool),
}
impl Found {
fn writes(&self) -> bool {
match self {
Self::Plugin { metadata, .. } => !metadata.read_only,
Self::Builtin(tool) => !tool.metadata.read_only,
}
}
}
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
match host.project(window).ok().filter(|p| !p.light) {
@@ -110,6 +137,16 @@ impl Registry {
}
}
/// The tool `name` for `root`: a plugin's first. Loads nothing.
fn find(&self, root: &Path, name: &str) -> Option<Found> {
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
{
return Some(Found::Plugin { plugins, plugin, tool, metadata });
}
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
}
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
/// a background project that is not loaded is judged as its open will judge it.
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
@@ -150,6 +187,9 @@ impl ToolRegistry for Registry {
let trusted = self.lists_as_trusted(root)?;
Ok(tools_for(&self.0, root, trusted))
}
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
tools_for(&self.0, Path::new(""), true)
}
fn call(
&self,
root: &Path,
@@ -167,19 +207,27 @@ impl ToolRegistry for Registry {
cancel: CancellationToken,
client: &str,
) -> Result<String, ToolCallError> {
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
// Before the project loads, so the refusal neither loads a background project nor
// unloads an idle one at the limit to make room.
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
}
// The guard lives until the call ends, whichever way it leaves: neither the idle
// sweep nor the limit unloads a background project a call runs in.
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
if let Some(plugins) = self.0.plugin_host()
&& let Some((plugin, tool, metadata)) =
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
{
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
// Found again: a plugin can change while a background project opens, and the call
// runs the tool as it is now.
let found = self.find(root, name).ok_or_else(unknown)?;
if found.writes() {
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
}
let tool = tools()
.into_iter()
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
let tool = match found {
Found::Plugin { plugins, plugin, tool, metadata } => {
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
}
Found::Builtin(tool) => tool,
};
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
let call = tool::Call {
host: self.0.clone(),
+9 -3
Переглянути файл
@@ -5,6 +5,14 @@ use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The argument that names the project a call is for; the server routes the call by it.
pub(crate) const PROJECT_PATH: &str = "projectPath";
/// The schema of [`PROJECT_PATH`], which every tool takes.
pub(crate) fn project_path() -> Value {
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
}
pub struct Call {
pub client: String,
pub tool: String,
@@ -242,9 +250,7 @@ impl Tool {
read_only: true,
destructive: false,
output_schema: None,
input_schema: json!({ "type": "object", "properties": {
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
}, "required": [] }),
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
},
handler: Arc::new(move |call| Box::pin(handler(call))),
}
+87 -11
Переглянути файл
@@ -448,13 +448,18 @@ async fn start_inner(
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI: the command is resolved in the container, and
// this machine's toolchains and `PYTHONPATH` don't apply.
let mut config = config;
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let (config, note) = container::prepare(host, &project.root, target, config).await?;
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
// The settings of the workspace member it belongs to derived its values.
let mut member = config.clone();
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
let (config, note) = if target.kind == RunTargetKind::Wsl {
(container::prepare_wsl(host, &project.root, target, config).await?, None)
} else {
container::prepare(host, &project.root, target, config).await?
};
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
@@ -462,7 +467,7 @@ async fn start_inner(
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
// A folder on this machine: not in the container.
// A folder on this machine: not in the container or distribution.
ruby_reporter: None,
plots: None,
capture_junit_reports: false,
@@ -864,6 +869,44 @@ pub use commands::*;
mod ownership_tests {
use super::*;
#[cfg(unix)]
#[test]
fn a_remote_run_gets_none_of_this_machines_derived_values() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let venv = root.join(".venv");
std::fs::create_dir_all(venv.join("bin")).unwrap();
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
std::fs::write(venv.join("bin/python"), "").unwrap();
let mut settings = ide_core::settings::Settings::default();
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
let mut config = RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: "python".into(),
args: vec!["main.py".into()],
cwd: None,
env: [("FOO".to_owned(), "bar".to_owned())].into(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
config.extras.target = Some("wsl".into());
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
let derived = Derived { root, fallback: None, settings: &settings };
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
assert_eq!(out.command, "python", "the interpreter is the target's");
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
}
#[cfg(unix)]
#[test]
fn source_roots_go_on_the_container_pythonpath() {
@@ -1062,6 +1105,9 @@ pub async fn run_container_path(
if !path.starts_with('/') {
return Ok(None);
}
if run_target.kind == RunTargetKind::Wsl {
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
}
let library = snapshots
.and_then(|dir| ide_sdk::container_python::current(&dir))
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
@@ -1074,9 +1120,39 @@ pub async fn run_container_path(
.await
}
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
/// they are mounted with the project, and `container::prepare` maps their paths. The
/// container's separator is `:`, whatever this machine's is.
/// `config` for a container or WSL distribution: without what settings derived from this
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
/// still apply there and are kept.
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
let mut out = config.clone();
out.command = plain.command;
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
if ide_run::is_python_kind(&out.kind) {
container_python_path(&mut out.env, python_roots, root);
}
out
}
/// The settings a configuration's derived values come from (see [`settings_for`]).
#[derive(Clone, Copy)]
struct Derived<'a> {
root: &'a Path,
fallback: Option<&'a Path>,
settings: &'a ide_core::settings::Settings,
}
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
/// as `GOPROXY`'s is not: its first part is `https`).
fn has_local_path(value: &str) -> bool {
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
}
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
/// run gets them: they are mounted with the project, and `container::prepare` /
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
let mut paths: Vec<String> =
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
+33 -2
Переглянути файл
@@ -1,5 +1,5 @@
//! Docker and Compose run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`).
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
use crate::Host;
use ide_core::remote_settings::{RunTarget, RunTargetKind};
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
.await
}
/// `config` rewritten to run in `target`'s WSL distribution.
pub(super) async fn prepare_wsl(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<RunConfig> {
if !cfg!(windows) {
return Err(IdeError::invalid(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let root = root.to_path_buf();
host.blocking(move || {
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
let file_env = env_files(&root, &config)?;
let inherited = std::env::var("WSLENV").ok();
ide_remote::wsl::wsl_config(
&config,
&target,
&root,
&linux_root,
ide_core::wsl::EXE,
&file_env,
inherited.as_deref(),
)
})
.await
}
/// The project can only be bind-mounted from a daemon on this machine.
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
if !ide_docker::endpoint_is_local(endpoint)? {
+1 -1
Переглянути файл
@@ -12,7 +12,7 @@ use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
pub mod container_python;
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
/// Executables found for "run this file", and where single files are compiled to.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
+126 -12
Переглянути файл
@@ -4,6 +4,9 @@
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
//! the stopped container with `docker cp`. Nothing is installed in the container.
//!
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
//! in place through `\\wsl.localhost\<distro>`.
use crate::Host;
use crate::project::Project;
@@ -23,6 +26,8 @@ use std::time::Duration;
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
const QUICK: Duration = Duration::from_secs(30);
/// Starting the distribution may come first.
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
/// The project interpreter when it is a run target's.
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
@@ -34,8 +39,10 @@ pub struct ContainerPython {
pub name: String,
/// The Python version of the snapshot in use; `None`: no snapshot yet.
pub version: Option<String>,
/// The image the snapshot was copied from.
/// The image the snapshot was copied from; `None` for WSL.
pub image: Option<String>,
/// The interpreter's path in the container or distribution.
pub executable: Option<String>,
/// The copied library folders on this machine.
pub folders: Vec<IpcPath>,
/// Packages of the snapshot (read-only).
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
}
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
#[command(trust = trusted)]
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
host.require_trust(window)?;
let project = host.project(window)?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
let target = settings.languages.python.run_target()?;
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
let dir = Dirs::of(host).target(root, target);
let dir = dirs.target(root, target);
let mut out = ContainerPython {
target: target.to_owned(),
name,
version: None,
image: None,
executable: None,
folders: Vec::new(),
packages: Vec::new(),
updating: updating(&dir),
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
out.packages = snapshots::packages(&dir, &snapshot);
out.version = Some(snapshot.probe.version);
out.image = Some(snapshot.image);
out.executable = Some(snapshot.probe.executable);
out.image = snapshot.distro.is_none().then_some(snapshot.image);
}
Some(out)
}
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
host.require_trust(window)?;
let project = host.project(window)?;
update(Dirs::of(host), &project, true).await?;
Ok(describe(host, &project.root, &project.settings.effective()))
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
}
/// Takes a snapshot when the project interpreter is a run target's and the current image
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
return;
}
let (dirs, project) = (Dirs::of(host), project.clone());
let settings = project.settings.effective();
let wsl = settings
.languages
.python
.run_target()
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
let title =
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
host.runtime.spawn(async move {
if let Err(e) = update(dirs, &project, false).await
&& e.kind != ide_core::error::ErrorKind::Cancelled
{
project.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: "Cannot copy the container's Python libraries".into(),
title: title.into(),
body: Some(e.message),
});
}
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind == RunTargetKind::Ssh {
return Err(IdeError::invalid(format!(
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
target.name
)));
}
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
return Ok(());
}
let _done = Updating(dir.clone());
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
let endpoint = match target.kind {
RunTargetKind::Wsl => None,
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
};
let task = TaskId::next();
let title = format!("Python libraries of {}", target.name);
let (root, sink) = (project.root.clone(), project.sink.clone());
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
};
let report = progress.clone();
let result = tokio::task::spawn_blocking(move || {
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
let report = |message: &str| report(message, false);
match endpoint {
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
}
})
.await
.map_err(|e| IdeError::internal(e.to_string()))
@@ -288,6 +316,7 @@ fn take(
image: image.clone(),
probe,
folders,
distro: None,
};
snapshots::write(&partial, &snapshot)?;
if dir.exists() {
@@ -298,6 +327,72 @@ fn take(
Ok(true)
}
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
fn take_wsl(
root: &Path,
target: &RunTarget,
target_dir: &Path,
cache: &Path,
progress: &dyn Fn(&str),
) -> IdeResult<bool> {
if !cfg!(windows) {
return Err(IdeError::unavailable(format!(
"Run target '{}' is a WSL distribution: WSL needs Windows",
target.name
)));
}
let linux_root = ide_remote::wsl::project_root(target, root)?;
let distro = target.distro.trim();
progress("Starting the WSL Python");
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
let probe = snapshots::parse_probe(&out)?;
let id = format!("wsl-{}-{}", probe.executable, probe.version);
let snapshot = Snapshot {
image: id.clone(),
folders: wsl_folders(&probe, &linux_root),
neutral_python: snapshots::neutral_python(cache, &probe.version),
distro: Some(distro.to_owned()),
probe,
};
// What the language server is given: the probe's other details (its raw `sys.path` order,
// say) are kept in the snapshot but don't restart it.
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
let dir = target_dir.join(snapshots::dir_name(&id));
std::fs::create_dir_all(&dir)?;
snapshots::write(&dir, &snapshot)?;
snapshots::make_current(target_dir, &id)?;
Ok(changed)
}
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
let root = linux_root.trim_end_matches('/');
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
}
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
#[command(trust = trusted)]
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
host.require_trust(window)?;
if !cfg!(windows) {
return Ok(Vec::new());
}
let root = host.project(window)?.root.clone();
host.blocking(move || {
let distro = distro.trim();
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
})
.await
}
/// Distinguishes probe containers.
fn unique() -> String {
use std::sync::atomic::{AtomicU32, Ordering};
@@ -306,4 +401,23 @@ fn unique() -> String {
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
#[cfg(test)]
mod wsl_tests {
#[test]
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
let probe = super::snapshots::Probe {
version: "3.12.3".into(),
executable: "/mnt/c/p/.venv/bin/python".into(),
stdlib: vec![Some("/usr/lib/python3.12".into())],
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
.map(String::from)
.to_vec(),
};
assert_eq!(
super::wsl_folders(&probe, "/mnt/c/p"),
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
);
}
}
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
+35 -6
Переглянути файл
@@ -118,21 +118,50 @@ impl PluginHost {
.find(|(p, n, _)| p == plugin && n == tool)
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
let validator =
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
let arguments = arguments_for(&declared.input_schema, args)?;
let tool = tool.to_owned();
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
rt.mcp_call(&tool, &arguments, inv)
})
}
}
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
/// server routes a call by; a schema that refuses it gets the call without it.
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
if !validator.is_valid(&args)
&& let Some(args) = args.as_object_mut()
{
args.remove(crate::mcp::PROJECT_PATH);
}
if !validator.is_valid(&args) {
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
}
Ok(args.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
let strict = serde_json::json!({
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
});
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
// Declared through a local `$ref` and required: the plugin keeps it.
let declared = serde_json::json!({
"$ref": "#/$defs/call",
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
});
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
assert_eq!(kept["projectPath"], "/work/inventory");
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
}
#[test]
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
let tmp = tempfile::tempdir().unwrap();
+5
Переглянути файл
@@ -760,6 +760,11 @@ impl PluginHost {
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
.map(|(id, _)| id.clone())
.collect();
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
// plugins again, and listing restricts an untrusted project again, which looped while idle.
if ids.is_empty() {
return;
}
for id in ids {
self.unload(&id);
}
+40 -10
Переглянути файл
@@ -565,6 +565,21 @@ impl Host {
.collect();
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
});
// `git worktree add` writes the worktree's gitfile before its gitdir's
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
// rescans too while its worktree is unknown and one a rescan would find.
git_dirs |= batch.vcs.iter().any(|p| {
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
return false;
}
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
})
});
// A repository folder moved or restored into the project: no `.git` event is
// written inside it before the watcher sees the new directory, its creation is
// the signal. A `git clone` / `git init` inside the project already arrives
@@ -1048,17 +1063,16 @@ impl Host {
}
}
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
impl Project {
pub fn is_trusted(&self) -> bool {
self.trusted.load(Ordering::Acquire)
}
pub fn require_trust(&self) -> IdeResult<()> {
if self.is_trusted() {
Ok(())
} else {
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
}
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
}
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
@@ -1186,18 +1200,34 @@ fn detect_repositories(
build_cache: &Path,
trusted: bool,
) -> IdeResult<Repos> {
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &repository_scan_skips(settings))
}
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
let ignored = settings.ignored_names();
let skip = |p: &Path| {
move |p: &Path| {
p.file_name().is_some_and(|n| {
let name = n.to_string_lossy();
ignored.is_ignored_name(&name)
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
&& p.parent().is_some_and(ide_workspace::unity::is_project))
})
};
let mut roots = vec![root.to_path_buf()];
roots.extend(content_roots(settings, root, build_cache, trusted));
Repos::discover_roots(&roots, &skip)
}
}
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
settings.vcs.git.enabled
&& !settings
.vcs
.mappings
.excluded
.iter()
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
impl Project {
+1 -1
Переглянути файл
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
eprintln!("run target interpreter: {after:?}");
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
assert_eq!(info.name, "Compose web");
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
+79 -6
Переглянути файл
@@ -252,6 +252,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
assert!(!h.host.project("main").unwrap().is_trusted());
let registry = Registry::new(h.host.clone());
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
// A tool that writes, called all the same, says why it can't run.
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
assert!(!h.root.join("x.txt").exists());
assert!(!h.host.global_settings.effective().mcp_server.enabled);
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
assert_eq!(
@@ -1546,22 +1550,91 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
}
#[tokio::test(flavor = "multi_thread")]
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
let h = Harness::new();
let inventory = h.root.parent().unwrap().join("inventory");
std::fs::create_dir_all(&inventory).unwrap();
let (_server, discovery) = h.server();
let list = rpc(1, "tools/list", json!({}));
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
for reply in bridged(&discovery, &inventory, &[list, read]).await {
assert_eq!(reply["error"]["code"], -32001, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
}
let replies = bridged(&discovery, &inventory, &[list, read]).await;
let tools = replies[0]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
let message = replies[1]["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't served in the background"), "{message}");
assert!(h.background().is_empty());
assert_eq!(h.host.projects().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
let h = Harness::new();
// A folder that only holds repositories: one trusted, one not.
let work = h.root.parent().unwrap().join("work");
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
for project in [&inventory, &ledger] {
std::fs::create_dir_all(project.join("src")).unwrap();
}
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
h.set("enabled", json!(true));
h.set("backgroundProjects", json!("listed"));
h.set("backgroundProjectPaths", json!([inventory, ledger]));
h.host.set_project_trust(&inventory, true, false).await.unwrap();
let (_server, discovery) = h.server();
let requests =
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &work, &requests).await;
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
let tools = replies[1]["result"]["tools"].as_array().unwrap();
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
// A tool that writes is refused for the untrusted project before it loads; a call that
// names no project is refused too.
let create = rpc(
4,
"tools/call",
json!({"name":"create_new_file","arguments":{
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
);
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
assert!(refused.contains("Restricted Mode"), "{refused}");
assert!(!ledger.join("notes.txt").exists());
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
assert!(h.background().is_empty(), "refusals open nothing");
// Inside a served project, servesFolder names it, and loads nothing either.
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
assert!(h.background().is_empty());
let read = rpc(
6,
"tools/call",
json!({"name":"read_file","arguments":{
"projectPath":inventory,"file_path":"src/stock.txt"}}),
);
let replies = bridged(&discovery, &work, &[read]).await;
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
assert_eq!(h.background(), std::slice::from_ref(&inventory));
// A remote window's root is that host's to serve.
let remote = work.join("remote");
std::fs::create_dir_all(&remote).unwrap();
h.host.mcp_reports.set_remote("remote", remote.clone());
let replies = bridged(&discovery, &remote, &serves).await;
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
h.host.close_project_detached("remote");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
let h = Harness::new();
+30
Переглянути файл
@@ -189,6 +189,36 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
}
#[tokio::test(flavor = "multi_thread")]
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
let registry = Registry::new(f.host.clone());
// A connection without a project of its own lists the tool with `projectPath`, which its
// calls have to pass, and the plugin's strict schema still takes the call.
let listed = registry.tools_without_project();
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
assert!(result.contains("hello"), "{result}");
// A tool that writes refuses the untrusted folder, and nothing loads.
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
+17
Переглянути файл
@@ -8170,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
assert_eq!(dirs.len(), 1);
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
}
#[test]
fn restricting_a_project_without_its_plugins_announces_nothing() {
let tmp = tempfile::tempdir().unwrap();
let events: Events = Arc::default();
let sink = {
let events = events.clone();
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
};
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
host.load_all();
events.lock().clear();
// A restricted window lists the plugins, which restricts its project again each time.
host.restrict_project(tmp.path());
host.restrict_project(tmp.path());
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
}
+50 -1
Переглянути файл
@@ -28,6 +28,10 @@ struct Fixture {
impl Fixture {
async fn new() -> Self {
Self::with_sink(Arc::new(ide_core::NullSink)).await
}
async fn with_sink(sink: ide_core::SharedSink) -> Self {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
@@ -40,7 +44,8 @@ impl Fixture {
std::fs::write(root.join("file.txt"), "original\n").unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "original"]);
let host = Host::new(common::host_config(&base));
let host =
Host::new(ide_host::HostConfig { sink_for: Box::new(move |_| sink.clone()), ..common::host_config(&base) });
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
wait_for_repos(&project, 1).await;
@@ -278,6 +283,50 @@ async fn watcher_picks_up_a_worktree_added_below_the_project() {
assert!(roots.contains(&linked), "watcher did not discover the worktree added below the project: {roots:?}");
}
/// `git worktree add` writes the worktree's gitfile before its gitdir's `commondir` and `HEAD`; a
/// slow git lets the watcher rescan in between and find no repository there yet.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watcher_picks_up_a_worktree_whose_head_is_written_after_a_rescan() {
let changes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = changes.clone();
let sink: ide_core::SharedSink = Arc::new(move |event: ide_core::IdeEvent| {
if matches!(event, ide_core::IdeEvent::VcsChanged { .. }) {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
let f = Fixture::with_sink(sink).await;
// The watcher reports a batch that rescans only once the rescan is done.
let next_change = || {
let (changes, seen) = (changes.clone(), changes.load(std::sync::atomic::Ordering::SeqCst));
async move {
for _ in 0..200 {
if changes.load(std::sync::atomic::Ordering::SeqCst) > seen {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
panic!("the watcher reported no change");
}
};
let linked = f.root.join("watched");
let gitdir = f.root.join(".git/worktrees/watched");
let registered = next_change();
std::fs::create_dir_all(&gitdir).unwrap();
std::fs::write(gitdir.join("gitdir"), format!("{}\n", linked.join(".git").display())).unwrap();
registered.await;
let rescanned = next_change();
std::fs::create_dir_all(&linked).unwrap();
std::fs::write(linked.join(".git"), format!("gitdir: {}\n", gitdir.display())).unwrap();
rescanned.await;
assert_eq!(f.project.repos().all().len(), 1, "a gitfile without its gitdir's HEAD is no repository yet");
std::fs::write(gitdir.join("commondir"), "../..\n").unwrap();
// As git does: through a lock file.
std::fs::write(gitdir.join("HEAD.lock"), "ref: refs/heads/main\n").unwrap();
std::fs::rename(gitdir.join("HEAD.lock"), gitdir.join("HEAD")).unwrap();
wait_for_repos(&f.project, 2).await;
assert!(f.project.repos().roots().contains(&linked));
}
impl Fixture {
async fn open(&self, root: &std::path::Path) {
self.host.trust.decide(root, true, false).unwrap();
+4
Переглянути файл
@@ -227,6 +227,10 @@ pub struct LanguageServerConfig {
/// it parses a document.
#[serde(default)]
pub resync_on_configuration: bool,
/// Server-created work-done tokens to ignore, including slash-delimited suffixes.
/// Client-created request tokens are handled independently.
#[serde(default)]
pub ignored_progress_token_prefixes: Vec<String>,
/// Set by the settings hook: what the user sees as the server when another program serves
/// in its place (TypeScript 7's own `tsc --lsp` for vtsls).
#[serde(skip)]
+4 -1
Переглянути файл
@@ -909,7 +909,10 @@ mod tests {
let cfg = reg.get(&LanguageId::new("php")).unwrap();
let names: Vec<&str> = cfg.language_servers.iter().map(|s| s.name.as_str()).collect();
// After the fallback: hover, rename and symbols stay with Intelephense.
assert_eq!(names, ["intelephense", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
assert_eq!(names, ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls", "laravel-lsp"]);
let phpantom = &cfg.language_servers[1];
assert!(phpantom.fallback && phpantom.args.is_empty());
assert_eq!(phpantom.command, "phpantom_lsp");
// Phoxite answers the Laravel strings itself.
let phoxite = cfg.language_servers.iter().find(|s| s.name == "phoxite").unwrap();
assert!(phoxite.fallback && phoxite.replaces == ["laravel-lsp"]);
+1
Переглянути файл
@@ -73,6 +73,7 @@ fn server_config() -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+17
Переглянути файл
@@ -151,6 +151,23 @@ impl ClientHandler {
}
fn progress(&self, mgr: &LspManager, params: Value) {
if let Some(token) = params["token"].as_str() {
if let Some(id) = token.strip_prefix(crate::server::REQUEST_PROGRESS_PREFIX) {
if let (Ok(id), Ok(update)) = (id.parse::<u32>(), serde_json::from_value(params["value"].clone())) {
self.server.request_progress(mgr.sink(), TaskId(id), update);
}
return;
}
if self
.server
.config
.ignored_progress_token_prefixes
.iter()
.any(|prefix| token.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')))
{
return;
}
}
let token = progress_key(&params["token"]);
let value = &params["value"];
let kind = value.get("kind").and_then(Value::as_str);
+12 -2
Переглянути файл
@@ -1598,10 +1598,20 @@ impl LspManager {
cancel: Option<&CancellationToken>,
timeout: Duration,
) -> IdeResult<R> {
let params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
let mut params = serde_json::to_value(params).map_err(|e| IdeError::internal(e.to_string()))?;
// ImplementationParams accepts an optional client work-done token. Servers
// may report on it even when implementationProvider is advertised as `true`.
let progress = (method == "textDocument/implementation")
.then(|| t.server.track_request_progress(t.run.generation, self.sink(), cancel));
let cancel = if let Some(progress) = &progress {
params["workDoneToken"] = json!(progress.wire_token());
Some(progress.cancel.clone())
} else {
cancel.cloned()
};
let stamp = self.injected_request_stamp(&params);
let fut = async {
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel.cloned()).await?;
let mut value = t.run.peer.request::<Value, Value>(method, params, cancel).await?;
virtual_doc::normalize_uris(&mut value);
serde_json::from_value(value).map_err(|e| RpcError::Protocol(format!("{method}: {e}")))
};
+107
Переглянути файл
@@ -53,10 +53,58 @@ struct State {
generation: u64,
conn: Conn,
restarting: bool,
request_progress: HashMap<TaskId, RequestProgressState>,
events: VecDeque<IdeEvent>,
publishing: bool,
}
pub(crate) const REQUEST_PROGRESS_PREFIX: &str = "openidea/request/";
struct RequestProgressState {
title: Option<String>,
message: Option<String>,
fraction: Option<f32>,
_cancel: ide_core::task::CancelHandle,
}
impl RequestProgressState {
fn event(&self, id: TaskId, done: bool) -> Option<IdeEvent> {
Some(IdeEvent::Task {
id,
title: self.title.clone()?,
message: self.message.clone(),
fraction: self.fraction,
done,
cancellable: !done,
})
}
}
/// Progress provided to an LSP request. Dropping the request always retires its token.
pub(crate) struct RequestProgress<'a> {
id: TaskId,
server: &'a Server,
sink: &'a SharedSink,
pub(crate) cancel: CancellationToken,
}
impl RequestProgress<'_> {
pub(crate) fn wire_token(&self) -> String {
format!("{REQUEST_PROGRESS_PREFIX}{}", self.id.0)
}
}
impl Drop for RequestProgress<'_> {
fn drop(&mut self) {
let mut st = self.server.state.lock();
if let Some(progress) = st.request_progress.remove(&self.id) {
st.events.extend(progress.event(self.id, true));
}
drop(st);
self.server.publish(self.sink);
}
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
@@ -172,6 +220,7 @@ impl Server {
generation: 0,
conn: Conn::Idle,
restarting: false,
request_progress: HashMap::new(),
events: VecDeque::new(),
publishing: false,
}),
@@ -552,6 +601,9 @@ impl Server {
fn queue_cleanup(&self, st: &mut State) {
*self.initializing.lock() = None;
for (id, progress) in st.request_progress.drain() {
st.events.extend(progress.event(id, true));
}
for (id, title) in self.take_progress() {
st.events.push_back(IdeEvent::Task {
id,
@@ -572,6 +624,61 @@ impl Server {
}
}
pub(crate) fn track_request_progress<'a>(
&'a self,
generation: u64,
sink: &'a SharedSink,
parent_cancel: Option<&CancellationToken>,
) -> RequestProgress<'a> {
let id = TaskId::next();
let cancel = parent_cancel.map(CancellationToken::child_token).unwrap_or_default();
let mut st = self.state.lock();
if st.generation == generation && matches!(st.conn, Conn::Ready(_)) {
let token = cancel.clone();
st.request_progress.insert(
id,
RequestProgressState {
title: None,
message: None,
fraction: None,
_cancel: ide_core::task::on_cancel(id, move || token.cancel()),
},
);
}
RequestProgress { id, server: self, sink, cancel }
}
pub(crate) fn request_progress(&self, sink: &SharedSink, id: TaskId, update: lsp::WorkDoneProgress) {
let mut st = self.state.lock();
let Some(progress) = st.request_progress.get_mut(&id) else { return };
let fraction = |p: u32| p.min(100) as f32 / 100.0;
let event = match update {
lsp::WorkDoneProgress::Begin(begin) => {
progress.title = Some(begin.title);
progress.message = begin.message;
progress.fraction = begin.percentage.map(fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::Report(report) => {
progress.message = report.message.or_else(|| progress.message.take());
progress.fraction = report.percentage.map(fraction).or(progress.fraction);
progress.event(id, false)
}
lsp::WorkDoneProgress::End(end) => {
progress.message = end.message.or_else(|| progress.message.take());
progress.fraction = Some(1.0);
let event = progress.event(id, true);
st.request_progress.remove(&id);
event
}
};
// Queue under the state lock so a reply or cancellation can't publish `done`
// before a concurrent progress update and leave a stale row.
st.events.extend(event);
drop(st);
self.publish(sink);
}
pub fn emit(&self, sink: &SharedSink, event: IdeEvent) {
self.state.lock().events.push_back(event);
self.publish(sink);
+161
Переглянути файл
@@ -277,6 +277,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
@@ -2225,6 +2226,54 @@ async fn a_progress_token_begun_again_ends_the_task_it_replaces() {
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn toml_progress_quirk_ignores_server_tokens_left_open_after_cancel() {
let registry = LanguageRegistry::load(None).unwrap();
let php = registry.get(&LanguageId::new("php")).unwrap();
let quirk = &php.language_servers.iter().find(|s| s.name == "phpantom").unwrap().ignored_progress_token_prefixes;
let h = harness_configured("php", "php", &[("mock", incremental_caps())], |cfg| {
cfg.ignored_progress_token_prefixes = quirk.clone();
});
let (doc, path) = h.open("a.php", "<?php target();");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let peer = server.peer();
let progress = |token, kind, title| {
peer.notify("$/progress", json!({ "token": token, "value": { "kind": kind, "title": title } })).unwrap();
};
let method = "textDocument/references";
let search = || h.mgr.references_streaming(doc, Pos::new(0, 7), true, false, true, Default::default(), None);
progress("find_references/1", "begin", "Find References");
progress("find_references", "begin", "Find References");
progress("goto_implementation/1", "begin", "Go to Implementation");
progress("find_references_index/1", "begin", "Indexing");
h.wait_status("mock", ServerStatus::Busy).await;
server.errors.lock().insert(method.into(), (-32800, "Canceled".into()));
assert_eq!(search().await.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
server.errors.lock().remove(method);
server.respond(
method,
json!([{
"uri": uri_of(&path),
"range": { "start": { "line": 0, "character": 6 }, "end": { "line": 0, "character": 12 } }
}]),
);
progress("find_references/2", "begin", "Find References");
assert_eq!(search().await.unwrap().locations.len(), 1);
progress("find_references/2", "end", "Find References");
progress("find_references_index/1", "end", "Indexing");
h.wait_status("mock", ServerStatus::Ready).await;
let events = h.events.lock();
assert!(!events.iter().any(
|e| matches!(e, IdeEvent::Task { title, .. } if title == "Find References" || title == "Go to Implementation")
));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: false, .. } if title == "Indexing")));
assert!(events.iter().any(|e| matches!(e, IdeEvent::Task { title, done: true, .. } if title == "Indexing")));
}
#[tokio::test(flavor = "multi_thread")]
async fn replacing_progress_keeps_cancellation_reports_and_indexing_on_the_new_task() {
let h = harness(&[("mock", incremental_caps())]);
@@ -4239,6 +4288,118 @@ async fn implementations_per_position() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn implementation_progress_ends_on_cancel_without_server_end() {
implementation_progress_ends_with_request(false).await;
}
#[tokio::test]
async fn implementation_progress_ends_on_timeout_without_server_end() {
implementation_progress_ends_with_request(true).await;
}
async fn implementation_progress_ends_with_request(timeout: bool) {
let caps = json!({ "textDocumentSync": 1, "implementationProvider": true });
let h = harness_for("php", "php", &[("mock", caps)], &[]);
let (doc, path) = h.open("a.php", "<?php\ninterface A {}\nclass B implements A {}\n");
h.wait_status("mock", ServerStatus::Ready).await;
let server = h.launcher.state("mock");
let method = "textDocument/implementation";
let gate = Arc::new(Gate::default());
let uri = uri_of(&path);
*server.responder.lock() =
Some(Arc::new({
let gate = gate.clone();
move |server, requested, params| {
if requested != method {
return None;
}
let token = &params["workDoneToken"];
let peer = server.peer();
peer.notify("$/progress", json!({
"token": token, "value": { "kind": "begin", "title": "Go to Implementation", "cancellable": false }
})).unwrap();
if params["position"]["character"] == 10 {
peer.notify(
"$/progress",
json!({
"token": token, "value": { "kind": "report", "percentage": 88 }
}),
)
.unwrap();
gate.hold();
}
// The mock answers without sending `end`.
Some(json!([{
"uri": uri,
"range": { "start": { "line": 2, "character": 6 }, "end": { "line": 2, "character": 7 } }
}]))
}
}));
let mgr = h.mgr.clone();
let batch = tokio::spawn(async move {
mgr.implementations(doc, &[Pos::new(1, 10), Pos::new(2, 6)], Default::default()).await.unwrap()
});
let task_events = || {
h.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Task { id, title, done, fraction, cancellable, .. } if title == "Go to Implementation" => {
Some((*id, *done, *fraction, *cancellable))
}
_ => None,
})
.collect::<Vec<_>>()
};
eventually(|| {
let events = task_events();
gate.entered() && events.iter().any(|e| e.2 == Some(0.88)) && events.iter().any(|(_, done, _, _)| *done)
})
.await;
let scanning = task_events().into_iter().find(|e| e.2 == Some(0.88)).expect("scan reported 88%");
let (task, _, _, cancellable) = scanning;
assert!(cancellable);
assert!(!task_events().iter().any(|(id, done, _, _)| *id == task && *done));
let requests = server.requested(method);
assert_eq!(requests.len(), 2);
assert_ne!(requests[0]["workDoneToken"], requests[1]["workDoneToken"]);
if timeout {
tokio::time::pause();
tokio::time::advance(Duration::from_secs(31)).await;
tokio::time::resume();
} else {
assert!(ide_core::task::cancel(task));
}
let found = batch.await.unwrap();
gate.open();
eventually(|| !server.notified("$/cancelRequest").is_empty()).await;
assert!(found[0].is_empty());
assert_eq!(found[1][0].range.start.line, 2);
assert!(!ide_core::task::cancel(task));
assert_eq!(task_events().iter().filter(|(id, done, _, _)| *id == task && *done).count(), 1);
// Late progress for either retired token must not bring back its task.
let before = task_events();
let peer = server.peer();
for request in requests {
peer.notify(
"$/progress",
json!({
"token": request["workDoneToken"], "value": { "kind": "begin", "title": "Go to Implementation" }
}),
)
.unwrap();
}
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
assert_eq!(task_events(), before);
peer.notify("$/progress", json!({ "token": "index", "value": { "kind": "end" } })).unwrap();
h.wait_status("mock", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn java_implementations_come_from_sources_first() {
let caps = json!({
+3
Переглянути файл
@@ -428,6 +428,7 @@ async fn missing_binary_is_reported_with_install_hint() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -721,6 +722,7 @@ async fn typescript_language_server_end_to_end() {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
};
@@ -775,6 +777,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+11 -1
Переглянути файл
@@ -9,7 +9,11 @@
//! `Origin` or `Host` are refused (DNS rebinding).
//! - **Projects:** the `X-OpenIDEA-Project` header or the `?project=` query
//! names a folder; the server picks the open project containing it, or the
//! project the IDE serves it from without a window.
//! project the IDE serves it from without a window. A connection whose
//! folder no project serves lists the tools a trusted project gets, and each
//! call names its project with `projectPath`. `openidea/servesFolder`
//! answers which project serves the connection's folder (`{"root": null}`
//! for none).
//! - **Discovery:** `<app-data>/mcp/server.json` (`address`, `port`, `token`,
//! `pid`, `version`; readable only by the user) while the server runs.
//! - **Stdio:** `<app exe> --mcp-stdio [--project <path>]` reads the discovery
@@ -76,6 +80,12 @@ pub trait ToolRegistry: Send + Sync + 'static {
/// The tools callable for `project` (one of [`Self::projects`] or a root
/// [`Self::resolve`] gave). `Err` says why there are none (an unsupported project).
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String>;
/// The tools listed on a connection whose project doesn't resolve (a folder no project
/// serves, or no folder and not exactly one window): those a trusted project gets. Each
/// call still resolves its project and refuses by that project's trust.
fn tools_without_project(&self) -> Vec<Tool> {
Vec::new()
}
fn call_with_client(
&self,
project: &Path,
+34 -12
Переглянути файл
@@ -1,6 +1,6 @@
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`
//! and notifications, for one POST body (a message or a batch). Blocking: the
//! server runs it on a blocking thread.
//! MCP over JSON-RPC 2.0: `initialize`, `ping`, `tools/list`, `tools/call`,
//! our own `openidea/servesFolder` and notifications, for one POST body (a
//! message or a batch). Blocking: the server runs it on a blocking thread.
use crate::{CancellationToken, Tool, ToolCallError, ToolRegistry};
use serde_json::{Value, json};
@@ -26,16 +26,22 @@ impl Drop for InFlight<'_> {
}
}
/// How long a cancellation that arrived before its call is kept.
const EARLY_CANCELLATION: std::time::Duration = std::time::Duration::from_secs(60);
/// The protocol version answered when the client asks for one this server doesn't know.
pub(crate) const LATEST: &str = "2025-06-18";
pub(crate) const SUPPORTED: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
pub(crate) const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
/// The requested folder isn't in a project the IDE serves (or has no tools there).
pub(crate) const NOT_OPEN: i64 = -32001;
/// Which project serves the connection's folder: `{"root": "<path>"}`, or `{"root": null}`
/// for none. The stdio bridge asks it to pick the IDE process for its folder.
pub(crate) const SERVES_FOLDER: &str = "openidea/servesFolder";
pub(crate) struct RpcError {
code: i64,
@@ -105,7 +111,12 @@ impl Session<'_> {
let mut state = self.requests.0.lock().unwrap();
if let Some(cancel) = state.running.get(&key) {
cancel.cancel();
} else if state.early.len() < 1024 {
return None;
}
// The stdio bridge sends a cancellation to every server, so one that runs few
// calls drops the stale ones here as well.
state.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
if state.early.len() < 1024 {
state.early.insert(key, std::time::Instant::now());
}
}
@@ -116,7 +127,7 @@ impl Session<'_> {
let cancel = self.cancel.child_token();
{
let mut requests = self.requests.0.lock().unwrap();
requests.early.retain(|_, at| at.elapsed() < std::time::Duration::from_secs(60));
requests.early.retain(|_, at| at.elapsed() < EARLY_CANCELLATION);
if requests.running.contains_key(&key) {
return Some(error_response(id, INVALID_REQUEST, "request id already in flight"));
}
@@ -139,11 +150,18 @@ impl Session<'_> {
"initialize" => Ok(self.initialize(&params)),
"ping" => Ok(json!({})),
"tools/list" => {
let project = self.project()?;
let tools = self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?;
let tools = match self.project() {
Ok(project) => self.registry.tools(&project).map_err(|e| RpcError::new(NOT_OPEN, e))?,
Err(_) => self.registry.tools_without_project(),
};
Ok(json!({ "tools": tools.iter().map(tool_json).collect::<Vec<_>>() }))
}
"tools/call" => self.call(params, cancel),
SERVES_FOLDER => {
// A root without tools here (a remote window's) is another server's to serve.
let root = self.project().ok().filter(|root| self.registry.tools(root).is_ok());
Ok(json!({ "root": root.map(|root| root.display().to_string()) }))
}
_ => Err(RpcError::new(METHOD_NOT_FOUND, format!("no method {method:?}"))),
}
}
@@ -157,9 +175,13 @@ impl Session<'_> {
}
let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(LATEST);
let version = if SUPPORTED.contains(&asked) { asked } else { LATEST };
let about = match self.project() {
Ok(root) => format!("the project OpenIDEA serves at {}", root.display()),
Err(_) => "a project open in OpenIDEA or served in the background".to_owned(),
let (about, without_project) = match self.project() {
Ok(root) => (format!("the project OpenIDEA serves at {}", root.display()), ""),
Err(_) => (
"a project open in OpenIDEA or served in the background".to_owned(),
" This connection has no project of its own: pass `projectPath`, a folder inside a project \
OpenIDEA serves, in every call, `get_workspace_roots` included.",
),
};
json!({
"protocolVersion": version,
@@ -174,7 +196,7 @@ impl Session<'_> {
its `roots` are every project in the IDE workspace. That is the scope to search and read, \
not a list of projects to change; it doesn't change your working directory or \
permissions. Pass another root as `projectPath` to reach that project. Call it again \
when the user switches projects or attaches one."
when the user switches projects or attaches one.{without_project}"
),
})
}
+124 -24
Переглянути файл
@@ -4,7 +4,7 @@
//! running IDE's server, found through the discovery file.
use crate::discovery::Discovery;
use crate::protocol::{NOT_OPEN, error_response};
use crate::protocol::{METHOD_NOT_FOUND, NOT_OPEN, SERVES_FOLDER, error_response};
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{Request, StatusCode, header};
@@ -17,7 +17,11 @@ use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
#[derive(Default)]
struct BridgeState {
preferred: Option<SocketAddr>,
/// The server that serves the connection's folder, or the first one when none does. A
/// server restarted on its port is another one: its entry names another process or token.
preferred: Option<Discovery>,
/// The servers there were when `preferred` was picked: one started since may serve the folder.
picked_among: Vec<Discovery>,
init_message: Option<Value>,
initialized_on: HashSet<SocketAddr>,
}
@@ -171,18 +175,28 @@ async fn post(
if candidates.is_empty() {
return Err(not_running());
}
if let Some(preferred) = state.lock().unwrap().preferred
&& let Some(pos) = candidates.iter().position(|c| SocketAddr::new(c.address, c.port) == preferred)
{
if message.get("method").and_then(Value::as_str) == Some("notifications/cancelled") {
return cancel_everywhere(candidates, project, message, scope, sent).await.ok_or_else(not_running);
}
let preferred = state.lock().unwrap().preferred.clone();
if let Some(pos) = preferred.and_then(|preferred| candidates.iter().position(|c| *c == preferred)) {
let chosen = candidates.remove(pos);
candidates.insert(0, chosen);
}
// `initialize` picks the server that serves the connection's folder, and later messages
// keep it: a call whose `projectPath` another server serves doesn't move `tools/list`
// there. A message after that server stopped, or after another one started, picks again.
let initializing = is_initialize(message);
let mut fallback: Option<(SocketAddr, Answer)> = None;
if !initializing {
pick_again(&mut candidates, project, scope, state).await;
}
let listed = candidates.clone();
let mut answered = None;
let mut fallback: Option<(Discovery, Answer)> = None;
let mut last_error: Option<String> = None;
let total = candidates.len();
for (idx, info) in candidates.into_iter().enumerate() {
let at = SocketAddr::new(info.address, info.port);
let at = address(&info);
if !initializing {
let init = {
let guard = state.lock().unwrap();
@@ -190,7 +204,7 @@ async fn post(
};
if let Some(mut init_msg) = init {
if let Some(obj) = init_msg.as_object_mut() {
obj.insert("id".into(), Value::String(format!("__openidea_init_{idx}__")));
obj.insert("id".into(), Value::String(own_id("init")));
}
if post_one(&info, project, &init_msg, scope, sent).await.is_ok() {
state.lock().unwrap().initialized_on.insert(at);
@@ -202,34 +216,120 @@ async fn post(
if initializing {
state.lock().unwrap().initialized_on.insert(at);
if total > 1 && !serves_project(&info, project, scope).await {
fallback.get_or_insert((at, answer));
fallback.get_or_insert((info, answer));
continue;
}
} else if idx + 1 < total && is_not_open_reply(&answer) {
fallback = Some((at, answer));
fallback = Some((info, answer));
continue;
}
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
answered = Some((info, answer));
break;
}
Err(err) => last_error = Some(err),
}
}
if let Some((at, answer)) = fallback {
state.lock().unwrap().preferred = Some(at);
return Ok(answer);
let Some((info, answer)) = answered.or(fallback) else {
return Err(last_error.unwrap_or_else(not_running));
};
if initializing {
let mut state = state.lock().unwrap();
state.preferred = Some(info);
state.picked_among = listed;
}
Err(last_error.unwrap_or_else(not_running))
Ok(answer)
}
/// Whether the server of `info` has `project` open: its `tools/list` doesn't answer "not open".
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
let probe = serde_json::json!({ "jsonrpc": "2.0", "id": "__openidea_probe__", "method": "tools/list" });
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
match post_one(info, project, &probe, scope, &discard).await {
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
_ => false,
fn address(info: &Discovery) -> SocketAddr {
SocketAddr::new(info.address, info.port)
}
/// An id of the bridge's own for a request it makes: concurrent messages can make one to the
/// same server at once, and a server refuses an id that is already in flight.
fn own_id(kind: &str) -> String {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
format!("__openidea_{kind}_{}__", NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
}
/// How long a server has to answer a probe or take a cancellation.
const PROBE_WAIT: std::time::Duration = std::time::Duration::from_secs(2);
/// Sends a cancellation to every server at once, since the call may run in any of them (its
/// `projectPath` picks one); the answer of one that took it. A server that doesn't run the call
/// keeps the id for a while, in case the call reaches it later. One that doesn't answer in
/// time holds up neither the others nor the bridge.
async fn cancel_everywhere(
candidates: Vec<Discovery>,
project: &Path,
message: &Value,
scope: &str,
sent: &tokio::sync::mpsc::UnboundedSender<Value>,
) -> Option<Answer> {
let mut posts = tokio::task::JoinSet::new();
for info in candidates {
let (project, message, scope, sent) = (project.to_owned(), message.clone(), scope.to_owned(), sent.clone());
posts.spawn(async move {
tokio::time::timeout(PROBE_WAIT, post_one(&info, &project, &message, &scope, &sent)).await
});
}
let mut accepted = None;
while let Some(posted) = posts.join_next().await {
if let Ok(Ok(Ok(answer))) = posted {
accepted.get_or_insert(answer);
}
}
accepted
}
/// Picks the server for the connection's folder again when the one picked is gone or another
/// server started since, as `initialize` picks it: the first of `candidates` (the one picked
/// before leads) that serves the folder, else the first. Puts it first.
async fn pick_again(candidates: &mut Vec<Discovery>, project: &Path, scope: &str, state: &Mutex<BridgeState>) {
{
let state = state.lock().unwrap();
let kept = state.preferred.as_ref().is_some_and(|preferred| candidates.contains(preferred));
if kept && candidates.iter().all(|c| state.picked_among.contains(c)) {
return;
}
}
let mut chosen = 0;
if candidates.len() > 1 {
for (pos, info) in candidates.iter().enumerate() {
if serves_project(info, project, scope).await {
chosen = pos;
break;
}
}
}
let picked = candidates.remove(chosen);
candidates.insert(0, picked);
let mut state = state.lock().unwrap();
state.preferred = Some(candidates[0].clone());
state.picked_among = candidates.clone();
}
/// Whether the server of `info` serves `project`: its `openidea/servesFolder` names a root.
/// An IDE older than that method answers "method not found"; its `tools/list` answers "not
/// open" for a folder it doesn't serve, so that answers instead. A server that doesn't answer
/// in time doesn't serve it.
async fn serves_project(info: &Discovery, project: &Path, scope: &str) -> bool {
let probe = |method| serde_json::json!({ "jsonrpc": "2.0", "id": own_id("probe"), "method": method });
let (discard, _) = tokio::sync::mpsc::unbounded_channel();
let ask = async {
let reply = match post_one(info, project, &probe(SERVES_FOLDER), scope, &discard).await {
Ok(Answer::Body(StatusCode::OK, body)) => serde_json::from_slice::<Value>(&body).ok(),
_ => None,
};
let Some(reply) = reply else { return false };
if reply.pointer("/error/code").and_then(Value::as_i64) == Some(METHOD_NOT_FOUND) {
return match post_one(info, project, &probe("tools/list"), scope, &discard).await {
Ok(answer @ Answer::Body(StatusCode::OK, _)) => !is_not_open_reply(&answer),
_ => false,
};
}
reply.pointer("/result/root").is_some_and(Value::is_string)
};
tokio::time::timeout(PROBE_WAIT, ask).await.unwrap_or(false)
}
fn is_not_open_reply(answer: &Answer) -> bool {
@@ -253,7 +353,7 @@ async fn post_one(
project.display()
)
};
let at = SocketAddr::new(info.address, info.port);
let at = address(info);
let stream = tokio::net::TcpStream::connect(at).await.map_err(|_| not_running())?;
let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream))
.await
+447 -25
Переглянути файл
@@ -5,7 +5,7 @@ use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegi
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
struct Registry {
project: PathBuf,
@@ -28,6 +28,10 @@ impl ToolRegistry for Registry {
}])
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("everything")]
}
fn call(
&self,
project: &Path,
@@ -48,6 +52,18 @@ impl ToolRegistry for Registry {
}
}
/// A read-only tool with no arguments.
fn named(name: &str) -> Tool {
Tool {
name: name.into(),
description: format!("The tool {name}"),
input_schema: json!({ "type": "object" }),
read_only: true,
destructive: false,
output_schema: None,
}
}
struct Setup {
_tmp: tempfile::TempDir,
project: PathBuf,
@@ -215,25 +231,30 @@ async fn requests_without_the_token_or_from_web_pages_are_refused() {
async fn folders_that_are_not_open_are_named_in_the_error() {
let s = setup();
let elsewhere = s.project.parent().unwrap().join("elsewhere");
let header = format!("X-OpenIDEA-Project: {}", elsewhere.display());
let (status, body) =
post(&s, "/mcp", &[&bearer(&s), &header], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
assert_eq!(status, 200);
let reply: Value = serde_json::from_str(&body).unwrap();
assert!(reply["error"]["message"].as_str().unwrap().contains("isn't open in OpenIDEA"));
// The connection's folder isn't open: the list is the one without a project, and a call
// that names no project of its own is refused with the folder named.
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
assert_eq!(call["error"]["code"], -32001, "{call}");
let message = call["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
// No folder named and one window: that window's project lists its tools.
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
}
/// One project open in a window and the folders served without a window.
/// One project open in a window, the folders served without a window and, optionally, the
/// root of a window on a remote host (which has no tools here).
struct WithBackground {
open: PathBuf,
background: Vec<PathBuf>,
remote: Option<PathBuf>,
}
impl ToolRegistry for WithBackground {
fn projects(&self) -> Vec<PathBuf> {
vec![self.open.clone()]
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
}
/// The innermost served folder containing `path`, strictly inside `within`, as the
/// background policy answers.
@@ -242,7 +263,13 @@ impl ToolRegistry for WithBackground {
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
served.max_by_key(|root| root.components().count()).cloned()
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("anything")]
}
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
if self.remote.as_deref() == Some(project) {
return Err("project is on a remote host".into());
}
Ok(vec![Tool {
name: "where".into(),
description: format!("Names {}", project.display()),
@@ -257,20 +284,23 @@ impl ToolRegistry for WithBackground {
}
}
/// Stops the server of `s` and serves `registry` in its place.
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
s.server.take().unwrap().stop();
let runtime = tokio::runtime::Handle::current();
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
}
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
/// that holds the open project; the folder `inventory` next to the open project.
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
let mut s = setup();
s.server.take().unwrap().stop();
let base = s.project.parent().unwrap().to_path_buf();
let inventory = base.join("inventory");
std::fs::create_dir_all(inventory.join("src")).unwrap();
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
let registry = WithBackground { open: s.project.clone(), background };
s.server = Some(
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
.unwrap(),
);
let registry = WithBackground { open: s.project.clone(), background, remote: None };
restart(&mut s, registry);
(s, inventory)
}
@@ -291,6 +321,7 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
assert!(!instructions.contains("no project of its own"), "{instructions}");
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
@@ -334,16 +365,41 @@ async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_ser
#[tokio::test(flavor = "multi_thread")]
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
let (s, inventory) = setup_with_background(&[]);
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
let reply = rpc_for(&s, &inventory, method, params).await;
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
}
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
assert_eq!(reply["error"]["code"], -32001, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
assert!(init["result"]["instructions"].is_string(), "initialize answers without a project: {init}");
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
"{instructions}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
let (mut s, inventory) = setup_with_background(&[]);
let base = s.project.parent().unwrap().to_owned();
let remote = base.join("remote");
let registry =
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
restart(&mut s, registry);
let cases = [
(s.project.join("src"), json!(s.project)),
(inventory.join("src"), json!(inventory)),
(base.join("elsewhere"), Value::Null),
// A remote window's root is that host's to serve.
(remote, Value::Null),
];
for (folder, root) in cases {
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
}
}
#[tokio::test(flavor = "multi_thread")]
@@ -413,6 +469,9 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
Ok(Vec::new())
}
fn tools_without_project(&self) -> Vec<Tool> {
vec![named("anywhere")]
}
fn call(
&self,
project: &Path,
@@ -436,8 +495,14 @@ async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects()
)
.unwrap(),
);
// No folder named and two windows: the list without a project, and a call has to name one.
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
let list: Value = serde_json::from_str(&body).unwrap();
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
let reply: Value = serde_json::from_str(&body).unwrap();
assert_eq!(reply["error"]["code"], -32602, "{reply}");
let message = reply["error"]["message"].as_str().unwrap();
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
@@ -624,3 +689,360 @@ async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_clos
server_a.stop();
assert!(!discovery.exists());
}
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
/// out once the answer to the one before has come back.
struct Client {
input: tokio::io::DuplexStream,
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
id: u64,
}
impl Client {
fn start(discovery: &Path, folder: &Path) -> Self {
let (input, bridge_input) = tokio::io::duplex(1 << 16);
let (bridge_output, output) = tokio::io::duplex(1 << 16);
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
let bridge = tokio::spawn(async move {
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
});
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
}
/// Sends a request without waiting for its answer; its id.
async fn send(&mut self, method: &str, params: Value) -> u64 {
self.id += 1;
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
self.id
}
async fn notify(&mut self, message: Value) {
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
}
async fn answer(&mut self, id: u64) -> Value {
let answer = async {
loop {
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
let reply: Value = serde_json::from_str(&line).unwrap();
if reply["id"] == id {
return reply;
}
}
};
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
}
async fn ask(&mut self, method: &str, params: Value) -> Value {
let id = self.send(method, params).await;
self.answer(id).await
}
async fn close(self) {
let Self { input, output, bridge, .. } = self;
drop(input);
bridge.await.unwrap().unwrap();
drop(output);
}
}
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
let runtime = tokio::runtime::Handle::current();
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
}
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
/// servers that share its data directory.
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
for folder in folders {
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
}
let discovery = discovery_path(&base.join("app-data"));
(tmp, base, discovery)
}
impl WithBackground {
/// A window on `open` and `background` served without one.
fn serving(open: &Path, background: &Path) -> Self {
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
}
}
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
/// Each order makes the other server the one in `server.json`.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
for b_first in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &proj_b);
let servers = if b_first {
[start_in(&discovery, b()), start_in(&discovery, a())]
} else {
[start_in(&discovery, a()), start_in(&discovery, b())]
};
let mut client = Client::start(&discovery, &proj_b.join("src"));
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
let call = client.ask("tools/call", json!({ "name": "where" })).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
client.close().await;
for server in servers {
server.stop();
}
}
}
/// A client started in `work`, a folder neither server serves: the tools of the server
/// `initialize` picked, and each call goes where its `projectPath` is served.
#[tokio::test(flavor = "multi_thread")]
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
for b_first in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
let repo = work.join("repo");
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &repo);
// The server started last is in `server.json`; with neither serving the folder,
// `initialize` settles on it.
let (servers, listed) = if b_first {
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
} else {
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
};
let mut client = Client::start(&discovery, &work);
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
assert!(instructions.contains("no project of its own"), "{instructions}");
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
let call = client.ask("tools/call", in_repo).await;
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
let call = client.ask("tools/call", in_a).await;
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
// A call sent to the other server doesn't move the connection there.
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
client.close().await;
for server in servers {
server.stop();
}
}
}
/// The server `initialize` picked stops, or one that serves the folder starts later: the
/// next message picks again, as `initialize` does.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let a = || Registry { project: proj_a.clone() };
let b = || WithBackground::serving(&proj_c, &proj_b);
let serving_b = format!("Names {}", proj_b.display());
// Only A runs at `initialize`; B starts afterwards.
let server_a = start_in(&discovery, a());
let mut client = Client::start(&discovery, &proj_b.join("src"));
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let server_b = start_in(&discovery, b());
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
// B restarts, and A restarts after it, so A is first in the discovery file.
server_b.stop();
let server_b = start_in(&discovery, b());
server_a.stop();
let server_a = start_in(&discovery, a());
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
/// that didn't serve the folder may serve it now.
#[tokio::test(flavor = "multi_thread")]
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let port = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
let fixed = ServerOptions { port: Some(port), ..Default::default() };
let runtime = tokio::runtime::Handle::current();
let start_b = |registry: WithBackground| {
McpServer::start_with(Arc::new(registry), Some(discovery.clone()), &runtime, fixed.clone()).unwrap()
};
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
let server_b = start_b(WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
let mut client = Client::start(&discovery, &proj_b.join("src"));
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
server_b.stop();
let server_b = start_b(WithBackground::serving(&proj_c, &proj_b));
assert_eq!(server_b.port(), port);
let list = client.ask("tools/list", json!({})).await;
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
struct Holding {
open: PathBuf,
background: PathBuf,
}
impl ToolRegistry for Holding {
fn projects(&self) -> Vec<PathBuf> {
vec![self.open.clone()]
}
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
path.starts_with(&self.background).then(|| self.background.clone())
}
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
Ok(vec![named("hold")])
}
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
tokio::runtime::Handle::current().block_on(cancel.cancelled());
Err(ToolCallError::Failed("cancelled".into()))
}
}
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
/// cancellation reaches B.
#[tokio::test(flavor = "multi_thread")]
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
let mut client = Client::start(&discovery, &proj_a);
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
client
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
.await;
let answer = client.answer(call).await;
assert_eq!(answer["result"]["isError"], true, "{answer}");
client.close().await;
server_a.stop();
server_b.stop();
}
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
/// outside `serves`.
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
use http_body_util::{BodyExt, Full};
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let serves = serves.clone();
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
let serves = serves.clone();
async move {
let query = request.uri().query().unwrap_or_default().to_owned();
let folder = query.strip_prefix("project=").unwrap_or_default();
let folder =
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
let body = request.into_body().collect().await.unwrap().to_bytes();
let message: Value = serde_json::from_slice(&body).unwrap();
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
let id = message["id"].clone();
let reply = match message["method"].as_str().unwrap_or_default() {
_ if id.is_null() => None,
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
"instructions": "an older OpenIDEA" } })),
"tools/list" if served => {
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
}
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
"tools/list" | "tools/call" => Some(
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
),
_ => Some(
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
),
};
let response = match reply {
Some(reply) => hyper::Response::builder()
.header("content-type", "application/json")
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
};
Ok::<_, std::convert::Infallible>(response.unwrap())
}
});
tokio::spawn(async move {
let io = hyper_util::rt::TokioIo::new(stream);
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
});
}
});
// Written once it listens, so the stale-entry sweep of the next server keeps it.
let info = Discovery {
address: std::net::Ipv4Addr::LOCALHOST.into(),
port,
token: "test-token-older".into(),
pid: std::process::id(),
version: "0.1.0".into(),
};
info.write(discovery).unwrap();
server
}
#[tokio::test(flavor = "multi_thread")]
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
for older_serves in [false, true] {
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
// Either way the server that doesn't serve the folder is in `server.json`.
let (older, real) = if older_serves {
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
} else {
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
(fake_older_ide(&discovery, None).await, real)
};
let mut client = Client::start(&discovery, &folder.join("src"));
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
let instructions = init["result"]["instructions"].as_str().unwrap();
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
let call = client.ask("tools/call", json!({ "name": "where" })).await;
let answered = match older_serves {
true => call["result"]["content"][0]["text"] == "older",
false => call["result"]["structuredContent"]["project"] == json!(folder),
};
assert!(answered, "older_serves {older_serves}: {call}");
client.close().await;
real.stop();
older.abort();
}
}
+4 -2
Переглянути файл
@@ -225,7 +225,9 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
args.push("--no-TTY".into());
}
}
RunTargetKind::Ssh => return Err(IdeError::internal("an SSH target does not run in a container")),
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::internal("this run target does not run in a container"));
}
}
args.extend(["--name".into(), run.name.to_owned(), "--label".into(), format!("openidea.run={}", config.id)]);
args.extend(["--workdir".into(), command.cwd.clone()]);
@@ -341,7 +343,7 @@ pub fn python_probe_args(target: &RunTarget, root: &Path, name: &str, code: &str
}
args.extend(["run", "--no-deps", "--no-TTY"].map(String::from));
}
RunTargetKind::Ssh => {
RunTargetKind::Ssh | RunTargetKind::Wsl => {
return Err(IdeError::invalid(format!("Run target '{}' is not a container", target.name)));
}
}
+3 -1
Переглянути файл
@@ -1,5 +1,6 @@
//! Remote work over SSH: SFTP deployment ([`deploy`], [`mapping`]) and run
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`]).
//! configurations on run targets ([`target`]; Docker and Compose ones in [`docker`], WSL
//! ones in [`wsl`]).
pub mod container_tunnel;
pub mod deploy;
@@ -10,6 +11,7 @@ pub mod mapping;
pub mod service;
pub mod target;
pub mod upload;
pub mod wsl;
pub use deploy::{
Deployment, DeploymentCoverage, SyncAction, SyncEntry, SyncStatus, SyncStep, TransferReport, coverage,
+1 -1
Переглянути файл
@@ -438,7 +438,7 @@ impl RemoteService {
let target_id = config.extras.target.as_deref().unwrap_or_default();
let target = run_target(settings, target_id)?;
if target.kind != ide_core::remote_settings::RunTargetKind::Ssh {
return Err(IdeError::internal("container run targets start as local runs of the docker CLI"));
return Err(IdeError::internal("container and WSL run targets start as local runs"));
}
let session = self.ssh.session(&target.ssh_config).await?;
let fs = RemoteFs::new(session.sftp().await?).with_shell(session.clone());
+8 -2
Переглянути файл
@@ -72,7 +72,8 @@ fn replace_root(s: &str, root: &str, remote: &str) -> String {
out.push_str(remote);
if root.contains('\\') {
let end = after
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ',' | '"' | '\''))
// `:` too: past the drive letter, it only separates a POSIX path list.
.find(|c: char| c.is_whitespace() || matches!(c, ';' | ':' | ',' | '"' | '\''))
.unwrap_or(after.len());
out.push_str(&after[..end].replace('\\', "/"));
after = &after[end..];
@@ -191,7 +192,7 @@ pub fn debugpy_probe(debug: &RemoteCommand, bootstrap: &str) -> String {
/// `java` flags whose value is a path list that may point outside the project
/// (`~/.m2` jars, `--module-path` entries): deployment sync only uploads the
/// project root, so these entries need their own sync + rewrite (#2641).
const PATH_LIST_FLAGS: [&str; 6] =
pub(crate) const PATH_LIST_FLAGS: [&str; 6] =
["-cp", "-classpath", "--class-path", "-p", "--module-path", "--upgrade-module-path"];
/// The separator of a `-cp` value on this (client) machine.
@@ -635,6 +636,11 @@ mod tests {
assert_eq!(replace_root("/work/proj2/x:/work/proj/y", "/work/proj", "/srv"), "/work/proj2/x:/srv/y");
assert_eq!(replace_root("/work/proj", "/work/proj", "/srv"), "/srv");
assert_eq!(replace_root(r"C:\p\src/a.py C:\p2", r"C:\p", "/srv"), r"/srv/src/a.py C:\p2");
assert_eq!(
replace_root(r"C:\work\proj:C:\work\proj\src", r"C:\work\proj", "/mnt/c/work/proj"),
"/mnt/c/work/proj:/mnt/c/work/proj/src",
"each root of a PYTHONPATH list"
);
}
/// Unix/Windows spellings of the same layout: one inside-root entry, one
+426
Переглянути файл
@@ -0,0 +1,426 @@
//! Run configurations on WSL run targets: rewritten into a local run of
//! `wsl.exe -d <distro> --cd <dir> --exec <program> <args>`, with the project's paths
//! and interpreters swapped for their Linux counterparts. The console, stdin, Stop and
//! test parsers then work as for any local run.
use crate::target::remote_command;
use ide_core::remote_settings::RunTarget;
use ide_core::{IdeError, IdeResult};
use ide_run::RunConfig;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Where the project is inside the target's distribution.
pub fn project_root(target: &RunTarget, root: &Path) -> IdeResult<String> {
match target.project_root.trim().trim_end_matches('/') {
"" if target.project_root.trim().starts_with('/') => Ok("/".into()),
"" => ide_core::wsl::linux_path(root, target.distro.trim()).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach {} from WSL: set the project's Linux path in Settings › Run Targets",
target.name,
root.display()
))
}),
folder => Ok(folder.to_owned()),
}
}
/// The file on this machine of a path a run in the target's distribution printed (a
/// traceback line): in the project, on a drive under `/mnt/<drive>`, else in the
/// distribution's own file system (`\\wsl.localhost\<distro>`).
pub fn local_file(path: &str, target: &RunTarget, root: &Path) -> Option<PathBuf> {
if !path.starts_with('/') {
return None;
}
if let Ok(linux_root) = project_root(target, root) {
let linux_root = linux_root.trim_end_matches('/');
if let Some(rest) =
path.strip_prefix(linux_root).filter(|r| r.is_empty() || r.starts_with('/') || linux_root.is_empty())
{
return Some(ide_core::wsl::path_parts(rest).into_iter().fold(root.to_path_buf(), |p, c| p.join(c)));
}
}
Some(ide_core::wsl::windows_path(path, target.distro.trim()))
}
fn is_java(command: &str) -> bool {
let name = command.trim().rsplit(['/', '\\']).next().unwrap_or("");
name.to_ascii_lowercase().trim_end_matches(".exe") == "java"
}
/// The `-cp` / `--module-path` values of `java` arguments as the distribution reads them:
/// each absolute entry outside the project through its `/mnt` path, joined with `:`.
/// Entries in the project stay as they are: `remote_command` maps them onto its folder there.
fn linux_path_lists(args: &[String], root: &Path, distro: &str) -> Vec<String> {
let mut out = args.to_vec();
for i in 1..out.len() {
if !crate::target::PATH_LIST_FLAGS.contains(&out[i - 1].as_str()) || out[i].contains("${") {
continue;
}
let entries: Vec<String> = out[i]
.split(crate::target::classpath_separator())
.filter(|e| !e.is_empty())
.map(|e| {
let path = Path::new(e);
if path.starts_with(root) {
return e.to_owned();
}
match path.is_absolute().then(|| ide_core::wsl::linux_path(path, distro)).flatten() {
Some(linux) => linux,
None => e.replace('\\', "/"),
}
})
.collect();
out[i] = entries.join(":");
}
out
}
/// The target's Python: its own, or `python3` on the distribution's `PATH`.
pub fn python(target: &RunTarget) -> &str {
match target.python.trim() {
"" => "python3",
python => python,
}
}
/// Run with `sh -c` in a distribution, the project's Linux folder as `$1`: prints the
/// Pythons found there, one path a line.
pub const FIND_PYTHONS: &str = r#"for p in "$(command -v python3)" "$(command -v python)" /usr/bin/python3* /usr/local/bin/python3* "$HOME"/.pyenv/versions/*/bin/python "$1/.venv/bin/python" "$1/venv/bin/python"; do case "$p" in *-config) continue ;; esac; [ -f "$p" ] && [ -x "$p" ] && echo "$p"; done; true"#;
/// The paths [`FIND_PYTHONS`] printed, without repeats and without the tools named after
/// Python (`python3-pytest`, `python3.12-config`).
pub fn parse_pythons(out: &str) -> Vec<String> {
let interpreter = |path: &str| {
let name = path.rsplit('/').next().unwrap_or("");
let version = name.strip_prefix("python").unwrap_or("-");
version.chars().all(|c| c.is_ascii_digit() || c == '.')
};
let mut found: Vec<String> = Vec::new();
for line in out.lines().map(str::trim).filter(|l| l.starts_with('/') && interpreter(l)) {
if !found.iter().any(|f| f == line) {
found.push(line.to_owned());
}
}
found
}
/// `config` as a local run of `wsl_exe` that runs it in the target's distribution.
/// `file_env` holds the variables of the configuration's `.env` files, already read;
/// `inherited_wslenv` is this machine's `WSLENV`, kept for the distribution.
pub fn wsl_config(
config: &RunConfig,
target: &RunTarget,
root: &Path,
linux_root: &str,
wsl_exe: &str,
file_env: &BTreeMap<String, String>,
inherited_wslenv: Option<&str>,
) -> IdeResult<RunConfig> {
let distro = target.distro.trim();
if !ide_core::wsl::is_valid_distro(distro) {
return Err(IdeError::invalid(format!(
"Run target '{}' has no WSL distribution; choose one in Settings › Run Targets",
target.name
)));
}
let mut command = if is_java(&config.command) {
let mut java = config.clone();
java.args = linux_path_lists(&config.args, root, distro);
remote_command(&java, target, root, linux_root)
} else {
remote_command(config, target, root, linux_root)
};
// Outside the project `remote_command` falls back to the project folder: a folder of
// this machine is reached through its own `/mnt` path instead.
if let Some(dir) = config.cwd.as_ref().map(|d| d.to_path_buf()).filter(|d| d.is_absolute() && !d.starts_with(root))
{
command.cwd = ide_core::wsl::linux_path(&dir, distro).ok_or_else(|| {
IdeError::invalid(format!(
"Run target '{}' can't reach the working folder {} from WSL",
target.name,
dir.display()
))
})?;
}
let mut env = file_env.clone();
if ide_run::is_python_kind(&config.kind) && !command.env.contains_key("PYTHONUNBUFFERED") {
env.insert("PYTHONUNBUFFERED".into(), "1".into());
}
env.extend(command.env.clone());
// The distribution keeps its own `PATH`: a value here is this machine's, or a `.env`
// `PATH=$PATH:…` already expanded against it.
env.remove("PATH");
let mut args: Vec<String> = ["-d", distro, "--cd", &command.cwd, "--exec"].map(String::from).to_vec();
// A Python run finds the console scripts next to the target's interpreter (a virtualenv's
// `pytest`) first, as a local run with the project interpreter does.
let scripts = (ide_run::is_python_kind(&config.kind) && target.python.trim().starts_with('/'))
.then(|| target.python.trim().rsplit_once('/').map(|(dir, _)| dir.to_owned()))
.flatten()
.filter(|dir| !dir.is_empty());
match (command.shell_line, scripts) {
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
(Some(line), Some(dir)) => args.extend(["sh".into(), "-c".into(), format!("PATH=\"$0:$PATH\"; {line}"), dir]),
(None, None) => {
args.push(command.program);
args.extend(command.args);
}
(None, Some(dir)) => {
args.extend(["sh".into(), "-c".into(), r#"PATH="$0:$PATH" exec "$@""#.into(), dir, command.program]);
args.extend(command.args);
}
}
// Values cross into the distribution through the environment (`WSLENV` lists the
// names), so they stay out of the command line echoed in the console. The configuration's
// own `WSLENV` entries (`FOO/p`) are kept with their flags.
let own = env.remove("WSLENV");
let mut wslenv: Vec<&str> = inherited_wslenv
.into_iter()
.chain(own.as_deref())
.flat_map(|v| v.split(':'))
.filter(|n| !n.is_empty())
.collect();
let listed = |name: &str, list: &[&str]| list.iter().any(|n| n.split('/').next() == Some(name));
for name in env.keys() {
if !listed(name, &wslenv) {
wslenv.push(name);
}
}
let wslenv = wslenv.join(":");
if !wslenv.is_empty() {
env.insert("WSLENV".into(), wslenv);
}
let mut out = config.clone();
out.command = wsl_exe.to_owned();
out.args = args;
out.cwd = Some(root.to_path_buf().into());
out.env = env;
let extras = &mut out.extras;
extras.target = None;
extras.env_files.clear();
// `wsl.exe` needs this machine's environment; the distribution gets only `WSLENV`'s names.
extras.include_system_env = true;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::remote_settings::RunTargetKind;
fn target() -> RunTarget {
RunTarget { kind: RunTargetKind::Wsl, name: "wsl".into(), distro: "Ubuntu-24.04".into(), ..Default::default() }
}
fn config(command: &str, args: &[&str]) -> RunConfig {
RunConfig {
id: "app".into(),
name: "app".into(),
kind: "python".into(),
command: command.into(),
args: args.iter().map(|a| (*a).to_owned()).collect(),
cwd: None,
env: BTreeMap::new(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
}
}
#[test]
fn the_project_root_is_the_targets_or_its_mnt_path() {
let t = target();
assert_eq!(project_root(&t, Path::new(r"C:\work\proj")).unwrap(), "/mnt/c/work/proj");
assert_eq!(project_root(&t, Path::new(r"\\wsl.localhost\Ubuntu-24.04\home\me\p")).unwrap(), "/home/me/p");
let err = project_root(&t, Path::new(r"\\server\share\p")).unwrap_err();
assert!(err.message.contains("set the project's Linux path"), "{}", err.message);
let custom = RunTarget { project_root: " /c/work/proj/ ".into(), ..t.clone() };
assert_eq!(project_root(&custom, Path::new(r"\\server\share\p")).unwrap(), "/c/work/proj");
let slash = RunTarget { project_root: "/".into(), ..t };
assert_eq!(project_root(&slash, Path::new("x")).unwrap(), "/");
}
// Unix paths are not absolute on Windows; `windows_paths_are_mapped` covers Windows.
#[cfg(unix)]
#[test]
fn a_program_runs_through_wsl_exe_with_its_variables_by_name() {
let mut c = config("/work/proj/.venv/bin/python", &["-u", "/work/proj/main.py", "a b"]);
c.cwd = Some(Path::new("/work/proj/src").to_path_buf().into());
c.env.insert("DATA".into(), "/work/proj/data".into());
c.extras.target = Some("t".into());
c.extras.env_files = vec![".env".into()];
let files = BTreeMap::from([("SECRET".to_owned(), "s3".to_owned())]);
let out =
wsl_config(&c, &target(), Path::new("/work/proj"), "/mnt/c/proj", "wsl.exe", &files, Some("USERPROFILE/p"))
.unwrap();
assert_eq!(out.command, "wsl.exe");
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj/src", "--exec", "python3", "-u", "/mnt/c/proj/main.py", "a b"]
);
assert_eq!(out.env["DATA"], "/mnt/c/proj/data");
assert_eq!(out.env["SECRET"], "s3");
assert_eq!(out.env["PYTHONUNBUFFERED"], "1");
assert_eq!(out.env["WSLENV"], "USERPROFILE/p:DATA:PYTHONUNBUFFERED:SECRET");
assert_eq!(out.cwd.as_ref().map(|p| p.to_path_buf()), Some(Path::new("/work/proj").to_path_buf()));
assert_eq!(out.extras.target, None);
assert!(out.extras.env_files.is_empty());
assert!(out.extras.include_system_env);
}
#[test]
fn a_shell_line_runs_in_sh_and_the_targets_interpreter_is_used() {
let mut shell = config("npm run dev", &[]);
shell.kind = "shell".into();
let out =
wsl_config(&shell, &target(), Path::new("proj"), "/mnt/c/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args, ["-d", "Ubuntu-24.04", "--cd", "/mnt/c/proj", "--exec", "sh", "-c", "npm run dev"]);
assert!(!out.env.contains_key("WSLENV"));
let t = RunTarget { python: "/home/me/.venv/bin/python".into(), ..target() };
let out =
wsl_config(&config("python.exe", &["-V"]), &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap();
let path_first = r#"PATH="$0:$PATH" exec "$@""#;
assert_eq!(
&out.args[4..],
["--exec", "sh", "-c", path_first, "/home/me/.venv/bin", "/home/me/.venv/bin/python", "-V"],
"the virtualenv's scripts come first on PATH"
);
let mut pytest = config("pytest", &["tests"]);
pytest.kind = "pytest".into();
let out = wsl_config(&pytest, &t, Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(&out.args[9..], ["pytest", "tests"]);
}
#[test]
fn a_configurations_wslenv_keeps_its_flags_and_an_outside_folder_is_refused() {
let mut c = config("python", &[]);
c.env.insert("WSLENV".into(), "DATA/p".into());
c.env.insert("DATA".into(), "x".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), Some("A/u")).unwrap();
assert_eq!(out.env["WSLENV"], "A/u:DATA/p:PYTHONUNBUFFERED");
c.env.insert("PATH".into(), "/here/bin:/usr/bin".into());
let out = wsl_config(&c, &target(), Path::new("proj"), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert!(!out.env.contains_key("PATH") && !out.env["WSLENV"].contains("PATH"), "{:?}", out.env);
// An absolute folder of this machine outside the project (`/elsewhere` has no `/mnt` path).
let outside = if cfg!(windows) { r"\\server\share\x" } else { "/elsewhere" };
c.cwd = Some(Path::new(outside).to_path_buf().into());
let root = if cfg!(windows) { r"C:\proj" } else { "/proj" };
let err = wsl_config(&c, &target(), Path::new(root), "/p", "wsl.exe", &BTreeMap::new(), None).unwrap_err();
assert!(err.message.contains("can't reach the working folder"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn java_path_lists_are_joined_with_colons() {
let args: Vec<String> = ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"].map(String::from).to_vec();
assert_eq!(linux_path_lists(&args, Path::new("/p"), "Ubuntu"), ["-cp", "out:lib/*", "-p", "/opt/mods", "Main"]);
assert!(is_java("/usr/lib/jvm/bin/java") && is_java(r"C:\jdk\bin\JAVA.EXE") && !is_java("javac"));
}
#[test]
fn printed_paths_lead_back_to_files_here() {
let t = RunTarget { project_root: "/mnt/c/work/proj".into(), ..target() };
let root = Path::new("proj-here");
assert_eq!(local_file("/mnt/c/work/proj/app/main.py", &t, root), Some(root.join("app").join("main.py")));
assert_eq!(
local_file("/mnt/d/lib/x.py", &t, root),
Some(PathBuf::from("D:\\").join("lib").join("x.py")),
"another drive"
);
assert_eq!(
local_file("/usr/lib/python3/dist-packages/a.py", &t, root),
Some(
ide_core::wsl::share_root("Ubuntu-24.04")
.join("usr")
.join("lib")
.join("python3")
.join("dist-packages")
.join("a.py")
)
);
assert_eq!(
local_file("/mnt/c/work/proj2/a.py", &t, root),
Some(PathBuf::from("C:\\").join("work").join("proj2").join("a.py"))
);
assert_eq!(local_file("main.py", &t, root), None);
assert_eq!(local_file("/mnt/c/work/proj/app/../lib/a.py", &t, root), Some(root.join("lib").join("a.py")));
}
#[test]
fn pythons_are_listed_once_and_python3_is_the_default() {
let out = "/usr/bin/python3\n\n/usr/bin/python3\n/usr/bin/python3.12\nsh: 1: bad\n/usr/bin/python3-pytest\n\
/usr/bin/python3.12-config\n/mnt/c/p/.venv/bin/python\r\n";
assert_eq!(parse_pythons(out), ["/usr/bin/python3", "/usr/bin/python3.12", "/mnt/c/p/.venv/bin/python"]);
assert_eq!(python(&target()), "python3");
assert_eq!(python(&RunTarget { python: " /opt/py/bin/python ".into(), ..target() }), "/opt/py/bin/python");
}
// The script itself, in this machine's `sh`.
#[cfg(unix)]
#[test]
fn the_python_finder_lists_a_venv_of_the_project() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join(".venv/bin");
std::fs::create_dir_all(&bin).unwrap();
let python = bin.join("python");
std::fs::write(&python, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&python, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let out = std::process::Command::new("sh").args(["-c", FIND_PYTHONS, "sh"]).arg(dir.path()).output().unwrap();
assert!(out.status.success());
let found = parse_pythons(&String::from_utf8_lossy(&out.stdout));
assert!(found.contains(&python.to_string_lossy().into_owned()), "{found:?}");
assert!(found.iter().all(|p| !p.ends_with("-config")), "{found:?}");
}
#[test]
fn a_target_without_a_valid_distribution_is_refused() {
for distro in ["", " ", "-u root", "a;b"] {
let t = RunTarget { distro: distro.into(), ..target() };
let err = wsl_config(&config("python", &[]), &t, Path::new("p"), "/p", "wsl.exe", &BTreeMap::new(), None)
.unwrap_err();
assert!(err.message.contains("no WSL distribution"), "{distro}: {}", err.message);
}
}
#[cfg(windows)]
#[test]
fn windows_paths_are_mapped() {
let root = Path::new(r"C:\work\proj");
let linux = project_root(&target(), root).unwrap();
let mut c = config(r"C:\work\proj\.venv\Scripts\python.exe", &[r"C:\work\proj\app\main.py"]);
c.cwd = Some(Path::new(r"C:\work\proj\app").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
out.args,
["-d", "Ubuntu-24.04", "--cd", "/mnt/c/work/proj/app", "--exec", "python3", "/mnt/c/work/proj/app/main.py"]
);
let java = config(
r"C:\jdk\bin\java.exe",
&["-cp", r"C:\work\proj\out;D:\m2\a.jar;lib\*", "--module-path", r"C:\work\proj\mods", "app.Main"],
);
let out = wsl_config(&java, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(
&out.args[4..],
[
"--exec",
"java",
"-cp",
"/mnt/c/work/proj/out:/mnt/d/m2/a.jar:lib/*",
"--module-path",
"/mnt/c/work/proj/mods",
"app.Main"
]
);
let custom = RunTarget { project_root: "/home/me/proj".into(), ..target() };
let java = config(r"C:\jdk\bin\java.exe", &["-cp", r"C:\work\proj\out;D:\m2\a.jar", "app.Main"]);
let out = wsl_config(&java, &custom, root, "/home/me/proj", "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[7], "/home/me/proj/out:/mnt/d/m2/a.jar", "project entries go to its folder there");
c.cwd = Some(Path::new(r"D:\data").to_path_buf().into());
let out = wsl_config(&c, &target(), root, &linux, "wsl.exe", &BTreeMap::new(), None).unwrap();
assert_eq!(out.args[3], "/mnt/d/data", "a folder outside the project, through its /mnt path");
}
}
+1
Переглянути файл
@@ -1811,6 +1811,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+39 -5
Переглянути файл
@@ -81,7 +81,11 @@ pub fn folders_to_copy(probe: &Probe, container_root: &str) -> Vec<String> {
/// Where a snapshot in `dir` keeps its copy of the container folder `container`.
pub fn local_folder(dir: &Path, container: &str) -> PathBuf {
container.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(dir.join("fs"), |p, c| p.join(c))
below(dir.join("fs"), container)
}
fn below(base: PathBuf, path: &str) -> PathBuf {
path.split('/').filter(|c| !c.is_empty() && *c != "." && *c != "..").fold(base, |p, c| p.join(c))
}
/// Where a snapshot in `dir` keeps the file `container_path` of its container (a
@@ -91,7 +95,7 @@ pub fn snapshot_file(dir: &Path, snapshot: &Snapshot, container_path: &str) -> O
.folders
.iter()
.any(|f| container_path.strip_prefix(f.trim_end_matches('/')).is_some_and(|rest| rest.starts_with('/')));
(copied && !container_path.split('/').any(|c| c == "..")).then(|| local_folder(dir, container_path))
(copied && !container_path.split('/').any(|c| c == "..")).then(|| snapshot.local(dir, container_path))
}
/// `snapshot.json` of a snapshot folder.
@@ -105,6 +109,21 @@ pub struct Snapshot {
pub folders: Vec<String>,
/// The neutral interpreter given to the language server; `None` without a local Python.
pub neutral_python: Option<PathBuf>,
/// A WSL interpreter's distribution. Its folders are read in place, not copied: on their
/// drive under `/mnt/<drive>`, the rest through `\\wsl.localhost\<distro>`.
#[serde(skip_serializing_if = "Option::is_none")]
pub distro: Option<String>,
}
impl Snapshot {
/// Where this machine reads the interpreter's folder or file `path`.
pub fn local(&self, dir: &Path, path: &str) -> PathBuf {
match &self.distro {
// `..` never climbs above the drive or the distribution's share.
Some(distro) => ide_core::wsl::windows_path(path, distro),
None => local_folder(dir, path),
}
}
}
const SNAPSHOT_FILE: &str = "snapshot.json";
@@ -160,8 +179,11 @@ pub fn make_current(target_dir: &Path, image: &str) -> IdeResult<()> {
}
/// The local folders of a snapshot that exist.
/// A WSL snapshot's folders are taken as they were probed: checking them would read the
/// distribution's file system, which may be slow or still starting.
pub fn local_folders(dir: &Path, snapshot: &Snapshot) -> Vec<PathBuf> {
snapshot.folders.iter().map(|f| local_folder(dir, f)).filter(|p| p.is_dir()).collect()
let folders = snapshot.folders.iter().map(|f| snapshot.local(dir, f));
if snapshot.distro.is_some() { folders.collect() } else { folders.filter(|p| p.is_dir()).collect() }
}
/// basedpyright / pyright: the neutral interpreter and the snapshot's folders as
@@ -189,8 +211,8 @@ pub fn library_group(target_name: &str, dir: &Path, snapshot: &Snapshot) -> Opti
let roots: Vec<LibraryRoot> = snapshot
.folders
.iter()
.map(|f| (f, local_folder(dir, f)))
.filter(|(_, p)| p.is_dir())
.map(|f| (f, snapshot.local(dir, f)))
.filter(|(_, p)| snapshot.distro.is_some() || p.is_dir())
.map(|(f, p)| LibraryRoot { name: f.rsplit('/').next().unwrap_or(f).to_owned(), path: p.into() })
.collect();
(!roots.is_empty()).then(|| LibraryGroup {
@@ -318,6 +340,17 @@ mod tests {
local_folder(dir, "/usr/local/lib/../site-packages"),
Path::new("snap").join("fs").join("usr").join("local").join("lib").join("site-packages")
);
let wsl = Snapshot { distro: Some("U".into()), ..Snapshot::default() };
assert_eq!(
wsl.local(dir, "/usr/lib/python3/dist-packages"),
ide_core::wsl::share_root("U").join("usr").join("lib").join("python3").join("dist-packages"),
"a WSL snapshot reads the distribution in place"
);
assert_eq!(
wsl.local(dir, "/mnt/c/p/.venv/lib"),
PathBuf::from("C:\\").join("p").join(".venv").join("lib"),
"a drive directly"
);
assert_eq!(dir_name("sha256:0123456789abcdef0123"), "0123456789abcdef");
assert_eq!(dir_name("target/../x y"), "target____x_y");
}
@@ -344,6 +377,7 @@ mod tests {
probe: probe(),
folders: vec!["/usr/local/lib/python3.12/site-packages".into(), "/gone".into()],
neutral_python: neutral,
distro: None,
};
let site = local_folder(dir, &snapshot.folders[0]);
std::fs::create_dir_all(site.join("Django-5.1.3.dist-info")).unwrap();
+1
Переглянути файл
@@ -46,6 +46,7 @@ pub(crate) fn server(name: &str) -> LanguageServerConfig {
tsserver_project: false,
tsserver_project_extras: Default::default(),
resync_on_configuration: false,
ignored_progress_token_prefixes: vec![],
display_name: None,
pinned: None,
}
+22
Переглянути файл
@@ -681,6 +681,28 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/laravel/lsp",
needs: &[],
},
ToolSpec {
name: "phpantom",
display: "PHPantom",
kind: LanguageServer,
commands: &["phpantom_lsp"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "PHPantom-dev/phpantom_lsp" },
assets: &[
rule(Mac, Arm64, "phpantom_lsp-aarch64-apple-darwin.tar.gz"),
rule(Mac, X64, "phpantom_lsp-x86_64-apple-darwin.tar.gz"),
rule(Linux, Arm64, "phpantom_lsp-aarch64-unknown-linux-gnu.tar.gz"),
rule(Linux, X64, "phpantom_lsp-x86_64-unknown-linux-gnu.tar.gz"),
rule(Windows, Arm64, "phpantom_lsp-aarch64-pc-windows-msvc.zip"),
rule(Windows, X64, "phpantom_lsp-x86_64-pc-windows-msvc.zip"),
],
locate: &["phpantom_lsp"],
},
fallback: None,
version: ver("phpantom_lsp"),
homepage: "https://github.com/PHPantom-dev/phpantom_lsp",
needs: &[],
},
ToolSpec {
name: "phoxite",
display: "Phoxite",
+8
Переглянути файл
@@ -190,6 +190,7 @@ fn everything_missing_on_an_empty_system() {
#[test]
fn interchangeable_servers_list_their_alternatives() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 1");
let list = env.tools().list(&langs());
let python = ["basedpyright", "pyright", "ty", "pyrefly"];
for name in python {
@@ -203,6 +204,13 @@ fn interchangeable_servers_list_their_alternatives() {
for name in ["kotlin-lsp", "kotlin-language-server"] {
assert_eq!(find(&list, name).alternatives, ["kotlin-lsp", "kotlin-language-server", "kmp-lsp"]);
}
let php = ["intelephense", "phpantom", "phpactor", "phoxite", "devsense-php-ls"];
for name in php {
assert_eq!(find(&list, name).alternatives, php);
}
let phpantom = find(&list, "phpantom");
assert!(phpantom.can_install, "{:?}", phpantom.unavailable_reason);
assert!(find(&list, "laravel-lsp").alternatives.is_empty());
// A regular server after a fallback starts no group with it.
assert!(find(&list, "angular-language-server").alternatives.is_empty());
assert!(find(&list, "ruff").alternatives.is_empty());
+37 -3
Переглянути файл
@@ -15,6 +15,12 @@ const MAX_DEPTH: usize = 4;
/// Folders never searched for nested repositories (dependencies, build output).
const SKIPPED: &[&str] = &["node_modules", "target", "build", "dist", "out", "vendor", "venv", "__pycache__"];
/// A folder the nested-repository search neither looks at nor descends into.
fn not_searched(path: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
let name = path.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(path)
}
/// The repositories of a project, sorted by root; lookups pick the innermost one.
#[derive(Clone, Default)]
pub struct Repos {
@@ -46,6 +52,18 @@ impl Repos {
Ok(Self { repos, primary })
}
/// Whether [`Self::discover`] from `project_root` looks for a repository at `dir`, below it.
pub fn searched(project_root: &Path, dir: &Path, skip: &dyn Fn(&Path) -> bool) -> bool {
let Ok(rel) = dir.strip_prefix(project_root) else { return false };
let depth = rel.components().count();
let mut path = project_root.to_path_buf();
(1..=MAX_DEPTH).contains(&depth)
&& rel.components().all(|c| {
path.push(c);
!not_searched(&path, skip)
})
}
/// The repository containing `project_root` and every repository whose worktree
/// root lies below it (up to [`MAX_DEPTH`] levels; hidden and dependency folders and
/// folders `skip` rejects are not searched).
@@ -61,10 +79,8 @@ impl Repos {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let name = entry.file_name();
let name = name.to_string_lossy();
let path = entry.path();
if name.starts_with('.') || SKIPPED.contains(&name.as_ref()) || skip(&path) {
if not_searched(&path, skip) {
continue;
}
if path.join(".git").exists()
@@ -350,6 +366,24 @@ mod tests {
assert!(ok, "git {args:?}");
}
#[test]
fn searched_matches_what_discover_finds() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
git_init(&root);
let dirs = ["a", "a/b/c/d", "a/b/c/d/e", ".hidden/x", "vendor/x", "skipped/x", "a/skipped/x"];
for dir in dirs {
git_init(&root.join(dir));
}
let skip = |p: &Path| p.file_name().is_some_and(|n| n == "skipped");
let found = Repos::discover(&root, &skip).unwrap().roots();
for dir in dirs {
let dir = root.join(dir);
assert_eq!(Repos::searched(&root, &dir, &skip), found.contains(&dir), "{}", dir.display());
}
assert!(!Repos::searched(&root, &root, &skip), "the project root itself is no nested repository");
}
#[test]
fn ignored_files_use_git_rules_without_listing_other_repositories_twice() {
let tmp = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -79,6 +79,8 @@ Use the executable path from **Copy Stdio Config**; the macOS path above is only
OpenIDEA must be running for the tools to work, and the project must be open in a window or served as a [background project](#background-projects). A client may name any folder inside such a project, and the server picks the innermost project that contains it, whether a window has it open or it is served in the background. A project served in the background inside a project open in a window answers for its own folders, so relative paths in a call are relative to its root. For example, with **Trusted projects** a repository inside a trusted location, a Git submodule among them, loads as a background project of its own when a call names its folder, even while a window has the project around it open. HTTP clients name it with the `X-OpenIDEA-Project` header or the `?project=` query.
A client started in a folder outside every project, such as a folder that only holds repositories, still gets the tools. Each call then names its project with `projectPath`, and the server refuses a call without one.
While the server runs, OpenIDEA writes its port and token to `mcp/server.json` in its application data directory (readable only by you); the stdio bridge reads it from there.
## Tools
@@ -175,7 +177,7 @@ A background project has no window, so some tools differ:
## Safety
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted.
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up.
- Tools that write refuse paths outside the project.
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
+11
Переглянути файл
@@ -145,6 +145,17 @@ The **Ports** tool window is available in a WSL window too. Because the distribu
`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it
does for SSH.
### Run a Windows project in WSL
A project on the Windows file system can keep its local window and run its configurations in a distribution: in
**Settings › Build, Execution, Deployment › Run Targets**, add a target of **Type** **WSL** (offered when a
distribution is installed) and pick the **WSL distribution**. A configuration with that target under **Run on** runs as
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>`. Project paths become their `/mnt/<drive>`
paths (`C:\work\app` is `/mnt/c/work/app`); set **Project folder in WSL** when the distribution mounts drives
elsewhere. Interpreters left empty are looked up on the distribution's `PATH` (`python3`, `node`, `java`). Environment
variables reach the distribution through `WSLENV`. Debugging, coverage and profiling are not available on a WSL
target.
## Other uses of SSH configurations
- **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See
+8
Переглянути файл
@@ -68,6 +68,14 @@ When the project's dependencies are installed only in an image, choose a Docker
A `pyrightconfig.json` or a `[tool.basedpyright]` / `[tool.pyright]` section with its own `extraPaths` replaces the copied paths. The interpreter's Python version is the empty virtualenv's, from a local Python of the same version when there is one.
### A Python in WSL as the interpreter
On Windows with WSL, **Add Python Interpreter** has a **WSL** entry: pick the **Distribution** and the **Python interpreter** (the ones found on its `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's `.venv` / `venv`; another path can be typed). **OK** adds a WSL [run target](/en/guide/remote/ssh#run-a-windows-project-in-wsl) with that Python and makes it the project interpreter.
- **Editor.** The IDE runs that Python once in the distribution to read its `sys.path`. basedpyright and Pyright read those folders in place through `\\wsl.localhost\<distribution>` (nothing is copied), with an empty local virtualenv as their interpreter, as for a Docker target. They are shown under **External Libraries**.
- **Run.** Python run configurations without a run target of their own run in the distribution.
- **Packages.** The list is read-only: install packages in WSL, then reload it.
### Creating an environment
On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add Python Interpreter** and pick the **Interpreter type**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
The dialog and the plugin's details in **Settings › Plugins** show it below the IDE's description, marked as the plugin's own words; it never replaces that description. Keys must be capabilities listed under `required` or `optional`, or ones a contribution brings (`java.agent` from `[[contributes.javaAgents]]`, `project.read` from `[[contributes.documentIndexers]]`), and each reason is 1 to 500 characters. Translate it like the plugin's other strings, with the English text as the key in `locales/<tag>.json`.
When code finds an optional capability refused, `host::open_permissions()` opens **Settings › Plugins** at the plugin's permissions, so a notice can offer a button that goes straight there (from a command or event only).
+3 -1
Переглянути файл
@@ -78,6 +78,8 @@ stdio 配置大致如下(路径以你机器上的为准):
工具只在 OpenIDEA 运行,且项目已在窗口中打开或作为[后台项目](#后台项目)提供服务时可用。客户端可以指定这类项目中的任意目录,服务器会选出包含它的最内层项目,无论该项目在窗口中打开还是作为后台项目提供服务。位于窗口项目之内的后台项目负责它自己的目录,调用中的相对路径以它的根目录为准。例如在 **受信任的项目** 模式下,受信任位置中的仓库(包括 Git 子模块)在调用指定它的目录时会作为单独的后台项目加载,即使外层项目已在窗口中打开。HTTP 客户端通过 `X-OpenIDEA-Project` 请求头或 `?project=` 查询参数指定项目。
如果客户端在所有项目之外的目录中启动,例如只存放仓库的目录,它仍能拿到工具。此时每次调用都要用 `projectPath` 指定项目,服务器会拒绝没有指定项目的调用。
服务器运行期间,OpenIDEA 会把端口和令牌写入应用数据目录下的 `mcp/server.json`(只有你自己可读),stdio 转发程序从这里读取。
## 工具
@@ -174,7 +176,7 @@ stdio 配置大致如下(路径以你机器上的为准):
## 安全
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。
- 会写入的工具拒绝项目之外的路径。
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
+8
Переглянути файл
@@ -114,6 +114,14 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或
WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。
### 在 WSL 中运行 Windows 项目
位于 Windows 文件系统上的项目可以保留本地窗口,把运行配置放到发行版中运行:在**设置 › 构建、执行、部署 › 运行目标**中添加
**类型**为 **WSL** 的目标(装有发行版时才会出现),并选择 **WSL 发行版**。在**运行于**中选了该目标的配置,会以
`wsl.exe -d <distribution> --cd <folder> --exec <program> <arguments>` 运行。项目路径换成对应的 `/mnt/<盘符>` 路径
(`C:\work\app` 对应 `/mnt/c/work/app`);发行版把磁盘挂载在别处时,请填写 **WSL 中的项目文件夹**。留空的解释器从发行版的
`PATH` 查找(`python3`、`node`、`java`)。环境变量通过 `WSLENV` 传入发行版。WSL 目标不支持调试、覆盖率和性能分析。
## SSH 配置的其他用途
- **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。
+8
Переглянути файл
@@ -68,6 +68,14 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
如果 `pyrightconfig.json` 或 `[tool.basedpyright]` / `[tool.pyright]` 设置了自己的 `extraPaths`,它们会取代复制的路径。解释器的 Python 版本取自空虚拟环境;本机有相同版本的 Python 时会用它来创建。
### 以 WSL 中的 Python 作为解释器
在装有 WSL 的 Windows 上,**添加 Python 解释器**中有 **WSL** 一项:选择**发行版**和 **Python 解释器**(列出其 `PATH` 上、`/usr/bin` 和 `/usr/local/bin` 中、pyenv 的,以及项目 `.venv` / `venv` 中的 Python;也可以输入其他路径)。点击**确定**后会添加一个使用该 Python 的 WSL [运行目标](/zh/guide/remote/ssh#在-wsl-中运行-windows-项目),并将其设为项目解释器。
- **编辑器。** IDE 在发行版中运行一次该 Python 来读取其 `sys.path`。basedpyright 和 Pyright 通过 `\\wsl.localhost\<发行版>` 直接读取这些文件夹(不复制),解释器与 Docker 目标一样是一个本地的空虚拟环境。这些文件夹显示在**外部库**下。
- **运行。** 没有设置自己运行目标的 Python 运行配置会在该发行版中运行。
- **软件包。** 列表只读:请在 WSL 中安装软件包,然后重新加载列表。
### 创建环境
在 **设置 › 语言和框架 › Python 解释器** 中选择 **添加 Python 解释器**,再选 **解释器类型**:
+1 -1
Переглянути файл
@@ -35,7 +35,7 @@ optional = ["net:127.0.0.1", "clipboard.read"]
"clipboard.read" = "Imports a log you copied, on the Log to SQL tab only."
```
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
授权对话框和 **设置 › 插件** 的插件详情会把这句话显示在 IDE 说明的下方,并标明是插件自己的说法;它不会替换 IDE 的说明。键必须是 `required` 或 `optional` 里列出的能力,或者由贡献点带来的能力(`[[contributes.javaAgents]]` 带来的 `java.agent`、`[[contributes.documentIndexers]]` 带来的 `project.read`),每条 1 到 500 个字符。翻译方式与插件的其他字符串相同:在 `locales/<tag>.json` 里以英文原文为键。
代码发现某个 optional 能力被拒绝时,可以调用 `host::open_permissions()` 打开 **设置 › 插件** 并定位到本插件的权限,这样通知里可以放一个直接跳过去的按钮(仅限命令或事件中调用)。
+54
Переглянути файл
@@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
let configuredAccount = "";
const status = (): GhProjectAccountStatus => ({
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount,
effectiveAccount: configuredAccount || "alice",
suggestedAccount: configuredAccount ? null : "alice-work",
});
Object.assign(window.__ipc.handlers, {
vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }),
vcs_remote: () => {
throw {
kind: "invalid",
message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found",
};
},
gh_project_account_status: () => status(),
gh_set_project_account: ({ account }: { account: string }) => {
configuredAccount = account;
return status();
},
settings_get_global: () => ({}),
window_open_settings: () => {
throw { kind: "unavailable", message: "separate settings window disabled in browser test" };
},
});
const opsModule = "/src/features/vcs/ops.ts";
const { runRemote } = await import(/* @vite-ignore */ opsModule);
await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]);
});
await expect(page.getByText("Update failed", { exact: true })).toBeVisible();
await expect(page.getByText(/Repository not found/)).toBeVisible();
await expect(page.getByText(/alice may not have access/)).toBeVisible();
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]);
const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true });
await expect(settingsLink).toBeVisible();
if (process.env.CAPTURE_GH_AUTH_FAILURE) {
await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" });
}
await settingsLink.click();
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)");
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work");
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
});
test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({
workbench: page,
}) => {
+9 -14
Переглянути файл
@@ -63,14 +63,13 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
const location = panel.getByText(directory, { exact: true });
await expect.poll(() => location.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
const divider = panel.getByRole("separator", { name: "Resize shelf panes" });
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
const files = panel.getByRole("tree", { name: "Shelved files" });
await expect(files.getByRole("treeitem")).toHaveCount(2);
const pathBox = (await location.boundingBox())!;
const filesBox = (await files.boundingBox())!;
expect(pathBox.x).toBeLessThan(filesBox.x + filesBox.width - 50);
const files = patches;
await expect(patches.getByRole("treeitem").filter({ hasText: filename })).toHaveCount(1);
const row = files.getByRole("treeitem").filter({ hasText: filename });
const nameBox = (await row.getByText(filename, { exact: true }).boundingBox())!;
const pathBox = (await location.boundingBox())!;
expect(pathBox.x).toBeGreaterThan(nameBox.x + nameBox.width);
expect(Math.abs(pathBox.y + pathBox.height - nameBox.y - nameBox.height)).toBeLessThan(3);
await row.click({ position: { x: 90, y: 12 } });
await expect(row).toHaveAttribute("aria-selected", "true");
await panel.getByRole("button", { name: "Unshelve…", exact: true }).click();
@@ -81,13 +80,9 @@ test("Shelf keeps patch and file selection available in a narrow dock", async ({
await expect(dialog.getByText("README.md", { exact: true })).toHaveCount(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await page.evaluate(async () => {
const dock = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ dock)).setToolWindowSize("left", 640);
});
await expect(divider).toHaveAttribute("aria-orientation", "vertical");
await expect(row).toHaveAttribute("aria-selected", "true");
await patches.getByRole("treeitem").filter({ hasText: "Update release notes" }).click();
await expect(files.getByRole("treeitem")).toHaveCount(1);
const other = patches.getByRole("treeitem").filter({ hasText: "Update release notes" });
await other.click();
if ((await other.getAttribute("aria-expanded")) === "false") await page.keyboard.press("ArrowRight");
await expect(files.getByText("CHANGELOG.md", { exact: true })).toBeVisible();
});
+2 -1
Переглянути файл
@@ -51,7 +51,8 @@ with tempfile.TemporaryDirectory() as scratch:
"##teamcity[testFailed name='fails' className='sample.SampleTest' message='org.opentest4j.AssertionFailedError: it|'s wrong ==> expected: <1> but was: <2>'",
"##teamcity[testIgnored name='disabled' className='sample.SampleTest'",
"##teamcity[testIgnored name='aborted' className='sample.SampleTest']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest'",
"##teamcity[testStarted name='parameterized' className='sample.SampleTest' invocation='|[1|] 1']",
"##teamcity[testFailed name='parameterized' className='sample.SampleTest' invocation='|[2|] 2'",
"##teamcity[testFinished name='nested' className='sample.SampleTest$Inner' duration=",
"7 tests completed, 2 failed, 2 skipped",
]
Бінарний файл не відображається.
+14 -7
Переглянути файл
@@ -153,18 +153,25 @@ final class PlatformRunner implements TestExecutionListener {
for (Output o : outputs) o.flushLines(true);
}
/** `name='method' className='a.B$Nested'`, the method and class of the test or its closest source. */
/**
* `name='method' className='a.B$Nested'`, the method and class of the test or its closest source;
* an invocation of a parameterized, repeated or dynamic test adds `invocation='[1] a'`, its display name.
*/
private String id(TestIdentifier id) {
// The outermost method of the chain: the test itself, or the method container of its invocations.
TestIdentifier method = null;
for (TestIdentifier at = id; at != null; at = plan.getParent(at).orElse(null)) {
TestSource source = at.getSource().orElse(null);
if (source instanceof MethodSource) {
MethodSource m = (MethodSource) source;
return Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
}
if (source instanceof ClassSource)
if (source instanceof MethodSource) method = at;
else if (method != null) break;
else if (source instanceof ClassSource)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", ((ClassSource) source).getClassName());
}
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
if (method == null)
return Reporter.attr("name", id.getLegacyReportingName()) + Reporter.attr("className", id.getDisplayName());
MethodSource m = (MethodSource) method.getSource().get();
String own = Reporter.attr("name", m.getMethodName()) + Reporter.attr("className", m.getClassName());
return method == id ? own : own + Reporter.attr("invocation", id.getDisplayName());
}
private Optional<String> className(TestIdentifier id) {
+1
Переглянути файл
@@ -10,6 +10,7 @@ const config: KnipConfig = {
"!src/editor/core/cm/jsp/parser.terms.ts",
"!src/editor/core/cm/astro/parser.terms.ts",
"!src/editor/core/cm/django/parser.terms.ts",
"!src/editor/core/cm/freemarker/parser.terms.ts",
"scripts/**/*.ts",
"perf/**/*.ts",
"evals/**/*.ts",
+10
Переглянути файл
@@ -17,6 +17,16 @@ install-hint = "npm i -g intelephense"
# Intelephense applies the PHP version only to documents it parses after reading it.
resync-on-configuration = true
[[language-servers]]
name = "phpantom"
# PHPantom 1.1.0 can cancel these operations without ending server-created progress.
ignored-progress-token-prefixes = ["find_references", "goto_implementation"]
fallback = true
command = "phpantom_lsp"
args = []
root-markers = ["composer.json", "index.php"]
install-hint = "Install PHPantom in Settings › Languages & Frameworks › Language Servers"
[[language-servers]]
name = "phpactor"
# Alternative: used only when the server above is not installed.
+1
Переглянути файл
@@ -23,6 +23,7 @@
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
"gen:jsp-grammar": "lezer-generator src/editor/core/cm/jsp/jsp.grammar --typeScript -o src/editor/core/cm/jsp/parser.ts",
"gen:django-grammar": "lezer-generator src/editor/core/cm/django/django.grammar --typeScript -o src/editor/core/cm/django/parser.ts",
"gen:freemarker-grammar": "lezer-generator src/editor/core/cm/freemarker/freemarker.grammar --typeScript -o src/editor/core/cm/freemarker/parser.ts",
"gen:astro-grammar": "lezer-generator src/editor/core/cm/astro/astro.grammar --typeScript -o src/editor/core/cm/astro/parser.ts",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
"gen:plugin-catalog": "node scripts/gen-plugin-catalog.ts",
+4
Переглянути файл
@@ -72,6 +72,10 @@ ide-android = { path = "../crates/ide-android" }
[dev-dependencies]
tempfile.workspace = true
[[test]]
name = "background_tab_appkit"
harness = false
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6"
# Plugin secrets in the login keychain.
+4
Переглянути файл
@@ -0,0 +1,4 @@
disallowed-methods = [
{ path = "tauri::webview::WebviewWindow::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
{ path = "tauri::webview::Webview::with_webview", reason = "panics on a detached background tab on macOS; use macos::with_web_view" },
]
+71
Переглянути файл
@@ -0,0 +1,71 @@
//! AppKit side of a background tab's detached web view; no tauri types, so a test can include it.
use objc2::{
Message,
rc::Retained,
runtime::{AnyClass, ProtocolObject},
};
use objc2_app_kit::{
NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowDidChangeOcclusionStateNotification,
NSWindowOcclusionState, NSWindowOrderingMode,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Return {
Key,
Visible,
}
pub fn web_view(native: &NSWindow) -> Option<Retained<NSView>> {
let class = AnyClass::get(c"WKWebView")?;
native.contentView()?.subviews().iter().find(|v| v.isKindOfClass(class))
}
/// At the bottom so the title bar views stay above it.
pub fn put_back(native: &NSWindow, view: &NSView) {
let Some(content) = native.contentView() else { return };
view.setFrame(content.bounds());
content.addSubview_positioned_relativeTo(view, NSWindowOrderingMode::Below, None);
native.makeFirstResponder(Some(view));
}
/// Calls `f` when the window becomes key, or visible (AppKit can bring a window back by itself,
/// e.g. when a tab it closes next to leaves the group). The observers have no queue, so `f` runs
/// synchronously inside the post. For the key notification that is inside `makeKeyWindow`, before the
/// window's first display; occlusion arrives when the window is already on screen.
pub fn on_return(
native: &NSWindow,
f: impl Fn(Return) + 'static,
) -> Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>> {
let f = std::rc::Rc::new(f);
let center = NSNotificationCenter::defaultCenter();
let key = {
let f = f.clone();
let block = block2::RcBlock::new(move |_| f(Return::Key));
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidBecomeKeyNotification),
Some(native),
None,
&block,
)
}
};
let visible = {
let window: Retained<NSWindow> = native.retain();
let block = block2::RcBlock::new(move |_| {
if window.occlusionState().contains(NSWindowOcclusionState::Visible) {
f(Return::Visible);
}
});
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(NSWindowDidChangeOcclusionStateNotification),
Some(native),
None,
&block,
)
}
};
vec![key, visible]
}
+3 -3
Переглянути файл
@@ -170,9 +170,9 @@ async fn webview_processes(app: &AppHandle, state: &AppState) -> Vec<MemoryRoot>
let mut pending = Vec::new();
for (label, w) in app.webview_windows() {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = w.with_webview(move |pv| {
// SAFETY: `with_webview` runs on the main thread with the live WKWebView.
let _ = tx.send(unsafe { memory::webkit_process_ids(pv.inner()) });
let sent = crate::macos::with_web_view(&w, move |view| {
// SAFETY: runs on the main thread with the live WKWebView, detached or not.
let _ = tx.send(unsafe { memory::webkit_process_ids(view) });
});
if sent.is_ok() {
pending.push((label, rx));
+1
Переглянути файл
@@ -233,6 +233,7 @@ pub fn window_flash_taskbar(window: WebviewWindow, flash: bool) -> IdeResult<()>
#[specta::specta]
pub fn window_set_smooth_scrolling(window: WebviewWindow, enabled: bool) -> IdeResult<()> {
#[cfg(target_os = "linux")]
#[allow(clippy::disallowed_methods)]
window
.with_webview(move |platform| crate::linux_webkit::set_smooth_scrolling(&platform, enabled))
.map_err(|e| IdeError::internal(e.to_string()))?;
+3
Переглянути файл
@@ -7,6 +7,8 @@
#![recursion_limit = "512"]
mod application_focus;
#[cfg(target_os = "macos")]
mod background_tab;
mod cli;
mod commands;
#[cfg(debug_assertions)]
@@ -308,6 +310,7 @@ pub fn run() {
#[cfg(target_os = "macos")]
{
page_swipe::forget(window.label());
macos::forget_background(window.label());
titlebar::forget(window);
}
if windows::auxiliary_parent(window.label()).is_none() {
+1
Переглянути файл
@@ -91,6 +91,7 @@ pub fn smooth_scrolling_plugin() -> tauri::plugin::TauriPlugin<tauri::Wry> {
let enabled = webview
.try_state::<crate::state::AppState>()
.is_some_and(|s| s.global_settings.effective().appearance.smooth_scrolling);
#[allow(clippy::disallowed_methods)]
let _ = webview.with_webview(move |platform| set_smooth_scrolling(&platform, enabled));
})
.build()
+242 -3
Переглянути файл
@@ -1,15 +1,101 @@
//! macOS project tabs: native window tab groups behind the page's own tab bar.
use crate::background_tab::{self, Return};
use crate::windows::{Launch, WindowsState};
use ide_core::{IdeError, IdeResult};
use ide_workspace::window_groups::{TabbingPreference, should_group_new_project};
use objc2::{
MainThreadMarker,
rc::Retained,
runtime::{AnyClass, AnyObject, Imp, Sel},
runtime::{AnyClass, AnyObject, Imp, ProtocolObject, Sel},
};
use objc2_app_kit::{
NSApplication, NSView, NSWindow, NSWindowOcclusionState, NSWindowOrderingMode, NSWindowStyleMask,
NSWindowUserTabbingPreference,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol, NSOperationQueue};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
ffi::c_void,
time::Duration,
};
use objc2_app_kit::{NSWindow, NSWindowUserTabbingPreference};
use tauri::{AppHandle, Manager, WebviewWindow};
/// WebKit frees a page's graphics 10 s and its caches 2 min after the page leaves its window.
const DETACH_BACKGROUND_TAB_AFTER: Duration = Duration::from_secs(30);
enum Background<V> {
Pending(u64),
Detached(V),
}
struct BackgroundTabs<V> {
next: u64,
tabs: HashMap<String, Background<V>>,
}
impl<V> Default for BackgroundTabs<V> {
fn default() -> Self {
Self { next: 0, tabs: HashMap::new() }
}
}
impl<V> BackgroundTabs<V> {
/// None when the label already has an entry: a repeated select must not restart the clock.
fn schedule(&mut self, label: &str) -> Option<u64> {
if self.tabs.contains_key(label) {
return None;
}
self.next += 1;
self.tabs.insert(label.to_string(), Background::Pending(self.next));
Some(self.next)
}
fn due(&self, label: &str, generation: u64) -> bool {
matches!(self.tabs.get(label), Some(Background::Pending(g)) if *g == generation)
}
fn detached(&mut self, label: &str, view: V) {
self.tabs.insert(label.to_string(), Background::Detached(view));
}
fn cancel(&mut self, label: &str) {
self.tabs.remove(label);
}
fn view(&self, label: &str) -> Option<&V> {
match self.tabs.get(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
/// Also cancels a pending detach.
fn attach(&mut self, label: &str) -> Option<V> {
match self.tabs.remove(label) {
Some(Background::Detached(view)) => Some(view),
_ => None,
}
}
}
struct DetachedView {
view: Retained<NSView>,
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
impl Drop for DetachedView {
fn drop(&mut self) {
for observer in &self.observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
}
}
thread_local! {
static BACKGROUND: RefCell<BackgroundTabs<DetachedView>> = RefCell::new(BackgroundTabs::default());
}
fn tabbing_preference(app: &AppHandle) -> IdeResult<TabbingPreference> {
fn read(mtm: MainThreadMarker) -> TabbingPreference {
match NSWindow::userTabbingPreference(mtm) {
@@ -83,6 +169,101 @@ fn same_group(a: &NSWindow, b: &NSWindow) -> bool {
}
}
fn schedule_detach(window: &WebviewWindow) {
// The debug-only MCP bridge calls `with_webview` directly, which panics on a detached view.
if cfg!(debug_assertions) {
return;
}
let Some(generation) = BACKGROUND.with_borrow_mut(|tabs| tabs.schedule(window.label())) else { return };
let target = window.clone();
tauri::async_runtime::spawn(async move {
tokio::time::sleep(DETACH_BACKGROUND_TAB_AFTER).await;
let window = target.clone();
let _ = window.run_on_main_thread(move || detach_if_background(&target, generation));
});
}
fn detach_if_background(window: &WebviewWindow, generation: u64) {
if !BACKGROUND.with_borrow(|tabs| tabs.due(window.label(), generation)) {
return;
}
let Some(native) = native(window) else { return };
// A visible window is never a background tab.
if native.occlusionState().contains(NSWindowOcclusionState::Visible) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
}
// An inactive app's full-screen group can be mid-transition, where AppKit has crashed (#6937): wait for activation.
let inactive = MainThreadMarker::new().is_some_and(|mtm| !NSApplication::sharedApplication(mtm).isActive());
if inactive && native.styleMask().contains(NSWindowStyleMask::FullScreen) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
schedule_detach(window);
return;
}
let view = (|| {
let group = native.tabGroup()?;
let selected = group.selectedWindow()?;
let background = group.windows().count() > 1
&& !std::ptr::eq(Retained::as_ptr(&selected), native)
&& native.attachedSheet().is_none();
background.then(|| background_tab::web_view(native)).flatten()
})();
let Some(view) = view else {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(window.label()));
return;
};
view.removeFromSuperview();
let target = window.clone();
let observers = background_tab::on_return(native, move |why| {
attach_for(&target, if why == Return::Key { "key" } else { "visible" }, true)
});
BACKGROUND.with_borrow_mut(|tabs| tabs.detached(window.label(), DetachedView { view, observers }));
}
/// Puts a detached web view back and cancels a pending detach.
pub fn attach(window: &WebviewWindow) {
attach_for(window, "select", false);
}
fn attach_for(window: &WebviewWindow, reason: &str, from_observer: bool) {
let Some(detached) = BACKGROUND.with_borrow_mut(|tabs| tabs.attach(window.label())) else {
return;
};
if let Some(native) = native(window) {
background_tab::put_back(native, &detached.view);
tracing::debug!(label = window.label(), reason, "re-attached background tab web view");
}
if from_observer {
// Dropping removes the observer whose block is running; wait until the post returns.
let detached = Cell::new(Some(detached));
let block = block2::RcBlock::new(move || drop(detached.take()));
unsafe { NSOperationQueue::mainQueue().addOperationWithBlock(&block) };
}
}
/// Calls `f` on the main thread with the window's `WKWebView`, attached or not.
/// tauri's webview size/position APIs (`core:webview:default` grants `webview_size`/`webview_position`) unwrap
/// `superview()` in wry and are not safe while a tab is detached.
pub fn with_web_view(window: &WebviewWindow, f: impl FnOnce(*mut c_void) + Send + 'static) -> tauri::Result<()> {
let target = window.clone();
window.run_on_main_thread(move || {
// On the main thread tauri handles with_webview synchronously, so the tab cannot be detached between
// the check and the call; wry's with_webview panics on a windowless view.
let detached = BACKGROUND.with_borrow(|tabs| tabs.view(target.label()).map(|d| Retained::as_ptr(&d.view)));
match detached {
Some(view) => f(view as *mut c_void),
None => {
#[allow(clippy::disallowed_methods)]
let _ = target.with_webview(move |w| f(w.inner()));
}
}
})
}
pub fn forget_background(label: &str) {
BACKGROUND.with_borrow_mut(|tabs| tabs.cancel(label));
}
/// Adds `members` to the existing anchor's native tab group and shows `selected`.
pub fn sync_tab_group(
members: Vec<WebviewWindow>,
@@ -99,14 +280,18 @@ pub fn sync_tab_group(
if let Some(window) = native(member)
&& !same_group(anchor_window, window)
{
anchor_window.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
anchor_window.addTabbedWindow_ordered(window, NSWindowOrderingMode::Above);
}
}
attach(&target);
if let Some(group) = shown.tabGroup() {
group.setSelectedWindow(Some(shown));
}
shown.makeKeyAndOrderFront(None);
for member in &members {
if member.label() != target.label() {
schedule_detach(member);
}
if let Some(window) = native(member) {
hide_tab_bar(window);
}
@@ -129,6 +314,7 @@ pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
on_main(window, move || {
let Some(native) = native(&target) else { return };
attach(&target);
if native.tabbedWindows().is_some_and(|tabs| tabs.count() > 1) {
native.moveTabToNewWindow(None);
}
@@ -226,3 +412,56 @@ pub fn native_modal_open() -> bool {
let application = objc2_app_kit::NSApplication::sharedApplication(mtm);
application.modalWindow().is_some() || application.windows().iter().any(|window| window.attachedSheet().is_some())
}
#[cfg(test)]
mod tests {
use super::BackgroundTabs;
#[test]
fn repeated_schedule_keeps_the_first_generation() {
let mut tabs = BackgroundTabs::<u32>::default();
let first = tabs.schedule("a").unwrap();
assert_eq!(tabs.schedule("a"), None);
assert!(tabs.due("a", first));
}
#[test]
fn attach_cancels_a_pending_detach() {
let mut tabs = BackgroundTabs::<u32>::default();
let generation = tabs.schedule("a").unwrap();
assert_eq!(tabs.attach("a"), None);
assert!(!tabs.due("a", generation));
}
#[test]
fn stale_generation_is_not_due_after_reschedule() {
let mut tabs = BackgroundTabs::<u32>::default();
let stale = tabs.schedule("a").unwrap();
tabs.attach("a");
let fresh = tabs.schedule("a").unwrap();
assert_ne!(stale, fresh);
assert!(!tabs.due("a", stale));
assert!(tabs.due("a", fresh));
}
#[test]
fn view_is_only_there_while_detached() {
let mut tabs = BackgroundTabs::<&'static str>::default();
tabs.schedule("a").unwrap();
assert_eq!(tabs.view("a"), None);
tabs.detached("a", "view");
assert_eq!(tabs.view("a"), Some(&"view"));
tabs.attach("a");
assert_eq!(tabs.view("a"), None);
}
#[test]
fn attach_returns_the_detached_view_once() {
let mut tabs = BackgroundTabs::<&'static str>::default();
let generation = tabs.schedule("a").unwrap();
tabs.detached("a", "view");
assert!(!tabs.due("a", generation));
assert_eq!(tabs.attach("a"), Some("view"));
assert_eq!(tabs.attach("a"), None);
}
}
+4 -3
Переглянути файл
@@ -33,9 +33,10 @@ fn stroke(window: &WebviewWindow, right: bool) {
pub fn install(window: &WebviewWindow) {
let target = window.clone();
let _ = window.with_webview(move |webview| {
let view = unsafe { Retained::retain(webview.inner().cast::<NSView>()).unwrap() };
let native = webview.ns_window() as usize;
let _ = crate::macos::with_web_view(window, move |webview| {
let view = unsafe { Retained::retain(webview.cast::<NSView>()).unwrap() };
let Ok(native) = target.ns_window() else { return };
let native = native as usize;
let window = target.clone();
let block = block2::RcBlock::new(move |event: NonNull<NSEvent>| {
let event = unsafe { event.as_ref() };
+5 -3
Переглянути файл
@@ -458,10 +458,12 @@ fn track(window: &NSWindow, app: &tauri::AppHandle) -> Tracked {
pub fn set_height(window: &tauri::WebviewWindow, height: f64) -> tauri::Result<()> {
let label = window.label().to_owned();
let app = window.app_handle().clone();
// with_webview runs on the AppKit thread.
window.with_webview(move |webview| unsafe {
let target = window.clone();
// The window's own handle works while a background tab's web view is detached.
window.run_on_main_thread(move || unsafe {
let Some(mtm) = MainThreadMarker::new() else { return };
let native = &*webview.ns_window().cast::<NSWindow>();
let Ok(native) = target.ns_window() else { return };
let native = &*native.cast::<NSWindow>();
let (state, buttons, strip) = WINDOWS.with_borrow_mut(|windows| {
let tracked = windows.entry(label).or_insert_with(|| track(native, &app));
tracked.height.set(height);
+2 -2
Переглянути файл
@@ -2764,8 +2764,8 @@ fn disable_macos_text_input_selection_updates(preferences: &objc2_web_kit::WKPre
/// suppresses the affordance even if `NSTextInputContext` queries the view directly.
#[cfg(target_os = "macos")]
fn suppress_window_writing_tools_affordance(window: &WebviewWindow) {
let _ = window.with_webview(|webview| unsafe {
let ptr = webview.inner().cast::<objc2::runtime::AnyObject>();
let _ = crate::macos::with_web_view(window, |webview| unsafe {
let ptr = webview.cast::<objc2::runtime::AnyObject>();
if !ptr.is_null() {
let cls = (*ptr).class();
suppress_webview_class_writing_tools_affordance(cls);
+1
Переглянути файл
@@ -11,6 +11,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
plugin::Builder::new("webview-keys").on_webview_ready(disable_browser_keys).build()
}
#[allow(clippy::disallowed_methods)]
fn disable_browser_keys(webview: Webview) {
let label = webview.label().to_owned();
if let Err(error) = webview.with_webview(move |platform| {
+1
Переглянути файл
@@ -50,6 +50,7 @@ pub fn init() -> plugin::TauriPlugin<Wry> {
.build()
}
#[allow(clippy::disallowed_methods)]
fn install(webview: Webview) {
let app = webview.app_handle().clone();
let label = webview.label().to_owned();
+70
Переглянути файл
@@ -0,0 +1,70 @@
#[cfg(not(target_os = "macos"))]
fn main() {}
#[cfg(target_os = "macos")]
#[path = "../src/background_tab.rs"]
mod background_tab;
#[cfg(target_os = "macos")]
#[link(name = "WebKit", kind = "framework")]
unsafe extern "C" {}
#[cfg(target_os = "macos")]
fn main() {
// nextest runs a harness-less binary as `--list --format terse [--ignored]`, then `<name> --exact --nocapture`.
let args: Vec<String> = std::env::args().collect();
if args.iter().any(|a| a == "--list") {
if !args.iter().any(|a| a == "--ignored") {
println!("background_tab_appkit: test");
}
return;
}
use background_tab::Return;
use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::AnyClass};
use objc2_app_kit::{
NSApplication, NSBackingStoreType, NSView, NSWindow, NSWindowDidBecomeKeyNotification, NSWindowStyleMask,
};
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};
use std::{cell::Cell, rc::Rc};
let mtm = MainThreadMarker::new().expect("main thread");
let _app = NSApplication::sharedApplication(mtm);
let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0));
let window = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
mtm.alloc(),
rect,
NSWindowStyleMask::Titled,
NSBackingStoreType::Buffered,
false,
)
};
let class = AnyClass::get(c"WKWebView").expect("WebKit is linked");
let web: Retained<NSView> = unsafe { msg_send![msg_send![class, alloc], initWithFrame: rect] };
window.contentView().unwrap().addSubview(&web);
let view = background_tab::web_view(&window).expect("web view in content view");
view.removeFromSuperview();
assert!(view.window().is_none());
// Not asked for its process ids: on a web view that never loaded a page, WebKit asserts in
// `_networkProcessIdentifier` (macOS 15), which a real tab never is.
let reason = Rc::new(Cell::new(None));
let observers = {
let (reason, window, view) = (reason.clone(), window.clone(), view.clone());
background_tab::on_return(&window.clone(), move |why| {
background_tab::put_back(&window, &view);
reason.set(Some(why));
})
};
unsafe {
NSNotificationCenter::defaultCenter()
.postNotificationName_object(NSWindowDidBecomeKeyNotification, Some(&window));
}
assert_eq!(reason.get(), Some(Return::Key));
assert!(view.window().is_some_and(|w| Retained::as_ptr(&w) == Retained::as_ptr(&window)));
for observer in &observers {
unsafe { NSNotificationCenter::defaultCenter().removeObserver(observer.as_ref()) };
}
println!("ok: re-attached synchronously inside the key notification");
}
+2 -1
Переглянути файл
@@ -693,7 +693,7 @@ scaffold_options always project_host bin
scaffold_requirements always project_host bindings async
scaffold_target_taken always project_host bindings async
scope_files always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python trusted project_host bindings async
sdk_container_python_refresh trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_flutter_at trusted project_host bindings async
@@ -714,6 +714,7 @@ sdk_python_pip outside_restricted project_host bin
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_sys_path outside_restricted project_host bindings async
sdk_python_user_path_problems outside_restricted project_host bindings async
sdk_wsl_pythons trusted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
+30 -6
Переглянути файл
@@ -1981,7 +1981,10 @@ export const commands = {
*/
scaffoldTargetTaken: (location: string, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("scaffold_target_taken", { location, name })),
scopeFiles: (pattern: string, limit: number) => typedError<ScopeFiles, IdeError>(__TAURI_INVOKE("scope_files", { pattern, limit })),
/** The project interpreter when it is a Docker or Compose run target's, with its snapshot. */
/**
* The project interpreter when it is a Docker or Compose run target's, with its snapshot.
* Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
*/
sdkContainerPython: () => typedError<{
/** The run target's id. */
target: string,
@@ -1989,8 +1992,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2006,8 +2011,10 @@ export const commands = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -2116,6 +2123,11 @@ export const commands = {
* (`None`: it is used). The folders may not be saved yet.
*/
sdkPythonUserPathProblems: (paths: string[]) => typedError<(UserPathProblem | null)[], IdeError>(__TAURI_INVOKE("sdk_python_user_path_problems", { paths })),
/**
* The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
* `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
*/
sdkWslPythons: (distro: string) => typedError<string[], IdeError>(__TAURI_INVOKE("sdk_wsl_pythons", { distro })),
/**
* Find in Files. Results stream through `on_event`; ends with `Done`.
* Cancel with `cancel_request(request)`.
@@ -5782,8 +5794,10 @@ export type ContainerPython = {
name: string,
/** The Python version of the snapshot in use; `None`: no snapshot yet. */
version: string | null,
/** The image the snapshot was copied from. */
/** The image the snapshot was copied from; `None` for WSL. */
image: string | null,
/** The interpreter's path in the container or distribution. */
executable: string | null,
/** The copied library folders on this machine. */
folders: IpcPath[],
/** Packages of the snapshot (read-only). */
@@ -14406,7 +14420,10 @@ export type RunTarget = {
name?: string,
/** [`SshConfiguration::id`] (SSH). */
sshConfig?: string,
/** Remote folder the project is synchronised to and run from (SSH). */
/**
* Remote folder the project is synchronised to and run from (SSH); the project's Linux
* path, empty = its `/mnt/<drive>` path (WSL).
*/
projectRoot?: string,
/** Upload changed project files before each run (SSH). */
syncBeforeRun?: boolean,
@@ -14436,6 +14453,8 @@ export type RunTarget = {
runOptions?: string,
/** Run as the image's user instead of the project folder's owner (Linux). */
imageUser?: boolean,
/** Distribution name, as `wsl.exe -l -q` lists it (WSL). */
distro?: string,
};
/** Where a run target runs configurations. */
@@ -14445,7 +14464,12 @@ export type RunTargetKind =
/** A new container of an image (`docker run --rm`), the project bind-mounted. */
"docker" |
/** A new container of a Compose service (`docker compose run --rm`). */
"compose";
"compose" |
/**
* A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
* through `/mnt/<drive>`.
*/
"wsl";
export type RustSettings = {
/** Directory holding `cargo` / `rustc`; empty = `PATH` / rustup default. */
-154
Переглянути файл
@@ -1,154 +0,0 @@
/**
* FreeMarker editor mode: HTML outside the template syntax, FreeMarker inside
* directives (`<#if …>`, `<@macro …/>`), interpolations (`${…}`) and comments.
* The first directive fixes the tag syntax, angle (`<#if>`) or square (`[#if]`),
* as FreeMarker itself does; `[=…]` interpolations count only in square syntax.
*/
import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language";
import { tags } from "@lezer/highlight";
type State<H> = {
html: H;
mode: "comment" | "directive" | "interpolation" | null;
/** Tag syntax: `null` until the first directive, then square or not. */
square: boolean | null;
/** What ends the current comment, directive or interpolation. */
close: string;
/** Brackets open inside the expression; the closer counts only at 0. */
depth: number;
/** The directive's name comes next. */
name: "#" | "@" | null;
};
// `(?=…)` lookahead only: WebKit lacks lookbehind.
const OPENER = /<#--|\[#--|<\/?[#@](?=[A-Za-z_])|\[\/?[#@](?=[A-Za-z_])|\$\{|\[=/g;
const KEYWORDS = new Set(["as", "in", "using", "gt", "gte", "lt", "lte"]);
function nextOpener(line: string, from: number, square: boolean | null): RegExpExecArray | null {
OPENER.lastIndex = from;
for (let m = OPENER.exec(line); m; m = OPENER.exec(line)) {
const text = m[0];
if (text === "${") return m;
if (text === "[=" ? square === true : square === null || square === (text[0] === "[")) return m;
}
return null;
}
function tokenComment<H>(stream: StringStream, state: State<H>): string {
const end = stream.string.indexOf(state.close, stream.pos);
stream.pos = end < 0 ? stream.string.length : end + state.close.length;
if (end >= 0) state.mode = null;
return "comment";
}
function tokenExpression<H>(stream: StringStream, state: State<H>): string | null {
if (stream.eatSpace()) return null;
if (state.depth === 0 && stream.match(state.close)) {
state.mode = null;
return "ftlDelimiter";
}
if (state.depth === 0 && state.mode === "directive" && stream.match("/" + state.close)) {
state.mode = null;
return "ftlDelimiter";
}
if (stream.match(/^r?"(?:[^"\\]|\\.)*"?/) || stream.match(/^r?'(?:[^'\\]|\\.)*'?/)) return "string";
if (stream.match(/^\d+(?:\.\d+)?/)) return "number";
if (stream.match("??")) return "operator";
if (stream.match(/^\?[A-Za-z_]\w*/)) return "ftlBuiltin";
if (stream.match(/^\.[A-Za-z_]\w*/)) return "propertyName";
if (stream.match(/^[A-Za-z_$][\w$]*/)) {
const word = stream.current();
if (word === "true" || word === "false") return "bool";
return KEYWORDS.has(word) ? "keyword" : "variableName";
}
const ch = stream.next()!;
if ("([{".includes(ch)) {
state.depth++;
return "bracket";
}
if (")]}".includes(ch)) {
state.depth = Math.max(0, state.depth - 1);
return "bracket";
}
if (ch === "." && stream.match(/^\.[<!*]?/)) return "operator";
return "+-*/%!=<>&|:,;.".includes(ch) ? "operator" : null;
}
function freemarkerParser<H>(html: StreamParser<H>): StreamParser<State<H>> {
const copy = (state: H): H =>
html.copyState
? html.copyState(state)
: (Object.fromEntries(
Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]),
) as H);
/** Runs the HTML mode on `stream` cut at `end`, then advances `stream` to where it stopped. */
const tokenHtml = (stream: StringStream, end: number, state: H): string | null => {
const sub = new StringStream(stream.string.slice(0, end), 4, stream.indentUnit);
sub.pos = stream.pos;
sub.start = stream.start;
const style = html.token(sub, state);
stream.pos = Math.max(sub.pos, stream.pos + (sub.pos === stream.pos ? 1 : 0));
return style;
};
return {
name: "freemarker",
languageData: { ...html.languageData, commentTokens: { block: { open: "<#--", close: "-->" } } },
tokenTable: {
...html.tokenTable,
ftlDelimiter: tags.special(tags.brace),
ftlBuiltin: tags.standard(tags.function(tags.variableName)),
ftlMacro: tags.function(tags.variableName),
},
startState: (indentUnit) => ({
html: html.startState!(indentUnit),
mode: null,
square: null,
close: "",
depth: 0,
name: null,
}),
copyState: (s) => ({ ...s, html: copy(s.html) }),
blankLine: (s, unit) => (s.mode ? undefined : html.blankLine?.(s.html, unit)),
indent: (s, text, cx) => (s.mode ? null : (html.indent?.(s.html, text, cx) ?? null)),
token(stream, state) {
if (state.mode === "comment") return tokenComment(stream, state);
if (state.name) {
const sigil = state.name;
state.name = null;
if (stream.match(/^[A-Za-z_][\w.:-]*/)) return sigil === "#" ? "keyword" : "ftlMacro";
}
if (state.mode) return tokenExpression(stream, state);
const open = nextOpener(stream.string, stream.pos, state.square);
if (open?.index !== stream.pos) {
return tokenHtml(stream, open ? open.index : stream.string.length, state.html);
}
const text = open[0];
stream.pos += text.length;
const square = text[0] === "[";
state.depth = 0;
if (text.endsWith("--")) {
state.mode = "comment";
state.close = square ? "--]" : "-->";
return tokenComment(stream, state);
}
if (text === "${" || text === "[=") {
state.mode = "interpolation";
state.close = text === "${" ? "}" : "]";
return "ftlDelimiter";
}
state.square ??= square;
state.mode = "directive";
state.close = square ? "]" : ">";
state.name = text.endsWith("@") ? "@" : "#";
return "ftlDelimiter";
},
};
}
export async function freemarker(): Promise<LanguageSupport> {
const { html } = await import("@codemirror/legacy-modes/mode/xml");
return new LanguageSupport(StreamLanguage.define(freemarkerParser(html)));
}
+101
Переглянути файл
@@ -0,0 +1,101 @@
// FreeMarker templates: the template layer. Directives (`<#if …>`), user-defined
// directive calls (`<@badge …/>`), interpolations (`${…}`) and comments are parsed
// here; the text between them is HTML, mounted by `./index.ts`. The first directive
// fixes the tag syntax, angle (`<#if>`) or square (`[#if]`), as FreeMarker does.
// Block directives nest (`<#if>…<#elseif>…<#else>…</#if>`); others stand alone.
// Regenerate with `pnpm gen:freemarker-grammar`.
@context blocks from "./tokens"
@top Template { node* }
node {
Text |
Comment |
Interpolation |
Tag |
Element |
RawElement |
StrayEndTag
}
// A block directive or user-defined directive call, its middle tags
// (`elseif`, `else`, `recover`, `case`…) and its end tag.
Element { OpenTag node* (MidTag node*)* EndTag }
// `<#noparse>…</#noparse>`, `<#comment>…</#comment>`: the content is not parsed.
RawElement { RawTag RawBody? EndTag }
@skip { space } {
OpenTag { OpenTagStart tagName argument* TagEnd }
RawTag { RawTagStart tagName argument* TagEnd }
MidTag { MidTagStart tagName argument* (TagEnd | SelfCloseEnd) }
EndTag { EndTagStart tagName? TagEnd }
// An end tag without its start tag, or of a directive that may or may not be a block (`</#sep>`).
StrayEndTag { StrayEndTagStart tagName? TagEnd }
Tag { TagStart tagName argument* (TagEnd | SelfCloseEnd) }
Interpolation { InterpolationStart argument* InterpolationEnd }
argument {
VariableName |
Member { "." PropertyName } |
BuiltIn { "?" BuiltInName } |
String |
Number |
Operator |
CompareOp |
kw<"as"> | kw<"in"> | kw<"using"> |
kw<"gt"> | kw<"gte"> | kw<"lt"> | kw<"lte"> |
@specialize[@name=BooleanLiteral]<identifier, "true" | "false"> |
ParenGroup { "(" argument* ")" } |
BracketGroup { "[" argument* "]" } |
HashGroup { "{" argument* "}" }
}
}
tagName { DirectiveName | MacroName }
VariableName { identifier }
PropertyName { identifier }
BuiltInName { identifier }
kw<term> { @specialize[@name={term}]<identifier, term> }
// Tried in this order, before the tokens below.
@external tokens comment from "./tokens" { Comment }
@external tokens rawBody from "./tokens" { RawBody }
@external tokens text from "./tokens" { Text }
@external tokens tagStart from "./tokens" {
OpenTagStart, RawTagStart, MidTagStart, EndTagStart, StrayEndTagStart, TagStart, InterpolationStart
}
@external tokens tagName from "./tokens" { DirectiveName, MacroName }
@external tokens tagEnd from "./tokens" { TagEnd, SelfCloseEnd, InterpolationEnd }
@tokens {
space { $[ \t\n\r]+ }
identifier { $[a-zA-Z_$\u{a1}-\u{10ffff}] $[a-zA-Z0-9_$\u{a1}-\u{10ffff}]* }
Number { @digit+ ("." @digit+)? }
String {
"r"? '"' (!["\\] | "\\" _)* '"'? |
"r"? "'" (!['\\] | "\\" _)* "'"?
}
Operator {
"+" | "-" | "*" | "/" | "%" | "!" | "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "++" | "--" |
"&&" | "||" | "&" | "|" | "??" | ".." | "..<" | "..!" | "..*" | "," | ":" | ";" | "->"
}
CompareOp { "==" | "!=" | "<" | "<=" | ">=" | ">" }
@precedence { String, identifier }
"." "?" "(" ")" "[" "]" "{" "}"
}
@detectDelim
+202
Переглянути файл
@@ -0,0 +1,202 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete";
import { foldable, getIndentation, indentUnit, matchBrackets } from "@codemirror/language";
import { buildParserFile } from "@lezer/generator";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { completedSyntaxState, completedSyntaxTree } from "@/test/syntax";
import { commentBlock } from "../comments";
import { freemarker, freemarkerLanguage } from "./index";
const highlighter = tagHighlighter([
{ tag: t.special(t.brace), class: "delim" },
{ tag: t.blockComment, class: "comment" },
{ tag: t.keyword, class: "keyword" },
{ tag: t.variableName, class: "var" },
{ tag: t.propertyName, class: "prop" },
{ tag: t.attributeName, class: "attr" },
{ tag: t.string, class: "str" },
{ tag: t.tagName, class: "tag" },
]);
function state(doc: string, selection?: number): EditorState {
return completedSyntaxState(
EditorState.create({
doc,
selection: selection == undefined ? undefined : EditorSelection.cursor(selection),
extensions: [freemarker(), indentUnit.of(" ")],
}),
);
}
/** `text:class` of the styled tokens of `doc`, HTML and embedded languages included. */
function tokens(doc: string): string[] {
const out: string[] = [];
highlightTree(completedSyntaxTree(state(doc)), highlighter, (from, to, cls) =>
out.push(`${doc.slice(from, to)}:${cls}`),
);
return out;
}
/** The error nodes of `doc`'s template layer, with the text they start. */
function errors(doc: string): string[] {
const out: string[] = [];
freemarkerLanguage.parser.parse(doc).iterate({
enter: (node) => void (node.type.isError && out.push(doc.slice(node.from, node.from + 12))),
});
return out;
}
const outline = (doc: string) => freemarkerLanguage.parser.parse(doc).toString();
/** A view on `doc` with `|` marking the caret. */
function view(marked: string): EditorView {
const at = marked.indexOf("|");
return new EditorView({ state: state(marked.slice(0, at) + marked.slice(at + 1), at) });
}
/** Types `text` at the caret through the input handlers, like a keystroke. */
function type(v: EditorView, text: string): string {
const { from, to } = v.state.selection.main;
const handled = v.state.facet(EditorView.inputHandler).some((h) => h(v, from, to, text, () => v.state.update({})));
if (!handled)
v.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.cursor(from + text.length) });
const head = v.state.selection.main.head;
return v.state.sliceDoc(0, head) + "|" + v.state.sliceDoc(head);
}
/** The labels completion offers at the end of `doc`. */
function complete(doc: string): string[] | undefined {
const s = state(doc);
const sources = s.languageDataAt<CompletionSource>("autocomplete", doc.length);
const result = sources.map((src) => src(new CompletionContext(s, doc.length, true))).find(Boolean) as
| CompletionResult
| undefined;
return result?.options.map((o) => o.label);
}
describe("FreeMarker template layer", () => {
it("nests block directives with their middle tags and leaves other directives alone", () => {
expect(outline("<#if a>x<#elseif b>y<#else>z</#if><#assign n = 1>")).toBe(
"Template(Element(OpenTag(OpenTagStart,DirectiveName,VariableName,TagEnd),Text," +
"MidTag(MidTagStart,DirectiveName,VariableName,TagEnd),Text,MidTag(MidTagStart,DirectiveName,TagEnd),Text," +
"EndTag(EndTagStart,DirectiveName,TagEnd)),Tag(TagStart,DirectiveName,VariableName,Operator,Number,TagEnd))",
);
// `assign` without `=` captures its content; a call with content is a block, one without isn't.
expect(outline("<#assign x>v</#assign><@m/><@m>c</@m>")).toMatch(
/^Template\(Element\(.*\),Tag\(.*SelfCloseEnd\),Element\(.*\)\)$/,
);
});
it("doesn't parse the content of noparse and comment", () => {
expect(outline("<#noparse><#if>${x}</#noparse>")).toBe(
"Template(RawElement(RawTag(RawTagStart,DirectiveName,TagEnd),RawBody,EndTag(EndTagStart,DirectiveName,TagEnd)))",
);
});
it("parses common templates without errors", () => {
const doc = [
'<#ftl output_format="HTML">',
'<#import "/lib/ui.ftl" as ui>',
"<#macro row item><tr><td>${item.name}</td></tr></#macro>",
"<#function total xs><#local s = 0><#list xs as x><#local s += x.price></#list><#return s></#function>",
"<#list orders?filter(o -> o.paid) as order><@row item=order/><#sep>, </#sep><#else>none</#list>",
'<#switch kind><#case "a">A<#break><#default>B</#switch>',
"<#attempt>${risky}<#recover>failed</#attempt>",
"<#if (a > 1) && b?? && c?has_content>${a..<5}</#if>",
'<@ui.card title="x" items=[1, 2] opts={"k": true}>c</@ui.card>',
"<#list map as k, v>${k}=${v}</#list>",
].join("\n");
expect(errors(doc)).toEqual([]);
});
it("highlights script and style content as JavaScript and CSS", () => {
const out = tokens('<script>let a = "${x}";</script><style>p { color: red }</style>');
expect(out).toContain("let:keyword");
expect(out).toContain("x:var");
expect(out).toContain("color:prop");
});
it("nests markup across directives", () => {
const out = tokens('<#if a><div class="x"></#if><#if a></div></#if>');
expect(out.filter((t) => t == "div:tag")).toHaveLength(2);
expect(out).toContain("class:attr");
});
it("is generated from freemarker.grammar", () => {
const dir = import.meta.dirname;
const { parser, terms } = buildParserFile(readFileSync(resolve(dir, "freemarker.grammar"), "utf8"), {
fileName: "src/editor/core/cm/freemarker/freemarker.grammar",
moduleStyle: "es",
typeScript: true,
});
const lf = (s: string) => s.replace(/\r\n/g, "\n");
expect(lf(parser)).toBe(lf(readFileSync(resolve(dir, "parser.ts"), "utf8")));
expect(lf(terms)).toBe(lf(readFileSync(resolve(dir, "parser.terms.ts"), "utf8")));
});
});
describe("FreeMarker template editing", () => {
it("folds blocks", () => {
const doc = "<#list xs as x>\n <p>${x}</p>\n</#list>\n";
expect(foldable(state(doc), 0, doc.indexOf("\n"))).toEqual({ from: doc.indexOf(">") + 1, to: doc.indexOf("</#") });
});
it("indents a block's content and puts its middle and end tags back", () => {
const s = state("<#if a>\nx\n<#else>\ny\n</#if>");
const lineStart = (n: number) => s.doc.line(n).from;
expect(getIndentation(s, lineStart(2))).toBe(2);
expect(getIndentation(s, lineStart(3))).toBe(0);
expect(getIndentation(s, lineStart(4))).toBe(2);
expect(getIndentation(s, lineStart(5))).toBe(0);
});
it("matches a block directive with its end tag", () => {
const doc = "<#list xs as x>${x}</#list>";
const match = matchBrackets(state(doc), 3, 1);
expect(match?.matched).toBe(true);
expect(doc.slice(match!.end!.from, match!.end!.to)).toBe("list");
});
it("adds the end tag of a block directive when its > is typed", () => {
expect(type(view("<#if a|"), ">")).toBe("<#if a>|</#if>");
expect(type(view("<@card title=t|"), ">")).toBe("<@card title=t>|</@card>");
expect(type(view("[#ftl][#list xs as x|"), "]")).toBe("[#ftl][#list xs as x]|[/#list]");
// It has one already.
expect(type(view("<#if a|\n</#if>"), ">")).toBe("<#if a>|\n</#if>");
// Not a block, or closed by `/>`.
expect(type(view("<#include 'a.ftl'|"), ">")).toBe("<#include 'a.ftl'>|");
expect(type(view("<@card /|"), ">")).toBe("<@card />|");
// A capturing assign only without `=`.
expect(type(view("<#assign x|"), ">")).toBe("<#assign x>|</#assign>");
// Not in a script.
expect(type(view("<script>if (a <#b|</script>"), ">")).toBe("<script>if (a <#b>|</script>");
});
it("completes directives, the open blocks' end tags and built-ins", () => {
expect(complete("<p><#")).toContain("list");
expect(complete("<#list xs as x><@card><#if a></")).toEqual(["#if", "@card", "#list"]);
expect(complete("<#list xs as x><@card><#if a></#")).toEqual(["#if", "@card", "#list"]);
expect(complete("${name?")).toContain("upper_case");
expect(complete("<p>Why?")).not.toContain("upper_case");
});
it("comments with <#-- -->", () => {
const v = view("|<p>a</p>");
v.dispatch({ selection: EditorSelection.range(0, v.state.doc.length) });
commentBlock(v);
expect(v.state.doc.toString()).toBe("<#-- <p>a</p> -->");
const square = view("[#ftl]\n|<p>a</p>");
square.dispatch({ selection: EditorSelection.range(7, square.state.doc.length) });
commentBlock(square);
expect(square.state.doc.toString()).toBe("[#ftl]\n[#-- <p>a</p> --]");
// JavaScript keeps its own.
const script = view("<script>|a()</script>");
script.dispatch({ selection: EditorSelection.range(8, 11) });
commentBlock(script);
expect(script.state.doc.toString()).toBe("<script>/* a() */</script>");
});
});
+14 -4
Переглянути файл
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { completedSyntaxTree } from "@/test/syntax";
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
import { findLanguageDescription, loadSupport } from "./languages";
import { findLanguageDescription, loadSupport } from "../languages";
const highlighter = tagHighlighter([
{ tag: t.keyword, class: "keyword" },
@@ -25,9 +25,19 @@ async function tokens(source: string) {
const support = await loadSupport(desc);
const state = EditorState.create({ doc: source, extensions: [support!] });
const result: { text: string; style: string }[] = [];
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) =>
result.push({ text: source.slice(from, to), style }),
);
let last = { to: -1, style: "" };
// One span per run of a style on a line, as the editor draws it.
highlightTree(completedSyntaxTree(state), highlighter, (from, to, style) => {
source
.slice(from, to)
.split("\n")
.forEach((text, i) => {
const prev = result.at(-1);
if (i == 0 && prev && last.to == from && last.style == style) prev.text += text;
else result.push({ text, style });
});
last = { to, style };
});
return result;
}
+320
Переглянути файл
@@ -0,0 +1,320 @@
/**
* FreeMarker templates: `freemarker.grammar` parses the template layer (directives,
* user-defined directive calls, interpolations, comments), and the text between its
* elements is one HTML document, an overlay as in Django and JSP templates, so markup
* split by a directive still nests, `href="${url}"` is an attribute with a hole, and
* `<script>` / `<style>` get JavaScript and CSS. Block directives fold, indent their
* content and match their end tags; finishing a block directive adds its end tag.
* Completion offers directives after `<#`, the open blocks' end tags after `</` and
* built-ins after `?`.
*/
import {
LRLanguage,
LanguageSupport,
bracketMatchingHandle,
foldNodeProp,
indentNodeProp,
syntaxTree,
type TreeIndentContext,
} from "@codemirror/language";
import { html } from "@codemirror/lang-html";
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { EditorSelection, EditorState, Prec, type Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { styleTags, tags as t } from "@lezer/highlight";
import { NodeProp, parseMixed, type SyntaxNode, type SyntaxNodeRef } from "@lezer/common";
import { VERSIONED_SCRIPT_TYPES } from "../htmlScripts";
import { parser } from "./parser";
import { BLOCK_DIRECTIVES, CAPTURING, DIRECTIVES, RAW_DIRECTIVES } from "./tokens";
const baseHTML = html({ selfClosingTags: true, nestedLanguages: VERSIONED_SCRIPT_TYPES });
const FTL_COMMENT = { block: { open: "<#--", close: "-->" } };
const SQUARE_COMMENT = { block: { open: "[#--", close: "--]" } };
const OPENERS = ["OpenTag", "RawTag"];
const startTagOf = (element: SyntaxNode) => element.firstChild;
const endTagOf = (element: SyntaxNode) => (element.lastChild?.name == "EndTag" ? element.lastChild : null);
const tagNameOf = (node: SyntaxNode) => node.getChild("DirectiveName") ?? node.getChild("MacroName");
/** The content of a block: from the end of its start tag to its end tag (or the end of the block). */
function foldBlock(element: SyntaxNode, state: EditorState) {
const start = startTagOf(element);
const end = endTagOf(element);
if (!start) return null;
// An end tag the parser inserted to recover is empty.
const to = end && end.to > end.from ? end.from : element.to;
return start.to < to && state.doc.lineAt(start.to).number < state.doc.lineAt(to).number
? { from: start.to, to }
: null;
}
const MIDDLE = new Set([...BLOCK_DIRECTIVES.values()].flat());
const CLOSING_LINE = /^\s*(?:<|\[)(?:\/[#@]|#([A-Za-z]+))/;
/** A block's content one unit in from its start tag's line; its middle and end tags at that line's indent. */
function indentBlock(cx: TreeIndentContext) {
const start = startTagOf(cx.node);
if (!start) return null;
const base = cx.lineIndent(start.from);
const m = CLOSING_LINE.exec(cx.textAfter);
return m && (!m[1] || MIDDLE.has(m[1])) ? base : base + cx.unit;
}
const templateParser = parser.configure({
props: [
styleTags({
"TagStart OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagEnd SelfCloseEnd InterpolationStart InterpolationEnd":
t.special(t.brace),
DirectiveName: t.keyword,
MacroName: t.function(t.variableName),
"Comment RawBody": t.blockComment,
VariableName: t.variableName,
"PropertyName Member/.": t.propertyName,
"BuiltInName BuiltIn/?": t.standard(t.function(t.variableName)),
String: t.string,
Number: t.number,
BooleanLiteral: t.bool,
"Operator CompareOp": t.operator,
"as in using gt gte lt lte": t.keyword,
"( ) [ ] { }": t.bracket,
}),
foldNodeProp.add({ "Element RawElement": foldBlock }),
indentNodeProp.add({
Element: indentBlock,
// The raw content keeps its own indentation.
RawElement: () => null,
}),
NodeProp.closedBy.add({ "OpenTag RawTag": ["EndTag"] }),
NodeProp.openedBy.add({ EndTag: OPENERS }),
bracketMatchingHandle.add({ "OpenTag RawTag EndTag": tagNameOf }),
],
});
// HTML's document gives no indentation past its last text; there the block around it does.
const htmlBase = (baseHTML.language as LRLanguage).parser;
const htmlDocumentIndent = htmlBase.nodeSet.types.find((type) => type.name == "Document")?.prop(indentNodeProp);
const htmlParser = htmlBase.configure({
props: [indentNodeProp.add({ Document: (cx) => htmlDocumentIndent?.(cx) ?? cx.continue() })],
});
// The template text is one HTML document.
const htmlMixed = { parser: htmlParser, overlay: (node: SyntaxNodeRef) => node.name == "Text" };
export const freemarkerLanguage = LRLanguage.define({
name: "freemarker",
parser: templateParser.configure({ wrap: parseMixed((node) => (node.type.isTop ? htmlMixed : null)) }),
});
/** Where the template layer reaches: FreeMarker's own nodes, or the HTML outside `<script>` and `<style>`. */
function inTemplate(state: EditorState, pos: number): boolean {
return freemarkerLanguage.isActiveAt(state, pos, -1) || baseHTML.language.isActiveAt(state, pos, -1);
}
const squareSyntaxOf = new WeakMap<Text, boolean>();
/** The square tag syntax, when the template's first directive uses it. */
function squareSyntax(state: EditorState): boolean {
let square = squareSyntaxOf.get(state.doc);
if (square == undefined) {
const head = state.sliceDoc(0, Math.min(state.doc.length, 20_000));
square = /<\/?[#@][A-Za-z]|\[\/?[#@][A-Za-z]/.exec(head)?.[0][0] == "[";
squareSyntaxOf.set(state.doc, square);
}
return square;
}
/** The blocks open at `pos`, innermost first, as `#if` / `@badge`. */
function openBlocks(state: EditorState, pos: number): string[] {
const names: string[] = [];
for (let node: SyntaxNode | null = syntaxTree(state).resolve(pos, -1); node; node = node.parent) {
if (node.name != "Element" && node.name != "RawElement") continue;
const start = startTagOf(node);
const name = start && tagNameOf(start);
if (start && name && start.to <= pos) {
names.push(state.sliceDoc(start.from, name.from).replace(/^[<[]/, "") + state.sliceDoc(name.from, name.to));
}
}
return names;
}
/** Whether the block `name` opened before `pos` has no end tag after it, nested blocks counted. */
function unclosed(state: EditorState, sigil: string, name: string, pos: number): boolean {
const rest = state.sliceDoc(pos);
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`[<\\[](/)?${sigil}${escaped}(?![\\w.:-])`, "g");
let depth = 0;
for (let m; (m = re.exec(rest));) {
if (!m[1]) depth++;
else if (depth-- == 0) return false;
}
return true;
}
const TAG_BEFORE = /[<[]([#@])([A-Za-z_][\w.:-]*)(?:\s[^<>[\]]*)?$/;
/** Typing the `>` (`]`) of a block directive or a call with content adds its end tag after the caret. */
const closeBlock = EditorView.inputHandler.of((view, from, to, text) => {
const { state } = view;
if ((text != ">" && text != "]") || from != to || state.selection.ranges.length > 1 || state.readOnly) return false;
const square = squareSyntax(state);
if ((text == "]") != square) return false;
const line = state.doc.lineAt(from);
const before = state.sliceDoc(line.from, from);
const m = TAG_BEFORE.exec(before);
if (!m || before.endsWith("/") || (m[0][0] == "[") != square) return false;
const [, sigil, name] = m;
// `<#assign x>…</#assign>` captures its content; `<#assign x = 1>` doesn't.
const assigns = /(?:^|[^=!<>])=(?!=)/.test(before.slice(before.length - m[0].length + 2 + name!.length));
const block = BLOCK_DIRECTIVES.has(name!) || RAW_DIRECTIVES.has(name!) || (CAPTURING.has(name!) && !assigns);
if (sigil == "#" && !block) return false;
if (!inTemplate(state, from - m[0].length)) return false;
if (!unclosed(state, sigil!, name!, from)) return false;
const close = square ? `[/${sigil}${name}]` : `</${sigil}${name}>`;
view.dispatch({
changes: { from, insert: text + close },
selection: EditorSelection.cursor(from + 1),
userEvent: "input.type",
});
return true;
});
const DIRECTIVE_OPTIONS: Completion[] = DIRECTIVES.map((label) => ({ label, type: "keyword" }));
/** Built-ins most templates use, for completion after `?`. */
const BUILT_INS = [
"api",
"boolean",
"c",
"c_lower_case",
"cap_first",
"capitalize",
"chop_linebreaks",
"chunk",
"contains",
"counter",
"date",
"datetime",
"default",
"drop_while",
"ends_with",
"ensure_ends_with",
"ensure_starts_with",
"eval",
"eval_json",
"filter",
"first",
"groups",
"has_content",
"has_next",
"html",
"if_exists",
"index",
"index_of",
"interpret",
"is_boolean",
"is_date",
"is_even_item",
"is_first",
"is_hash",
"is_last",
"is_number",
"is_odd_item",
"is_sequence",
"is_string",
"item_cycle",
"item_parity",
"j_string",
"join",
"js_string",
"json_string",
"keep_after",
"keep_after_last",
"keep_before",
"keep_before_last",
"keys",
"last",
"last_index_of",
"left_pad",
"length",
"lower_case",
"map",
"matches",
"max",
"min",
"no_esc",
"number",
"number_to_date",
"number_to_datetime",
"remove_beginning",
"remove_ending",
"replace",
"reverse",
"right_pad",
"round",
"seq_contains",
"seq_index_of",
"size",
"sort",
"sort_by",
"split",
"starts_with",
"string",
"substring",
"switch",
"take_while",
"then",
"time",
"trim",
"truncate",
"uncap_first",
"upper_case",
"url",
"values",
"word_list",
"xhtml",
"xml",
].map((label): Completion => ({ label, type: "function" }));
/** `<#…`, `</#…` and `?…` inside the template layer. */
function templateCompletion(context: CompletionContext): CompletionResult | null {
const { state } = context;
const end = context.matchBefore(/[<[]\/(?:[#@][\w.:-]*)?$/);
if (end) {
const from = end.from + 2;
const options = openBlocks(state, from).map((block, i) => ({ label: block, type: "keyword", boost: 99 - i }));
return options.length ? { from, options, validFor: /^(?:[#@][\w.:-]*)?$/ } : null;
}
const directive = context.matchBefore(/[<[]#\w*$/);
if (directive) {
if ((directive.text[0] == "[") != squareSyntax(state)) return null;
const name = /\w*$/.exec(directive.text)![0];
return { from: directive.to - name.length, options: DIRECTIVE_OPTIONS, validFor: /^\w*$/ };
}
const builtIn = context.matchBefore(/\?\w*$/);
// The `?` is a built-in's, not text or a string's.
const mark = builtIn && syntaxTree(state).resolveInner(builtIn.from + 1, -1);
if (builtIn && mark && (mark.name == "BuiltIn" || mark.parent?.name == "BuiltIn")) {
return { from: builtIn.from + 1, options: BUILT_INS, validFor: /^\w*$/ };
}
return null;
}
export function freemarker(): LanguageSupport {
return new LanguageSupport(freemarkerLanguage, [
// Before HTML's, so the template's completions come first.
baseHTML.language.data.of({ autocomplete: templateCompletion }),
baseHTML.support,
// Markup is commented out with a template comment, which FreeMarker drops from the page.
baseHTML.language.data.of({ commentTokens: FTL_COMMENT }),
freemarkerLanguage.data.of({ autocomplete: templateCompletion, commentTokens: FTL_COMMENT }),
// In the square syntax, `[#-- --]`.
Prec.highest(
EditorState.languageData.of((state, pos) =>
squareSyntax(state) && inTemplate(state, pos) ? [{ commentTokens: SQUARE_COMMENT }] : [],
),
),
Prec.high(closeBlock),
]);
}
+42
Переглянути файл
@@ -0,0 +1,42 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
export const
Comment = 1,
RawBody = 2,
Text = 3,
OpenTagStart = 4,
RawTagStart = 5,
MidTagStart = 6,
EndTagStart = 7,
StrayEndTagStart = 8,
TagStart = 9,
InterpolationStart = 10,
DirectiveName = 11,
MacroName = 12,
TagEnd = 13,
SelfCloseEnd = 14,
InterpolationEnd = 15,
Template = 16,
Interpolation = 17,
VariableName = 18,
PropertyName = 21,
BuiltInName = 24,
String = 25,
Number = 26,
Operator = 27,
CompareOp = 28,
as = 29,
_in = 30,
using = 31,
gt = 32,
gte = 33,
lt = 34,
lte = 35,
BooleanLiteral = 36,
Tag = 46,
Element = 47,
OpenTag = 48,
MidTag = 49,
EndTag = 50,
RawElement = 51,
RawTag = 52,
StrayEndTag = 53
+24
Переглянути файл
@@ -0,0 +1,24 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
import {LRParser} from "@lezer/lr"
import {comment, rawBody, text, tagStart, tagName, tagEnd, blocks} from "./tokens"
const spec_identifier = {__proto__:null,as:58, in:60, using:62, gt:64, gte:66, lt:68, lte:70, true:72, false:72}
export const parser = LRParser.deserialize({
version: 14,
states: "*nQVO]OOO!xQ#SO'#CmO#PQ!rO'#D[O#PQ!rO'#D^O#XO]O'#D]O#PQ!rO'#DbO#cOYO'#DaO#kQ#dO'#DcOOO]'#Dj'#DjOOO]'#Dd'#DdQVO]OOOOQp'#Cn'#CnO#vQ!bO'#CoO#{Q!bO'#CrO$QQ!bO'#DTO$XQ!bO'#DWO$`Q!bO'#DZOOQp'#Dk'#DkOOQp'#De'#DeO$gQ#SO,59XOOO],59X,59XOOQp'#Dm'#DmO$nQ#SO,59vO$xQ#SO,59xO#PQ!rO'#D_O%PO]O'#DfO%ZOWO,59wO%cQ#dO'#D`OOO],59w,59wO#XO]O,59wO%nQ#SO,59|OOO],59{,59{O#fOWO,59{OOO],59},59}O%uQ#SO,59}OOO]-E7b-E7bOOQp'#Cq'#CqOOQp,59Z,59ZOOQp'#Ct'#CtOOQp,59^,59^OOQp,59o,59oO%zQ!bO,59oOOQp,59r,59rO&RQ!bO,59rOOQp,59u,59uO&YQ!bO,59uOOQp-E7c-E7cOOO]1G.s1G.sO&aQ#SO1G/bOOO]1G/b1G/bO&kQ#SO1G/dOOO]1G/d1G/dO&rQ#SO,59yO&|O]O,5:QOOOW-E7d-E7dOOO]1G/c1G/cOOO],59z,59zO'WQ#SO,59zO%ZOWO1G/cO']Q#SO1G/hOOOY1G/h1G/hOOO]1G/g1G/gOOO]1G/i1G/iOOQp1G/Z1G/ZOOQp1G/^1G/^OOQp1G/a1G/aOOO]7+$|7+$|OOO]7+%O7+%OO'dQ#SO1G/eOOO]1G/e1G/eOOO]1G/f1G/fOOO]7+$}7+$}OOOY7+%S7+%SOOO]7+%P7+%P",
stateData: "'q~O!]OS~OPWORWOSROTTOWVOXQOYPO~Od[Og]OiaOjaOkaOlaOmaOnaOoaOpaOqaOraOsaOtaOv^Oy_O|`O!`ZO~O_dO~PnOZeO[eO~OUhOVkO~PVOQpOVkO~OZeO[eO]qO~O!`tO~O!`vO~OuxO~PnOxzO~PnO{|O~PnO_!PO~PnO]!RO^!RO~PnO]!TO~PnOU!YXV!YX~PVOUhOVkO~OZeO[eO]!YO~O]!^O~PnO]!`O~Ou!aO~PnOx!bO~PnO{!cO~PnO]!dO^!dO~PnO]!eO~PnO]!gO^!gO~PnOU!YaV!Ya~PVO]!hO~O]!jO~PnO]!kO^!kO~PnOi!`~",
goto: "&V!bPPPPPPPPPPPPPPPPP!c!k!kP!}!kP#QPPPPPPPPPPPPPP!kPP!kPP!k!c!c#T#]#c!c#s!c#{$Z$}PPP%X%aP%s]WOSYim!VqaP^_`cfgny{}!Q!S!U!]!fRu[Rw]]SOSYim!VXiSjm![QlSQoUS!XjmQ!_pR!i![]UOSYim!VQYOQmSUsYm!VR!ViQcPQy^Q{_Q}``!Ocy{}!Q!S!]!fQ!QfQ!SgQ!]nR!f!UQjSS!Wj![R![m]XOSYim!VqbP^_`cfgny{}!Q!S!U!]!fQfQQgRQnTQrVQ!UhR!Zk",
nodeNames: "⚠ Comment RawBody Text OpenTagStart RawTagStart MidTagStart EndTagStart StrayEndTagStart TagStart InterpolationStart DirectiveName MacroName TagEnd SelfCloseEnd InterpolationEnd Template Interpolation VariableName Member . PropertyName BuiltIn ? BuiltInName String Number Operator CompareOp as in using gt gte lt lte BooleanLiteral ) ( ParenGroup ] [ BracketGroup } { HashGroup Tag Element OpenTag MidTag EndTag RawElement RawTag StrayEndTag",
maxTerm: 63,
context: blocks,
nodeProps: [
["openedBy", 37,"(",40,"[",43,"{"],
["closedBy", 38,")",41,"]",44,"}"]
],
skippedNodes: [0],
repeatNodeCount: 3,
tokenData: ",X~RvXY#iYZ#i]^#ipq#iqr#zrs$Xtu%yuv&nvw&{wx'Txy(pyz(uz{&n{|(z|}&v}!O)V!O!P)e!P!Q&n!Q![){![!]&v!]!^&v!^!_*f!_!`#z!`!a*f!a!b*n!c!}%y!}#O*v#P#Q*{#R#S%y#T#f%y#f#g+Q#g#o%y#o#p+u#p#q+z#q#r,S$g;'S%y;'S;=`&h<%lO%y~#nS!]~XY#iYZ#i]^#ipq#i~$PPk~!_!`$S~$XOl~~$^Vi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s<%lO$X~$xOi~~${RO;'S$X;'S;=`%U;=`O$X~%ZWi~Or$Xrs$ss#O$X#O#P$x#P;'S$X;'S;=`%s;=`<%l$X<%lO$X~%vP;=`<%l$X~&OW!`~tu%y!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~&kP;=`<%l%y~&sPk~!_!`&v~&{Ok~~'QPk~vw&v~'YVi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j<%lO'T~'rRO;'S'T;'S;=`'{;=`O'T~(QWi~Ow'Twx$sx#O'T#O#P'o#P;'S'T;'S;=`(j;=`<%l'T<%lO'T~(mP;=`<%l'T~(uOv~~(zOu~~)PQk~{|&v!_!`&v~)[Rk~}!O&v!_!`&v!`!a&v~)jPd~!O!P)m~)rRk~qr&vz{&v!^!_&v~*QQj~!O!P*W!Q![){~*ZP!Q![*^~*cPj~!Q![*^~*kPl~!_!`$S~*sPg~!a!b&v~*{Oy~~+QOx~~+VY!`~rs$Xtu%ywx'T!Q![%y!c!}%y#R#S%y#T#o%y$g;'S%y;'S;=`&h<%lO%y~+zO|~~,PPk~#p#q&v~,XO{~",
tokenizers: [comment, rawBody, text, tagStart, tagName, tagEnd, 0],
topRules: {"Template":[0,16]},
specialized: [{term: 62, get: (value: keyof typeof spec_identifier) => spec_identifier[value] || -1}],
tokenPrec: 306
})
+350
Переглянути файл
@@ -0,0 +1,350 @@
/**
* External tokens of `freemarker.grammar`: the text between template elements, the
* comments, the raw content of `noparse`, the start of each tag, classified by its name
* against the blocks open around it, the tag's name and the delimiters that end tags
* and interpolations, which depend on the tag syntax.
*/
import { ContextTracker, ExternalTokenizer, type InputStream, type Stack } from "@lezer/lr";
import {
Comment,
DirectiveName,
Element,
EndTagStart,
InterpolationEnd,
InterpolationStart,
MacroName,
MidTagStart,
OpenTagStart,
RawBody,
RawElement,
RawTagStart,
SelfCloseEnd,
StrayEndTagStart,
TagEnd,
TagStart,
Text,
} from "./parser.terms";
const LT = 60,
GT = 62,
SLASH = 47,
HASH = 35,
AT = 64,
DOLLAR = 36,
EQ = 61,
BRACE_L = 123,
BRACE_R = 125,
BRACKET_L = 91,
BRACKET_R = 93,
PAREN_L = 40,
PAREN_R = 41,
DASH = 45,
QUOTE = 34,
APOS = 39,
BACKSLASH = 92,
BANG = 33;
/** Block directives, with the middle tags each one allows. */
export const BLOCK_DIRECTIVES: ReadonlyMap<string, readonly string[]> = new Map([
["attempt", ["recover"]],
["autoesc", []],
["compress", []],
["escape", []],
["function", []],
["if", ["elseif", "else"]],
["items", []],
["list", ["else"]],
["macro", []],
["noautoesc", []],
["noescape", []],
["outputformat", []],
["switch", ["case", "default", "on"]],
]);
/** `<#assign x>…</#assign>`: these capture their content when they have no `=`. */
export const CAPTURING: ReadonlySet<string> = new Set(["assign", "global", "local"]);
/** Directives whose content FreeMarker doesn't parse. */
export const RAW_DIRECTIVES: ReadonlySet<string> = new Set(["noparse", "comment"]);
/** Every built-in directive, for completion. */
export const DIRECTIVES = [
"assign",
"attempt",
"autoesc",
"break",
"case",
"compress",
"continue",
"default",
"else",
"elseif",
"escape",
"fallback",
"flush",
"ftl",
"function",
"global",
"if",
"import",
"include",
"items",
"list",
"local",
"lt",
"macro",
"nested",
"noautoesc",
"noescape",
"noparse",
"nt",
"on",
"outputformat",
"recover",
"recurse",
"return",
"rt",
"sep",
"setting",
"stop",
"switch",
"t",
"visit",
];
/** The blocks open around a position, innermost first, and the tag syntax (`null`: not fixed yet). */
class Context {
readonly hash: number;
constructor(
/** `#if`, `@badge`. */
readonly name: string | null,
readonly parent: Context | null,
readonly square: boolean | null,
) {
let hash = parent ? parent.hash : square === null ? 1 : square ? 2 : 3;
for (let i = 0; name && i < name.length; i++) hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0;
this.hash = hash;
}
}
const TOP = new Context(null, null, null);
const isNameStart = (ch: number) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95;
const isName = (ch: number) => isNameStart(ch) || (ch >= 48 && ch <= 57);
/** User-defined directive names may be qualified (`lib.badge`) or carry `:` and `-`. */
const isMacroName = (ch: number) => isName(ch) || ch == 46 || ch == 58 || ch == DASH;
/** A tag opening `offset` code units ahead: its kind, sigil and name. */
interface TagHead {
/** Code units up to the name. */
length: number;
end: boolean;
sigil: "#" | "@";
name: string;
square: boolean;
}
function tagHead(input: InputStream, offset: number, square: boolean | null): TagHead | null {
const open = input.peek(offset);
if (open == LT ? square === true : open == BRACKET_L ? square === false : true) return null;
let i = offset + 1;
const end = input.peek(i) == SLASH;
if (end) i++;
const sigil = input.peek(i);
if (sigil != HASH && sigil != AT) return null;
i++;
let name = "";
const accept = sigil == HASH ? isName : isMacroName;
for (let ch; accept((ch = input.peek(i))); i++) {
if (!name && !isNameStart(ch)) break;
name += String.fromCharCode(ch);
}
// `<#--` is a comment, `</@>` ends the innermost call; anything else needs a name.
if (!name && !(end && sigil == AT)) return null;
return { length: i - offset - name.length, end, sigil: sigil == HASH ? "#" : "@", name, square: open == BRACKET_L };
}
const commentAt = (input: InputStream, offset: number, square: boolean | null) => {
const open = input.peek(offset);
return (
(open == LT ? square !== true : open == BRACKET_L && square !== false) &&
input.peek(offset + 1) == HASH &&
input.peek(offset + 2) == DASH &&
input.peek(offset + 3) == DASH
);
};
const interpolationAt = (input: InputStream, offset: number, square: boolean | null) => {
const ch = input.peek(offset);
return (
(ch == DOLLAR && input.peek(offset + 1) == BRACE_L) ||
(square === true && ch == BRACKET_L && input.peek(offset + 1) == EQ)
);
};
/** Whether a comment, a tag or an interpolation starts `offset` code units ahead. */
function elementStart(input: InputStream, offset: number, square: boolean | null): boolean {
const ch = input.peek(offset);
if (ch != LT && ch != BRACKET_L && ch != DOLLAR) return false;
return interpolationAt(input, offset, square) || commentAt(input, offset, square) || !!tagHead(input, offset, square);
}
/** How far a tag scan looks for the tag's end. */
const MAX_TAG = 4000;
/**
* The rest of a tag after its name: whether it ends with `/>` (`/]`) and whether it has an
* assignment `=` outside brackets, skipping strings and brackets.
*/
function tagTail(input: InputStream, offset: number, square: boolean): { selfClosing: boolean; assigns: boolean } {
const close = square ? BRACKET_R : GT;
let depth = 0;
let assigns = false;
for (let i = offset; i < offset + MAX_TAG; i++) {
const ch = input.peek(i);
if (ch < 0) break;
if (ch == QUOTE || ch == APOS) {
for (i++; ; i++) {
const c = input.peek(i);
if (c < 0 || c == ch) break;
if (c == BACKSLASH) i++;
}
continue;
}
if (ch == PAREN_L || ch == BRACE_L || ch == BRACKET_L) {
depth++;
continue;
}
if (depth > 0 && (ch == PAREN_R || ch == BRACE_R || ch == BRACKET_R)) {
depth--;
continue;
}
if (depth == 0 && ch == close) return { selfClosing: input.peek(i - 1) == SLASH, assigns };
if (depth == 0 && ch == EQ) {
const before = input.peek(i - 1);
const after = input.peek(i + 1);
if (after != EQ && before != EQ && before != BANG && before != LT && before != GT) assigns = true;
}
}
return { selfClosing: false, assigns };
}
export const blocks = new ContextTracker<Context>({
start: TOP,
shift(context, term, _stack, input) {
const opens = term == OpenTagStart || term == RawTagStart;
const tag = opens || term == MidTagStart || term == EndTagStart || term == StrayEndTagStart || term == TagStart;
if (!tag) return context;
const square = context.square ?? input.next == BRACKET_L;
if (!opens) return square === context.square ? context : fixSyntax(context, square);
const head = tagHead(input, 0, square);
const base = square === context.square ? context : fixSyntax(context, square);
return new Context(head ? head.sigil + head.name : null, base, square);
},
reduce(context, term) {
return (term == Element || term == RawElement) && context.parent ? context.parent : context;
},
hash: (context) => context.hash,
strict: false,
});
/** `context` with the tag syntax fixed, for the blocks around it too. */
function fixSyntax(context: Context, square: boolean): Context {
return context.parent
? new Context(context.name, fixSyntax(context.parent, square), square)
: new Context(null, null, square);
}
/** `<#-- … -->` (`[#-- … --]`), to the end of the document when unterminated. */
export const comment = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
if (!commentAt(input, 0, context.square)) return;
const close = input.next == BRACKET_L ? BRACKET_R : GT;
input.advance(4);
for (let ch; (ch = input.next) >= 0;) {
if (ch == DASH && input.peek(1) == DASH && input.peek(2) == close) {
input.advance(3);
break;
}
input.advance();
}
input.acceptToken(Comment);
});
/** Template text: up to a tag, an interpolation or a comment. */
export const text = new ExternalTokenizer((input, stack: Stack) => {
const square = (stack.context as Context).square;
const start = input.pos;
while (input.next >= 0 && !elementStart(input, 0, square)) input.advance();
if (input.pos > start) input.acceptToken(Text);
});
/** The opening delimiter of a tag or an interpolation, a token telling what it is in the blocks open around it. */
export const tagStart = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
if (interpolationAt(input, 0, context.square)) {
if (stack.canShift(InterpolationStart)) input.acceptToken(InterpolationStart, 2);
return;
}
const head = tagHead(input, 0, context.square);
if (!head) return;
const open = context.name;
const name = head.sigil + head.name;
let term = TagStart;
if (head.end) {
term =
open && (name == open || (head.sigil == "@" && !head.name && open.startsWith("@")))
? EndTagStart
: StrayEndTagStart;
} else if (head.sigil == "#" && RAW_DIRECTIVES.has(head.name)) {
term = RawTagStart;
} else if (open?.startsWith("#") && BLOCK_DIRECTIVES.get(open.slice(1))?.includes(head.name)) {
term = MidTagStart;
} else if (head.sigil == "@" || BLOCK_DIRECTIVES.has(head.name) || CAPTURING.has(head.name)) {
const tail = tagTail(input, head.length + head.name.length, head.square);
const block = !tail.selfClosing && (!CAPTURING.has(head.name) || !tail.assigns);
if (block) term = OpenTagStart;
}
if (!stack.canShift(term)) term = term == EndTagStart ? StrayEndTagStart : TagStart;
if (stack.canShift(term)) input.acceptToken(term, head.length);
});
/** A tag's name: a directive's (`if`) or a user-defined directive's (`lib.badge`). */
export const tagName = new ExternalTokenizer((input) => {
const sigil = input.peek(-1);
if (sigil != HASH && sigil != AT) return;
const accept = sigil == HASH ? isName : isMacroName;
if (!isNameStart(input.next)) return;
while (accept(input.next)) input.advance();
input.acceptToken(sigil == HASH ? DirectiveName : MacroName);
});
/** `>` / `/>` (`]` / `/]`) ending a tag, `}` (`]`) ending an interpolation. */
export const tagEnd = new ExternalTokenizer((input, stack: Stack) => {
const square = (stack.context as Context).square === true;
const close = square ? BRACKET_R : GT;
if (input.next == SLASH && input.peek(1) == close) {
if (stack.canShift(SelfCloseEnd)) input.acceptToken(SelfCloseEnd, 2);
return;
}
if (input.next == close && stack.canShift(TagEnd)) {
input.acceptToken(TagEnd, 1);
return;
}
if ((input.next == BRACE_R || (square && input.next == BRACKET_R)) && stack.canShift(InterpolationEnd)) {
input.acceptToken(InterpolationEnd, 1);
}
});
/** The content of `noparse` or `comment`: up to the end tag closing it. */
export const rawBody = new ExternalTokenizer((input, stack: Stack) => {
const context: Context = stack.context;
const name = context.name;
if (!name) return;
const start = input.pos;
for (; input.next >= 0; input.advance()) {
const head = (input.next == LT || input.next == BRACKET_L) && tagHead(input, 0, context.square);
if (head && head.end && head.sigil + head.name == name) break;
}
if (input.pos > start) input.acceptToken(RawBody);
});
+9 -2
Переглянути файл
@@ -43,6 +43,7 @@ import {
useTextEditorWrappers,
type EditorCloseSession,
type EditorInput,
type EditorKindContribution,
type OpenOptions,
type FileEditorResolution,
type OpenEditorTab,
@@ -310,6 +311,11 @@ function tabModified(tab: Tab): boolean {
);
}
/** Whether `input` opens in the preview tab when asked: always for kinds that reuse one, else per the setting. */
function previewTabsFor(input: EditorInput, kinds: ReadonlyMap<string, EditorKindContribution>): boolean {
return editorPrefs().tabs.previewTab || !!kinds.get(input.kind)?.reusesPreviewTab;
}
export class EditorController implements SlotHost {
manager: DocumentManager;
readonly slots = new Map<string, EditorSlot>();
@@ -1529,7 +1535,7 @@ export class EditorController implements SlotHost {
const kinds = useContributions.getState().editorKinds;
const lifecycle = documentLifecycle(input, kinds);
const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle }));
const preview = !!o.preview && editorPrefs().tabs.previewTab && canPreview;
const preview = !!o.preview && previewTabsFor(input, kinds) && canPreview;
if (!activate && preview) return;
const kind = kinds.get(input.kind);
let paneId = s.panes[generation.pane] ? generation.pane : activate ? s.activePane : null;
@@ -2447,7 +2453,8 @@ export class EditorController implements SlotHost {
activeInput(options?: { previewOnly?: boolean }): EditorInput | null {
const tab = this.activeTabOf();
if (options?.previewOnly && (!tab?.preview || !editorPrefs().tabs.previewTab)) return null;
const kinds = useContributions.getState().editorKinds;
if (options?.previewOnly && (!tab?.preview || !previewTabsFor(tab.input, kinds))) return null;
return tab?.input ?? null;
}
+30
Переглянути файл
@@ -151,6 +151,36 @@ describe("file open order", () => {
expect(activePath()).toBe("/p/b.ts");
});
it("reuses one tab for kinds that ask for it while the preview tab is off", async () => {
useProject.setState({ settings: { editor: { tabs: { previewTab: false } } } });
dispose = registerEditorKind({
kind: "test-diff",
reusesPreviewTab: true,
component: () => null,
title: (input) => input.key,
});
const controller = setup();
const diff = (key: string) => ({ kind: "test-diff", key });
await controller.openInput(diff("one"), { preview: true, focus: false });
await controller.openInput(diff("two"), { preview: true, focus: false });
const tabs = () => Object.values(useTabs.getState().panes).flatMap((pane) => pane.tabs);
expect(tabs().map((t) => [t.input.key, t.preview])).toEqual([["two", true]]);
expect(controller.activeInput({ previewOnly: true })?.key).toBe("two");
// Files still don't preview.
await controller.openFile("/p/a.ts", { preview: true, focus: false });
await controller.openFile("/p/b.ts", { preview: true, focus: false });
expect(openFilePaths(useTabs.getState()).sort()).toEqual(["/p/a.ts", "/p/b.ts"]);
// A kept diff tab stays.
const pane = useTabs.getState().activePane;
controller.keepTab(pane, tabs().find((t) => t.input.key == "two")!.id);
await controller.openInput(diff("three"), { preview: true, focus: false });
expect(
tabs()
.filter((t) => t.input.kind == "test-diff")
.map((t) => t.input.key),
).toEqual(["two", "three"]);
});
it("keeps an earlier regular file without removing the newer preview", async () => {
const { started, response } = delayProvider();
const controller = setup();
+45
Переглянути файл
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import type { CodeAction } from "@/bindings";
import { unambiguousImport } from "./autoImport";
const action = (title: string, over: Partial<CodeAction> = {}): CodeAction => ({
title,
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 1,
...over,
});
describe("unambiguousImport", () => {
it("applies the one import fix among other quick fixes", () => {
const fix = action("Import 'ArrayList' (java.util)");
expect(unambiguousImport([action("Create class 'ArrayList'"), fix])).toBe(fix);
});
it("recognizes C#'s add-using fix, titled with the directive", () => {
// csharp-ls (Roslyn) for an unresolved `SceneManager`.
const using = action("using UnityEngine.SceneManagement;", { isPreferred: true });
const actions = [
using,
action("Generate field 'SceneManager' in 'Player'", { kind: null }),
action("UnityEngine.SceneManagement.SceneManager", { kind: null }),
action("Generate class 'SceneManager'", { kind: null }),
];
expect(unambiguousImport(actions)).toBe(using);
expect(unambiguousImport([action("using static System.Math;")])?.title).toBe("using static System.Math;");
});
it("leaves ambiguous, disabled and non-import fixes alone", () => {
expect(unambiguousImport([action("using A.Scenes;"), action("using B.Scenes;")])).toBeNull();
expect(
unambiguousImport([action("using UnityEngine.SceneManagement;", { disabledReason: "unavailable" })]),
).toBeNull();
expect(unambiguousImport([action("using UnityEngine.SceneManagement;", { kind: "refactor" })])).toBeNull();
expect(unambiguousImport([action("Remove unnecessary usings")])).toBeNull();
expect(unambiguousImport([action("UnityEngine.SceneManagement.SceneManager")])).toBeNull();
});
});
+9 -1
Переглянути файл
@@ -16,13 +16,21 @@ import { offsetsToRange, rangeToOffsets } from "./positions";
import { featureBackoff } from "./availability";
const IDLE_MS = 1500;
/**
* C#'s add-import fix: Roslyn (csharp-ls) titles it with the directive itself,
* `using UnityEngine.SceneManagement;`, never with the word "import".
*/
export const CSHARP_USING_FIX = /^using (?:static )?[\w.]+;$/;
const IMPORT_TITLE = /\bimport\b/i;
const importBackoff = featureBackoff();
/** The single import fix among `actions`, if exactly one exists. */
export function unambiguousImport(actions: readonly CodeAction[]): CodeAction | null {
const imports = actions.filter(
(a) => !a.disabledReason && IMPORT_TITLE.test(a.title) && (!a.kind || a.kind.startsWith("quickfix")),
(a) =>
!a.disabledReason &&
(IMPORT_TITLE.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
(!a.kind || a.kind.startsWith("quickfix")),
);
return imports.length === 1 ? imports[0]! : null;
}
+4
Переглянути файл
@@ -151,6 +151,8 @@ describe("paste import selection", () => {
"Import `std::collections::HashMap`",
'Add import: "fmt"',
"Add 'useState' to existing import declaration from 'react'",
"using UnityEngine.SceneManagement;",
"using static System.Math;",
])("recognizes the import quick fix %s", (title) => {
expect(pastedImport([action({ title }), action({ title: "Create class ArrayList" })])?.title).toBe(title);
});
@@ -165,6 +167,8 @@ describe("paste import selection", () => {
{ title: "Remove unused import" },
{ title: "Import all missing names" },
{ title: "Optimize imports" },
{ title: "UnityEngine.SceneManagement.SceneManager" },
{ title: "Remove unnecessary usings" },
])
expect(pastedImport([action(over)])).toBeNull();
expect(pastedImport([action({ isPreferred: true }), action({ title: "Import 'ArrayList' (other)" })])).toBeNull();
+2 -1
Переглянути файл
@@ -11,6 +11,7 @@ import { docOf, lspRequest } from "./lsp";
import { comparePos, rangeToOffsets } from "./positions";
import { closePopup, openPopup, useLspPopup, type LspPopup } from "./popupStore";
import { actionsForDiagnostic } from "./intentions";
import { CSHARP_USING_FIX } from "./autoImport";
const WAIT_MS = 8000;
const SETTLE_MS = 200;
@@ -47,7 +48,7 @@ export function pastedImport(actions: readonly CodeAction[]): CodeAction | null
(a) =>
a.disabledReason == null &&
(!a.kind || a.kind === "quickfix" || a.kind.startsWith("quickfix.")) &&
IMPORT_FIX.test(a.title) &&
(IMPORT_FIX.test(a.title) || CSHARP_USING_FIX.test(a.title)) &&
!/^import (?:all|missing)\b/i.test(a.title),
);
return imports.length === 1 ? imports[0]! : null;
+20 -1
Переглянути файл
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Diagnostic, FileProblems } from "@/bindings";
const state = vi.hoisted(() => ({
trusted: true as boolean | undefined,
projectChanged: () => {},
trustChanged: () => {},
remoteChanged: () => {},
report: vi.fn(),
}));
@@ -20,9 +22,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => ({
vi.mock("@/platform/project", () => ({
useProject: {
getState: () => ({ project: { root: "/p" } }),
getState: () => ({ project: { root: "/p", trusted: state.trusted } }),
subscribe: (fn: (s: unknown, prev: unknown) => void) => {
state.projectChanged = () => fn({ project: { root: "/p" } }, { project: null });
state.trustChanged = () =>
fn({ project: { root: "/p", trusted: true } }, { project: { root: "/p", trusted: false } });
return () => {};
},
},
@@ -58,6 +62,7 @@ describe("reportProblems", () => {
clearProblems();
reports.length = 0;
state.report.mockReset();
state.trusted = true;
applyDiagnosticsEvent("/p/a.rs", "ra", [d(1), d(2)]);
stop = reportProblems();
});
@@ -76,6 +81,20 @@ describe("reportProblems", () => {
]);
});
it("reports nothing without a retry timer in a restricted project, then once when trusted", async () => {
stop();
state.trusted = false;
reports.length = 0;
stop = reportProblems();
await vi.advanceTimersByTimeAsync(5000);
expect(reports).toHaveLength(0);
expect(vi.getTimerCount()).toBe(0);
state.trusted = true;
state.trustChanged();
await vi.advanceTimersByTimeAsync(1000);
expect(summary()).toEqual([[true, [["/p/a.rs", 2]]]]);
});
it("retries a failed delta with the full snapshot", async () => {
await vi.advanceTimersByTimeAsync(1000);
state.report.mockRejectedValueOnce(new Error("disconnected"));
+4 -2
Переглянути файл
@@ -13,7 +13,9 @@ export function reportProblems(): () => void {
let timer: ReturnType<typeof setTimeout> | null = null;
const flush = () => {
timer = null;
if (!useProject.getState().project) return;
const project = useProject.getState().project;
// Restricted Mode refuses this command; the trust change below resets and reschedules.
if (!project || project.trusted === false) return;
const map = useProblems.getState().map;
const files: FileProblems[] = [];
for (const [path, sources] of map)
@@ -37,7 +39,7 @@ export function reportProblems(): () => void {
if (s.map !== prev.map) schedule();
});
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) {
if (s.project?.root !== prev.project?.root || s.project?.trusted !== prev.project?.trusted) {
reset = true;
reported = new Map();
schedule();
+2 -2
Переглянути файл
@@ -439,7 +439,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
</marker>
</defs>
{arrangement &&
edges.map((e, i) => {
edges.map((e) => {
const [from, to] = [nodes[e.from]!, nodes[e.to]!];
const [a, b] = [boxOf(from.key), boxOf(to.key)];
if (!a || !b || arrangement.hidden.has(from.key) || arrangement.hidden.has(to.key)) return null;
@@ -447,7 +447,7 @@ export function DiagramView({ data, onJump }: { data: DiagramData; onJump?: () =
const toY = rowCenter(to, b, arrangement.collapsed.has(to.key), e.toColumns[0]);
return (
<path
key={i}
key={`${from.key}:${e.fromColumns.join(",")}→${to.key}:${e.toColumns.join(",")}`}
className={clsx(styles.link, e.optional && styles.optional)}
d={linkPath(a, fromY, b, toY)}
markerEnd={`url(#${markerId})`}
+9 -1
Переглянути файл
@@ -1495,7 +1495,15 @@ function QuickDoc({ node, anchor }: { node: DbNode; anchor: { x: number; y: numb
);
}
function SourceFolderDialog({ folder, sources = [] }: { folder: DbSourceFolder | null; sources?: string[] }) {
const NO_SOURCES: readonly string[] = [];
function SourceFolderDialog({
folder,
sources = NO_SOURCES,
}: {
folder: DbSourceFolder | null;
sources?: readonly string[];
}) {
const [name, setName] = useState(folder?.name ?? "");
const [busy, setBusy] = useState(false);
const submit = async () => {
+5 -1
Переглянути файл
@@ -742,7 +742,11 @@ export function WorkspaceEditor({ input }: { input: EditorInput }) {
) : (
<div role="log" tabIndex={0} className={dbStyles.output} aria-label={t("Feedback")}>
{results.map(({ data }, index) => (
<div key={index} className={dbStyles.outputLine}>
<div
// oxlint-disable-next-line react/no-array-index-key -- results are append-only; the result number is the identity
key={index}
className={dbStyles.outputLine}
>
{resultLabel(index + 1)} · {t`${data.rows.length} rows`}
{data.elapsedMs !== null && ` · ${formatElapsed(data.elapsedMs)}`}
</div>
+10 -2
Переглянути файл
@@ -31,7 +31,11 @@ function Row({ row, width, target }: { row: MemoryRow; width: number; target: bi
{COLUMN_OFFSETS.map((_, i) => {
const byte = row.bytes[i];
return (
<span key={i} className={clsx(styles.byte, i === at && styles.target, byte === null && styles.unreadable)}>
<span
// oxlint-disable-next-line react/no-array-index-key -- byte column position is the cell's identity
key={i}
className={clsx(styles.byte, i === at && styles.target, byte === null && styles.unreadable)}
>
{byte === undefined ? " " : hexByte(byte)}
</span>
);
@@ -39,7 +43,11 @@ function Row({ row, width, target }: { row: MemoryRow; width: number; target: bi
</span>
<span role="gridcell" className={styles.ascii}>
{row.bytes.map((byte, i) => (
<span key={i} className={clsx(i === at && styles.target, byte === null && styles.unreadable)}>
<span
// oxlint-disable-next-line react/no-array-index-key -- an unreadable byte has no value; position is the identity
key={i}
className={clsx(i === at && styles.target, byte === null && styles.unreadable)}
>
{asciiChar(byte)}
</span>
))}
+3 -1
Переглянути файл
@@ -42,7 +42,9 @@ export function activate(): () => void {
const report = () => {
if (timer) clearTimeout(timer);
timer = null;
if (!useProject.getState().project) return;
const project = useProject.getState().project;
// Restricted Mode refuses these commands; the trust change below reschedules the report.
if (!project || project.trusted === false) return;
const paths = openEditorPaths();
const editor = activeEditor();
const focused = document.hasFocus();
+21
Переглянути файл
@@ -181,6 +181,27 @@ describe("MCP editor reports", () => {
await vi.advanceTimersByTimeAsync(300);
expect(state.uiReady).toHaveBeenCalledWith(true);
});
it("sends no editor reports and runs no retry timer in a restricted project", async () => {
stop();
state.trusted = false;
state.reportOpen.mockClear();
state.reportFocused.mockClear();
stop = activate();
await vi.advanceTimersByTimeAsync(5000);
expect(state.reportOpen).not.toHaveBeenCalled();
expect(state.reportFocused).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
state.trusted = true;
state.trustChanged();
await vi.advanceTimersByTimeAsync(300);
expect(state.reportOpen).toHaveBeenCalledTimes(1);
expect(state.reportFocused).toHaveBeenCalledTimes(1);
});
it("retries a failed editor report in a trusted project", async () => {
state.reportOpen.mockRejectedValueOnce(new Error("disconnected"));
await vi.advanceTimersByTimeAsync(600);
expect(state.reportOpen).toHaveBeenCalledTimes(2);
});
it("forwards remote editor reports and stops after disposal", async () => {
state.remote = true;
await vi.advanceTimersByTimeAsync(300);
+1
Переглянути файл
@@ -685,6 +685,7 @@ export function TomcatSettings({ config, onChange }: { config: RunConfig; onChan
<div className={styles.appServersList} role="listbox" aria-label={tx("Deploy at the server startup")}>
{deployments.map((d, i) => (
<div
// oxlint-disable-next-line react/no-array-index-key -- deployments are reordered and selected by position; position is the identity
key={i}
role="option"
aria-selected={i === selectedIdx}
+18 -7
Переглянути файл
@@ -12,6 +12,17 @@ def tc = { String s ->
.replace('[', '|[').replace(']', '|]')
}
// `name='method(Type)[1]' className='a.B'`; an invocation of a parameterized, repeated or dynamic
// test (its parent is the method, not the class) adds `invocation='[1] a'`, its display name.
def id = { TestDescriptor test ->
def own = "name='${tc(test.name)}' className='${tc(test.className)}'"
def parent = test.parent
if (parent == null || parent.className != test.className || parent.name == test.className) return own
// `getDisplayName` is Gradle 4.10+.
def shown = test.hasProperty('displayName') ? test.displayName : test.name
"${own} invocation='${tc(shown)}'"
}
allprojects {
each(tasks.withType(Test)) { Test task ->
task.outputs.upToDateWhen { false }
@@ -21,29 +32,29 @@ allprojects {
void afterSuite(TestDescriptor suite, TestResult result) {}
void beforeTest(TestDescriptor test) {
println "##teamcity[testStarted name='${tc(test.name)}' className='${tc(test.className)}']"
println "##teamcity[testStarted ${id(test)}]"
}
void afterTest(TestDescriptor test, TestResult result) {
def id = "name='${tc(test.name)}' className='${tc(test.className)}'"
def own = id(test)
def type = result.resultType.toString()
if (type == 'FAILURE') {
def error = result.exception
def trace = new StringWriter()
error?.printStackTrace(new PrintWriter(trace))
println "##teamcity[testFailed ${id} message='${tc(error?.toString())}' details='${tc(trace.toString())}']"
println "##teamcity[testFailed ${own} message='${tc(error?.toString())}' details='${tc(trace.toString())}']"
} else if (type == 'SKIPPED') {
println "##teamcity[testIgnored ${id}]"
println "##teamcity[testIgnored ${own}]"
}
println "##teamcity[testFinished ${id} duration='${result.endTime - result.startTime}']"
println "##teamcity[testFinished ${own} duration='${result.endTime - result.startTime}']"
}
})
task.addTestOutputListener(new TestOutputListener() {
void onOutput(TestDescriptor test, TestOutputEvent output) {
if (test.className == null) return
// A class's own output (`@BeforeAll`, `@AfterAll`) carries no test name.
def name = test.composite ? '' : " name='${tc(test.name)}'"
println "##teamcity[testStdOut${name} className='${tc(test.className)}' out='${tc(output.message)}']"
def own = test.composite ? "className='${tc(test.className)}'" : id(test)
println "##teamcity[testStdOut ${own} out='${tc(output.message)}']"
}
})
}
+14
Переглянути файл
@@ -574,6 +574,14 @@ describe("coverage and profiling", () => {
);
});
it("are refused on WSL, with a notification", () => {
const wsl: RunTargetValid = { ...DEFAULT_RUN_TARGET, kind: "wsl", id: "w", name: "Ubuntu", distro: "Ubuntu" };
expect(containerExecutorBlocked(cfg("app", { target: "w" }), [box, wsl])).toBe(true);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Coverage and profiling are not supported on WSL", level: "warning" }),
);
});
it("are left alone locally and over SSH", () => {
expect(containerExecutorBlocked(cfg("app"), [box, container])).toBe(false);
expect(containerExecutorBlocked(cfg("app", { target: "box" }), [box, container])).toBe(false);
@@ -598,6 +606,12 @@ describe("the container a run is in", () => {
expect(containerTarget(cfg("a", { kind: "python" }), targets)).toBeNull();
expect(containerTarget(cfg("a", { target: "web" }), targets)).toBe("web");
});
it("is a WSL target too: its printed paths are looked up there", () => {
const wsl: RunTargetValid = { ...DEFAULT_RUN_TARGET, kind: "wsl", id: "w", name: "w", distro: "Ubuntu" };
settings(".venv/bin/python");
expect(containerTarget(cfg("a", { target: "w" }), [box, wsl])).toBe("w");
});
});
describe("SSH remedies when starting", () => {
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more