diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96ac166..e054f17 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,17 +2,39 @@ 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: + platforms: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + commands: ${{ steps.matrix.outputs.commands }} + steps: + - id: matrix + env: + FULL: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + run: | + if [[ "$FULL" == true ]]; then + echo 'commands={"include":[{"os":"ubuntu-latest","platform":"linux-x64"},{"os":"macos-latest","platform":"darwin-arm64"},{"os":"windows-latest","platform":"windows-x64"},{"os":"windows-11-arm","platform":"windows-arm64"}]}' >> "$GITHUB_OUTPUT" + else + echo 'commands={"include":[{"os":"ubuntu-latest","platform":"linux-x64"}]}' >> "$GITHUB_OUTPUT" + fi + package: uses: ./.github/workflows/package.yml verify-store: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft needs: package runs-on: ubuntu-latest timeout-minutes: 15 @@ -50,21 +72,12 @@ jobs: " commands: - needs: package + needs: [package, platforms] runs-on: ${{ matrix.os }} timeout-minutes: 20 strategy: fail-fast: false - matrix: - include: - - os: ubuntu-latest - platform: linux-x64 - - os: macos-latest - platform: darwin-arm64 - - os: windows-latest - platform: windows-x64 - - os: windows-11-arm - platform: windows-arm64 + matrix: ${{ fromJSON(needs.platforms.outputs.commands) }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -93,6 +106,7 @@ jobs: node scripts/test.mjs host-e2e: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft needs: package runs-on: macos-latest timeout-minutes: 45 diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 4cfb10e..f399e65 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -11,31 +11,29 @@ permissions: contents: read jobs: + platforms: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + package: ${{ steps.matrix.outputs.package }} + steps: + - id: matrix + env: + FULL: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + run: | + if [[ "$FULL" == true ]]; then + echo 'package={"include":[{"os":"macos-latest","platform":"darwin-arm64","target":"aarch64-apple-darwin"},{"os":"macos-15-intel","platform":"darwin-x64","target":"x86_64-apple-darwin"},{"os":"ubuntu-latest","platform":"linux-x64","target":"x86_64-unknown-linux-musl"},{"os":"ubuntu-24.04-arm","platform":"linux-arm64","target":"aarch64-unknown-linux-musl"},{"os":"windows-latest","platform":"windows-x64","target":"x86_64-pc-windows-msvc"},{"os":"windows-11-arm","platform":"windows-arm64","target":"aarch64-pc-windows-msvc"}]}' >> "$GITHUB_OUTPUT" + else + echo 'package={"include":[{"os":"ubuntu-latest","platform":"linux-x64","target":"x86_64-unknown-linux-musl"}]}' >> "$GITHUB_OUTPUT" + fi + package: + needs: platforms runs-on: ${{ matrix.os }} timeout-minutes: 20 strategy: fail-fast: false - matrix: - include: - - os: macos-latest - platform: darwin-arm64 - target: aarch64-apple-darwin - - os: macos-15-intel - platform: darwin-x64 - target: x86_64-apple-darwin - - os: ubuntu-latest - platform: linux-x64 - target: x86_64-unknown-linux-musl - - os: ubuntu-24.04-arm - platform: linux-arm64 - target: aarch64-unknown-linux-musl - - os: windows-latest - platform: windows-x64 - target: x86_64-pc-windows-msvc - - os: windows-11-arm - platform: windows-arm64 - target: aarch64-pc-windows-msvc + matrix: ${{ fromJSON(needs.platforms.outputs.package) }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -46,8 +44,8 @@ jobs: env: TARGET: ${{ matrix.target }} run: | - rustup toolchain install 1.87 --profile minimal --target "$TARGET" - rustup override set 1.87 + rustup toolchain install 1.100.0 --profile minimal --target "$TARGET" + rustup override set 1.100.0 - name: Test backend run: cargo test --locked --manifest-path backend/Cargo.toml - name: Assemble plugin archive diff --git a/README.md b/README.md index 7062d58..bd56983 100644 --- a/README.md +++ b/README.md @@ -14,13 +14,21 @@ Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda > [#2316](https://github.com/1lck/Lithe-IDEA/issues/2316) 的版本),旧版本不能安装,请继续用 1.1.0(支持 0.8.9 或更新版本)。 > 各版本的变化见 [docs/releases](docs/releases)。 +## 当前文件与单个函数/测试运行 + +普通 `.py` / `.pyw` 文件直接执行 `python ./文件名`,不要求 `__main__` guard;pytest 函数和类方法通过精确 node ID 单独运行。 + +点击前重新读取文档、校验路径和版本,保存成功后才启动;rerun 会重新验证当前声明。工作区相对路径统一使用 `/`,拒绝绝对路径、盘符、反斜杠、`.`、`..` 与控制字符。gutter 使用宿主选择的 Python;旧的 Python executable 绝对路径覆盖设置只作用于原有构建流程,不覆盖新 gutter 入口。 + +2026-11-30,Windows 11 x64 的真实运行、精确单测试、陈旧版本、保存失败、rerun 和不安全路径回归通过。截图由固定 Viva 无头宿主生成,覆盖明暗主题、中英文及 before/after/hover,见 [截图目录](docs/assets/current-file-runs/)。macOS 原生窗口仍待 CI/实机复验。后端构建工具链固定 Rust 1.100.0。 + ## 功能 | 功能 | 说明 | | --- | --- | | 代码智能 | 补全、自动导入、跳转定义、悬停、类型诊断,由随包的 [Pyrefly](https://github.com/facebook/pyrefly) 1.4.1 提供 | | 识别文件 | `.py`、`.pyi`、`.pyw`;首行是 Python shebang 的无后缀脚本也按 Python 打开 | -| 运行 | 工具栏「当前文件」运行带 `if __name__ == "__main__"` 的脚本和包里的 `__main__.py`;构建窗口列出 `[project.scripts]`、Django `manage.py`、FastAPI、Flask 等入口;「运行/调试配置 → + → Python」可以手动配置脚本或模块 | +| 运行 | 工具栏「当前文件」运行普通脚本和包里的 `__main__.py`(不要求 main guard);构建窗口列出 `[project.scripts]`、Django `manage.py`、FastAPI、Flask 等入口;「运行/调试配置 → + → Python」可以手动配置脚本或模块 | | 测试 | `pytest --collect-only` 收集函数、类方法、参数化用例和 doctest,组成测试树;可以运行整个套件或单个用例 | | 依赖 | 构建窗口的「依赖」列出所选解释器里已安装的包、版本和依赖关系,不需要 pip | | 任务 | `pip install -r requirements.txt`、`mypy`;有 `uv.lock` 时 `uv sync`、`uv lock`;有 `environment.yml` 或 `environment.yaml` 时 `conda env update`(两者都有时使用 `environment.yml`);有 `ruff.toml` 或 `.ruff.toml` 时 `ruff check`、`ruff format`,优先使用项目虚拟环境里的 Ruff | @@ -30,6 +38,7 @@ Pyrefly 和 debugpy 随插件包分发,Python 解释器、pytest、uv、conda | 工具链 | 找到项目的 `.venv`,Poetry、Pipenv、Hatch、virtualenvwrapper 建在项目外的环境,以及电脑上 uv、pyenv、conda、Homebrew、python.org 装的 Python;按 `.python-version` 和 `requires-python` 选版本,见下文“Python 解释器” | | 设置预览 | 语言页和构建工具页画出设置的效果和解释器的查找顺序,见下文“设置预览” | + ## 设置 **插件设置**(「语言与框架 › Python」,也在 设置 → 插件 → Python Support →「设置」),除覆盖路径外都立即生效: @@ -131,7 +140,7 @@ Pyrefly 和 debugpy 的启动结果由 Lithe 记在插件的日志通道。debug ## 本地打包 -需要 Node.js 22+、Rust 1.87+ 和对应的 target(`rustup target add`)。上游的 Pyrefly、debugpy、Tomli、Packaging 按 `vendor-lock.json` +需要 Node.js 22+、Rust 1.100.0+ 和对应的 target(`rustup target add`)。上游的 Pyrefly、debugpy、Tomli、Packaging 按 `vendor-lock.json` 的 SHA-256 下载到 `.cache/`,可以复制到其他工作树复用。 ```bash diff --git a/backend/Cargo.lock b/backend/Cargo.lock index d2b2e27..59b6abf 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "base64" version = "0.22.1" @@ -17,6 +26,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "cc" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -64,6 +83,18 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "find-msvc-tools" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "generic-array" version = "0.14.7" @@ -123,6 +154,8 @@ dependencies = [ "serde_json", "sha2", "toml", + "tree-sitter", + "tree-sitter-python", ] [[package]] @@ -167,6 +200,35 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "serde" version = "1.0.229" @@ -203,6 +265,8 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash", + "indexmap", "itoa", "memchr", "serde", @@ -230,6 +294,18 @@ dependencies = [ "digest", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + [[package]] name = "syn" version = "3.0.10" @@ -280,6 +356,36 @@ version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" +[[package]] +name = "tree-sitter" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87" +dependencies = [ + "cc", + "regex", + "regex-syntax", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" + +[[package]] +name = "tree-sitter-python" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index d8d00dc..81f80f8 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -2,7 +2,7 @@ name = "lithe-python-backend" version = "0.1.0" edition = "2021" -rust-version = "1.87" +rust-version = "1.100" license = "Apache-2.0" publish = false @@ -14,6 +14,8 @@ pep440_rs = "0.7" serde_json = "1" sha2 = "0.10" toml = "0.9" +tree-sitter = "0.25.10" +tree-sitter-python = "0.25.0" [profile.release] strip = "symbols" diff --git a/backend/src/main.rs b/backend/src/main.rs index 52d7712..163b132 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -4,6 +4,8 @@ mod discovery; mod inspect; mod pyrefly; mod requirements; +mod run; +mod run_targets; mod type_errors; mod view; @@ -11,6 +13,11 @@ use lithe_plugin_sdk::Backend; fn main() { let mut backend = Backend::new("python-support-backend"); + let runs = run::Runs::register(&mut backend).expect("run action functions register"); + backend.on_contexts_changed(move |_| { + runs.sync_reporting(); + Ok(()) + }); let launch = pyrefly::LaunchResolver::default(); backend .function("pyrefly.resolveLaunch", move |params, context| { diff --git a/backend/src/run.rs b/backend/src/run.rs new file mode 100644 index 0000000..2ae9a8d --- /dev/null +++ b/backend/src/run.rs @@ -0,0 +1,234 @@ +//! Python script and pytest actions from the live syntax tree. + +use crate::run_targets; + +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 = "python.collectActions"; +const INVOKE: &str = "python.runAction"; +const RERUN: &str = "python.rerun"; + +pub struct Runs { + handle: BackendHandle, + stop: Cancellation, + worker: Mutex>>, + bindings: Mutex>, +} + +// The desktop presents its translated editor-action failure; no plugin UI text is returned. +fn invalid() -> FunctionError { + FunctionError::internal("python.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 collect(params: Value, context: &Context) -> Result { + context.check_cancelled()?; + let path = params["document"]["path"] + .as_str() + .filter(|path| safe_path(path)) + .ok_or_else(invalid)?; + let source = params["text"].as_str().ok_or_else(invalid)?; + let actions: Vec<_> = run_targets::discover(path, source).iter().take(1000).enumerate().map(|(index, target)| { + json!({"id": format!("python-{index}"), "title": target.name.chars().take(200).collect::(), + "icon": match target.kind {"script" => "run", "all" => "run-all", _ => "test"}, + "range": {"start": {"line": target.line, "column": 1}, "end": {"line": target.line, "column": 1}}, + "invoke": {"functionID": INVOKE, "params": {"path": path, "kind": target.kind, "name": target.name}}}) + }).collect(); + Ok(json!({"actions": actions})) +} + +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() + .filter(|path| safe_path(path)) + .ok_or_else(invalid)?; + let source = snapshot["text"].as_str().ok_or_else(invalid)?; + let target = run_targets::discover(path, source) + .into_iter() + .find(|target| data["name"] == target.name && data["kind"] == target.kind) + .ok_or_else(invalid)?; + 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": target.name.chars().take(256).collect::(), + "process": {"executable": {"kind": "tool", "tool": "python"}, "arguments": run_targets::arguments(path, &target), + "workingDirectory": ".", "environment": {}}, "rerun": {"function": RERUN, "data": data}}))?) +} + +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()), + }); + 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() + }); + 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("python-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", + "python.run.registrationFailed", + Some(1), + ); + return; + } + } + runs.sync_reporting(); + }) + .map_err(|_| FunctionError::internal("python.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", + "python.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": "pythonRunActions", "function": COLLECT, + "selector": {"fileExtensions": ["py", "pyw"], "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()?; + } + } + 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", + "python.run.registrationFailed", + Some(1), + ); + } + } + // The host withdraws all session bindings atomically at shutdown. + self.bindings.lock().unwrap().clear(); + } +} diff --git a/backend/src/run_targets.rs b/backend/src/run_targets.rs new file mode 100644 index 0000000..77f1f54 --- /dev/null +++ b/backend/src/run_targets.rs @@ -0,0 +1,146 @@ +//! Static Python/pytest discovery. tree-sitter parses dirty buffers without +//! importing user modules, evaluating decorators or collecting fixtures. + +use serde_json::{json, Value}; +use tree_sitter::{Node, Parser}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Target { + pub kind: &'static str, + pub name: String, + pub line: usize, +} + +fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str { + node.utf8_text(source.as_bytes()).unwrap_or_default() +} + +pub fn discover(path: &str, source: &str) -> Vec { + if !path.ends_with(".py") && !path.ends_with(".pyw") { + return vec![]; + } + let mut parser = Parser::new(); + parser + .set_language(&tree_sitter_python::LANGUAGE.into()) + .expect("pinned Python grammar"); + let Some(tree) = parser.parse(source, None) else { + return vec![]; + }; + if tree.root_node().has_error() { + return vec![]; + } + let filename = path.rsplit('/').next().unwrap_or(path); + let tests = (filename.starts_with("test_") || filename.ends_with("_test.py")) + && filename.ends_with(".py"); + let mut targets = Vec::new(); + if tests { + targets.push(Target { + kind: "all", + name: path.to_owned(), + line: 1, + }); + visit(tree.root_node(), source, &mut Vec::new(), &mut targets); + } else if !matches!(filename, "conftest.py" | "__main__.py" | "setup.py") { + // A Python script does not need a main guard. Running it preserves + // Python's __name__, sys.argv and sibling-import behavior. + let mut cursor = tree.root_node().walk(); + let main = tree + .root_node() + .named_children(&mut cursor) + .find_map(|node| { + let node = if node.kind() == "decorated_definition" { + node.child_by_field_name("definition")? + } else { + node + }; + (node.kind() == "function_definition" + && node + .child_by_field_name("name") + .is_some_and(|n| text(n, source) == "main")) + .then_some(node.start_position().row + 1) + }); + targets.push(Target { + kind: "script", + name: path.to_owned(), + line: main.unwrap_or(1), + }); + } + targets +} + +fn visit(node: Node<'_>, source: &str, classes: &mut Vec, targets: &mut Vec) { + let mut cursor = node.walk(); + for child in node.named_children(&mut cursor) { + let declaration = if child.kind() == "decorated_definition" { + child.child_by_field_name("definition").unwrap_or(child) + } else { + child + }; + let name = declaration + .child_by_field_name("name") + .map(|n| text(n, source)) + .unwrap_or_default(); + if declaration.kind() == "class_definition" && name.starts_with("Test") { + classes.push(name.to_owned()); + if let Some(body) = declaration.child_by_field_name("body") { + visit(body, source, classes, targets); + } + classes.pop(); + } else if declaration.kind() == "function_definition" && name.starts_with("test_") { + let mut chain = classes.clone(); + chain.push(name.to_owned()); + targets.push(Target { + kind: "test", + name: chain.join("::"), + line: declaration.start_position().row + 1, + }); + } + // Never descend into arbitrary functions: nested helpers aren't + // pytest items, even if their names begin with test_. + } +} + +pub fn arguments(path: &str, target: &Target) -> Value { + let file = format!("./{path}"); + match target.kind { + "script" => json!([file]), + "all" => json!(["-m", "pytest", file]), + _ => json!(["-m", "pytest", format!("{file}::{}", target.name)]), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_scripts_run_without_a_main_guard() { + let targets = discover("hello world.py", "print('hello')\n"); + assert_eq!( + arguments("hello world.py", &targets[0]), + json!(["./hello world.py"]) + ); + assert!(discover("stub.pyi", "def main(): ...").is_empty()); + // Package main files use the existing module-aware toolbar provider. + assert!(discover("pkg/__main__.py", "from . import helpers\n").is_empty()); + } + + #[test] + fn pytest_items_have_exact_class_qualified_node_ids() { + let source = "# def test_comment(): pass\ndef test_one(): pass\ndef test_other(): pass\nclass TestSuite:\n @pytest.mark.parametrize('n', [1, 2])\n def test_case(self, n): pass\ndef helper():\n def test_nested(): pass\n"; + let targets = discover("tests/test_demo.py", source); + assert_eq!( + targets.iter().map(|t| t.name.as_str()).collect::>(), + [ + "tests/test_demo.py", + "test_one", + "test_other", + "TestSuite::test_case" + ] + ); + assert_eq!( + arguments("tests/test_demo.py", &targets[3]), + json!(["-m", "pytest", "./tests/test_demo.py::TestSuite::test_case"]) + ); + } +} diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-after.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-after.png" new file mode 100644 index 0000000..2a4ba12 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-after.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-before.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-before.png" new file mode 100644 index 0000000..7e3404e Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-before.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-hover.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-hover.png" new file mode 100644 index 0000000..8f9cd60 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-en-hover.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-after.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-after.png" new file mode 100644 index 0000000..f031092 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-after.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-before.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-before.png" new file mode 100644 index 0000000..574c8a4 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-before.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-hover.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-hover.png" new file mode 100644 index 0000000..01d2a85 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-dark-zh-Hans-hover.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-after.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-after.png" new file mode 100644 index 0000000..b289c36 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-after.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-before.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-before.png" new file mode 100644 index 0000000..02be625 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-before.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-hover.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-hover.png" new file mode 100644 index 0000000..bb5e9df Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-en-hover.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-after.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-after.png" new file mode 100644 index 0000000..5ace28d Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-after.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-before.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-before.png" new file mode 100644 index 0000000..5d609e9 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-before.png" differ diff --git "a/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-hover.png" "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-hover.png" new file mode 100644 index 0000000..4cb0f27 Binary files /dev/null and "b/docs/assets/current-file-runs/scripts-hello world \344\270\255\346\226\207.py-light-zh-Hans-hover.png" differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-en-after.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-after.png new file mode 100644 index 0000000..4fb91bc Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-after.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-en-before.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-before.png new file mode 100644 index 0000000..e88cb36 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-before.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-en-hover.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-hover.png new file mode 100644 index 0000000..474d9af Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-en-hover.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-after.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-after.png new file mode 100644 index 0000000..8769459 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-after.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-before.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-before.png new file mode 100644 index 0000000..a2945f8 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-before.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-hover.png b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-hover.png new file mode 100644 index 0000000..7d94750 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-dark-zh-Hans-hover.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-en-after.png b/docs/assets/current-file-runs/tests-test_selected.py-light-en-after.png new file mode 100644 index 0000000..c0247ab Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-en-after.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-en-before.png b/docs/assets/current-file-runs/tests-test_selected.py-light-en-before.png new file mode 100644 index 0000000..1fb68aa Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-en-before.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-en-hover.png b/docs/assets/current-file-runs/tests-test_selected.py-light-en-hover.png new file mode 100644 index 0000000..dc0ca1b Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-en-hover.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-after.png b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-after.png new file mode 100644 index 0000000..72a8ad3 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-after.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-before.png b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-before.png new file mode 100644 index 0000000..3e7892e Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-before.png differ diff --git a/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-hover.png b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-hover.png new file mode 100644 index 0000000..763d7f7 Binary files /dev/null and b/docs/assets/current-file-runs/tests-test_selected.py-light-zh-Hans-hover.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 60c7883..93a02fa 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -19,7 +19,7 @@ | 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(桌面主线) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_editor_debug_e2e_test.go` | | 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。工具定义声明 `executableLinksOutsideHome`:项目外虚拟环境和 Homebrew 的 `bin/python3` 链接到主目录外时,Core 按主目录下的布局路径探测和启动,Python 仍在自己的环境里运行([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316),需要 Core #177 与宿主 #2321;旧宿主不认识这个字段,会拒绝整个清单)。 | ✅ 已验证(固定项目外的 venv 端到端) | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-23`(`darwin-arm64`,宿主 `58b527ed`(含 [#2321](https://github.com/1lck/Lithe-IDEA/pull/2321));Homebrew 未实机验证) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | | 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 当前文件运行 (`buildProviders: 1`) | 工具栏支持带 `__main__` 入口的脚本或包内 `__main__.py`。使用工具链解析出的解释器(包括为项目固定的安装或项目外的虚拟环境),设置了覆盖路径时用覆盖路径。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(macOS ARM64,宿主 `58b527ed`(含 [#2321](https://github.com/1lck/Lithe-IDEA/pull/2321))工作台端到端,含固定安装、固定项目外 venv 与覆盖路径) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | +| 当前文件运行 (`buildProviders: 1`) | 工具栏支持普通脚本(不要求 `__main__` guard)或包内 `__main__.py`。使用工具链解析出的解释器(包括为项目固定的安装或项目外的虚拟环境),设置了覆盖路径时用覆盖路径。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(macOS ARM64,宿主 `58b527ed`(含 [#2321](https://github.com/1lck/Lithe-IDEA/pull/2321))工作台端到端,含固定安装、固定项目外 venv 与覆盖路径) | `io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/scripts/run_entrypoint.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go` | | 手动 Python 运行配置 (`runConfigurationTypes: 0`) | 「运行/调试配置 → + → Python」支持脚本路径和模块名、解释器选项、参数、环境变量和工作目录。使用工具链为项目解析出的解释器,设置了覆盖路径时用覆盖路径。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-23(宿主 `58b527ed`(含 [#2321](https://github.com/1lck/Lithe-IDEA/pull/2321)),脚本与模块) | `io.github.lithe-idea.python-support/plugin.json`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 构建面板依赖树 (`litheDependencies`) | 展开「依赖」时用 `python -I -B` 读取所选 Python 环境中已安装的包、版本和依赖关系,跳过用户级 site-packages 及其启动钩子,解析 PEP 508 条件和可选依赖。仅有 Conda 环境清单的项目也可加载。支持无 pip 的环境。 | ✅ 已验证(macOS ARM64) | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-21(固定宿主与打包命令) | `io.github.lithe-idea.python-support/scripts/dependencies.py`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_project_workflow_e2e_test.go` | | 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(桌面主线) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | @@ -38,3 +38,13 @@ - macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。 - 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。 - 宿主按 Core 的文件事实校验安装。python 工具定义声明了 `executableLinksOutsideHome`,程序链接到主目录外时,宿主观测布局路径上的各级目录,Core 确认它们都在主目录内、不在工作区里,再按布局路径启动([#2316](https://github.com/1lck/Lithe-IDEA/issues/2316))。`RunCurrentFilePinnedEnvironment` 在项目外建一个符号链接式的 venv 并固定它,运行输出的 `sys.prefix` 必须是这个环境;去掉这个字段后同一用例失败。项目内环境由宿主信任流程单独处理。 + +## 当前文件与单个函数/测试运行(本次改动) + +| 能力 | macOS | Windows | 证据 | +| --- | --- | --- | --- | +| 当前文件入口、单函数/测试 gutter、保存与 rerun 校验、相对路径安全 | implemented / pending | implemented / pending | `backend/src/run.rs`、`backend/src/run_targets.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/实机验证。 + +普通 `.py` / `.pyw` 文件直接执行 `python ./文件名`,不要求 `__main__` guard;pytest 函数和类方法通过精确 node ID 单独运行。 gutter 使用宿主选择的 Python;旧的 Python executable 绝对路径覆盖设置只作用于原有构建流程,不覆盖新 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.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 51dd6ad..2faec18 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -34,7 +34,12 @@ "process.build", "project.generate", "toolchains.provide", - "ui.contribute" + "ui.contribute", + "documents.read", + "documents.save", + "editor.actions", + "run.start", + "workspace.metadata" ], "activationEvents": [ "onBuildSystem:conda", @@ -42,7 +47,8 @@ "onBuildSystem:ruff", "onBuildSystem:uv", "onDebug:debugpy", - "onLanguage:python" + "onLanguage:python", + "onWorkspaceOpen" ], "backend": { "launch": { diff --git a/io.github.lithe-idea.python-support/scripts/build_model.py b/io.github.lithe-idea.python-support/scripts/build_model.py index bf83c52..aad2601 100644 --- a/io.github.lithe-idea.python-support/scripts/build_model.py +++ b/io.github.lithe-idea.python-support/scripts/build_model.py @@ -661,7 +661,6 @@ def inspect_file_entrypoints(root_dir: Path, rel_file_posix: str, project_select tree = _read_ast(fpath) if tree is None: return [] - facts = _analyze_python_file(tree) has_src_dir = (root_dir / "src").is_dir() and _safe_within(root_real, root_dir / "src") results: list[dict] = [] @@ -679,7 +678,9 @@ def inspect_file_entrypoints(root_dir: Path, rel_file_posix: str, project_select }) return results - if facts["has_main_guard"]: + # Ordinary scripts are runnable too: Python executes their top-level code + # even without an explicit main function or __name__ guard. + if fpath.suffix in (".py", ".pyw"): results.append({ "run": "main", "name": clean_rel, 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/lib/backend.mjs b/scripts/lib/backend.mjs index 1f4ead7..a846dca 100644 --- a/scripts/lib/backend.mjs +++ b/scripts/lib/backend.mjs @@ -64,6 +64,11 @@ export function dependencyNotices(root) { // The Git SDK shares its license with the sibling SDK packages. licenses.push(join(directory, "..", "..", "..", "LICENSE")); } + if (pkg.name === "tree-sitter" && pkg.version === "0.25.10" && licenses.length === 0) { + // Upstream's Cargo include list omits its MIT license. Ship the + // verbatim license from the same pinned upstream revision. + licenses.push(join(root, "third_party", "tree-sitter", "LICENSE")); + } if (licenses.length === 0 || licenses.some((path) => !existsSync(path))) { throw new Error(`Missing dependency license for ${pkg.name} ${pkg.version}`); } diff --git a/scripts/run/actions.mjs b/scripts/run/actions.mjs new file mode 100644 index 0000000..9399608 --- /dev/null +++ b/scripts/run/actions.mjs @@ -0,0 +1,64 @@ +// Live protocol and execution regression. The host boundary is scripted; the +// packaged backend and Python/pytest processes are real and own no install state. +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync} from 'node:fs'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {performance} from 'node:perf_hooks'; +import {Client} from './client.mjs'; + +const repository=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +const executable=process.platform==='win32'?'lithe-python-backend.exe':'lithe-python-backend'; +const target=process.platform==='win32'?'x86_64-pc-windows-msvc':null; +const backend=resolve(process.argv[2]??join(repository,'backend/target',...(target?[target]:[]),'release',executable)); +const python=process.env.PYTEST_PYTHON??process.env.PYTHON??(process.platform==='win32'?'python':'python3'); +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='scripts/hello world 中文.py',testRelative='tests/test_selected.py'; +const source='from helper import message\nprint(message())\n'; +const testSource='def test_selected():\n print("SELECTED_OK")\n assert 2 + 2 == 4\n\ndef test_sibling():\n raise AssertionError("SIBLING_MUST_NOT_RUN")\n\nclass TestSuite:\n def test_method(self):\n assert True\n'; +function write(path,text){const full=join(root,path);mkdirSync(dirname(full),{recursive:true});writeFileSync(full,text);} +write(relative,source);write('scripts/helper.py','def message():\n return "SCRIPT_OK"\n');write(testRelative,testSource); +const digest=createHash('sha256').update(readFileSync(backend)).digest('hex'); +let snapshot,saveFailure=false,operation=0,registered; +const registration=new Promise(resolve=>{registered=resolve;}); +const launches=[],events=[],results=[]; +const client=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/documents/getSnapshot':()=>snapshot, + 'lithe/host/documents/list':()=>({documents:[snapshot.document]}), + 'lithe/host/documents/save':()=>{events.push('save');if(saveFailure)throw Error('test save refused');write(snapshot.document.path,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 client.request('lithe/function/invoke',{context:reference,operationID:`run-${++operation}`,functionID,params},15000);} +function document(path,text,version=1){snapshot={document:{documentID:'document',version,path},text};} +function click(action,version=snapshot.document.version){return invoke('python.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:'python'});const run=spawnSync(python,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 client.request('initialize',{capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}},10000);client.notify('initialized',{}); + let timer;try{await Promise.race([registration,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Action registration timed out')),10000);})]);}finally{clearTimeout(timer);} + document(relative,source); + const main=(await invoke('python.collectActions',snapshot)).actions[0];assert.equal(main.icon,'run'); + await check('plain current file runs without a main guard and imports its sibling',async()=>{events.length=0;await click(main);assert.deepEqual(events,['save','start']);assert.deepEqual(launches.at(-1).process.arguments,[`./${relative}`]);assert.match(execute(launches.at(-1)),/SCRIPT_OK/);}); + document(testRelative,testSource);const actions=(await invoke('python.collectActions',snapshot)).actions; + const selected=actions.find(value=>value.title==='test_selected');assert.ok(selected);assert.ok(actions.find(value=>value.icon==='run-all')); + await check('one pytest function excludes a failing sibling',async()=>{await click(selected);const output=execute(launches.at(-1));assert.match(output,/1 passed/);assert.doesNotMatch(output,/SIBLING_MUST_NOT_RUN/);}); + await check('class methods use a qualified pytest node ID',async()=>{await click(actions.find(value=>value.title==='TestSuite::test_method'));assert.match(execute(launches.at(-1)),/1 passed/);}); + await check('stale version never saves or starts',async()=>{events.length=0;await assert.rejects(click(selected,0));assert.deepEqual(events,[]);}); + await check('removed declaration never launches',async()=>{document(testRelative,'# removed\n',2);events.length=0;await assert.rejects(click(selected));assert.deepEqual(events,[]);}); + document(testRelative,testSource,3); + 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('python.rerun',selected.invoke.params);assert.deepEqual(events,['save','start']);}); + await check('unsafe paths and non executable stubs are rejected',async()=>{for(const path of ['../main.py','C:/main.py','a\\main.py','/main.py'])await assert.rejects(invoke('python.collectActions',{document:{path},text:source}));assert.deepEqual((await invoke('python.collectActions',{document:{path:'types.pyi'},text:'def main(): ...\n'})).actions,[]);}); + 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:[main]},{path:testRelative,text:testSource,actions}],commands:launches.map(value=>value.process)},null,2)); +}finally{try{await client.request('shutdown',null,5000);client.notify('exit');}catch{}await client.close();rmSync(root,{recursive:true,force:true});} diff --git a/scripts/run/client.mjs b/scripts/run/client.mjs new file mode 100644 index 0000000..42c0c60 --- /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:{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(Error(JSON.stringify(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`); diff --git a/scripts/test.mjs b/scripts/test.mjs index 9cfea72..e7b26ec 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -196,6 +196,12 @@ class FramedStdioPeer { if (this.buffer.length < bodyStart + length) return; const payload = JSON.parse(this.buffer.subarray(bodyStart, bodyStart + length).toString("utf8")); this.buffer = this.buffer.subarray(bodyStart + length); + // These older smoke scenarios do not offer editor actions. Answer + // capability discovery so the backend's startup worker can finish. + if (payload.method === "lithe/host/getCapabilities" && payload.id !== undefined) { + this.send({ jsonrpc: "2.0", id: payload.id, result: { services: {} } }); + continue; + } this.allReceived.push(payload); let consumed = false; for (let i = 0; i < this.waiters.length; i += 1) { @@ -484,11 +490,16 @@ for files, selected in [((), "environment.yml"), (("environment.yaml",), "enviro "backend.launch", "debug.attach", "debug.launch", + "documents.read", + "documents.save", + "editor.actions", "languageServer.launch", "process.build", "project.generate", + "run.start", "toolchains.provide", "ui.contribute", + "workspace.metadata", ]); assert.deepEqual(variant.backend, { @@ -758,7 +769,7 @@ for files, selected in [((), "environment.yml"), (("environment.yaml",), "enviro assert.deepEqual(initOk.result.capabilities.experimental.litheLogging, { version: 0 }); assert.deepEqual(initOk.result.capabilities.experimental.litheFunctions, { version: 0, - functions: [{ id: "pyrefly.resolveLaunch" }, { id: "python.inspectEnvironment" }, { id: "settings.view" }], + functions: ["pyrefly.resolveLaunch", "python.collectActions", "python.inspectEnvironment", "python.rerun", "python.runAction", "settings.view"].map((id) => ({ id })), }); assert.deepEqual(initOk.result.capabilities.experimental.litheToolchains, { version: 0, @@ -1413,7 +1424,7 @@ for files, selected in [((), "environment.yml"), (("environment.yaml",), "enviro // Start with an intentionally malformed pyproject.toml to verify degraded -> recovered! writeFileSync(join(wsDir, "pyproject.toml"), "[project\nname = 'broken'\n"); - writeFileSync(join(wsDir, "worker.py"), 'if __name__ == "__main__":\n print("run worker")\n'); + writeFileSync(join(wsDir, "worker.py"), 'print("run worker")\n'); writeFileSync(join(wsDir, "conftest.py"), [ "def pytest_sessionstart(session):", " if session.config.option.collectonly:", @@ -2219,6 +2230,13 @@ for files, selected in [((), "environment.yml"), (("environment.yaml",), "enviro ); }); + await check("current script and individual pytest actions execute through the packaged backend", () => { + run(process.execPath, [join(ROOT, "scripts/run/actions.mjs"), backendExecutable], { + cwd: ROOT, + env: { ...process.env, PYTEST_PYTHON: resolvePytestRuntime() }, + }); + }); + await check("unpacked plugin package file manifest and SHA-256 hashes remain 100% unchanged after all workflows", () => { const afterSnapshot = snapshotDirectoryHashes(unpackedPluginDir); assert.deepEqual(afterSnapshot, beforeSnapshot); diff --git a/third_party/tree-sitter/LICENSE b/third_party/tree-sitter/LICENSE new file mode 100644 index 0000000..451fe1d --- /dev/null +++ b/third_party/tree-sitter/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2018-2024 Max Brunsfeld + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/tree-sitter/README.md b/third_party/tree-sitter/README.md new file mode 100644 index 0000000..b3869e0 --- /dev/null +++ b/third_party/tree-sitter/README.md @@ -0,0 +1,10 @@ +# tree-sitter license + +The tree-sitter 0.25.10 Cargo archive omits its root MIT license. This file is +copied verbatim from the upstream revision recorded in that archive's +.cargo_vcs_info.json: da6fe9beb4f7f67beb75914ca8e0d48ae48d6406. + +Source: https://github.com/tree-sitter/tree-sitter/blob/da6fe9beb4f7f67beb75914ca8e0d48ae48d6406/LICENSE + +The package build includes this notice in THIRD_PARTY_LICENSES.txt. It is a +read-only build input, with no runtime cache or download.