diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aaea24b..7e50db2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -115,7 +115,7 @@ jobs:
path: dist
- name: Install pytest for the host suite
run: python -m pip install --disable-pip-version-check pytest
- - name: Verify Python highlighting on Lithe 0.8.9
- run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPluginGrammarHighlighting$'
+ - name: Verify Python highlighting and current-file run on Lithe 0.8.9
+ run: node scripts/e2e-host.mjs --ref 4d1b88f03f243356c855299464baa2647cc57226 --run '^TestPythonSupportPlugin(GrammarHighlighting|RunCurrentFile(InterpreterOverride)?)$'
- name: Run the full Python host suite on the pinned desktop
run: PYTEST_PYTHON="$(command -v python)" node scripts/e2e-host.mjs
diff --git a/README.md b/README.md
index df8aee9..d821b70 100644
--- a/README.md
+++ b/README.md
@@ -26,12 +26,13 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the
- 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。
- Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。Pipenv 默认环境按完整的 `Pipfile` 路径匹配,并遵守同目录的 Python 版本约束。宿主观察这些输入并在变化后重新查询。
- 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。
-4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders`)**
+4. **构建、运行与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders: 1`)**
- `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。
- Python 构建提供者 `scripts/build_provider.py` 使用 `python -I -B` 启动,处理以下请求。
- `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置;
- `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
- - `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志;
+ - 顶部「当前文件 → 运行」支持带 `__main__` 入口的脚本和包内 `__main__.py`。`lithe/build/runEntrypoints` 静态发现入口,`lithe/build/prepareRun` 返回启动计划。默认使用项目选定的 Python;指定「Python 解释器覆盖」时,使用宿主解析的显式解释器。
+ - `scripts/run_entrypoint.py` 随插件 ZIP 安装,运行时只读。它在宿主管理的进程树内转发解释器覆盖,并检查包入口的实际来源。包名被其他模块遮蔽时给出错误。旧宿主未传界面语言时,入口错误同时提供中英文。
- 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
- `uv`(`uv.lock`):`uv sync`、`uv lock`。
- `conda`(`environment.yml` / `environment.yaml`):`conda env update --file environment.yml --prune`。
@@ -62,6 +63,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
| `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` |
| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
+| `lithe/build/prepareRun` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRunEntrypoint`、`python.staleRunEntrypoint`、`python.interpreterUnavailable`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
`toolchains/query` 是高频只读操作,成功由 SDK 返回事实。取消、读取失败、扫描超限与不安全输入通过 `plugin.toolchain.*` 结构化返回。宿主工具链层观察并处理查询及解码失败。协议 v0 的 SDK 无该操作的诊断回调。
diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md
index ab29eed..3b3239a 100644
--- a/docs/feature-matrix.md
+++ b/docs/feature-matrix.md
@@ -17,6 +17,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/*`) | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_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`。使用项目 Python 或经宿主解析的显式解释器。包入口执行前核对文件来源。 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | 2026-11-20(macOS ARM64,Lithe 0.8.9、0.8.11 工作台端到端) | `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` |
| 动态 `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` |
| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | 2026-11-20(macOS ARM64,桌面主线) | `io.github.lithe-idea.python-support/plugin.json`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`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` |
@@ -27,9 +28,9 @@
## 宿主版本与验证
-- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1` 和 `languages: 0`。桌面 0.8.9 支持安装与原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。
+- 插件要求宿主声明 `toolchainProviders: 0`、`buildSystems: 1`、`buildProviders: 1` 和 `languages: 0`。桌面 0.8.9 支持安装、当前文件运行和原有 Python 功能。支持 TextMate 首行匹配的桌面会额外识别无后缀脚本。
- `e2e/host/lithe-host.json` 固定支持 TextMate 首行匹配的桌面主线提交 `645a3aee8`。
-- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮,并在固定的桌面主线上运行完整宿主套件,覆盖项目生成、解释器切换、pytest、debugpy、普通文件高亮和无后缀脚本的编辑诊断。
+- 插件 CI 用同一个 macOS ARM64 ZIP 在 0.8.9 验证普通 Python 高亮和当前文件运行,并在固定的桌面主线上运行完整宿主套件,额外覆盖项目生成、解释器切换、pytest、debugpy 和无后缀脚本的编辑诊断。
- macOS ARM64 的工作台测试从 ZIP 安装插件,改变项目版本要求以切换外部解释器,检查全局候选和项目 `.venv` 信任,精确重跑一个参数化 pytest 用例并核对 JUnit。
- 无头工作台打开 `.py` 后,Pyrefly 返回所选环境独有模块的类型诊断。debugpy 使用同一环境执行当前文件,并将日志写入宿主分配目录。关闭后,已安装插件的文件清单和 SHA-256 与启动前一致。
- 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。
diff --git a/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go
new file mode 100644
index 0000000..4776efa
--- /dev/null
+++ b/e2e/host/desktop/internal/workbench/python_current_file_run_e2e_test.go
@@ -0,0 +1,154 @@
+package workbench
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/1lck/Lithe-IDEA/desktop/internal/core"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/store"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain"
+)
+
+func TestPythonSupportPluginRunCurrentFile(t *testing.T) {
+ checkPythonCurrentFileRun(t, false)
+}
+
+func TestPythonSupportPluginRunCurrentFileInterpreterOverride(t *testing.T) {
+ checkPythonCurrentFileRun(t, true)
+}
+
+func checkPythonCurrentFileRun(t *testing.T, override bool) {
+ t.Helper()
+ archive := pythonArchiveForE2E(t)
+ ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
+ defer cancel()
+ root, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ venv := filepath.Join(root, ".venv")
+ python := "python3"
+ if runtime.GOOS == "windows" {
+ python = "python"
+ }
+ if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", venv).CombinedOutput(); err != nil {
+ t.Fatalf("create project environment: %v\n%s", err, output)
+ }
+ source := filepath.Join(root, "main.py")
+ for name, contents := range map[string]string{
+ "pyproject.toml": "[project]\nname = 'current-file-run'\nversion = '0.1.0'\n",
+ "main.py": "import sys\n\nif __name__ == '__main__':\n print('current file ran')\n print(sys.prefix)\n",
+ } {
+ if err := os.WriteFile(filepath.Join(root, name), []byte(contents), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ kernel := core.NewClient()
+ preferences := store.At(t.TempDir())
+ // A headless test has no AppKit event loop to query the system appearance.
+ if err := preferences.Save(settingsFile, settings{Theme: themeDark}); err != nil {
+ t.Fatal(err)
+ }
+ // The toolchain resolver reads persisted trust before probing a project .venv.
+ trust, err := toolchain.ReadWorkspaceTrust(ctx, kernel, preferences.Dir(), root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := trust.Save(ctx, kernel, true, false); err != nil {
+ t.Fatal(err)
+ }
+ wantVenv := venv
+ if override {
+ overrideDir, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantVenv = filepath.Join(overrideDir, "configured interpreter")
+ if output, err := exec.CommandContext(ctx, python, "-m", "venv", "--without-pip", wantVenv).CombinedOutput(); err != nil {
+ t.Fatalf("create configured environment: %v\n%s", err, output)
+ }
+ configured := filepath.Join(wantVenv, "bin", "python")
+ if runtime.GOOS == "windows" {
+ configured = filepath.Join(wantVenv, "Scripts", "python.exe")
+ }
+ settings, err := json.Marshal(map[string]map[string]string{
+ pythonSupportPluginID: {"pythonExecutable": configured},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(preferences.Dir(), "plugin-settings.json"), settings, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ h := newHarnessWithOptions(t, Options{
+ Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences,
+ Languages: []string{"en"},
+ })
+ installPythonArchive(t, ctx, h.app.plugins, archive)
+ h.app.reloadPluginLanguages()
+ h.open(root)
+ p := h.app.project
+ if p == nil {
+ t.Fatal("the workspace did not open")
+ }
+ openSource(t, h, p, source)
+ h.app.post(func(a *App) {
+ a.chooseTitleConfiguration(p, "")
+ a.titleRun(p)
+ })
+ notRunnable := i18n.Shared(h.app.language(), "desktop.title.currentFileNotRunnable")
+ awaitStateWithin(t, h, 20*time.Second, "the current file to start running", func() bool {
+ for _, notice := range noticeTexts(h.app) {
+ if notice == notRunnable {
+ t.Fatalf("the toolbar rejected the Python entrypoint: %s", notice)
+ }
+ }
+ return p.runConfigs.selected != ""
+ })
+ run := awaitProcessRun(t, h, p, "main.py", nil)
+ checkOutput := func(output string) {
+ t.Helper()
+ if !strings.Contains(output, "current file ran") || !strings.Contains(output, wantVenv) {
+ t.Fatalf("expected the program to use Python environment %q:\n%s", wantVenv, output)
+ }
+ }
+ checkOutput(run.output.all())
+ saved := p.runConfigs.configuration(p.runConfigs.selected)
+ if saved == nil {
+ t.Fatal("the toolbar did not select the saved run configuration")
+ }
+ if ref, ok := saved.BuildReference(); !ok || ref.Run != "main" || ref.TargetID != "" {
+ t.Fatalf("current file saved the wrong build reference: %+v", ref)
+ }
+
+ for i := range p.build.instances {
+ instance := &p.build.instances[i]
+ if instance.BuildSystemID != "python" {
+ continue
+ }
+ for _, target := range instance.Model.Targets {
+ if target.Name == "main.py" {
+ action, ok := buildPrimaryAction(instance, &target)
+ if !ok || action.entryID == "" {
+ t.Fatal("main.py no longer has a command run in the Build panel")
+ }
+ h.app.post(func(a *App) {
+ a.selectBuildInstance(p, i)
+ a.runBuildTargetAction(p, target.ID, action)
+ })
+ checkOutput(awaitProcessRun(t, h, p, "main.py", run).output.all())
+ return
+ }
+ }
+ }
+ t.Fatal("the build model no longer exposes the main.py target")
+}
diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json
index 535f78e..bcb0ad3 100644
--- a/io.github.lithe-idea.python-support/plugin.json
+++ b/io.github.lithe-idea.python-support/plugin.json
@@ -12,7 +12,7 @@
"pluginAPIVersion": 0,
"requires": {
"backend": 0,
- "buildProviders": 0,
+ "buildProviders": 1,
"buildSystems": 1,
"debugAdapters": 0,
"languageServers": 0,
@@ -503,6 +503,7 @@
"runtimeArguments": ["-I", "-B"],
"entry": "scripts/build_provider.py"
},
+ "initializationOptions": { "pythonExecutable": "${setting:pythonExecutable}" },
"executesProjectCode": true,
"mayUseNetwork": false
},
@@ -543,6 +544,11 @@
}
],
"run": [
+ {
+ "id": "main",
+ "source": "provider",
+ "entrypoints": true
+ },
{
"id": "script",
"fromTargets": { "tags": ["script"] },
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 98737c0..bf83c52 100644
--- a/io.github.lithe-idea.python-support/scripts/build_model.py
+++ b/io.github.lithe-idea.python-support/scripts/build_model.py
@@ -673,7 +673,8 @@ def inspect_file_entrypoints(root_dir: Path, rel_file_posix: str, project_select
results.append({
"run": "main",
"name": mod_name,
- "entrypoint": f"module:{mod_name}",
+ # Keep the source path so preparation can distinguish root and src layouts.
+ "entrypoint": f"module:{clean_rel}",
"project": project_selection,
})
return results
diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py
index c8574d1..f050271 100644
--- a/io.github.lithe-idea.python-support/scripts/build_provider.py
+++ b/io.github.lithe-idea.python-support/scripts/build_provider.py
@@ -27,8 +27,10 @@
PluginError,
run_bounded_process,
)
+from run_entrypoint import run_message # noqa: E402
_JUNIT_REPORT_REL = ".pytest_cache/lithe-junit.xml"
+_ENTRYPOINT_LAUNCHER = str(Path(_SCRIPTS_DIR) / "run_entrypoint.py")
def file_uri_to_path(uri: str) -> Optional[Path]:
parsed = urlparse(uri)
@@ -182,8 +184,16 @@ def create_build_provider_server() -> JsonRpcServer:
workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()}
degraded_model_roots: set[str] = set()
state_lock = threading.Lock()
+ configured_interpreter = False
+ locale = ""
def _on_init(params: dict[str, Any]) -> None:
+ nonlocal configured_interpreter, locale
+ initialization = params.get("initializationOptions")
+ if isinstance(initialization, dict):
+ configured_interpreter = bool(initialization.get("pythonExecutable"))
+ if isinstance(params.get("locale"), str):
+ locale = params["locale"]
folders = params.get("workspaceFolders")
if isinstance(folders, list) and folders:
first = folders[0]
@@ -370,10 +380,66 @@ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str
"entrypoints": entrypoints,
}
+ def handle_prepare_run(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]:
+ ctx.raise_if_cancelled()
+ norm_root, instance_dir = _resolve_instance(params)
+ project = params.get("project")
+ launch = params.get("launchOptions")
+ if (params.get("run") != "main" or params.get("target") is not None
+ or not isinstance(project, dict) or project.get("path") != norm_root
+ or not isinstance(launch, dict)):
+ raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
+
+ entrypoint = launch.get("entrypoint")
+ if not isinstance(entrypoint, str):
+ raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
+ kind, _, relative_file = entrypoint.partition(":")
+ if (kind not in ("script", "module") or relative_file.startswith("/")
+ or any(char in relative_file for char in ("\\", ":", "\x00"))):
+ raise PluginError("python.invalidRunEntrypoint", run_message("invalid", locale))
+
+ # Saved configurations can outlive their source or its main guard.
+ entries = inspect_file_entrypoints(instance_dir, relative_file, project)
+ if not entries or entries[0]["entrypoint"] != entrypoint:
+ raise PluginError("python.staleRunEntrypoint", run_message("stale", locale))
+
+ working_directory = launch.get("workingDirectory") or norm_root
+ source = str(instance_dir / relative_file)
+ if kind == "script":
+ program = [source]
+ else:
+ module_root = instance_dir / "src" if relative_file.startswith("src/") else instance_dir
+ program = [_ENTRYPOINT_LAUNCHER, "package", str(module_root), entries[0]["name"], source, locale]
+
+ environment = dict(params.get("environment") or {})
+ environment.update(launch.get("environment") or {})
+ if kind == "module":
+ environment.setdefault("PYTHONIOENCODING", "utf-8")
+ arguments = [
+ *_string_args(launch.get("runtimeArguments")),
+ *program,
+ *_string_args(params.get("optionArguments")),
+ *_string_args(launch.get("arguments", params.get("userArguments"))),
+ ]
+ if configured_interpreter:
+ tool = params.get("tool")
+ executable = tool.get("executable") if isinstance(tool, dict) else None
+ if not isinstance(executable, str) or not Path(executable).is_absolute():
+ raise PluginError("python.interpreterUnavailable", run_message("interpreter", locale))
+ environment.setdefault("PYTHON_EXECUTABLE", executable)
+ arguments = ["-I", "-B", _ENTRYPOINT_LAUNCHER, "interpreter", executable, *arguments]
+ return {
+ "executable": {"kind": "toolchain", "value": "python"},
+ "arguments": arguments,
+ "workingDirectory": working_directory,
+ "environment": environment,
+ }
+
server.on_initialize(_on_init)
server.build_handler("lithe/build/model", handle_model)
server.build_handler("lithe/build/test", handle_test)
server.build_handler("lithe/build/runEntrypoints", handle_run_entrypoints)
+ server.build_handler("lithe/build/prepareRun", handle_prepare_run)
server.suppress_success_diagnostics("lithe/build/runEntrypoints")
return server
diff --git a/io.github.lithe-idea.python-support/scripts/run_entrypoint.py b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py
new file mode 100644
index 0000000..1aca606
--- /dev/null
+++ b/io.github.lithe-idea.python-support/scripts/run_entrypoint.py
@@ -0,0 +1,88 @@
+"""Launch Python entrypoints within the process tree owned by the host."""
+
+import os
+import sys
+from importlib import import_module
+from importlib.util import find_spec, module_from_spec
+from pathlib import Path
+
+
+_MESSAGES = {
+ "invalid": (
+ "Select a runnable Python file inside the project.",
+ "请选择项目内可运行的 Python 文件。",
+ ),
+ "stale": (
+ "The saved Python entrypoint is no longer available. Open the file and run it again.",
+ "保存的 Python 入口已失效。请打开文件并重新运行。",
+ ),
+ "interpreter": (
+ "Lithe could not resolve the configured Python interpreter. Check the Python executable override.",
+ "Lithe 无法解析配置的 Python 解释器。请检查 Python 解释器覆盖设置。",
+ ),
+ "shadowed": (
+ "A module or package with the same name shadows the selected Python entrypoint.",
+ "当前包入口被同名模块或包遮蔽。",
+ ),
+}
+
+
+def run_message(key: str, locale: str) -> str:
+ english, chinese = _MESSAGES[key]
+ if not locale:
+ # Desktop releases that omit the standard initialize locale get both translations.
+ return f"{english} {chinese}"
+ return chinese if locale.replace("_", "-").split("-", 1)[0].lower() == "zh" else english
+
+
+def _run_with_interpreter(executable: str, args: list[str]) -> int:
+ # Match the build invocation's executable-directory PATH precedence.
+ os.environ["PATH"] = os.pathsep.join(filter(None, (str(Path(executable).parent), os.environ.get("PATH"))))
+ argv = [executable, *args]
+ if os.name == "nt":
+ import subprocess
+
+ # The host's Job Object owns this child. Keep the parent alive to report its exit code.
+ return subprocess.call(argv, executable=executable)
+ os.execv(executable, argv)
+
+
+def _run_package(import_root: str, package: str, selected_file: str, locale: str, args: list[str]) -> int:
+ source = Path(selected_file).resolve()
+ if sys.path and sys.path[0] == str(Path(__file__).parent):
+ sys.path.pop(0)
+ sys.path.insert(0, import_root)
+ sys.argv = ["-m", *args]
+
+ # Check each package before importing it. Resolving a dotted name with find_spec
+ # alone would import a shadowing module before we could check its origin.
+ expected_dir = Path(import_root)
+ qualified_name = ""
+ for part in package.split("."):
+ expected_dir /= part
+ qualified_name = f"{qualified_name}.{part}" if qualified_name else part
+ parent_spec = find_spec(qualified_name)
+ locations = parent_spec.submodule_search_locations if parent_spec else None
+ if not locations or not any(Path(path).resolve() == expected_dir.resolve() for path in locations):
+ raise SystemExit(run_message("shadowed", locale))
+ import_module(qualified_name)
+
+ name = f"{package}.__main__"
+ spec = find_spec(name)
+ if spec is None or not spec.origin or not spec.loader or Path(spec.origin).resolve() != source:
+ raise SystemExit(run_message("shadowed", locale))
+ # Keep Python's module metadata and relative imports, and execute the checked loader.
+ module = module_from_spec(spec)
+ module.__name__ = "__main__"
+ sys.modules["__main__"] = module
+ sys.argv[0] = str(source)
+ exec(spec.loader.get_code(name), vars(module))
+ return 0
+
+
+if __name__ == "__main__":
+ action, *args = sys.argv[1:]
+ if action == "interpreter":
+ raise SystemExit(_run_with_interpreter(args[0], args[1:]))
+ import_root, package, selected_file, locale, *program_args = args
+ raise SystemExit(_run_package(import_root, package, selected_file, locale, program_args))
diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs
index 7c8c70d..6587528 100644
--- a/scripts/package/archives.test.mjs
+++ b/scripts/package/archives.test.mjs
@@ -101,6 +101,7 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla
`${PACKAGE_ID}/scripts/windows_job.py`,
`${PACKAGE_ID}/scripts/build_model.py`,
`${PACKAGE_ID}/scripts/build_provider.py`,
+ `${PACKAGE_ID}/scripts/run_entrypoint.py`,
`${PACKAGE_ID}/scripts/discover_tests.py`,
`${PACKAGE_ID}/scripts/debugpy_adapter.py`,
`${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`,
diff --git a/scripts/test.mjs b/scripts/test.mjs
index ab5ee9e..4959f7b 100644
--- a/scripts/test.mjs
+++ b/scripts/test.mjs
@@ -367,7 +367,7 @@ try {
"toolchainProviders",
]);
for (const [capability, version] of Object.entries(variant.requires)) {
- assert.equal(version, capability === "buildSystems" ? 1 : 0);
+ assert.equal(version, ["buildSystems", "buildProviders"].includes(capability) ? 1 : 0);
}
assert.deepEqual([...variant.permissions].sort(), [
"backend.launch",
@@ -418,6 +418,9 @@ try {
assert.equal(pyBuild.provider.executesProjectCode, true);
assert.equal(pyBuild.provider.mayUseNetwork, false);
assert.deepEqual(pyBuild.model, { source: "provider" });
+ assert.deepEqual(pyBuild.run.find(({ id }) => id === "main"), {
+ id: "main", source: "provider", entrypoints: true,
+ });
assert.equal(pyBuild.test.source, "provider");
assert.equal("discovery" in pyBuild.test, false);
assert.deepEqual(pyBuild.test.discoveryCommand, {
@@ -1591,6 +1594,73 @@ try {
"runEntrypoints must suppress high-frequency success INFO logs",
);
+ const prepareRun = async (id, launchOptions) => {
+ peer.send({
+ jsonrpc: "2.0", id, method: "lithe/build/prepareRun",
+ params: {
+ operationID: `op-prepare-run-${id}`, buildSystemID: "python", root: ".", run: "main",
+ project: epResp.result.entrypoints[0].project,
+ options: {}, optionArguments: ["option"], userArguments: ["fallback"],
+ environment: { LITHE_TEST_RUN_VALUE: "default" }, launchOptions,
+ },
+ });
+ return peer.waitFor((m) => m.id === id, "prepare a Python entrypoint");
+ };
+ const scriptLaunch = await prepareRun(71, {
+ entrypoint: epResp.result.entrypoints[0].entrypoint, runtimeArguments: ["-B"],
+ arguments: ["argument with spaces"], environment: { LITHE_TEST_RUN_VALUE: "override" },
+ });
+ assert.deepEqual(scriptLaunch.result, {
+ executable: { kind: "toolchain", value: "python" },
+ arguments: ["-B", join(realpathSync(wsDir), "worker.py"), "option", "argument with spaces"],
+ workingDirectory: ".", environment: { LITHE_TEST_RUN_VALUE: "override" },
+ });
+
+ const moduleDir = join(wsDir, "src", "run_demo");
+ mkdirSync(moduleDir, { recursive: true });
+ writeFileSync(join(moduleDir, "__init__.py"), "VALUE = 'from src'\n");
+ writeFileSync(join(moduleDir, "__main__.py"), "from . import VALUE\nimport sys\nprint(VALUE, *sys.argv[1:])\n");
+ const moduleLaunch = await prepareRun(72, {
+ entrypoint: "module:src/run_demo/__main__.py", runtimeArguments: ["-B"], workingDirectory: "tests",
+ });
+ assert.equal(moduleLaunch.result.workingDirectory, "tests");
+ assert.equal(run(pythonCmd, moduleLaunch.result.arguments, { cwd: join(wsDir, "tests") }).trim(), "from src option fallback");
+
+ const shadowed = join(wsDir, "shadowed_package");
+ mkdirSync(shadowed);
+ writeFileSync(join(shadowed, "__main__.py"), "print('selected namespace entrypoint')\n");
+ const shadowedLaunch = await prepareRun(75, {
+ entrypoint: "module:shadowed_package/__main__.py", runtimeArguments: ["-B"],
+ });
+ assert.equal(run(pythonCmd, shadowedLaunch.result.arguments, { cwd: wsDir }).trim(), "selected namespace entrypoint");
+ writeFileSync(join(wsDir, "shadowed_package.py"), "print('wrong source ran')\n");
+ const collision = spawnSync(pythonCmd, shadowedLaunch.result.arguments, {
+ cwd: wsDir, encoding: "utf8", timeout: 5000, windowsHide: true,
+ env: { ...process.env, ...shadowedLaunch.result.environment },
+ });
+ assert.ifError(collision.error);
+ assert.equal(collision.stdout, "", "a shadowed entrypoint must not start a different file");
+ assert.equal(collision.status, 1);
+ assert.match(collision.stderr, /当前包入口被同名模块或包遮蔽/);
+
+ const launcher = join(unpackedPluginDir, "scripts", "run_entrypoint.py");
+ const interpreter = run(pythonCmd, ["-c", "import sys; print(sys.executable)"]).trim();
+ const forwarded = spawnSync(pythonCmd, ["-I", "-B", launcher, "interpreter", interpreter,
+ "-c", "import sys; print(sys.argv[1]); sys.exit(17)", "argument with spaces"], {
+ cwd: wsDir, encoding: "utf8", timeout: 5000, windowsHide: true,
+ });
+ assert.ifError(forwarded.error);
+ assert.equal(forwarded.status, 17, forwarded.stderr);
+ assert.equal(forwarded.stdout.trim(), "argument with spaces");
+
+ for (const [id, entrypoint] of [[73, "script:../worker.py"], [74, "script:missing.py"]]) {
+ const response = await prepareRun(id, { entrypoint });
+ assert.equal(response.error?.code, -32000);
+ assert.match(response.error.message, /保存的 Python 入口已失效/);
+ assert.ok(peer.allReceived.some((m) => m.method === "lithe/log"
+ && m.params?.operationId === `op-prepare-run-${id}` && m.params?.code === "python.staleRunEntrypoint"));
+ }
+
// 6. $/cancelRequest terminates active pytest subprocess tree cleanly with zero orphan processes!
const pidFile = join(scratch, "slow-test.pid");
writeFileSync(