Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Python Support v1.0.0 requires Lithe 0.8.9 or later. Lithe 0.8.9 can install the
- 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。
- 按 shebang 识别的无后缀脚本同样支持 Python 高亮、注释和 Pyrefly 诊断。
2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)**
- 「设置 → 语言与框架 → Python」在设置表单上方展示类型诊断和代码补全的示例。修改设置时,预览直接显示草稿效果。
- 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。
- 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。
- `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。
Expand Down Expand Up @@ -63,6 +64,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0
| `initialize` | Rust 后端 / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | — | 握手失败由 Core / 宿主记录 | 宿主协议错误 |
| `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)<br>恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
| `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` |
| `settings.preview` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(预览更新成功不发 `INFO`) | — | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `python.preview.unknownRegion`、`sdk.view.invalidEvent`、`internal_error` |
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)<br>恢复:`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` |
Expand Down
5 changes: 5 additions & 0 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod discovery;
mod inspect;
mod pyrefly;
mod requirements;
mod settings_preview;

use lithe_plugin_sdk::Backend;

Expand All @@ -19,6 +20,10 @@ fn main() {
.expect("the inspect function ID is valid")
.suppress_success_diagnostics(inspect::FUNCTION)
.expect("the inspect function is registered")
.view(settings_preview::FUNCTION, settings_preview::draw)
.expect("the preview function ID is valid")
.suppress_success_diagnostics(settings_preview::FUNCTION)
.expect("the preview function is registered")
.toolchain_provider("python", discovery::query)
.expect("the Python provider ID is valid");
std::process::exit(backend.listen());
Expand Down
155 changes: 155 additions & 0 deletions backend/src/settings_preview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
//! Draws examples of Python diagnostics and completion from the settings window's draft.

use lithe_plugin_sdk::view::{ViewEvent, ViewEventKind, ViewResult, ViewSurface};
use lithe_plugin_sdk::{Context, FunctionError, PluginError};
use serde_json::{json, Value};

pub(crate) const FUNCTION: &str = "settings.preview";

pub(crate) fn draw(event: ViewEvent, context: &Context) -> Result<ViewResult, FunctionError> {
context.check_cancelled()?;
if !matches!(&event.surface, ViewSurface::SettingRegion(id) if id == "language") {
return Err(PluginError::new(
"python.preview.unknownRegion",
"The Python settings preview requires the Python language region.",
)
.into());
}
if !matches!(
event.kind,
ViewEventKind::Open | ViewEventKind::Settings | ViewEventKind::Resize
) {
return Ok(ViewResult::Unchanged);
}
Ok(ViewResult::View(vec![canvas(&event)]))
}

fn canvas(event: &ViewEvent) -> Value {
let language = event.language.split('-').next() == Some("zh");
let words = |en, zh| if language { zh } else { en };
let value = |key| event.draft.get(key).or_else(|| event.effective.get(key));
let changed = [
"displayTypeErrors",
"autoImportCompletions",
"completeFunctionParens",
"importFormat",
]
.into_iter()
.any(|key| {
event
.draft
.get(key)
.is_some_and(|draft| Some(draft) != event.effective.get(key))
});
let (diagnostic, tone) = match value("displayTypeErrors").and_then(Value::as_str) {
Some("force-off") => (
words("Type errors hidden", "隐藏类型错误"),
"$textSecondary",
),
Some("error-missing-imports") => (
words("Missing imports only", "仅报告缺失导入"),
"$textSecondary",
),
Some("default") => (
words(
"Depends on Pyrefly project configuration",
"由项目的 Pyrefly 配置决定",
),
"$textSecondary",
),
_ => (
words(
"Type error: expected int, got str",
"类型错误:应为 int,实际为 str",
),
"$error",
),
};
let auto_import = value("autoImportCompletions")
.and_then(Value::as_bool)
.unwrap_or(true);
let completion = if value("completeFunctionParens").and_then(Value::as_bool) == Some(true) {
"greet()"
} else {
"greet"
};
let import = if value("importFormat").and_then(Value::as_str) == Some("relative") {
"from .utils import greet"
} else {
"from app.utils import greet"
};

let width = event.width.unwrap_or(640.0).clamp(260.0, 4000.0);
let gap = 12.0;
let card_top = if changed { 53.0 } else { 30.0 };
let (card_width, second_x, second_y) = if width >= 570.0 {
let card_width = (width - gap) / 2.0;
(card_width, card_width + gap, card_top)
} else {
(width, 0.0, card_top + 90.0 + gap)
};
let height = (second_y + 91.0) as u16;
let title = words("Preview", "效果预览");
let mut nodes = vec![text(0.0, 17.0, width, title, "strong", "$text")];
if changed {
nodes.push(text(
0.0,
39.0,
width,
words("Includes changes not applied yet", "含未应用的修改"),
"caption",
"$textSecondary",
));
}
nodes.push(card(
0.0,
card_top,
card_width,
words("Type diagnostics", "类型诊断"),
[
("count: int = \"3\"", "monoSmall", "$text"),
(diagnostic, "caption", tone),
],
));
let first_line = if auto_import {
(import, "monoSmall", "$text")
} else {
(
words("Auto-import off", "自动导入已关闭"),
"caption",
"$textSecondary",
)
};
nodes.push(card(
second_x,
second_y,
card_width,
words("Code completion", "代码补全"),
[first_line, (completion, "monoSmall", "$accent")],
));
let mut result = json!({
"type": "canvas", "id": "pythonPreview", "label": words("Preview of Python settings", "Python 设置效果预览"),
"height": height, "viewBox": [0, 0, width, height], "nodes": nodes,
});
if event.width.is_some() {
result["on"] = json!(["resize"]);
}
result
}

fn card(x: f64, y: f64, width: f64, title: &str, lines: [(&str, &str, &str); 2]) -> Value {
let inner = width - 26.0;
let [(first, first_style, first_color), (second, second_style, second_color)] = lines;
json!({
"type": "group", "x": x, "y": y, "children": [
{"type": "rect", "x": 0.5, "y": 0.5, "w": width - 1.0, "h": 89, "radius": 8, "fill": "$surface", "stroke": "$line"},
text(13.0, 23.0, inner, title, "strong", "$text"),
text(13.0, 49.0, inner, first, first_style, first_color),
text(13.0, 72.0, inner, second, second_style, second_color),
],
})
}

fn text(x: f64, y: f64, width: f64, value: &str, style: &str, color: &str) -> Value {
json!({"type": "text", "x": x, "y": y, "text": value, "style": style, "color": color, "maxWidth": width})
}
1 change: 1 addition & 0 deletions docs/feature-matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

| 能力域 | 功能项 | `darwin-arm64` | `darwin-x64` | `windows-x64` / `windows-arm64` | `linux-x64` / `linux-arm64` | 最近实机验证 | 实现与测试证据路径(本仓库) |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Python 设置效果预览 (`settingRegions`) | 「语言与框架 → Python」显示类型诊断和代码补全示例,随当前设置草稿更新。预览使用固定示例,保存仍由宿主表单处理。 | ✅ 包内后端与无头设置窗口通过 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | ⏳ 待归档与宿主验证 | `2026-11-22`(`darwin-arm64`,固定宿主与 0.8.13,中文深色与英文浅色) | `backend/src/settings_preview.rs`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/settingswindow/python_settings_preview_e2e_test.go` |
| Python 解释器覆盖设置 | 在「设置 → 语言与框架 → Python」显示用于构建、运行和 pytest 的解释器覆盖路径。已保存的覆盖值继续按 `pythonExecutable` 读取。 | ✅ Core 设置目录与保存值回读通过 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | ⏳ 平台清单已验证 | `2026-11-22`(`darwin-arm64`,桌面 0.8.13 固定 Core) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/package/archives.test.mjs` |
| 语言基础 (`languages`) | `.py` / `.pyi` / `.pyw` 识别、`#` 行注释、括号/引号配对、项目标记与 `.venv` / `venv` / `.conda` 依赖目录 | ✅ 已验证 | ⏳ pending(归档与清单已校验) | ⏳ pending(归档与 Windows 清单已校验) | ⏳ pending(归档与清单已校验) | `2026-11-20`(`darwin-arm64`,0.8.9 复验 `.py` 高亮) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go`<br>`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
| 无后缀 Python 脚本 | 支持 TextMate 首行匹配的桌面按解释器路径或 `env` shebang 打开,提供 Python 高亮、注释与 Pyrefly 诊断 | ✅ 已验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | ⏳ 待实机验证 | `2026-11-20`(`darwin-arm64`,桌面 `645a3aee8`) | `io.github.lithe-idea.python-support/grammars/python.first-line.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_shebang_e2e_test.go` |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
//go:build vivahead

package settingswindow

import (
"context"
"encoding/json"
"os"
"path/filepath"
"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/plugininstall"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings"
"github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust"
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
"github.com/vivaui/viva/headless"
)

const pythonSettingsPlugin = "io.github.lithe-idea.python-support"

type pythonPreviewSource struct{ service *pluginservice.Service }

func (s pythonPreviewSource) Load(ctx context.Context, id string, language i18n.Language) (pluginservice.SettingsEditor, error) {
return s.service.LoadSettingsEditor(ctx, id, "", language.Code())
}

func (s pythonPreviewSource) Save(ctx context.Context, editor pluginservice.SettingsEditor, scope string, edits []core.PluginSettingEdit) (pluginsettings.SaveResult, error) {
return s.service.SaveSettingsEditor(ctx, editor, scope, edits, nil)
}

func (s pythonPreviewSource) View(ctx context.Context, editor pluginservice.SettingsEditor, region, function string, event, previous json.RawMessage, closing bool) (json.RawMessage, bool, error) {
return s.service.CallView(ctx, pluginservice.SettingsViewCall(editor, region, function, "", event, previous, closing))
}

func TestPythonPluginSettingsPreview(t *testing.T) {
archive := os.Getenv("LITHE_TEST_PYTHON_PLUGIN_ARCHIVE")
if archive == "" {
t.Skip("set LITHE_TEST_PYTHON_PLUGIN_ARCHIVE to the packaged Python plugin")
}
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
defer cancel()
kernel := core.NewClient()
service, err := pluginservice.Open(kernel, store.At(t.TempDir()), filepath.Join(t.TempDir(), "plugins"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(service.Host.StopAll)
plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: archive, Root: service.Root, Source: plugintrust.Disk})
if err != nil {
t.Fatal(err)
}
if plan.ID != pythonSettingsPlugin {
_ = service.Installer.Discard(plan)
t.Fatalf("unexpected package ID %q", plan.ID)
}
if _, err := service.Installer.Commit(plan); err != nil {
_ = service.Installer.Discard(plan)
t.Fatal(err)
}
if err := service.Manager.SetEnabled(pythonSettingsPlugin, true); err != nil {
t.Fatal(err)
}
for _, look := range []struct {
theme, title, toggle, draft string
language i18n.Language
}{
{"light", "Preview", "Complete function parentheses", "Includes changes not applied yet", i18n.English},
{"dark", "效果预览", "补全函数括号", "含未应用的修改", i18n.Chinese},
} {
t.Run(look.theme, func(t *testing.T) {
w := newWindow(NewController(Options{
Text: func() *i18n.Messages { return i18n.For(look.language) }, Language: func() i18n.Language { return look.language },
SystemLanguage: look.language, SystemDark: func() bool { return look.theme == "dark" },
SettingsPages: func(ctx context.Context, language i18n.Language) ([]core.SettingsPage, error) {
return service.SettingsPages(ctx, language.Code())
},
SettingsNavigation: kernel.SettingsNavigation,
PluginSettings: pythonPreviewSource{service},
}), Values{Theme: look.theme, Language: look.language.Code()})
w.sess.page = pageLanguages
w.sess.open[pageLanguages] = true
config := w.config()
config.Width, config.Height = 1080, 800
session, err := headless.Open(config, nil, headless.Options{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(session.Close)
t.Cleanup(w.closeRegion)
d := &windowDriver{t: t, w: w, driver: session.Driver()}
const page = "language:python"
d.until("installed Python settings page", func() bool { return w.dynamic.selected(page) != nil })
w.selectSettingsPage(pageLanguages, page)
d.until("Python settings preview and completion toggle", func() bool {
if err := w.pluginSettings.failed; err != nil {
t.Fatalf("load settings: %v", err)
}
if w.region != nil && w.region.session.Err() != nil {
t.Fatalf("draw preview: %v", w.region.session.Err())
}
return d.text(look.title) && d.has(look.toggle)
})
if d.text(look.draft) || !d.text("greet") {
t.Fatal("the preview did not show the saved default")
}
capture := func(state string) {
t.Helper()
out := os.Getenv("LITHE_PYTHON_VISUAL_DIR")
if out == "" {
return
}
if err := os.MkdirAll(out, 0o700); err != nil {
t.Fatal(err)
}
if err := session.Advance(250 * time.Millisecond); err != nil {
t.Fatal(err)
}
if err := session.Screenshot(filepath.Join(out, "python-settings-preview-"+look.theme+"-"+state+".png")); err != nil {
t.Fatal(err)
}
}
capture("saved")
d.click(look.toggle)
d.until("preview of the unsaved completion change", func() bool { return d.text(look.draft) && d.text("greet()") })
capture("draft")
if _, err := os.Stat(w.pluginSettings.editor.Snapshot.GlobalPath()); !os.IsNotExist(err) {
t.Fatalf("preview wrote the draft to the settings file: %v", err)
}
})
}
}
1 change: 1 addition & 0 deletions e2e/host/lithe-host.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"revision": "645a3aee86e3ee5d6a308defa350678f8048baa8",
"packages": {
"./internal/projectgen": "^TestPythonPlugin",
"./internal/settingswindow": "^TestPythonPluginSettingsPreview$",
"./internal/workbench": "^TestPythonSupportPlugin"
},
"requiredEnvironment": {
Expand Down
5 changes: 5 additions & 0 deletions io.github.lithe-idea.python-support/l10n/zh-Hans.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@
}
}
},
"settingRegions": {
"language": {
"keywords": ["类型检查", "诊断", "代码补全", "效果预览"]
}
},
"sections": {
"Python Interpreter": "Python 解释器",
"Pyrefly": "Pyrefly",
Expand Down
14 changes: 12 additions & 2 deletions io.github.lithe-idea.python-support/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"runConfigurationTypes": 0,
"settings": 0,
"toolDefinitions": 0,
"toolchainProviders": 0
"toolchainProviders": 0,
"ui": 0
},
"requiresTools": ["python"],
"permissions": [
Expand All @@ -32,7 +33,8 @@
"languageServer.launch",
"process.build",
"project.generate",
"toolchains.provide"
"toolchains.provide",
"ui.contribute"
],
"activationEvents": [
"onBuildSystem:conda",
Expand Down Expand Up @@ -186,6 +188,14 @@
"section": "Completions"
}
],
"settingRegions": [
{
"id": "language",
"page": { "languageID": "python" },
"keywords": ["Pyrefly", "type checking", "diagnostics", "completions", "preview"],
"view": { "function": "settings.preview" }
}
],
"languageServers": [
{
"languageID": "python",
Expand Down
Loading
Loading