From db49198e6e12c5773e0cc29e2feff25898ce428b Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Mon, 30 Nov 2026 16:31:18 +0800 Subject: [PATCH 1/7] feat(plugins): authorize native Tests runs and scoped result pages --- rust/crates/plugin-rpc/src/host_params.rs | 48 +++++++++++++++++ rust/crates/plugin-rpc/src/host_requests.rs | 54 +++++++++++++++++++ rust/crates/plugin-rpc/src/lib.rs | 1 + shared/plugins/contract/v1/README.md | 33 ++++++++++++ .../build-providers/native-tests-start.json | 11 ++++ .../contract/v1/plugin-manifest.schema.json | 1 + shared/plugins/reference/api-catalog.md | 4 ++ shared/plugins/sdk/go/lithe/host.go | 14 +++++ shared/plugins/sdk/go/lithe/protocol.go | 2 + .../io/github/litheidea/plugin/sdk/Host.java | 19 +++++++ .../github/litheidea/plugin/sdk/Protocol.java | 2 + shared/plugins/sdk/node/src/host.mjs | 4 ++ shared/plugins/sdk/node/src/index.d.ts | 5 ++ shared/plugins/sdk/node/src/protocol.mjs | 2 + .../plugins/sdk/rust/plugin-sdk/src/host.rs | 22 ++++++++ shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 2 +- .../sdk/rust/plugin-sdk/src/protocol.rs | 2 + 17 files changed, 225 insertions(+), 1 deletion(-) create mode 100644 shared/plugins/contract/v1/fixtures/build-providers/native-tests-start.json diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 91847a48..7efd4365 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -39,6 +39,17 @@ pub(crate) fn check_host_params( HostParams::HostPaths => &["context", "rootIDs"], HostParams::BuildConfiguration { watch: false } => &["context", "buildSystemID", "root"], HostParams::BuildConfiguration { watch: true } => &["context", "files"], + HostParams::Tests { results: false } => &[ + "context", + "buildSystemID", + "root", + "project", + "target", + "suite", + "case", + "onFinish", + ], + HostParams::Tests { results: true } => &["context", "runID", "offset"], HostParams::FunctionProviders => &["functionID"], HostParams::FunctionInvoke => &[ "pluginID", @@ -165,6 +176,43 @@ pub(crate) fn check_host_params( } } } + HostParams::Tests { results } => { + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + if results { + if !params + .get("runID") + .and_then(Value::as_str) + .is_some_and(is_credential_key) + || params + .get("offset") + .is_some_and(|v| v.as_u64().is_none_or(|n| n > 10000)) + { + return Err(invalid("Expected a run ID and an optional result offset.")); + } + } else { + let text = |key: &str| { + params.get(key).and_then(Value::as_str).is_some_and(|s| { + !s.is_empty() && s.len() <= 4096 && !s.chars().any(char::is_control) + }) + }; + if !params + .get("onFinish") + .and_then(Value::as_str) + .is_some_and(is_function_id) + || !text("buildSystemID") + || !text("root") + || ["project", "target", "suite", "case"] + .iter() + .any(|key| params.contains_key(*key) && !text(key)) + { + return Err(invalid( + "Expected a build instance, exact selectors and a completion function.", + )); + } + } + } HostParams::BuildConfiguration { watch } => { if !params.get("context").is_some_and(is_context_reference) { return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index 101a4393..08e08cde 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -47,6 +47,8 @@ pub(crate) enum HostParams { /// `{ context, rootIDs? }`: a well-formed context reference and at most /// 256 distinct root IDs (plan API-40). HostPaths, + /// Starts tests on a declared build instance or reads a page of its completed results. + Tests { results: bool }, /// Build option lookup or build configuration subscription. BuildConfiguration { watch: bool }, /// Snapshot source listing or one bounded chunk from a selected source. @@ -370,6 +372,18 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: None, params: HostParams::Context, }, + HostMethod { + method: "lithe/host/tests/start", + service: "tests", + permission: Some("tests.start"), + params: HostParams::Tests { results: false }, + }, + HostMethod { + method: "lithe/host/tests/results", + service: "tests", + permission: Some("tests.start"), + params: HostParams::Tests { results: true }, + }, HostMethod { method: "lithe/host/build/getOptions", service: "build", @@ -779,6 +793,46 @@ pub(crate) fn capabilities_answer(version: u64, granted: &BTreeSet) -> V }) } +#[cfg(test)] +mod native_tests { + use super::*; + + #[test] + fn test_start_and_pages_require_the_declared_grant_and_context() { + let method = "lithe/host/tests/start"; + let mut params: Value = serde_json::from_str(include_str!( + "../../../../shared/plugins/contract/v1/fixtures/build-providers/native-tests-start.json" + )).unwrap(); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &BTreeSet::new()) + .unwrap_err() + .code, + codes::HOST_PERMISSION_DENIED + ); + let granted = [method.to_owned(), "lithe/host/tests/results".to_owned()] + .into_iter() + .collect(); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted).unwrap(), + HostRoute::Forward("tests") + ); + params["case"] = json!(""); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + let page = json!({"context":params["context"],"runID":"test-1","offset":10001}); + assert_eq!( + host_request("lithe/host/tests/results", Some(&page), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + } +} + #[cfg(test)] mod build_configuration_tests { use super::*; diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 0072597d..6fded086 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -164,6 +164,7 @@ pub const HOST_PERMISSIONS: &[&str] = &[ "window.messages", "terminal.create", "keymaps.readSelectedSources", + "tests.start", "run.start", "debug.start", PERMISSION_LANGUAGE_SERVER_REQUEST, diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 882bac2e..bd4ae4ab 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5620,6 +5620,39 @@ launch the user's Docker CLI with an explicit engine and container ID; another tool can launch its interactive client through exactly the same service. Neither requires a fake Build/Run provider. +### Native test sessions + +API-29 adds two plugin-owned host methods under `tests.start`. Discover them through +`lithe/host/getCapabilities`. A host without the methods refuses them as unavailable. +The permission is independent of reading build options and registering editor actions. +The host requires a live context, its current generation and a trusted local workspace. + +| Method | Parameters | Result | +| --- | --- | --- | +| `lithe/host/tests/start` | `{context,buildSystemID,root,project?,target?,suite?,case?,onFinish}` | `{runID}` when admitted. Execution continues after this reply. | +| `lithe/host/tests/results` | `{context,runID,offset?}` | `{tests:[{project?,suite,case,status}],nextOffset?}`. Start at zero and follow `nextOffset` until absent. | + +The build instance must belong to the caller. `root` is its workspace-relative root +(`.` for the workspace). Project and target are model IDs. A target must belong to the +selected project. Suite and case selectors are opaque strings, limited to 4096 UTF-8 +bytes each. The declared test scopes and filters govern planning and row reruns. +An already occupied project returns `plugin.host.busy`. Missing instances and projects +return `plugin.host.notFound`; an incompatible target returns `plugin.host.preconditionFailed`. +An untrusted project returns `plugin.host.permissionDenied`; unsupported authority returns +`plugin.host.authorityUnsupported`. Expired contexts use `plugin.host.contextExpired`. +Unknown fields use `plugin.host.unsupportedOption`, malformed values `plugin.host.invalidParams`. + +`onFinish` names a function already registered in the calling backend session. Each run, +including a Tests-panel rerun, gets a fresh ID. Within the same live session the host calls +the function once with `{runID,outcome,total}`. Outcome is a Core test verdict, or `error` +for a planning, launch or decoding failure. The callback may read its case results in +pages of up to 16 rows while it runs. It returns `{documents:[documentID,...]}` (up to +128 open document IDs) after updating its marker state, or `{}` if none changed. +The host then recollects those documents' editor actions. A page belonging to a different +session or context, or read after the callback returns, yields `plugin.host.notFound`. +Closing the workspace or ending the backend cancels its run and releases pending work. +Ordinary runs started from Build or Tests do not call unrelated backends. + ### Run and debug sessions A backend can start a session that the host presents as its own: a Run session diff --git a/shared/plugins/contract/v1/fixtures/build-providers/native-tests-start.json b/shared/plugins/contract/v1/fixtures/build-providers/native-tests-start.json new file mode 100644 index 00000000..f59d7623 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/build-providers/native-tests-start.json @@ -0,0 +1,11 @@ +{ + "context": { + "contextID": "context-1", + "generation": 1 + }, + "buildSystemID": "sample", + "root": ".", + "suite": "cart", + "case": "add(2) / child", + "onFinish": "tests.finished" +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 328c4d22..686c2cb5 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -104,6 +104,7 @@ "browser.open", "window.messages", "terminal.create", + "tests.start", "run.start", "debug.start", "languageServer.request", diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5cca1867..2fd7a6a2 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -158,6 +158,8 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-25 | `languageServer/request` | 向本插件自己的语言服务器发 JSON-RPC 请求,受会话策略检查,返回 `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | 向本插件自己的语言服务器发通知,返回 `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | 注册编辑器动作:把后端的普通函数绑定到文件范围(`selector`),返回 `subscriptionID` | `editor.actions`(同时需要 `documents.read`) | 0 | +| API-29 | `tests/start` | 插件启动原生测试,完成及重跑时回调原会话 | `tests.start` | 0 | +| API-29 | `tests/results` | 完成回调期间分页读取本次用例结果 | `tests.start` | 0 | | API-29 | `build/getOptions` | 读取本插件构建实例的生效选项 | `build.options.read` | 0 | | API-29 | `build/watchConfiguration` | 订阅构建选项与配置文件变更 | `build.configuration.watch` | 0 | | API-29 | `lithe/build/prepareRun`(提供者方法) | 准备宿主启动的运行计划,可选 `outputEncoding` 声明进程管道编码;参数、失败码和生命周期见[运行准备](../contract/v1/README.md#provider-run-preparation) | `process.build` | `litheBuild` 0、1 | @@ -378,6 +380,8 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-25 | `languageServer/request` | Sends a JSON-RPC request to the plugin's own language server, checked against the session policy, and returns `{value}` | `languageServer.request` | 0 | | API-25 | `languageServer/notify` | Sends a notification to the plugin's own language server and returns `{delivered}` | `languageServer.request` | 0 | | API-27 | `editor/registerActions` | Registers editor actions that bind an ordinary backend function to file ranges (`selector`) and returns a `subscriptionID` | `editor.actions` (also needs `documents.read`) | 0 | +| API-29 | `tests/start` | Starts a native Tests run with session-owned completion and rerun routing | `tests.start` | 0 | +| API-29 | `tests/results` | Reads a page of per-case statuses during completion | `tests.start` | 0 | | API-29 | `build/getOptions` | Reads effective options of the calling plugin’s build instance | `build.options.read` | 0 | | API-29 | `build/watchConfiguration` | Subscribes to changes to build options and configuration files | `build.configuration.watch` | 0 | | API-29 | `lithe/build/prepareRun` (provider method) | Prepares a host-owned launch plan; optional `outputEncoding` declares the process pipe encoding; see [run preparation](../contract/v1/README.md#provider-run-preparation) for params, failures and lifecycle | `process.build` | `litheBuild` 0, 1 | diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 36f48777..441e5b62 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -446,6 +446,20 @@ func (h *Host) Browser() *Browser { return &Browser{host: h} } // Terminal is integrated native terminals. func (h *Host) Terminal() *Terminal { return &Terminal{host: h} } +// Tests provides native test runs scoped to this backend session. +func (h *Host) Tests() *Tests { return &Tests{host: h} } + +// Tests starts runs and reads the cases covered by the completed selection. +type Tests struct{ host *Host } + +func (t *Tests) Start(context WorkspaceContext, params any) (json.RawMessage, error) { + return t.host.scoped(methodTestsStart, context, params) +} + +func (t *Tests) Results(context WorkspaceContext, params any) (json.RawMessage, error) { + return t.host.scoped(methodTestsResults, context, params) +} + // Window is messages in the window. func (h *Host) Window() *Window { return &Window{host: h} } diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go index 7f0e6f62..dabbda70 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -63,6 +63,8 @@ const ( methodEditorInsert = "lithe/host/editor/insertText" methodEditorOpen = "lithe/host/editor/open" methodEditorReveal = "lithe/host/editor/reveal" + methodTestsStart = "lithe/host/tests/start" + methodTestsResults = "lithe/host/tests/results" methodWindowShowQuickPick = "lithe/host/window/showQuickPick" methodWindowShowInputBox = "lithe/host/window/showInputBox" methodPreviewOpenMarkdown = "lithe/host/preview/openMarkdown" diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index 86c80b1b..431cd6bd 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -213,6 +213,7 @@ public boolean isRemote() { private final Editor editor = new Editor(); private final Preview preview = new Preview(); private final Browser browser = new Browser(); + private final Tests tests = new Tests(); private final Window window = new Window(); private final Functions functions = new Functions(); @@ -307,6 +308,11 @@ public Terminal terminal() { return new Terminal(); } + /** Native test runs owned by this backend session. */ + public Tests tests() { + return tests; + } + public Window window() { return window; } @@ -722,6 +728,19 @@ public CompletableFuture onExit(Map context, Map> start(Map context, Map params) { + return scoped(Protocol.HOST_TESTS_START, context, params); + } + + public CompletableFuture> results(Map context, Map params) { + return scoped(Protocol.HOST_TESTS_RESULTS, context, params); + } + + private Tests() {} + } + /** * Messages in the window. {@code params}: {@code text, * actions?}; answers {@code { selectedIndex }}, null on dismissal. diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index c8cf7032..7b7e2cfc 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -88,6 +88,8 @@ public final class Protocol { public static final String HOST_EDITOR_INSERT_TEXT = "lithe/host/editor/insertText"; public static final String HOST_EDITOR_OPEN = "lithe/host/editor/open"; public static final String HOST_EDITOR_REVEAL = "lithe/host/editor/reveal"; + public static final String HOST_TESTS_START = "lithe/host/tests/start"; + public static final String HOST_TESTS_RESULTS = "lithe/host/tests/results"; public static final String HOST_WINDOW_SHOW_QUICK_PICK = "lithe/host/window/showQuickPick"; public static final String HOST_WINDOW_SHOW_INPUT_BOX = "lithe/host/window/showInputBox"; public static final String HOST_PREVIEW_OPEN_MARKDOWN = "lithe/host/preview/openMarkdown"; diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index f5d53acb..6a58044c 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -409,6 +409,10 @@ export function createHost(channel, callSignal, parentOperationId) { onExit: async (context, terminalID, onEvent, options) => subscribe(HOST_METHODS.terminalOnExit, { context: contextReference(context), terminalID }, onEvent, options), }), + tests: Object.freeze({ + start: scoped(HOST_METHODS.testsStart), + results: scoped(HOST_METHODS.testsResults), + }), window: Object.freeze({ showQuickPick: scoped(HOST_METHODS.windowShowQuickPick), showInputBox: scoped(HOST_METHODS.windowShowInputBox), diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index d8078f4b..59a0602a 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -467,6 +467,10 @@ export interface Host { options?: HostRequestOptions): Promise; }; /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ + readonly tests: { + start: Scoped<{buildSystemID: string; root: string; project?: string; target?: string; suite?: string; case?: string; onFinish: string}, {runID: string}>; + results: Scoped<{runID: string; offset?: number}, {tests: {project?: string; suite: string; case: string; status: string}[]; nextOffset?: number}>; + }; readonly window: { showQuickPick: Scoped<{title?:string;placeholder?:string;items:QuickPickItem[];canPickMany?:boolean},{selectedIDs:string[]}|null>; showInputBox: Scoped<{title?:string;prompt?:string;placeholder?:string;value?:string;password?:boolean},{value:string}|null>; @@ -1117,6 +1121,7 @@ export const HOST_METHODS: Readonly Tests { + Tests { host: self.clone() } + } + pub fn window(&self) -> Window { Window { host: self.clone() } } @@ -1319,6 +1324,23 @@ impl Browser { } } +/// Starts native Tests runs and reads the calling session's result pages. +pub struct Tests { + host: Host, +} + +impl Tests { + /// Starts one selection; the completion function receives the run ID and outcome. + pub fn start(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::TESTS_START, context, params) + } + + /// Reads one page of exact case identities and statuses from a completed run. + pub fn results(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::TESTS_RESULTS, context, params) + } +} + /// Messages in the window. `params`: `text, actions?`; answers /// `{ selectedIndex }`, `Value::Null` on dismissal. pub struct Window { diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index c11c4f1e..c7b99291 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -65,7 +65,7 @@ pub use error::{ pub use host::{ Browser, Clipboard, Credentials, Documents, Editor, Event, Functions, Host, HostFolder, HostPath, Network, Output, Preview, ProcessRoot, Progress, StatusBar, Subscription, - Subscriptions, Terminal, Views, Window, Workspace, WorkspaceContext, + Subscriptions, Terminal, Tests, Views, Window, Workspace, WorkspaceContext, }; pub use protocol::{is_command_id, is_credential_key, is_function_id, is_plugin_error_code}; pub use serde_json::Value; diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index f887012a..f12e6f1f 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -75,6 +75,8 @@ pub(crate) mod methods { pub const EDITOR_INSERT_TEXT: &str = "lithe/host/editor/insertText"; pub const EDITOR_OPEN: &str = "lithe/host/editor/open"; pub const EDITOR_REVEAL: &str = "lithe/host/editor/reveal"; + pub const TESTS_START: &str = "lithe/host/tests/start"; + pub const TESTS_RESULTS: &str = "lithe/host/tests/results"; pub const WINDOW_SHOW_QUICK_PICK: &str = "lithe/host/window/showQuickPick"; pub const WINDOW_SHOW_INPUT_BOX: &str = "lithe/host/window/showInputBox"; pub const PREVIEW_OPEN_MARKDOWN: &str = "lithe/host/preview/openMarkdown"; From 2788f6656c402b06f60334eb66a51c7ce8935e3b Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Mon, 30 Nov 2026 17:00:31 +0800 Subject: [PATCH 2/7] feat(tests): support standalone runner reports and lifecycle diagnostics --- rust/contracts/rust-core-api.md | 1 + rust/crates/build/src/commands.rs | 7 ++++ rust/crates/build/src/outputs.rs | 35 ++++++++++++++---- rust/crates/core/src/protocol/command.rs | 5 +++ .../core/src/runtime/dispatcher/build.rs | 5 +++ .../diagnostics/src/catalog_generated.rs | 14 ++++++++ rust/crates/plugin-rpc/src/host_params.rs | 36 +++++++++++++++++-- rust/crates/plugin-rpc/src/host_requests.rs | 21 +++++++++++ rust/logging/events/run.json | 25 +++++++++++++ shared/plugins/contract/v1/README.md | 20 +++++++++++ shared/plugins/sdk/node/src/index.d.ts | 2 +- 11 files changed, 162 insertions(+), 9 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 43d26ee4..6c97668d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -608,6 +608,7 @@ or removing a command fails until the table changes in the same commit. | `build.decodeRunEntrypoints` | Validate and deduplicate the run entrypoints a Provider named | | `build.dependencyPlan` | Expand the command that prints a project's dependency tree, or the request a build provider answers | | `build.decodeModel` | Decode model output or a provider result into projects, targets, tasks, content roots, option values, and run entries | +| `build.decodeInlineTestResults` | Decode an inline `litheTestResults` version 0 report from an independent test runner. Returns the same results envelope and workspace-relative locations as provider reports. | | `build.decodeTestResults` | Decode a test run's reports and output into per-case results and a summary | | `build.decodeDiagnostics` | Decode build output into workspace file diagnostics | | `build.decodeDependencies` | Decode dependency output or a provider result into one project's bounded tree | diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index a9eefd89..abd68f28 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -442,6 +442,13 @@ pub fn build_decode_test_results_command( ) } +/// Decodes a standalone runner's inline canonical report under its workspace root. +pub fn build_decode_inline_test_results_command(payload: Value) -> Result { + Ok(outcome( + outputs::inline_test_results(&payload, ".").map(|results| ("results", results)), + )) +} + /// `build.decodeDiagnostics`: file diagnostics from process output. pub fn build_decode_diagnostics_command( payload: Value, diff --git a/rust/crates/build/src/outputs.rs b/rust/crates/build/src/outputs.rs index 93665530..bc51d108 100644 --- a/rust/crates/build/src/outputs.rs +++ b/rust/crates/build/src/outputs.rs @@ -397,17 +397,14 @@ pub(crate) fn decode_test_results( None => root.clone(), }; decode::bounded_text(&request.output)?; - let mut coverage = Vec::new(); let cases = match source { TestResultsSource::Provider => { - let (cases, scopes) = provider_test_cases( + return inline_test_results( request.result.as_ref().ok_or_else(|| { decode::invalid_output("The provider returned no test report.") })?, &root, - )?; - coverage = scopes; - cases + ); } TestResultsSource::JunitXml { reports } => report_cases( &workspace, @@ -424,6 +421,17 @@ pub(crate) fn decode_test_results( |text, base| canonical_cases(text, &workspace, base), ), }; + Ok(summarize_results(cases, Vec::new())) +} + +/// Decodes the same inline report for a build provider and for a standalone plugin runner. +/// Filenames are workspace-relative. Reading or searching the workspace is unnecessary. +pub(crate) fn inline_test_results(value: &Value, root: &str) -> Validation { + let (cases, coverage) = provider_test_cases(value, root)?; + Ok(summarize_results(cases, coverage)) +} + +fn summarize_results(cases: Vec, coverage: Vec) -> Value { let cases = aggregate(cases); let summary = summary(&cases); let mut result = json!({ @@ -434,7 +442,22 @@ pub(crate) fn decode_test_results( if !coverage.is_empty() { result["coverage"] = json!(coverage); } - Ok(result) + result +} + +#[cfg(test)] +mod inline_runner_tests { + use super::*; + + #[test] + fn standalone_report_uses_provider_validation_and_outcomes() { + let mut report = json!({"format":"litheTestResults","version":0,"tests":[{"suite":"cart","case":"add","status":"failed","path":"tests/cart.txt","line":2},{"suite":"cart","case":"add","status":"passed"}]}); + let results = inline_test_results(&report, ".").unwrap(); + assert_eq!(results["tests"][0]["invocations"], 2); + assert_eq!(results["summary"]["failed"], 1); + report["tests"][0]["path"] = json!("../outside"); + assert!(inline_test_results(&report, ".").is_err()); + } } /// Validates an inline report without opening report files or inferring tool semantics. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 44585fca..a0a4ac0a 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -607,6 +607,8 @@ pub enum BuildCommand { DecodeModel, /// Normalizes build test results (`build.decodeTestResults`). DecodeTestResults, + /// Normalizes one inline native Tests report without a build-system declaration. + DecodeInlineTestResults, /// Normalizes build diagnostics from process output (`build.decodeDiagnostics`). DecodeDiagnostics, /// Normalizes a project's dependency tree (`build.decodeDependencies`). @@ -1486,6 +1488,9 @@ impl CoreCommand { "build.decodeRunEntrypoints" => Some(Self::Build(BuildCommand::DecodeRunEntrypoints)), "build.dependencyPlan" => Some(Self::Build(BuildCommand::DependencyPlan)), "build.decodeModel" => Some(Self::Build(BuildCommand::DecodeModel)), + "build.decodeInlineTestResults" => { + Some(Self::Build(BuildCommand::DecodeInlineTestResults)) + } "build.decodeTestResults" => Some(Self::Build(BuildCommand::DecodeTestResults)), "build.decodeDiagnostics" => Some(Self::Build(BuildCommand::DecodeDiagnostics)), "build.decodeDependencies" => Some(Self::Build(BuildCommand::DecodeDependencies)), diff --git a/rust/crates/core/src/runtime/dispatcher/build.rs b/rust/crates/core/src/runtime/dispatcher/build.rs index 7b84d01b..1679bf2c 100644 --- a/rust/crates/core/src/runtime/dispatcher/build.rs +++ b/rust/crates/core/src/runtime/dispatcher/build.rs @@ -151,6 +151,11 @@ pub(super) fn dispatch(command: BuildCommand, id: Option, payload: Value payload, crate::build::build_decode_model_command::, ), + BuildCommand::DecodeInlineTestResults => plugin_response( + id, + payload, + crate::build::build_decode_inline_test_results_command, + ), BuildCommand::DecodeTestResults => plugin_response( id, payload, diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 94058504..3ca57ad4 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1866,6 +1866,20 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 600, owner: "Lithe", }, + EventMetadata { + id: "run.tests.state_changed", + channel: "run", + level: LogLevel::Info, + message: "Native Tests run {run} reached {stage}", + fields: &[ + FieldMetadata { name: "outcome", field_type: FieldType::Token, required: false, description: "Core verdict or stable failure category when the test run ends", reason: None }, + FieldMetadata { name: "run", field_type: FieldType::Token, required: true, description: "Host-generated run ID returned to the originating plugin session", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Stable lifecycle stage of this test run: accepted, stop_requested or finished", reason: None }, + ], + span: None, + rate: 600, + owner: "Lithe", + }, EventMetadata { id: "terminal.input.failed", channel: "terminal", diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 7efd4365..d67c0295 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -48,6 +48,9 @@ pub(crate) fn check_host_params( "suite", "case", "onFinish", + "runner", + "data", + "filters", ], HostParams::Tests { results: true } => &["context", "runID", "offset"], HostParams::FunctionProviders => &["functionID"], @@ -201,8 +204,6 @@ pub(crate) fn check_host_params( .get("onFinish") .and_then(Value::as_str) .is_some_and(is_function_id) - || !text("buildSystemID") - || !text("root") || ["project", "target", "suite", "case"] .iter() .any(|key| params.contains_key(*key) && !text(key)) @@ -211,6 +212,37 @@ pub(crate) fn check_host_params( "Expected a build instance, exact selectors and a completion function.", )); } + if let Some(runner) = params.get("runner") { + let valid_filters = params.get("filters").is_none_or(|value| { + value.as_array().is_some_and(|filters| { + let mut seen = BTreeSet::new(); + filters.len() <= 2 + && filters.iter().all(|filter| { + matches!(filter.as_str(), Some("suite" | "case")) + && seen.insert(filter.as_str()) + }) + }) + }); + if !runner.as_str().is_some_and(is_function_id) + || ["root", "buildSystemID", "target"] + .iter() + .any(|key| params.contains_key(*key)) + || !valid_filters + || params + .get("data") + .is_some_and(|v| v.to_string().len() > 65536) + { + return Err(invalid("Invalid test runner, filters or rerun data.")); + } + } else if !text("buildSystemID") + || !text("root") + || params.contains_key("data") + || params.contains_key("filters") + { + return Err(invalid( + "Expected a declared build instance or a registered runner.", + )); + } } } HostParams::BuildConfiguration { watch } => { diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index 08e08cde..bc55fbe5 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -797,6 +797,27 @@ pub(crate) fn capabilities_answer(version: u64, granted: &BTreeSet) -> V mod native_tests { use super::*; + #[test] + fn independent_runner_cannot_combine_build_fields_or_invent_filters() { + let method = "lithe/host/tests/start"; + let grants = [method.to_owned()].into_iter().collect(); + let mut params = json!({"context":{"contextID":"ctx","generation":1},"runner":"tests.run","onFinish":"tests.done","filters":["case"]}); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &grants).unwrap(), + HostRoute::Forward("tests") + ); + for (field, value) in [("root", json!(".")), ("filters", json!(["file"]))] { + params[field] = value; + assert_eq!( + host_request(method, Some(¶ms), Some(0), &grants) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + params.as_object_mut().unwrap().remove(field); + } + } + #[test] fn test_start_and_pages_require_the_declared_grant_and_context() { let method = "lithe/host/tests/start"; diff --git a/rust/logging/events/run.json b/rust/logging/events/run.json index 9b05636d..11724ed4 100644 --- a/rust/logging/events/run.json +++ b/rust/logging/events/run.json @@ -2,6 +2,31 @@ "version": 1, "root": "run", "events": [ + { + "id": "run.tests.state_changed", + "channel": "run", + "level": "info", + "message": "Native Tests run {run} reached {stage}", + "fields": { + "run": { + "type": "token", + "required": true, + "description": "Host-generated run ID returned to the originating plugin session" + }, + "stage": { + "type": "token", + "required": true, + "description": "Stable lifecycle stage of this test run: accepted, stop_requested or finished" + }, + "outcome": { + "type": "token", + "required": false, + "description": "Core verdict or stable failure category when the test run ends" + } + }, + "rate": 600, + "owner": "Lithe" + }, { "id": "run.process.execution", "channel": "run", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index bd4ae4ab..dbb1e1ca 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5653,6 +5653,26 @@ session or context, or read after the callback returns, yields `plugin.host.notF Closing the workspace or ending the backend cancels its run and releases pending work. Ordinary runs started from Build or Tests do not call unrelated backends. +#### Standalone test runner + +A backend without a build system uses the same `tests/start` method. Supply +`runner` instead of `buildSystemID`, `root` and `target`. It names a function registered +by the calling session. Optional `data` (up to 64 KiB serialized) identifies the original +selection. Optional `filters` lists the distinct row reruns it accepts (`suite`, `case`). +Omitting the list offers whole-run rerun only. The host invokes the runner with +`{runID,data?,project?,suite?,case?}` and its workspace context. Row reruns carry the +reported project and exact suite/case names; the backend resolves these within its +original data. The original selection remains available for whole-run reruns. + +The runner reports bounded progress messages through function progress. Stop and the +30-minute deadline cancel that invocation using the existing function protocol. On normal +completion it returns `{exitCode,testResults}` with one inline `litheTestResults` version +0 report. The serialized reply must fit the function-result limit (1 MiB). The host +validates and aggregates the report in Core and publishes the final tree once. +A thrown error, timeout or cancellation has its own terminal outcome without invented +per-case statuses. Permission, ownership, result paging and editor refresh follow the +same rules as build-backed sessions. + ### Run and debug sessions A backend can start a session that the host presents as its own: a Run session diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 59a0602a..6bb83c2d 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -468,7 +468,7 @@ export interface Host { }; /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ readonly tests: { - start: Scoped<{buildSystemID: string; root: string; project?: string; target?: string; suite?: string; case?: string; onFinish: string}, {runID: string}>; + start: Scoped<({buildSystemID: string; root: string; target?: string} | {runner: string; data?: unknown; filters?: ('suite'|'case')[]}) & {project?: string; suite?: string; case?: string; onFinish: string}, {runID: string}>; results: Scoped<{runID: string; offset?: number}, {tests: {project?: string; suite: string; case: string; status: string}[]; nextOffset?: number}>; }; readonly window: { From ce7cf5944745fb147389f37ec3ae8f72436f66e3 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Mon, 30 Nov 2026 17:06:40 +0800 Subject: [PATCH 3/7] docs(plugins): register API-29 methods in the protocol history --- shared/plugins/reference/protocol-changelog.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 09204084..d4b26cd4 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | 插件函数协议 0,标准测试报告 0 | 后端可以从构建实例或独立运行器启动原生 Tests 会话,在完成回调中分页读取结果。四个 SDK 同步接入。 | | [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | | [#227](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/227)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 市场索引 `schemaVersion` 0 内的补充 | 一个仓库发布多个插件时,每个插件的 Release 标签用自己的前缀:`<前缀>MAJOR.MINOR.PATCH`(如 `codex-v0.1.0`、`claude-code-v0.1.0`)。索引字段不变:`plugins.marketplace.validateIndex` 的输出条目新增 `releaseTagPrefix`,由 Core 从下载地址的标签派生;每个标签都拆成同一个前缀加上列出它的版本号时为该前缀,否则为 `null`。宿主用它读取插件自己的更新日志(`listReleases` 的 `tagPrefix`)。只新增 Core 输出字段,旧宿主照常读取同一份索引;没有新增宿主方法、通知、错误码、能力版本或 SDK 版本。规则见 [`marketplace.md`](domains/marketplace.md#一个仓库发布多个插件)。 | | [#228](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/228)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `toolDefinitions` 0 / 1 内的补充 | 多个已启用插件声明同一个工具短 ID 且规范化定义完全一致时,`toolchains.registry` 与 `toolchains.discoveryPlan` 自动聚合成一条定义,并在有多个声明插件时附带排序后的 `pluginIDs`;定义不同仍作为 `conflicts` 拒绝。不提升 `toolDefinitions` 能力版本,不新增宿主方法、通知、错误码或 SDK 版本。规则见 [`toolchains/README.md`](../contract/v1/toolchains/README.md#commands-and-envelopes)。 | @@ -203,6 +204,8 @@ | API-25 | `languageServer/didReceiveNotification`(通知) | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-27 | `editor/registerActions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-27 | `editor/registerActions` | 0(`actionIcons` 新增 4 个导航图标 token) | 2026-11-24 | [#198](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/198) | +| API-29 | `tests/start` | 0 | 待合入 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | +| API-29 | `tests/results` | 0 | 待合入 | [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234) | | API-29 | `build/getOptions` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-29 | `build/watchConfiguration` | 0 | 2026-11-21 | [#155](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/155) | | API-29 | `lithe/build/prepareRun`(提供者方法) | `litheBuild` 0、1(返回值 `outputEncoding` 可选声明) | 2026-11-20 | [#128](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/128) | From 453594a1e33e960d8265e4fd79a1de62f6519919 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Mon, 30 Nov 2026 17:23:59 +0800 Subject: [PATCH 4/7] test(plugins): exercise typed Tests calls and document callback admission --- rust/crates/build/src/outputs.rs | 30 ++++++++++----------- shared/plugins/contract/v1/README.md | 2 +- shared/plugins/sdk/node/test/types/host.mts | 4 +++ 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/rust/crates/build/src/outputs.rs b/rust/crates/build/src/outputs.rs index bc51d108..6927f9a7 100644 --- a/rust/crates/build/src/outputs.rs +++ b/rust/crates/build/src/outputs.rs @@ -445,21 +445,6 @@ fn summarize_results(cases: Vec, coverage: Vec) -> result } -#[cfg(test)] -mod inline_runner_tests { - use super::*; - - #[test] - fn standalone_report_uses_provider_validation_and_outcomes() { - let mut report = json!({"format":"litheTestResults","version":0,"tests":[{"suite":"cart","case":"add","status":"failed","path":"tests/cart.txt","line":2},{"suite":"cart","case":"add","status":"passed"}]}); - let results = inline_test_results(&report, ".").unwrap(); - assert_eq!(results["tests"][0]["invocations"], 2); - assert_eq!(results["summary"]["failed"], 1); - report["tests"][0]["path"] = json!("../outside"); - assert!(inline_test_results(&report, ".").is_err()); - } -} - /// Validates an inline report without opening report files or inferring tool semantics. fn provider_test_cases( value: &Value, @@ -1140,3 +1125,18 @@ pub(crate) fn sync_fingerprint( "watch": files, })) } + +#[cfg(test)] +mod inline_runner_tests { + use super::*; + + #[test] + fn standalone_report_uses_provider_validation_and_outcomes() { + let mut report = json!({"format":"litheTestResults","version":0,"tests":[{"suite":"cart","case":"add","status":"failed","path":"tests/cart.txt","line":2},{"suite":"cart","case":"add","status":"passed"}]}); + let results = inline_test_results(&report, ".").unwrap(); + assert_eq!(results["tests"][0]["invocations"], 2); + assert_eq!(results["summary"]["failed"], 1); + report["tests"][0]["path"] = json!("../outside"); + assert!(inline_test_results(&report, ".").is_err()); + } +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index dbb1e1ca..9a318351 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5636,7 +5636,7 @@ The build instance must belong to the caller. `root` is its workspace-relative r (`.` for the workspace). Project and target are model IDs. A target must belong to the selected project. Suite and case selectors are opaque strings, limited to 4096 UTF-8 bytes each. The declared test scopes and filters govern planning and row reruns. -An already occupied project returns `plugin.host.busy`. Missing instances and projects +A project running a test or still delivering its preceding plugin callback returns `plugin.host.busy`. This bounds retained reports and preserves completion order. Missing instances and projects return `plugin.host.notFound`; an incompatible target returns `plugin.host.preconditionFailed`. An untrusted project returns `plugin.host.permissionDenied`; unsupported authority returns `plugin.host.authorityUnsupported`. Expired contexts use `plugin.host.contextExpired`. diff --git a/shared/plugins/sdk/node/test/types/host.mts b/shared/plugins/sdk/node/test/types/host.mts index d7b579d7..20fb3871 100644 --- a/shared/plugins/sdk/node/test/types/host.mts +++ b/shared/plugins/sdk/node/test/types/host.mts @@ -20,6 +20,10 @@ backend.function('query.run', async (_params, context) => { await context.host.credentials.set('connection.prod', secret ?? ''); const workspace: ContextReference | null = context.workspaceContext; if (!workspace) return null; + const { runID } = await context.host.tests.start(workspace, { runner: 'tests.run', filters: ['case'], onFinish: 'tests.done' }); + const page = await context.host.tests.results(workspace, { runID }); + const status: string | undefined = page.tests[0]?.status; + void status; const { folders } = await context.host.workspace.getFolders(workspace); const root = folders[0]; if (!root) return null; From 3e7133563d273b0e91c224fa2de54eb857142b7c Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Tue, 1 Dec 2026 13:07:14 +0800 Subject: [PATCH 5/7] fix(tests): reject standalone reports missing the tests array --- rust/crates/build/src/commands.rs | 11 ++++++++--- rust/crates/build/src/outputs.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index abd68f28..0f46d68e 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -444,9 +444,14 @@ pub fn build_decode_test_results_command( /// Decodes a standalone runner's inline canonical report under its workspace root. pub fn build_decode_inline_test_results_command(payload: Value) -> Result { - Ok(outcome( - outputs::inline_test_results(&payload, ".").map(|results| ("results", results)), - )) + let results = if payload.get("tests").is_none() { + Err(super::decode::invalid_output( + "The standalone test report is missing its tests array.", + )) + } else { + outputs::inline_test_results(&payload, ".") + }; + Ok(outcome(results.map(|results| ("results", results)))) } /// `build.decodeDiagnostics`: file diagnostics from process output. diff --git a/rust/crates/build/src/outputs.rs b/rust/crates/build/src/outputs.rs index 6927f9a7..7a1f4164 100644 --- a/rust/crates/build/src/outputs.rs +++ b/rust/crates/build/src/outputs.rs @@ -1130,6 +1130,18 @@ pub(crate) fn sync_fingerprint( mod inline_runner_tests { use super::*; + #[test] + fn standalone_report_requires_an_explicit_tests_array() { + let mut report = json!({"format": "litheTestResults", "version": 0}); + let rejected = crate::build_decode_inline_test_results_command(report.clone()).unwrap(); + assert_eq!(rejected["error"]["code"], "plugin.build.invalidOutput"); + + report["tests"] = json!([]); + let empty = crate::build_decode_inline_test_results_command(report).unwrap(); + assert_eq!(empty["status"], "ok"); + assert_eq!(empty["results"]["tests"], json!([])); + } + #[test] fn standalone_report_uses_provider_validation_and_outcomes() { let mut report = json!({"format":"litheTestResults","version":0,"tests":[{"suite":"cart","case":"add","status":"failed","path":"tests/cart.txt","line":2},{"suite":"cart","case":"add","status":"passed"}]}); From e48ba0eb59e40e2515fd462741f5feffaa158871 Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Tue, 1 Dec 2026 17:38:02 +0800 Subject: [PATCH 6/7] fix(plugins): require the project of a native test target and document compatibility --- rust/crates/plugin-rpc/src/host_params.rs | 1 + rust/crates/plugin-rpc/src/host_requests.rs | 12 ++++++++++++ shared/plugins/contract/v1/README.md | 11 ++++++++--- shared/plugins/sdk/go/lithe/host.go | 2 ++ shared/plugins/sdk/node/src/index.d.ts | 3 ++- 5 files changed, 25 insertions(+), 4 deletions(-) diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 7efd4365..e764609f 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -206,6 +206,7 @@ pub(crate) fn check_host_params( || ["project", "target", "suite", "case"] .iter() .any(|key| params.contains_key(*key) && !text(key)) + || (params.contains_key("target") && !params.contains_key("project")) { return Err(invalid( "Expected a build instance, exact selectors and a completion function.", diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index 08e08cde..9819f493 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -816,6 +816,18 @@ mod native_tests { host_request(method, Some(¶ms), Some(0), &granted).unwrap(), HostRoute::Forward("tests") ); + params["target"] = json!("unit"); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted) + .unwrap_err() + .code, + codes::HOST_INVALID_PARAMS + ); + params["project"] = json!("module"); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted).unwrap(), + HostRoute::Forward("tests") + ); params["case"] = json!(""); assert_eq!( host_request(method, Some(¶ms), Some(0), &granted) diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index ae29ec39..eaa87945 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5801,7 +5801,9 @@ Neither requires a fake Build/Run provider. ### Native test sessions API-29 adds two plugin-owned host methods under `tests.start`. Discover them through -`lithe/host/getCapabilities`. A host without the methods refuses them as unavailable. +`lithe/host/getCapabilities`. Older Core revisions that do not recognize `tests.start` +reject a manifest declaring it at installation with `plugin.permission.unknown`. +A host that recognizes the permission but does not provide the service omits its methods. The permission is independent of reading build options and registering editor actions. The host requires a live context, its current generation and a trusted local workspace. @@ -5811,8 +5813,9 @@ The host requires a live context, its current generation and a trusted local wor | `lithe/host/tests/results` | `{context,runID,offset?}` | `{tests:[{project?,suite,case,status}],nextOffset?}`. Start at zero and follow `nextOffset` until absent. | The build instance must belong to the caller. `root` is its workspace-relative root -(`.` for the workspace). Project and target are model IDs. A target must belong to the -selected project. Suite and case selectors are opaque strings, limited to 4096 UTF-8 +(`.` for the workspace). Project and target are model IDs. Supplying `target` requires +`project`; a target alone returns `plugin.host.invalidParams`. The target must belong +to the selected project. Suite and case selectors are opaque strings, limited to 4096 UTF-8 bytes each. The declared test scopes and filters govern planning and row reruns. An already occupied project returns `plugin.host.busy`. Missing instances and projects return `plugin.host.notFound`; an incompatible target returns `plugin.host.preconditionFailed`. @@ -5826,6 +5829,8 @@ the function once with `{runID,outcome,total}`. Outcome is a Core test verdict, for a planning, launch or decoding failure. The callback may read its case results in pages of up to 16 rows while it runs. It returns `{documents:[documentID,...]}` (up to 128 open document IDs) after updating its marker state, or `{}` if none changed. +Return the document service's opaque ID unchanged. For a numeric document handle supplied +when collecting editor actions, return its decimal representation as a JSON string. The host then recollects those documents' editor actions. A page belonging to a different session or context, or read after the callback returns, yields `plugin.host.notFound`. Closing the workspace or ending the backend cancels its run and releases pending work. diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 441e5b62..1c8a91bb 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -452,10 +452,12 @@ func (h *Host) Tests() *Tests { return &Tests{host: h} } // Tests starts runs and reads the cases covered by the completed selection. type Tests struct{ host *Host } +// Start requests a native test run in the calling workspace. func (t *Tests) Start(context WorkspaceContext, params any) (json.RawMessage, error) { return t.host.scoped(methodTestsStart, context, params) } +// Results reads a page of cases during the owning run's completion callback. func (t *Tests) Results(context WorkspaceContext, params any) (json.RawMessage, error) { return t.host.scoped(methodTestsResults, context, params) } diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index afb33b78..2fec4771 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -466,11 +466,12 @@ export interface Host { onEvent: (event: { type: 'exit'; terminalID: string; exitCode: number | null; reason: 'exited' | 'closed'; generation: number }, metadata: SubscriptionEventInfo) => void, options?: HostRequestOptions): Promise; }; - /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ + /** Permission `tests.start`. Results are available during the completion callback. */ readonly tests: { start: Scoped<{buildSystemID: string; root: string; project?: string; target?: string; suite?: string; case?: string; onFinish: string}, {runID: string}>; results: Scoped<{runID: string; offset?: number}, {tests: {project?: string; suite: string; case: string; status: string}[]; nextOffset?: number}>; }; + /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */ readonly window: { showQuickPick: Scoped<{title?:string;placeholder?:string;items:QuickPickItem[];canPickMany?:boolean},{selectedIDs:string[]}|null>; showInputBox: Scoped<{title?:string;prompt?:string;placeholder?:string;value?:string;password?:boolean},{value:string}|null>; From 950e196c57315ebbdc98bdb313d5ae604e36e47e Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Tue, 1 Dec 2026 17:46:35 +0800 Subject: [PATCH 7/7] docs(plugins): clarify standalone reruns and protocol availability --- shared/plugins/contract/v1/README.md | 3 +++ shared/plugins/reference/protocol-changelog.md | 2 +- shared/plugins/sdk/node/src/index.d.ts | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index a48524ba..9d54643e 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5835,6 +5835,9 @@ The host then recollects those documents' editor actions. A page belonging to a session or context, or read after the callback returns, yields `plugin.host.notFound`. Closing the workspace or ending the backend cancels its run and releases pending work. Ordinary runs started from Build or Tests do not call unrelated backends. +After the originating session ends, a build-backed selection can run again as an ordinary +build test if its instance is available. A standalone selection requires the original +live runner. Start a new run from the plugin after restarting its backend. #### Standalone test runner diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 5d7a4c10..25bc74c8 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | 插件函数协议 0,标准测试报告 0 | 后端可以从构建实例或独立运行器启动原生 Tests 会话,在完成回调中分页读取结果。四个 SDK 同步接入。 | +| [#234](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/234)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | 插件函数协议 0、标准测试报告 0 内的补充 | 新权限 `tests.start` 允许后端从构建实例或独立运行器启动原生 Tests 会话,并在完成回调中分页读取结果。四个 SDK 同步接入。Core 新增命令 `build.decodeInlineTestResults` 和日志事件 `run.tests.state_changed`。旧 Core 安装声明该权限的插件时会返回 `plugin.permission.unknown`。首个同时支持两种入口的 Core 修订为 [`2788f665`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/2788f6656c402b06f60334eb66a51c7ce8935e3b)。 | | [#241](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/241)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.search` 的命中新增 `generation` 和 `readBytes`,都是命中所在文件(可能是子代理文件)的值,宿主据此从命中处用 `agentSessions.page` 分页读取该文件。旧 Core 不回答这两个字段。没有新增宿主方法、通知、错误码或能力版本。 | | [#239](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/239)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 内的补充 | 原生会话增加立即补充、FIFO 排队、停止后暂停队列和结构化问答。`agents.prompt` 增加可选 `mode`(默认 `send`,另有 `queue`、`steer`)和 `expectedTurn`;`didPrompt` 仅立即补充时增加 `mode: "steer"`、`input`。新增通知 `didAnswerQuestion`;`report` 新增 `interactionCapabilities`、`questionRequested`、`questionClosed`、`questionAnswered`、`inputResolved`,后者可带封闭的 SDK 失败分类 `code`,四语 SDK 把立即补充失败的唯一终态诊断交给 Core;回答由 SDK 确认交付。Core 新增宿主命令 `agents.updateQueue`、`agents.respondQuestion`;`cancel` 进入 stopping 并暂停队列,真实结束前不宣告停止;通过 `interactionState`、`promptDispatched`、`promptRetracted` 和 `interactionFailed` 投影结果。事件重放同时限制 8192 条 / 16 MiB,交互状态只保留每会话最新快照;`agents.waitEvents` 增加 `recoveries` 与可选 `acknowledge`,拒绝的补充在预留的 64 条 / 16 MiB 容量中保留,直到宿主恢复并显式确认。停止后的有效当前轮次问题被抑制,不阻塞同批结束事件。共享用例为 `agents/native-session.json` 及 `rust/fixtures/agents/turn-interaction-v1.json`。没有提升 API、能力、清单或函数协议版本;旧 Core 严格拒绝新字段和事件,首个支持的 Core revision 为 [`1f843f8ee3aac802cda17ad8df43b51e30862b0d`](https://github.com/Lithe-IDEA/Lithe-core-rust/commit/1f843f8ee3aac802cda17ad8df43b51e30862b0d)(本 PR,尚未合入);桌面端尚未发布。 | | [#231](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/231)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 | `agents/usage` 支持按小时汇总。默认按指定 UTC 偏移对齐整点,也可用 `hourAnchorMs` 对齐滚动窗口。 | diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 29bfef85..31d7fc6c 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -468,7 +468,7 @@ export interface Host { }; /** Permission `tests.start`. Results are available during the completion callback. */ readonly tests: { - start: Scoped<({buildSystemID: string; root: string; target?: string} | {runner: string; data?: unknown; filters?: ('suite'|'case')[]}) & {project?: string; suite?: string; case?: string; onFinish: string}, {runID: string}>; + start: Scoped<(({buildSystemID: string; root: string} & ({project?: string; target?: never} | {project: string; target: string})) | {runner: string; project?: string; data?: unknown; filters?: ('suite'|'case')[]}) & {suite?: string; case?: string; onFinish: string}, {runID: string}>; results: Scoped<{runID: string; offset?: number}, {tests: {project?: string; suite: string; case: string; status: string}[]; nextOffset?: number}>; }; /** Permission `window.messages`. `selectedIndex` is zero-based, or null on dismissal. */