diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 056f3c7..e0ab8c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,18 +2,41 @@ name: CI on: pull_request: + types: [opened, synchronize, reopened, ready_for_review] push: branches: [main] permissions: contents: read +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: + linux: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: dtolnay/rust-toolchain@1.100.0 + with: + components: rustfmt, clippy, rust-analyzer, rust-src + - run: cargo fmt --manifest-path backend/Cargo.toml --all --check + - run: cargo clippy --manifest-path backend/Cargo.toml --all-targets --locked -- -D warnings + - run: cargo test --locked --manifest-path backend/Cargo.toml + - run: cargo build --locked --manifest-path backend/Cargo.toml + - run: node scripts/run/actions.mjs backend/target/debug/backend + # The backend, the Cargo build provider that also starts rust-analyzer, built # for each archive on the system that links it: a universal binary on macOS, # x64 and ARM64 (cross-built with the MSVC ARM64 tools) on Windows. Its unit # tests run where the runner can execute what it builds. backend: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft runs-on: ${{ matrix.os }} timeout-minutes: 30 strategy: @@ -37,15 +60,23 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Install the Rust targets - shell: bash - run: rustup target add ${{ matrix.targets }} + - uses: dtolnay/rust-toolchain@1.100.0 + with: + targets: ${{ matrix.targets }} + components: rust-analyzer, rust-src - name: Test the backend if: matrix.test working-directory: backend run: cargo test --locked - name: Build the backend run: node scripts/build-backend.mjs ${{ matrix.platform }} + - name: Execute current file and an individual test with rust-analyzer + if: matrix.test + shell: bash + run: | + backend=".artifacts/backend-${{ matrix.platform }}/backend" + if [[ "$RUNNER_OS" == Windows ]]; then backend+=".exe"; fi + node scripts/run/actions.mjs "$backend" - uses: actions/upload-artifact@v4 with: name: backend-${{ matrix.platform }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ef8da3..32ceb00 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,9 +36,9 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Install the Rust targets - shell: bash - run: rustup target add ${{ matrix.targets }} + - uses: dtolnay/rust-toolchain@1.100.0 + with: + targets: ${{ matrix.targets }} - name: Build the backend run: node scripts/build-backend.mjs ${{ matrix.platform }} - uses: actions/upload-artifact@v4 diff --git a/README.md b/README.md index 1f4b847..c0d1a93 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,14 @@ cargo、rustup 和 rust-analyzer 用你电脑上的,CodeLLDB 在第一次调 本插件取代 `lithe-plugin-cargo`。两个插件都声明了 `cargo` 构建系统,不要同时启用。 +## 当前文件与单个函数/测试运行 + +插件通过 rust-analyzer `experimental/runnables` 识别 main、测试模块和单个测试函数,保留 Cargo package、target、features、环境变量及精确 filter。 + +点击前重新读取文档、校验路径和版本,保存成功后才启动;rerun 会重新验证当前声明。工作区相对路径统一使用 `/`,拒绝绝对路径、盘符、反斜杠、`.`、`..` 与控制字符。构建窗口仍未提供测试树;单个测试可从编辑器 gutter 运行。 + +2026-11-30,Windows 11 x64 的真实运行、精确单测试、陈旧版本、保存失败、rerun 和不安全路径回归通过。截图由固定 Viva 无头宿主生成,覆盖明暗主题、中英文及 before/after/hover,见 [截图目录](docs/assets/current-file-runs/)。macOS 原生窗口仍待 CI/实机复验。后端构建工具链固定 Rust 1.100.0。 + ## 功能 | 功能 | 说明 | @@ -31,6 +39,7 @@ cargo、rustup 和 rust-analyzer 用你电脑上的,CodeLLDB 在第一次调 | 工具链 | 找到电脑上的 cargo、rustup 和 rust-analyzer;项目可以固定用其中一个 Cargo | | 设置预览 | Rust 语言页和 Cargo 构建工具页画出设置的效果,见下文“设置预览” | + ## 设置和构建选项 **插件设置**(设置 → 插件 → Rust Support →「设置」,也显示在「语言与框架 › Rust」页),开关默认都开启: @@ -181,7 +190,7 @@ rust-analyzer 和 CodeLLDB 的启动结果由 Lithe 记在插件的日志通道 ## 本地打包 -需要 Rust 工具链和对应的 target(`rustup target add`)、Node.js 22+ 和 `zip`。macOS 上构建 darwin(通用二进制,ad-hoc 签名), +需要 Rust 1.100.0 工具链和对应的 target(`rustup target add`)、Node.js 22+ 和 `zip`。macOS 上构建 darwin(通用二进制,ad-hoc 签名), Windows 上构建 windows-x64 和 windows-arm64: ```bash diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 624c7f3..383df94 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -8,6 +8,130 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "itoa" version = "1.0.19" @@ -20,6 +144,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lithe-plugin-sdk" version = "0.4.0" @@ -36,6 +166,21 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -62,6 +207,7 @@ dependencies = [ "lithe-plugin-sdk", "serde", "serde_json", + "url", ] [[package]] @@ -107,6 +253,18 @@ dependencies = [ "zmij", ] +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "syn" version = "3.0.10" @@ -118,12 +276,143 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index b36898a..735daf0 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -4,7 +4,7 @@ name = "rust-support-backend" version = "0.1.1" edition = "2021" license = "Apache-2.0" -rust-version = "1.87" +rust-version = "1.100" publish = false description = "The backend of the Rust Support plugin for Lithe: the Cargo build provider and the settings previews." @@ -18,6 +18,7 @@ path = "src/main.rs" lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust", rev = "06a4c7976efcc4ef06fb364a966777390c58df14" } serde = { version = "1", features = ["derive"] } serde_json = "1" +url = "2" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/backend/src/actions.rs b/backend/src/actions.rs new file mode 100644 index 0000000..7fb5408 --- /dev/null +++ b/backend/src/actions.rs @@ -0,0 +1,541 @@ +//! rust-analyzer runnables connected to the host Run window. + +use lithe_plugin_sdk::{ + Backend, BackendHandle, Cancellation, Context, FunctionError, Subscription, WorkspaceContext, +}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +const COLLECT: &str = "rust.collectActions"; +const INVOKE: &str = "rust.runAction"; +const RERUN: &str = "rust.rerun"; + +pub struct Runs { + handle: BackendHandle, + stop: Cancellation, + worker: Mutex>>, + bindings: Mutex>, + analysis_ready: Mutex>, + progress_ready: Mutex>, +} + +// The desktop presents its translated editor-action failure; no plugin UI text is returned. +fn invalid() -> FunctionError { + FunctionError::internal("rust.run.invalidTarget") +} + +fn safe_path(path: &str) -> bool { + !path.is_empty() + && !path.contains(['\\', ':']) + && !path.chars().any(char::is_control) + && path.split('/').all(|part| !matches!(part, "" | "." | "..")) +} + +fn workspace(context: &Context) -> Result { + let reference = context.workspace_context().ok_or_else(invalid)?; + let full = context.host().workspace().get_context(reference)?; + if full["authority"]["kind"] != "local" { + return Err(invalid()); + } + let folders = full["folders"] + .as_array() + .filter(|folders| folders.len() == 1) + .ok_or_else(invalid)?; + let root = folders[0]["path"].as_str().ok_or_else(invalid)?; + Ok(std::path::PathBuf::from(root)) +} + +/// Ask the already-running semantic service. No scan, Cargo process or user +/// code runs during collection, including for macro-generated test functions. +fn query(path: &str, context: &Context) -> Result, FunctionError> { + if !safe_path(path) { + return Err(invalid()); + } + let reference = context.workspace_context().ok_or_else(invalid)?; + let root = workspace(context)?; + let uri = url::Url::from_file_path(root.join(path)).map_err(|_| invalid())?; + let answer = match context.host().request( + "lithe/host/languageServer/request", + json!({ + "context": reference.to_value(), "serverID": "rust", "method": "experimental/runnables", + "params": {"textDocument": {"uri": uri.as_str()}}, "timeoutMilliseconds": 3500 + }), + ) { + Ok(answer) => answer, + Err(error) if error.code() == "plugin.host.languageServerUnavailable" => return Ok(vec![]), + // A concurrent edit or workspace load can cancel an otherwise valid + // semantic read. Completion notifications refresh the initial result; + // edits already trigger collection. Other upstream failures propagate. + Err(error) if analysis_pending(&error) => return Ok(vec![]), + Err(error) => return Err(error.into()), + }; + if answer["value"].is_null() { + return Ok(vec![]); + } + let values = answer["value"].as_array().ok_or_else(invalid)?; + Ok(values + .iter() + .filter(|value| { + value["location"]["targetUri"] + .as_str() + .is_some_and(|uri| same_file(uri, &root.join(path))) + }) + .filter(|value| value["kind"] == "cargo" && value["args"]["overrideCargo"].is_null()) + .take(1000) + .cloned() + .collect()) +} + +fn analysis_pending(error: &lithe_plugin_sdk::SdkError) -> bool { + error.code() == "plugin.host.languageServerError" + && error + .details() + .and_then(|details| details.get("code")) + .and_then(Value::as_i64) + .is_some_and(|code| matches!(code, -32801 | -32802)) +} + +/// Compare native file identities after URL decoding and filesystem resolution. +/// This handles drive casing, verbatim prefixes, spaces, Unicode and symlinks +/// without treating a similarly named file outside the workspace as this file. +fn same_file(uri: &str, file: &std::path::Path) -> bool { + let Ok(uri) = url::Url::parse(uri) else { + return false; + }; + if uri.query().is_some() || uri.fragment().is_some() { + return false; + } + let Ok(path) = uri.to_file_path() else { + return false; + }; + matches!((crate::paths::resolve(&path), crate::paths::resolve(file)), + (Some(left), Some(right)) if left == right) +} + +fn collect(params: Value, context: &Context) -> Result { + context.check_cancelled()?; + let path = params["document"]["path"].as_str().ok_or_else(invalid)?; + let values = query(path, context)?; + let source = params["text"].as_str().ok_or_else(invalid)?; + let actions: Vec<_> = values.iter().enumerate().filter_map(|(index, runnable)| { + let range = &runnable["location"]["targetSelectionRange"]; + if !valid_range(source, range) { return None; } + let line = range["start"]["line"].as_u64()? + 1; + let column = range["start"]["character"].as_u64()? + 1; + let label = runnable["label"].as_str().unwrap_or("Cargo"); + let test = runnable["args"]["cargoArgs"][0] == "test"; + let exact = runnable["args"]["executableArgs"].as_array().is_some_and(|args| args.iter().any(|arg| arg == "--exact")); + Some(json!({"id": format!("rust-{index}"), "title": label.chars().filter(|c| !c.is_control()).take(200).collect::(), + "icon": if test { if exact {"test"} else {"run-all"} } else {"run"}, + "range": {"start": {"line": line, "column": column}, "end": {"line": line, "column": column}}, + "invoke": {"functionID": INVOKE, "params": {"path": path, "label": label, "location": runnable["location"]}}})) + }).collect(); + Ok(json!({"actions": actions})) +} + +fn valid_range(source: &str, range: &Value) -> bool { + let valid = |position: &Value| -> Option<(u64, u64)> { + let row = position["line"].as_u64()?; + let column = position["character"].as_u64()?; + let line = source + .split('\n') + .nth(usize::try_from(row).ok()?)? + .trim_end_matches('\r'); + let mut utf16 = 0; + for ch in line.chars() { + if utf16 == column { + return Some((row, column)); + } + utf16 += ch.len_utf16() as u64; + } + (utf16 == column).then_some((row, column)) + }; + matches!((valid(&range["start"]), valid(&range["end"])), (Some(start), Some(end)) if start <= end) +} + +fn invoke(params: Value, context: &Context) -> Result { + context.check_cancelled()?; + let reference = context.workspace_context().ok_or_else(invalid)?; + let host = context.host(); + let snapshot = host + .documents() + .get_snapshot(reference, json!({"documentID": params["documentID"]}))?; + let data = ¶ms["data"]; + if snapshot["document"]["version"] != params["expectedVersion"] + || snapshot["document"]["path"] != data["path"] + { + return Err(invalid()); + } + let path = data["path"].as_str().ok_or_else(invalid)?; + let runnable = query(path, context)? + .into_iter() + .find(|value| value["label"] == data["label"] && value["location"] == data["location"]) + .ok_or_else(invalid)?; + let root = workspace(context)?; + let process = process(&root, &runnable)?; + host.request("lithe/host/documents/save", json!({"context": reference.to_value(), "documentID": params["documentID"], "expectedVersion": params["expectedVersion"]}))?; + context.check_cancelled()?; + Ok(host.request("lithe/host/run/start", json!({"context": reference.to_value(), + "label": runnable["label"].as_str().unwrap_or("Cargo").chars().filter(|c| !c.is_control()).take(256).collect::(), "process": process, "rerun": {"function": RERUN, "data": data}}))?) +} + +/// Preserve rust-analyzer's package/target/features/filter flags. The host +/// resolves the selected Cargo toolchain; absolute/outside working directories +/// and shell overrides cannot change that authority. +fn process(root: &std::path::Path, runnable: &Value) -> Result { + let args = &runnable["args"]; + let root = crate::paths::resolve(root).ok_or_else(invalid)?; + let cwd = crate::paths::resolve(std::path::Path::new( + args["cwd"].as_str().ok_or_else(invalid)?, + )) + .filter(|path| path.is_dir()) + .ok_or_else(invalid)?; + let relative = cwd.strip_prefix(&root).map_err(|_| invalid())?; + if relative + .components() + .any(|part| !matches!(part, std::path::Component::Normal(_))) + { + return Err(invalid()); + } + let directory = relative.to_str().ok_or_else(invalid)?.replace('\\', "/"); + fn strings(value: &Value) -> Result, FunctionError> { + value + .as_array() + .filter(|args| { + args.len() <= 1000 + && args + .iter() + .all(|arg| arg.as_str().is_some_and(|s| !s.contains('\0'))) + }) + .cloned() + .ok_or_else(invalid) + } + let mut arguments = strings(&args["cargoArgs"])?; + if !args["cargoExtraArgs"].is_null() { + arguments.extend(strings(&args["cargoExtraArgs"])?); + } + let executable = strings(&args["executableArgs"])?; + if !executable.is_empty() { + arguments.push(json!("--")); + arguments.extend(executable); + } + let environment = args + .get("environment") + .cloned() + .unwrap_or_else(|| json!({})); + if !environment + .as_object() + .is_some_and(|env| env.values().all(Value::is_string)) + { + return Err(invalid()); + } + Ok( + json!({"executable": {"kind": "tool", "tool": "cargo"}, "arguments": arguments, + "workingDirectory": if directory.is_empty() {"."} else {&directory}, "environment": environment}), + ) +} + +fn rerun(data: Value, context: &Context) -> Result { + let reference = context.workspace_context().ok_or_else(invalid)?; + let documents = context.host().documents().list(reference)?; + let document = documents["documents"] + .as_array() + .into_iter() + .flatten() + .find(|doc| doc["path"] == data["path"]) + .ok_or_else(invalid)?; + invoke( + json!({"documentID": document["documentID"], "expectedVersion": document["version"], "data": data}), + context, + ) +} + +impl Runs { + pub fn register(backend: &mut Backend) -> Result, FunctionError> { + let runs = Arc::new(Self { + handle: backend.handle(), + stop: Cancellation::new(), + worker: Mutex::new(None), + bindings: Mutex::new(HashMap::new()), + analysis_ready: Mutex::new(HashSet::new()), + progress_ready: Mutex::new(HashSet::new()), + }); + backend + .function(COLLECT, collect)? + .suppress_success_diagnostics(COLLECT)?; + backend.function(INVOKE, invoke)?.function(RERUN, rerun)?; + backend.on_initialize({ + let runs = Arc::clone(&runs); + move |init| { + if init.functions_version().is_some() { + runs.start_registration()?; + } + Ok(()) + } + }); + backend.on_shutdown({ + let runs = Arc::clone(&runs); + move || runs.close() + }); + for method in [ + "lithe/host/languageServer/didChangeState", + "lithe/host/languageServer/didReceiveNotification", + ] { + let runs = Arc::clone(&runs); + backend.on_host_notification(method, move |params| { + // Use standard progress and diagnostics: serverStatus requires + // a rust-analyzer capability the host does not advertise. + // Each boundary refreshes only once per context generation. + let progress = + params["method"] == "$/progress" && params["params"]["value"]["kind"] == "end"; + let ready = params["state"] == "running" + || params["method"] == "textDocument/publishDiagnostics" + || progress; + if params["serverID"] != "rust" || !ready { + return Ok(()); + } + let reference = WorkspaceContext::from_value(¶ms["context"])?; + let key = (reference.context_id().to_owned(), reference.generation()); + let mut analysis_ready = runs.analysis_ready.lock().unwrap(); + let mut progress_ready = runs.progress_ready.lock().unwrap(); + if params["state"] == "running" { + analysis_ready.remove(&key); + progress_ready.remove(&key); + } else if progress { + if !progress_ready.insert(key) { + return Ok(()); + } + } else if !analysis_ready.insert(key) { + // One refresh after initial analysis is sufficient. Edits + // already make the host collect from the current buffer. + return Ok(()); + } + drop(progress_ready); + drop(analysis_ready); + let mut bindings = runs.bindings.lock().unwrap(); + if bindings + .get(reference.context_id()) + .is_some_and(|(generation, _)| *generation == reference.generation()) + { + if let Some((_, old)) = bindings.remove(reference.context_id()) { + old.dispose()?; + } + } + drop(bindings); + runs.sync_reporting(); + Ok(()) + })?; + } + Ok(runs) + } + + /// The SDK holds its initialization state through the response. The one + /// startup worker waits for that boundary, with a deadline and cancellation. + fn start_registration(self: &Arc) -> Result<(), FunctionError> { + let runs = Arc::clone(self); + let worker = thread::Builder::new() + .name("rust-run-actions".into()) + .spawn(move || { + let deadline = Instant::now() + Duration::from_secs(10); + while !runs.handle.host().negotiated() { + if runs.stop.wait_timeout(Duration::from_millis(10)) { + return; + } + if Instant::now() >= deadline { + let _ = runs.handle.diagnostics().degraded( + "notification", + "rust.run.registrationFailed", + Some(1), + ); + return; + } + } + runs.sync_reporting(); + }) + .map_err(|_| FunctionError::internal("rust.run.registrationUnavailable"))?; + *self.worker.lock().unwrap() = Some(worker); + Ok(()) + } + + pub fn sync_reporting(&self) { + if self.stop.is_cancelled() { + return; + } + if let Err(error) = self.sync() { + if !self.stop.is_cancelled() && error.code() != "plugin.host.contextExpired" { + let _ = self.handle.diagnostics().degraded( + "notification", + "rust.run.registrationFailed", + Some(1), + ); + } + } + } + + fn sync(&self) -> Result<(), lithe_plugin_sdk::SdkError> { + let host = self.handle.host().with_cancellation(&self.stop); + if !host.supports("lithe/host/editor/registerActions")? + || !host.supports("lithe/host/run/start")? + { + return Ok(()); + } + let contexts = host.workspace().list_contexts()?; + let mut bindings = self.bindings.lock().unwrap(); + let mut seen = HashSet::new(); + for context in contexts["contexts"] + .as_array() + .into_iter() + .flatten() + .filter(|context| context["authority"]["kind"] == "local") + .take(32) + { + let reference = WorkspaceContext::from_value(context)?; + let id = reference.context_id().to_owned(); + seen.insert(id.clone()); + if bindings + .get(&id) + .is_some_and(|(generation, _)| *generation == reference.generation()) + { + continue; + } + if let Some((_, old)) = bindings.remove(&id) { + old.dispose()?; + } + let subscription = host.editor().register_actions( + &reference, + json!({ + "id": "rustRunActions", "function": COLLECT, + "selector": {"fileExtensions": ["rs"], "fileNames": []} + }), + )?; + bindings.insert(id, (reference.generation(), subscription)); + } + let gone: Vec<_> = bindings + .keys() + .filter(|id| !seen.contains(*id)) + .cloned() + .collect(); + for id in gone { + if let Some((_, old)) = bindings.remove(&id) { + old.dispose()?; + } + } + self.analysis_ready + .lock() + .unwrap() + .retain(|(id, generation)| { + bindings + .get(id) + .is_some_and(|(current, _)| current == generation) + }); + self.progress_ready + .lock() + .unwrap() + .retain(|(id, generation)| { + bindings + .get(id) + .is_some_and(|(current, _)| current == generation) + }); + Ok(()) + } + + fn close(&self) { + self.stop.cancel(); + if let Some(worker) = self.worker.lock().unwrap().take() { + // Cancelling also ends any outstanding SDK host request. + if worker.join().is_err() { + let _ = self.handle.diagnostics().degraded( + "shutdown", + "rust.run.registrationFailed", + Some(1), + ); + } + } + // The host withdraws all session bindings atomically at shutdown. + self.bindings.lock().unwrap().clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_the_exact_test_selector_and_toolchain() { + let directory = crate::paths::scratch("run-process"); + let root = directory.join("project with spaces 中文"); + std::fs::create_dir_all(root.join("member")).unwrap(); + let runnable = json!({"args": {"cwd": root.join("member"), "cargoArgs": ["test", "-p", "member", "--lib"], + "cargoExtraArgs": ["--features", "extra"], "executableArgs": ["tests::one", "--exact", "--nocapture"], + "environment": {"RUST_BACKTRACE": "1"}}}); + let process = process(&root, &runnable).unwrap(); + assert_eq!( + process["arguments"], + json!([ + "test", + "-p", + "member", + "--lib", + "--features", + "extra", + "--", + "tests::one", + "--exact", + "--nocapture" + ]) + ); + assert_eq!(process["workingDirectory"], "member"); + let mut outside = runnable; + outside["args"]["cwd"] = json!(directory); + assert!(super::process(&root, &outside).is_err()); + std::fs::remove_dir_all(directory).unwrap(); + } + + #[test] + fn file_uris_compare_decoded_native_paths() { + let root = crate::paths::scratch("run-uri"); + let path = root.join("main 中文 #.rs"); + std::fs::write(&path, "fn main() {}\n").unwrap(); + let uri = url::Url::from_file_path(&path).unwrap(); + assert!(same_file(uri.as_str(), &path)); + assert!(same_file(&uri.as_str().replace("%E4", "%e4"), &path)); + assert!(!same_file(&format!("{uri}#fragment"), &path)); + assert!(!same_file("https://example.invalid/main.rs", &path)); + assert!(!same_file(uri.as_str(), &root.join("another.rs"))); + #[cfg(windows)] + { + let drive = path.to_str().unwrap()[..1].to_ascii_lowercase(); + let lower = format!("file:///{drive}{}", &uri.as_str()[9..]); + assert!(same_file(&lower, &path), "{lower}"); + let verbatim = std::fs::canonicalize(&path).unwrap(); + assert!(same_file(uri.as_str(), &verbatim)); + } + std::fs::remove_dir_all(root).unwrap(); + } + + #[test] + fn ranges_follow_utf16_and_crlf_without_splitting_surrogates() { + let source = "// 😀\r\nfn main() {}\r\n"; + let range = |line, start, end| json!({"start": {"line": line, "character": start}, "end": {"line": line, "character": end}}); + assert!(valid_range(source, &range(0, 3, 5))); + assert!(!valid_range(source, &range(0, 4, 5))); + assert!(!valid_range(source, &range(0, 5, 6))); + assert!(!valid_range(source, &range(3, 0, 0))); + assert!(!valid_range(source, &range(1, 4, 2))); + } + + #[cfg(unix)] + #[test] + fn a_symlink_cannot_redirect_cargo_outside_the_workspace() { + let root = crate::paths::scratch("run-link"); + let outside = crate::paths::scratch("run-link-outside"); + std::os::unix::fs::symlink(&outside, root.join("member")).unwrap(); + let runnable = json!({"args": {"cwd": root.join("member"), "cargoArgs": ["run"], "executableArgs": []}}); + assert!(process(&root, &runnable).is_err()); + std::fs::remove_dir_all(root).unwrap(); + std::fs::remove_dir_all(outside).unwrap(); + } +} diff --git a/backend/src/main.rs b/backend/src/main.rs index 0dd4da2..57ef272 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -23,6 +23,7 @@ //! Cargo or rustup again. Cargo writes only to the project's target //! directory, and rustup only to its own toolchains. +mod actions; mod analyzer; mod cargo; mod dependencies; @@ -44,6 +45,11 @@ use std::sync::{Arc, OnceLock}; fn main() { let workspace: Arc> = Arc::new(OnceLock::new()); let mut backend = Backend::new("rust-support").version(env!("CARGO_PKG_VERSION")); + let runs = actions::Runs::register(&mut backend).expect("run action functions register"); + backend.on_contexts_changed(move |_| { + runs.sync_reporting(); + Ok(()) + }); let root = Arc::clone(&workspace); backend.on_initialize(move |initialize| { diff --git a/docs/assets/current-file-runs/src-main.rs-dark-en-after.png b/docs/assets/current-file-runs/src-main.rs-dark-en-after.png new file mode 100644 index 0000000..86517fa Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-en-after.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-dark-en-before.png b/docs/assets/current-file-runs/src-main.rs-dark-en-before.png new file mode 100644 index 0000000..c2f3096 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-en-before.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-dark-en-hover.png b/docs/assets/current-file-runs/src-main.rs-dark-en-hover.png new file mode 100644 index 0000000..7ebf706 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-en-hover.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-after.png b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-after.png new file mode 100644 index 0000000..4a64a64 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-after.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-before.png b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-before.png new file mode 100644 index 0000000..7173da6 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-before.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-hover.png b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-hover.png new file mode 100644 index 0000000..20235c7 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-dark-zh-Hans-hover.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-en-after.png b/docs/assets/current-file-runs/src-main.rs-light-en-after.png new file mode 100644 index 0000000..990b15f Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-en-after.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-en-before.png b/docs/assets/current-file-runs/src-main.rs-light-en-before.png new file mode 100644 index 0000000..7902de2 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-en-before.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-en-hover.png b/docs/assets/current-file-runs/src-main.rs-light-en-hover.png new file mode 100644 index 0000000..15bbeee Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-en-hover.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-after.png b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-after.png new file mode 100644 index 0000000..f6c91a3 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-after.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-before.png b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-before.png new file mode 100644 index 0000000..6b57046 Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-before.png differ diff --git a/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-hover.png b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-hover.png new file mode 100644 index 0000000..19f3f1b Binary files /dev/null and b/docs/assets/current-file-runs/src-main.rs-light-zh-Hans-hover.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 9c80b31..192df15 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -58,7 +58,7 @@ rustup 安装的 cargo 是指向 `rustup` 的符号链接,按启动时的名 **限制**: -- 不提供测试:构建窗口里没有测试树,也不能单独运行一个测试;`cargo test` 可以在终端里运行。 +- 构建窗口里没有测试树;编辑器 gutter 已支持 rust-analyzer 识别的测试模块和单个测试,使用 Cargo 精确 filter。 - 只读取打开的文件夹里的软件包;工作区成员在文件夹之外时不列出,记一条 WARN(`cargo.membersOutsideFolder`)。 - 依赖树超过 Core 的上限时截断(`cargo.dependencyTreeTruncated`)。 - 和 `lithe-plugin-cargo` 都声明了 `cargo` 构建系统,不要同时启用。 @@ -237,3 +237,13 @@ README 的“设置预览”放了其中的中文截图。没有做手工验收 `-windows-x64.zip` 和 `-windows-arm64.zip` 与 darwin 包只有后端程序不同(`bin/backend.exe`,包里的 `plugin.json` 相应改写启动路径)。CI 在 Windows x64 和 ARM64 上构建后端并跑单元测试,没有在 Windows 版 Lithe 里安装和运行过插件。 Windows 上 rustup 的代理是硬链接,cargo、rust-analyzer 的版本探针不受上面的 Core 修复影响。 + +## 当前文件与单个函数/测试运行(本次改动) + +| 能力 | macOS | Windows | 证据 | +| --- | --- | --- | --- | +| 当前文件入口、单函数/测试 gutter、保存与 rerun 校验、相对路径安全 | implemented / pending | implemented / pending | `backend/src/actions.rs`、`scripts/run/actions.mjs`、`docs/assets/current-file-runs/` | + +2026-11-30,本地开发包在原生 Windows 11 Pro x64 完成真实工具 action 回归和 Viva 无头截图。宿主固定 `4191c1553486247026c767ccd52b5cd9e8f38115`,Core 固定 `d426f018065c950754140295e857bc71b870139f`。已覆盖 main/脚本、精确单测试、保存失败、陈旧文档、声明移除、rerun 和含中文空格路径;没有把组件或无头测试记作完整原生窗口验收。macOS 原生窗口及其他架构仍待 CI/实机验证。 + +插件通过 rust-analyzer `experimental/runnables` 识别 main、测试模块和单个测试函数,保留 Cargo package、target、features、环境变量及精确 filter。 构建窗口仍未提供测试树;单个测试可从编辑器 gutter 运行。 diff --git a/e2e/host/desktop/internal/workbench/plugin_run_actions_visual_test.go b/e2e/host/desktop/internal/workbench/plugin_run_actions_visual_test.go new file mode 100644 index 0000000..b6f5b3a --- /dev/null +++ b/e2e/host/desktop/internal/workbench/plugin_run_actions_visual_test.go @@ -0,0 +1,139 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// This plugin-owned overlay paints public presentation fields from a real +// backend integration run. Execution is covered by scripts/run/actions.mjs; +// these images do not claim an installed-plugin click or a native window. +func TestPluginRunActionsVisual(t *testing.T) { + data, err := os.ReadFile(os.Getenv("LITHE_RUN_PROJECTION")) + if err != nil { + t.Fatal(err) + } + var fixtures []struct { + Path string + Text string + Actions []pluginservice.EditorAction + } + if err := json.Unmarshal(data, &fixtures); err != nil { + t.Fatal(err) + } + if len(fixtures) == 0 { + t.Fatal("missing integration fixtures") + } + out := os.Getenv("LITHE_RUN_VISUAL_OUTPUT") + if out == "" { + t.Fatal("missing screenshot output") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"light", "dark"} { + for _, language := range []string{"en", "zh-Hans"} { + for _, fixture := range fixtures { + t.Run(theme+"/"+language+"/"+filepath.Base(fixture.Path), func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(theme), Language: language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + root := filepath.Join(t.TempDir(), "RunSample") + path := filepath.Join(root, filepath.FromSlash(fixture.Path)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(fixture.Text), 0o600); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &semanticTestKernel{testKernel: &testKernel{Client: core.NewClient()}} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1440, 900 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(root) + p := h.app.project + h.app.openFile(p, path) + h.settleChain() + d := p.docs.byPath(path) + if d == nil { + t.Fatal("fixture did not open") + } + h.app.focusDocument(d.id) + paint := func() { h.app.invalidator.Invalidate(); h.settleChain() } + prefix := strings.ReplaceAll(fixture.Path, "/", "-") + "-" + theme + "-" + language + picture := func(state string) { + t.Helper() + if !h.shows(filepath.Base(path)) { + t.Fatal("editor tab is missing") + } + if err := session.Screenshot(filepath.Join(out, prefix+"-"+state+".png")); err != nil { + t.Fatal(err) + } + } + paint() + picture("before") + if len(fixture.Actions) == 0 { + t.Fatal("real backend returned no actions") + } + h.app.post(func(a *App) { + a.clearEditorActions(d) + snapshot := editorActionSnapshot{documentID: d.id, version: d.view.Revision(), collection: d.actionCollection} + a.presentEditorActions(p, snapshot, fixture.Actions, nil, nil) + }) + paint() + picture("after") + selected := fixture.Actions[0] + for _, action := range fixture.Actions { + if strings.Contains(strings.ToLower(action.Title), "selected") { + selected = action + break + } + } + lane, _, ok := editorActionPresentation(selected.Icon, h.app.colors.Dark) + if !ok { + t.Fatal("unknown backend icon") + } + slot := -1 + for index, current := range d.actionPanel.lanes { + if current == lane { + slot = index + break + } + } + if slot < 0 { + t.Fatal("action lane did not render") + } + cell := findGutterIconCell(t, d, selected.Range.StartLine-1, slot) + paint() + if err := h.driver.Move(cell.X+cell.Width/2, cell.Y+cell.Height/2); err != nil { + t.Fatal(err) + } + paint() + if !h.shows(selected.Title) { + t.Fatalf("missing real action tooltip %q", selected.Title) + } + picture("hover") + }) + } + } + } +} diff --git a/io.github.lithe-idea.rust-support/plugin.json b/io.github.lithe-idea.rust-support/plugin.json index 57abf43..fd80c10 100644 --- a/io.github.lithe-idea.rust-support/plugin.json +++ b/io.github.lithe-idea.rust-support/plugin.json @@ -35,12 +35,18 @@ "process.build", "project.generate", "ui.contribute", - "workspace.metadata" + "workspace.metadata", + "documents.read", + "documents.save", + "editor.actions", + "run.start", + "languageServer.request" ], "activationEvents": [ "onBuildSystem:cargo", "onDebug:codelldb", - "onLanguage:rust" + "onLanguage:rust", + "onWorkspaceOpen" ], "settings": [ { @@ -216,7 +222,14 @@ } } } - } + }, + "requestMethods": [ + "experimental/runnables" + ], + "forwardNotifications": [ + "textDocument/publishDiagnostics", + "$/progress" + ] } ], "buildSystems": [ diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..3bb51d5 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.100.0" +profile = "minimal" diff --git a/scripts/run/actions.mjs b/scripts/run/actions.mjs new file mode 100644 index 0000000..b130ab2 --- /dev/null +++ b/scripts/run/actions.mjs @@ -0,0 +1,82 @@ +// Real rust-analyzer -> real backend -> real Cargo. Only generic host services +// are scripted; selectors and launch arguments come from upstream semantics. +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {mkdirSync,mkdtempSync,readFileSync,writeFileSync} from 'node:fs'; +import {rm} from 'node:fs/promises'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath,pathToFileURL} from 'node:url'; +import {performance} from 'node:perf_hooks'; +import {Client} from './client.mjs'; + +const repository=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +const backend=resolve(process.argv[2]??join(repository,'backend/target/debug',process.platform==='win32'?'backend.exe':'backend')); +const stage=join(repository,'.artifacts/run');mkdirSync(stage,{recursive:true}); +const root=mkdtempSync(join(stage,'project with spaces 中文 ')); +const reference={contextID:'run-test',generation:1}; +const context={...reference,authority:{kind:'local'},folders:[{rootID:'root',path:root}]}; +const relative='src/main.rs'; +const source='fn main() { println!("MAIN_OK"); }\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn test_selected() { println!("SELECTED_OK"); }\n\n #[test]\n fn test_sibling() { panic!("SIBLING_MUST_NOT_RUN"); }\n}\n'; +mkdirSync(join(root,'src'));writeFileSync(join(root,relative),source);writeFileSync(join(root,'Cargo.toml'),'[package]\nname = "run-actions-fixture"\nversion = "0.1.0"\nedition = "2021"\n[workspace]\n'); +const uri=pathToFileURL(join(root,relative)).href; +const digest=createHash('sha256').update(readFileSync(backend)).digest('hex'); +const launches=[],events=[],results=[]; +let snapshot={document:{documentID:'document',version:1,path:relative},text:source},saveFailure=false,operation=0,registered,backendClient; +const registration=new Promise(resolve=>{registered=resolve;}); +let semanticError; +const analyzer=new Client(process.env.RUSTUP??'rustup',['run','1.100.0','rust-analyzer'],{cwd:root,windowsHide:true,notifications:(method,params)=>{ + if(['textDocument/publishDiagnostics','$/progress'].includes(method)&&backendClient)backendClient.notify('lithe/host/languageServer/didReceiveNotification',{context:reference,serverID:'rust',generation:1,method,params}); +}}); +backendClient=new Client(backend,[],{cwd:repository,windowsHide:true,hostRequests:{ + 'lithe/host/getCapabilities':()=>({services:{editor:{methods:['lithe/host/editor/registerActions']},run:{methods:['lithe/host/run/start']}}}), + 'lithe/host/workspace/listContexts':()=>({contexts:[context]}), + 'lithe/host/workspace/getContext':()=>context, + 'lithe/host/editor/registerActions':params=>{registered(params);return {subscriptionID:`actions-${++operation}`};}, + 'lithe/host/subscriptions/dispose':()=>({}), + 'lithe/host/languageServer/request':async params=>{ + if(semanticError!==undefined)throw Object.assign(Error('Test semantic response'),{rpcError:{code:-32023,message:'Language server error',data:{code:'plugin.host.languageServerError',details:{code:semanticError,message:'Test upstream response'}}}}); + try{return {value:await analyzer.request(params.method,params.params,15000)};}catch(error){if(!error.rpcError)throw error;throw Object.assign(Error('Language server error'),{rpcError:{code:-32023,message:'Language server error',data:{code:'plugin.host.languageServerError',details:error.rpcError}}});} + }, + 'lithe/host/documents/getSnapshot':()=>snapshot, + 'lithe/host/documents/list':()=>({documents:[snapshot.document]}), + 'lithe/host/documents/save':()=>{events.push('save');if(saveFailure)throw Error('test save refused');writeFileSync(join(root,relative),snapshot.text);return {document:snapshot.document};}, + 'lithe/host/run/start':params=>{events.push('start');launches.push(params);return {runID:`run-${launches.length}`};}, +}}); +function invoke(functionID,params){return backendClient.request('lithe/function/invoke',{context:reference,operationID:`run-${++operation}`,functionID,params},20000);} +function click(action,version=snapshot.document.version){return invoke('rust.runAction',{documentID:'document',expectedVersion:version,actionID:action.id,data:action.invoke.params});} +async function check(name,test){const start=performance.now();await test();results.push({name,milliseconds:Math.round(performance.now()-start)});console.log(`PASS ${name}`);} +function execute(plan){assert.deepEqual(plan.process.executable,{kind:'tool',tool:'cargo'});const run=spawnSync(process.env.CARGO??'cargo',plan.process.arguments,{cwd:join(root,plan.process.workingDirectory),env:{...process.env,...plan.process.environment},encoding:'utf8',timeout:60000,maxBuffer:4*1024*1024,windowsHide:true});assert.ifError(run.error);assert.equal(run.status,0,run.stdout+run.stderr);return run.stdout+run.stderr;} +try{ + await analyzer.request('initialize',{processId:null,rootUri:pathToFileURL(root).href,workspaceFolders:[{uri:pathToFileURL(root).href,name:'Run actions'}],capabilities:{window:{workDoneProgress:true},workspace:{configuration:true},textDocument:{publishDiagnostics:{}}},initializationOptions:{checkOnSave:false,cargo:{buildScripts:{enable:false}},procMacro:{enable:false}}},30000);analyzer.notify('initialized',{});analyzer.notify('textDocument/didOpen',{textDocument:{uri,languageId:'rust',version:1,text:source}}); + await backendClient.request('initialize',{capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}},10000);backendClient.notify('initialized',{}); + let timer;try{await Promise.race([registration,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Action registration timed out')),10000);})]);}finally{clearTimeout(timer);} + await check('only transient semantic cancellation is deferred',async()=>{ + try{for(const code of [-32801,-32802]){semanticError=code;assert.deepEqual((await invoke('rust.collectActions',snapshot)).actions,[]);}semanticError=-32603;await assert.rejects(invoke('rust.collectActions',snapshot));}finally{semanticError=undefined;} + }); + // Cold Cargo metadata loads asynchronously. The whole readiness loop is + // bounded and only used by this integration test, never during editor idle. + const deadline=performance.now()+45000;let actions=[]; + while(performance.now()value.title.includes('test_selected')))break;await new Promise(resolve=>setTimeout(resolve,100));} + const main=actions.find(value=>value.icon==='run'),selected=actions.find(value=>value.title.includes('test_selected')); + assert.ok(main,JSON.stringify(actions));assert.ok(selected,JSON.stringify(actions)); + await check('current file uses rust-analyzer main runnable',async()=>{events.length=0;await click(main);assert.deepEqual(events,['save','start']);assert.match(execute(launches.at(-1)),/MAIN_OK/);}); + await check('one exact Rust test excludes a failing sibling',async()=>{await click(selected);assert.ok(launches.at(-1).process.arguments.includes('--exact'));const output=execute(launches.at(-1));assert.match(output,/1 passed/);assert.doesNotMatch(output,/SIBLING_MUST_NOT_RUN/);}); + await check('stale version never saves or starts',async()=>{events.length=0;await assert.rejects(click(selected,0));assert.deepEqual(events,[]);}); + await check('save failure blocks execution',async()=>{events.length=0;saveFailure=true;try{await assert.rejects(click(selected));assert.deepEqual(events,['save']);}finally{saveFailure=false;}}); + await check('rerun revalidates the live document',async()=>{events.length=0;await invoke('rust.rerun',selected.invoke.params);assert.deepEqual(events,['save','start']);}); + await check('removed declaration never launches',async()=>{snapshot={...snapshot,document:{...snapshot.document,version:2},text:'fn main() {}\n'};analyzer.notify('textDocument/didChange',{textDocument:{uri,version:2},contentChanges:[{text:snapshot.text}]});events.length=0;await assert.rejects(click(selected));assert.deepEqual(events,[]);}); + await check('unsafe paths are rejected',async()=>{for(const path of ['../main.rs','C:/main.rs','a\\main.rs','/main.rs'])await assert.rejects(invoke('rust.collectActions',{document:{path},text:source}));}); + assert.equal(createHash('sha256').update(readFileSync(backend)).digest('hex'),digest); + writeFileSync(join(stage,'evidence.json'),JSON.stringify({platform:process.platform,architecture:process.arch,results,fixtures:[{path:relative,text:source,actions}],commands:launches.map(value=>value.process)},null,2)); +}finally{ + const cleanupErrors=[]; + for(const client of [backendClient,analyzer]){ + try{await client.request('shutdown',null,5000);client.notify('exit');}catch{} + try{await client.close();}catch(error){cleanupErrors.push(error);} + } + // Windows may retain handles briefly after the analyzer and Cargo exit. + // fs.rm retries only filesystem busy/permission failures, with a finite budget. + try{await rm(root,{recursive:true,force:true,maxRetries:10,retryDelay:100});}catch(error){cleanupErrors.push(error);} + if(cleanupErrors.length)throw new AggregateError(cleanupErrors,'Run integration cleanup failed'); +} diff --git a/scripts/run/client.mjs b/scripts/run/client.mjs new file mode 100644 index 0000000..f3407d0 --- /dev/null +++ b/scripts/run/client.mjs @@ -0,0 +1,46 @@ +// Bounded integration-test client. Each child owns a process group; cleanup +// runs after success, protocol failure, and request timeout. +import {spawn,execFileSync} from 'node:child_process'; +export class Client { + constructor(executable,args=[],options={}){ + this.hostRequests=options.hostRequests??{};this.notifications=options.notifications??(()=>{});const {hostRequests,notifications,...spawnOptions}=options; + this.next=1;this.pending=new Map();this.buffer=Buffer.alloc(0);this.stderr=''; + this.child=spawn(executable,args,{...spawnOptions,detached:true,stdio:['pipe','pipe','pipe']}); + this.exited=new Promise(resolve=>{this.child.once('exit',(code,signal)=>{this.fail(Error(`Process exited: ${code}/${signal}: ${this.stderr}`));resolve();});this.child.once('error',error=>{this.fail(error);resolve();});}); + this.child.stdin.on('error',error=>this.fail(error)); + this.child.stderr.on('data',bytes=>{this.stderr=(this.stderr+bytes).slice(-65536);}); + this.child.stdout.on('data',bytes=>{ + try{ + this.buffer=Buffer.concat([this.buffer,bytes]);if(this.buffer.length>16*1024*1024)throw Error('Protocol frame exceeds 16 MiB'); + while(true){ + const end=this.buffer.indexOf('\r\n\r\n');if(end<0)return; + const length=Number(/Content-Length: (\d+)/i.exec(this.buffer.subarray(0,end).toString())?.[1]); + if(!Number.isSafeInteger(length)||length>16*1024*1024)throw Error('Invalid protocol length'); + if(this.buffer.lengthhandler(message.params)).then(result=>this.send({id:message.id,result}),error=>this.send({id:message.id,error:error.rpcError??{code:-32603,message:error.message}}));} + else{const result=message.method==='workspace/configuration'?(message.params?.items??[]).map(()=>({})):null;this.send({id:message.id,result});} + }else if(message.method){this.notifications(message.method,message.params);} + else if(message.id!==undefined){const item=this.pending.get(message.id);if(item){this.pending.delete(message.id);clearTimeout(item.timer);message.error?item.reject(Object.assign(Error(JSON.stringify(message.error)),{rpcError:message.error})):item.resolve(message.result);}} + } + }catch(error){this.fail(error);} + }); + } + fail(error){this.failure=error;for(const item of this.pending.values()){clearTimeout(item.timer);item.reject(error);}this.pending.clear();} + send(message){const body=JSON.stringify({jsonrpc:'2.0',...message});this.child.stdin.write(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`);} + notify(method,params){this.send({method,params});} + request(method,params,timeout=60000){ + if(this.failure)return Promise.reject(this.failure); + const id=this.next++;return new Promise((resolve,reject)=>{ + const timer=setTimeout(()=>{this.pending.delete(id);reject(Error(`${method} timed out: ${this.stderr}`));},timeout); + this.pending.set(id,{resolve,reject,timer});this.send({id,method,params}); + }); + } + async close(){ + this.fail(Error('Client closed')); + if(this.child.pid){try{if(process.platform==='win32'){if(this.child.exitCode===null)execFileSync('taskkill.exe',['/PID',String(this.child.pid),'/T','/F'],{timeout:5000,windowsHide:true,stdio:'ignore'});}else process.kill(-this.child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH'&&!(process.platform==='win32'&&error.status===128))throw error;}} + let timer;try{await Promise.race([this.exited,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Process cleanup timed out')),5000);})]);}finally{clearTimeout(timer);} + } +} diff --git a/scripts/run/host.json b/scripts/run/host.json new file mode 100644 index 0000000..eda372d --- /dev/null +++ b/scripts/run/host.json @@ -0,0 +1,5 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA", + "revision": "4191c1553486247026c767ccd52b5cd9e8f38115", + "coreRevision": "d426f018065c950754140295e857bc71b870139f" +} diff --git a/scripts/run/process.mjs b/scripts/run/process.mjs new file mode 100644 index 0000000..d3ae40f --- /dev/null +++ b/scripts/run/process.mjs @@ -0,0 +1,37 @@ +// Integration-test tools run in owned process trees with bounded output and cleanup. +import {spawn,execFile} from 'node:child_process'; +const LIMIT=2*1024*1024; +export function runTool(tool,args,{cwd,env=process.env,timeout=120000}={}) { + let command=tool,parameters=args,verbatim=false; + if(process.platform==='win32'&&/\.(cmd|bat)$/i.test(tool)) { + const quote=value=>{if(/["%\r\n]/.test(value))throw Error('Unsupported batch test argument');return `"${value}"`;}; + command=process.env.ComSpec??'cmd.exe';parameters=['/d','/v:off','/s','/c',`"${[tool,...args].map(quote).join(' ')}"`];verbatim=true; + } + return new Promise((resolve,reject)=>{ + const child=spawn(command,parameters,{cwd,env,detached:process.platform!=='win32',windowsHide:true,windowsVerbatimArguments:verbatim,stdio:['ignore','pipe','pipe']}); + let output=Buffer.alloc(0),errorOutput=Buffer.alloc(0),failure,done=false,stopping=false,cleanup; + const kill=()=>{ + if(!child.pid)return; + if(process.platform==='win32') { + if(child.exitCode!==null)return; + execFile('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{timeout:5000,windowsHide:true},error=>{if(error&&child.exitCode===null)failure??=error;}); + } else {try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')failure??=error;}} + }; + const finish=()=>{ + if(done)return;done=true;clearTimeout(timer);clearTimeout(cleanup); + process.off('SIGINT',interrupt);process.off('SIGTERM',interrupt); + if(failure)reject(failure);else if(child.exitCode!==0)reject(Error(`Tool failed (${child.exitCode}): ${errorOutput.toString()}\n${output.toString()}`));else resolve(output); + }; + const stop=error=>{ + failure??=error;if(stopping)return;stopping=true;kill(); + cleanup=setTimeout(()=>{kill();child.stdout.destroy();child.stderr.destroy();child.unref();failure=Error('Tool cleanup timed out',{cause:failure});finish();},6000); + }; + const interrupt=()=>stop(Error('Tool interrupted')); + const timer=setTimeout(()=>stop(Error('Tool timed out')),timeout); + process.once('SIGINT',interrupt);process.once('SIGTERM',interrupt); + child.stdout.on('data',bytes=>{if(output.length+bytes.length>LIMIT)stop(Error('Tool output exceeds limit'));else output=Buffer.concat([output,bytes]);}); + child.stderr.on('data',bytes=>{if(errorOutput.length+bytes.length>LIMIT)stop(Error('Tool error output exceeds limit'));else errorOutput=Buffer.concat([errorOutput,bytes]);}); + child.once('error',error=>stop(error)); + child.once('close',()=>{kill();finish();}); + }); +} diff --git a/scripts/run/visual.mjs b/scripts/run/visual.mjs new file mode 100644 index 0000000..1c8e070 --- /dev/null +++ b/scripts/run/visual.mjs @@ -0,0 +1,42 @@ +// Render actual backend presentation fields in the pinned Viva workbench. +// This overlay remains in the plugin checkout; the host is never edited. +import assert from 'node:assert/strict'; +import {readFileSync,writeFileSync,mkdirSync,existsSync} from 'node:fs'; +import {resolve,join,dirname,delimiter} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {runTool} from './process.mjs'; +const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +if(!process.argv[2])throw Error('Usage: node scripts/run/visual.mjs '); +const host=resolve(process.argv[2]); +const bashCandidates=process.platform==='win32' + ? [process.env.LITHE_TEST_BASH,join(process.env.ProgramFiles??'C:\\Program Files','Git','usr','bin','bash.exe'),join(process.env['ProgramFiles(x86)']??'C:\\Program Files (x86)','Git','usr','bin','bash.exe'),'bash.exe'].filter(Boolean) + : [process.env.LITHE_TEST_BASH??'bash']; +const bash=bashCandidates.find(candidate=>candidate==='bash.exe'||candidate==='bash'||existsSync(candidate)); +if(!bash)throw Error('Git Bash is required on Windows; set LITHE_TEST_BASH to bash.exe'); +const visualEnv={...process.env}; +if(process.platform==='win32'&&existsSync(bash)) { + const bashDirectory=dirname(resolve(bash)); + const pathKey=Object.keys(visualEnv).find(key=>key.toLowerCase()==='path')??'PATH'; + visualEnv[pathKey]=[bashDirectory,visualEnv[pathKey]].filter(Boolean).join(delimiter); +} +const pin=JSON.parse(readFileSync(join(root,'scripts/run/host.json'))); +const revision=(await runTool('git',['-C',host,'rev-parse','HEAD'])).toString().trim(); +assert.equal(revision,pin.revision,'Use the pinned host for reproducible images'); +const stage=join(root,'.artifacts/run');mkdirSync(stage,{recursive:true}); +const evidence=JSON.parse(readFileSync(join(stage,'evidence.json'))); +const fixtures=evidence.fixtures.map(fixture=>({Path:fixture.path,Text:fixture.text,Actions:fixture.actions.map(action=>({ + ID:action.id,Title:action.title,Icon:action.icon, + Range:{StartLine:action.range.start.line,StartColumn:action.range.start.column,EndLine:action.range.end.line,EndColumn:action.range.end.column}, + Alternatives:(action.alternatives??[]).map(choice=>({ID:choice.id,Title:choice.title,Icon:choice.icon})) +}))})); +const projection=join(stage,'projection.json');writeFileSync(projection,JSON.stringify(fixtures)); +const overlay=join(stage,'visual-overlay.json'); +writeFileSync(overlay,JSON.stringify({Replace:{[join(host,'desktop/internal/workbench/plugin_run_actions_visual_test.go')]:join(root,'e2e/host/desktop/internal/workbench/plugin_run_actions_visual_test.go')}})); +const output=join(root,'docs/assets/current-file-runs');mkdirSync(output,{recursive:true}); +const args=['scripts/desktop/desktop-go.sh','test','-json','-overlay',overlay,'-tags','vivahead lithevisual','./internal/workbench','-run','^TestPluginRunActionsVisual$','-count=1','-timeout=120s']; +const log=await runTool(bash,args,{cwd:host,timeout:600000,env:{...visualEnv,LITHE_RUN_PROJECTION:projection,LITHE_RUN_VISUAL_OUTPUT:output}}); +writeFileSync(join(stage,'visual-tests.jsonl'),log); +const timings=log.toString().split('\n').filter(Boolean).map(line=>JSON.parse(line)).filter(event=>event.Action==='pass'&&event.Test).map(event=>({test:event.Test,seconds:event.Elapsed})); +assert.ok(timings.length>1,'No screenshot scenarios ran'); +writeFileSync(join(stage,'visual-timing.json'),JSON.stringify({host:pin,platform:process.platform,architecture:process.arch,size:[1440,900],timings},null,2)); +console.log(`PASS ${timings.length-1} Viva screenshot scenarios (${process.platform}/${process.arch}); output: docs/assets/current-file-runs`);