diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index ab837e82..60f77ab1 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -611,6 +611,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..0f46d68e 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -442,6 +442,18 @@ 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 { + 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. 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..7a1f4164 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,7 @@ pub(crate) fn decode_test_results( if !coverage.is_empty() { result["coverage"] = json!(coverage); } - Ok(result) + result } /// Validates an inline report without opening report files or inferring tool semantics. @@ -1117,3 +1125,30 @@ pub(crate) fn sync_fingerprint( "watch": files, })) } + +#[cfg(test)] +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"}]}); + 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/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 6a8f50cc..f2a3d780 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -618,6 +618,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`). @@ -1500,6 +1502,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 365971de..151e75ad 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1881,6 +1881,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 91847a48..3562bfa4 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -39,6 +39,20 @@ 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", + "runner", + "data", + "filters", + ], + HostParams::Tests { results: true } => &["context", "runID", "offset"], HostParams::FunctionProviders => &["functionID"], HostParams::FunctionInvoke => &[ "pluginID", @@ -165,6 +179,73 @@ 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) + || ["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.", + )); + } + 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 } => { 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..53411382 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,79 @@ pub(crate) fn capabilities_answer(version: u64, granted: &BTreeSet) -> V }) } +#[cfg(test)] +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"; + 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["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) + .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/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 00cbbf90..8bca53bb 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -5845,6 +5845,67 @@ 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`. 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. + +| 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. 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. +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`. +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. +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. +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 + +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/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 941d11c5..c018eccf 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 | @@ -379,6 +381,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/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8291820a..ee89d8e2 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -22,6 +22,7 @@ | [#245](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/245)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 宿主命令 `agentSessions.stats` 新增可选 `splitBy`(`agent`/`model`/`provider`/`modelProvider`,在 `groupBy` 之后再拆一层,第二个键在 summary 的 `split`)、筛选 `models`、`providers`、`failed`、`search`(同时作用于 `summaries` 和 `speeds`)和 `detail`(每组增加 `speed` 速度中位数与 `firstToken` 平均首字耗时);`groupBy` 新增只给宿主的 `provider`、`modelProvider`、`all`。`agentSessions.calls` 新增 `models`、`providers`、`search`,与 stats 的筛选规则相同。新增错误码 `agentSessions.invalidSplit`、`agentSessions.invalidFilter`。`agents/usage`(插件)的分组和回答不变。旧 Core 把新字段当未知字段拒绝,把新分组名当 `agentSessions.invalidGroup` 拒绝。没有新增宿主方法、通知或能力版本。 | | [#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,尚未合入);桌面端尚未发布。 | +| [#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)。 | | [#231](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/231)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-45 | `agents` 0 | `agents/usage` 支持按小时汇总。默认按指定 UTC 偏移对齐整点,也可用 `hourAnchorMs` 对齐滚动窗口。 | | [#240](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/240)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 会话来源 `read` 函数增加可选请求参数 `messageIDs`:只有 `true` 时才可在消息里返回可选 `id`(1–256 个可见 ASCII 字节,来源会话内稳定,同一消息的镜像相同);省略或为 `false` 时保留旧结果形状。同时增加可选请求参数 `toolCalls`:只有 `true` 时 `tool` 消息才可带实时 `toolCall` 的详情 `toolCallID`、`status`、`toolKind`、`title`、`locations`(同一调用和它的结果共用 `toolCallID`,宿主按实时方式合并,让历史轮次和实时显示一致)。Core 的新宿主命令 `agentSessions.page` 协商该参数并按整行双向分页,两个参数都由它发送,旧 `agentSessions.read` 和标题读取不协商,回答里出现这些详情字段(包括显式 `null`)时以 `agentSessions.invalidRead` 拒绝。`agentSessions.list` 的会话新增 `generation`:文件只增长时不变,被替换或截断后重新读取时换新值;`agentSessions.page` 必须带上同一次列表的 `generation`,不一致时回答 `changed`。四语 SDK 都使用已有普通 JSON 函数处理器,无类型或版本变化;旧插件可忽略参数。没有新增宿主方法、通知、错误码或能力版本。样例见 `fixtures/agents/record-read.json` 与 `rust/fixtures/agents/record-page-v1.json`;首次实现见 Core `15c0717`;宿主发布版本尚未产生。 | | [#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 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | @@ -209,6 +210,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) | diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 36f48777..1c8a91bb 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -446,6 +446,22 @@ 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 } + +// 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) +} + // 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 09ca5995..187fcc09 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 828768c4..3d14e1b2 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 31435a22..4cf18a62 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -466,6 +466,11 @@ export interface Host { onEvent: (event: { type: 'exit'; terminalID: string; exitCode: number | null; reason: 'exited' | 'closed'; generation: number }, metadata: SubscriptionEventInfo) => void, options?: HostRequestOptions): Promise; }; + /** Permission `tests.start`. Results are available during the completion callback. */ + readonly tests: { + 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. */ readonly window: { showQuickPick: Scoped<{title?:string;placeholder?:string;items:QuickPickItem[];canPickMany?:boolean},{selectedIDs:string[]}|null>; @@ -1131,6 +1136,7 @@ export const HOST_METHODS: Readonly { 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; diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index b6662561..dc7b34e0 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -536,6 +536,11 @@ impl Host { Terminal { host: self.clone() } } + /// Native test runs owned by this backend session (API-29). + pub fn tests(&self) -> 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 a789092a..fedf783c 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -66,7 +66,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 bd369d35..4994c825 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";