From bc9940299f18fb59175bdd0503e87f765d21d5ae Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 12:38:50 +0800 Subject: [PATCH 1/3] =?UTF-8?q?fix(build):=20=E5=9C=A8=E5=A4=9A=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E5=B7=A5=E4=BD=9C=E5=8C=BA=E8=A7=A3=E6=9E=90=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E8=BF=90=E8=A1=8C=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 4 +- rust/crates/build/src/run_types.rs | 83 ++++++++++++++----- .../crates/core/src/tests/plugin_run_types.rs | 45 ++++++++++ shared/plugins/contract/v1/README.md | 8 +- 4 files changed, 116 insertions(+), 24 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 276ed0b2..7b242224 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5509,8 +5509,8 @@ user to trust the workspace before an action the user started. | `build.decodeConfigurationEdit` | `{ snapshot, edits, result }` | `edit: { sourceID, revision, changed }`; validates bounded receipt and exact draft/source identity; native adapter verifies staged hash and publishes atomically | | `build.modelPlan`, `build.dependencyPlan` | plan fields plus `project?` (dependencies), `outputFile?`, and for provider sources `refresh?` (boolean) and `tool?: { executable }` (absolute path) | `plan`: `{ buildSystemID, root, arguments, environment, workingDirectory, execution, optionFingerprint, output, decoder, executesProjectCode, mayUseNetwork }`; for a `provider` source `{ buildSystemID, root, provider: { method, params }, decoder, executesProjectCode, mayUseNetwork, optionFingerprint }`, where `method` is `lithe/build/model` or `lithe/build/dependencies` and `params` is `{ buildSystemID, root, options, optionArguments, environment, project?, refresh?, tool? }`; `refresh` appears only when `true` and `tool` only when the host sent it | | `build.taskPlan` | plan fields plus `task`, `project?`, `target?`, `modelTask?`, `userArguments?` | command `plan` with `arguments`, `environment`, `workingDirectory`, `execution`, and `optionFingerprint`; a provider task instead returns `provider: {method: "lithe/build/execute", params}` with effective options, selected task/entities, user arguments and effect metadata | -| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | -| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | +| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The deepest enclosing instance is selected by the working directory, then by the sole active workspace file field if the working directory is the workspace root and no instance contains it. A sole instance works without a path match. The working directory is preserved. `plugin.build.invalidSelection` when no instance can be selected or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | +| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is the deepest enclosing the working directory, or the only one. `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | | `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. | diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index ef0bc940..f4bd9f0e 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -624,7 +624,17 @@ fn declared_plan( .expect("launch values name declared fields"); field_arguments.push((id.clone(), field_value_arguments(field, value)?)); } - let instance = instance_of(sources.instances, &launch.working_directory)?; + let file_directory = + if role.role == RunTypeRole::Configuration && launch.working_directory == "." { + sole_file_directory(workspace_root, declaration, &values) + } else { + None + }; + let instance = instance_of( + sources.instances, + &launch.working_directory, + file_directory.as_deref(), + )?; let base = PlanBase { model_inputs: instance.model_inputs.clone(), root: instance.root.clone(), @@ -684,13 +694,43 @@ fn field_value_arguments( } } -/// The instance a configuration runs with: the deepest one whose root holds -/// the working directory, or the only one when the working directory is -/// outside every instance, such as an absolute directory outside the -/// workspace. +/// A single effective file field identifies a project when the workspace +/// root does not identify one. Hidden fields are absent from `values`. +fn sole_file_directory( + workspace_root: &Path, + declaration: &RunTypeDeclaration, + values: &[(String, DeclaredValue)], +) -> Option { + let mut files = values.iter().filter_map(|(id, value)| { + let DeclaredValue::Text(path) = value else { + return None; + }; + declaration + .fields + .iter() + .any(|field| field.id == *id && field.kind == RunFieldKind::File) + .then_some(path) + }); + let file = Path::new(files.next()?); + if files.next().is_some() { + return None; + } + let directory = file.parent()?.strip_prefix(workspace_root).ok()?; + directory + .iter() + .map(|component| component.to_str()) + .collect::>>() + .map(|components| components.join("/")) +} + +/// Picks the deepest project that contains the working directory. When no +/// root holds it, a run at the workspace root can supply a file's directory +/// to select the instance while keeping the configured working directory. +/// A lone instance can run from outside its project. fn instance_of<'a>( instances: &'a [RunTypeInstance], working_directory: &str, + file_directory: Option<&str>, ) -> Validation<&'a RunTypeInstance> { if instances.is_empty() { return Err(invalid_selection( @@ -704,21 +744,24 @@ fn instance_of<'a>( .iter() .map(|instance| decode::request_path(&instance.root, "root")) .collect::>>()?; - let directory = decode::request_path(working_directory, "working directory").ok(); - let holding = directory.and_then(|directory| { - roots - .iter() - .enumerate() - .filter(|(_, root)| decode::contains(root, &directory)) - .max_by_key(|(_, root)| { - if *root == "." { - 0 - } else { - root.split('/').count() - } - }) - .map(|(index, _)| &instances[index]) - }); + let holding = [Some(working_directory), file_directory] + .into_iter() + .flatten() + .find_map(|directory| { + let directory = decode::request_path(directory, "working directory").ok()?; + roots + .iter() + .enumerate() + .filter(|(_, root)| decode::contains(root, &directory)) + .max_by_key(|(_, root)| { + if *root == "." { + 0 + } else { + root.split('/').count() + } + }) + .map(|(index, _)| &instances[index]) + }); match (holding, instances) { (Some(instance), _) | (None, [instance]) => Ok(instance), (None, _) => Err(invalid_selection( diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs index b374d4a6..9396f866 100644 --- a/rust/crates/core/src/tests/plugin_run_types.rs +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -518,6 +518,51 @@ fn saved_declared_runs_expand_into_the_types_command_line() { assert_eq!(planned["data"]["plan"]["root"], "."); } +/// A file run at the workspace root can resolve the one project that contains +/// that file. An explicit working directory still chooses its own instance. +#[test] +fn file_run_uses_its_project_when_the_workspace_root_has_no_instance() { + let root = temporary_root("run-types-file-project"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + fs::write(root.join("apps/worker/main.go"), "package main\n").unwrap(); + + for (name, directory, expected_instance) in [ + ("default", "", "apps/worker"), + ("explicit", "tools", "tools"), + ] { + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), + "values": { + "name": name, "workingDirectory": directory, + "field:runKind": "file", "field:file": "apps/worker/main.go", + }, + }), + ); + assert_eq!(saved["data"]["status"], "saved", "{saved}"); + apply_run_changes(&root, &saved["data"]); + let planned = plan( + &root, + manifest(), + json!({ + "configurationId": saved["data"]["id"], + "instances": [{"root": "apps"}, {"root": "apps/worker"}, {"root": "tools"}], + }), + ); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], expected_instance); + let expected_directory = if directory.is_empty() { "." } else { directory }; + assert_eq!( + planned["data"]["plan"]["workingDirectory"], + expected_directory + ); + } +} + #[test] fn a_type_without_program_arguments_stores_none() { let root = temporary_root("run-types-no-arguments"); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 1122a55f..f5614927 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3008,8 +3008,12 @@ configuration, which needs the plugin again to edit or run. To run one, the host calls `build.runConfigurationPlan` with the manifest, the build system, `workspaceRoot`, the configuration ID and the detected instances of the build system with their stored options. Core picks the -deepest instance whose root holds the configuration's working directory (or -the only instance) and returns a task plan: the global arguments, then the +deepest instance whose root contains the configuration's working directory. +When that directory is the workspace root and no instance contains it, Core +can instead use the deepest instance containing the sole active file field's +parent, if the file is inside the workspace. If neither path selects an +instance, a single detected instance still works. This choice does not change +the working directory. Core returns a task plan: the global arguments, then the type's `arguments` with the field values, the instance's options and the program arguments, at the configuration's working directory, with its environment over the options'. The host starts it like any build command. A From b8e9b3ea978a5d6fde235d55cceb239c342c7236 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 12:39:17 +0800 Subject: [PATCH 2/3] =?UTF-8?q?docs(plugins):=20=E7=99=BB=E8=AE=B0?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E8=BF=90=E8=A1=8C=E5=AE=9E=E4=BE=8B=E8=A7=A3?= =?UTF-8?q?=E6=9E=90=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/contract/v1/README.md | 5 +++-- shared/plugins/reference/protocol-changelog.md | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index f5614927..d7b1a638 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3074,8 +3074,9 @@ it, without that configuration's program arguments or environment. To run one, the host calls `build.beforeLaunchTaskPlan` with the manifest, the build system, `workspaceRoot`, the step and its working directory as `runConfig.beforeLaunch` returned them, and the detected instances of the -build system with their stored options. Core picks the instance as for a run -configuration and returns a task plan: the global arguments, then the task's +build system with their stored options. Core picks the deepest instance +containing the step's working directory, or the only instance, and returns +a task plan: the global arguments, then the task's `arguments` with the field values and the instance's options. A saved value that no longer fits the task is `plugin.build.invalidBeforeLaunchTask` with `field: "values."`; a task the plugin no longer declares is diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 44ff5c5e..1d2775d2 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,可以用唯一生效的工作区内文件字段定位最深的构建实例。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。 - [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141),[@1lck](https://github.com/1lck),**`languageServers` 1**(API-25、API-29、API-31):语言服务器新增可选 `executesProjectCode`(不写按 `true`),启动请求新增 `projectCodeAllowed`(不写按未信任,[1lck/Lithe-IDEA#2208](https://github.com/1lck/Lithe-IDEA/issues/2208))。未信任的工作区里,`plugins.declarative.languageServerLaunchPlan` 和 `plugins.languageServers.decodeLaunch` 只给声明 `executesProjectCode: false` 的语言服务器计划;自带进程的构建提供者按 `buildSystems[].provider.executesProjectCode` 判断,共用语言服务器的跟随该服务器;VCS 提供者一律不给计划。拒绝码是新的 `plugin.launch.untrustedWorkspace`。插件后端和独立调试适配器不受影响。用 `executesProjectCode` 要声明 `requires.languageServers: 1`。没有新增宿主方法、通知或 SDK 版本。 - [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139),[@1lck](https://github.com/1lck),**`buildSystems` 2**(API-29):构建提供者的 `application` 运行声明(含 `entrypoints: true`)可以通过 `debug.configurationType` 复用已注册的连接调试器。`lithe/build/prepareRun` 复用原有 `launchOptions.debug`,入口运行仍不带 `target`。已有服务运行声明继续适用旧版本。没有新增 RPC 方法、通知或 SDK 版本。 - [#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`toolDefinitions` 0 内的行为修正(API-23):外部安装的 `executableLayouts` 文件链接到另一个文件名时,`toolchains.candidates` 的待探针路径和 `toolchains.resolve` 的 `executable` 改为规范主目录下的布局路径,不再是链接目标。rustup 把 `cargo`、`rust-analyzer` 链接到自身、按启动时的名字决定运行哪个工具,以前 Core 返回 `rustup`,版本探针失败。链接目标的类型、可执行位和越界检查不变;同名链接仍返回规范路径。没有新增字段、版本号、宿主方法、通知或 SDK 版本。 From 8efef540204199b857dced2d8fbaa650ff356de4 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Sat, 21 Nov 2026 13:10:39 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(build):=20=E6=8C=89=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=90=8E=E7=9A=84=E6=96=87=E4=BB=B6=E7=9B=AE=E6=A0=87=E9=80=89?= =?UTF-8?q?=E6=8B=A9=E8=BF=90=E8=A1=8C=E5=AE=9E=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 只在工作目录没有匹配实例时解析文件回退。识别等价的工作区根路径,按符号链接实际目标定位项目,并为跨项目和工作区外的链接补回归。 --- rust/contracts/rust-core-api.md | 2 +- rust/crates/build/src/run_types.rs | 107 +++++++++------- .../crates/core/src/tests/plugin_run_types.rs | 117 +++++++++++++++--- shared/plugins/contract/v1/README.md | 8 +- .../plugins/reference/protocol-changelog.md | 2 +- 5 files changed, 168 insertions(+), 68 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 7b242224..faf3ead8 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5509,7 +5509,7 @@ user to trust the workspace before an action the user started. | `build.decodeConfigurationEdit` | `{ snapshot, edits, result }` | `edit: { sourceID, revision, changed }`; validates bounded receipt and exact draft/source identity; native adapter verifies staged hash and publishes atomically | | `build.modelPlan`, `build.dependencyPlan` | plan fields plus `project?` (dependencies), `outputFile?`, and for provider sources `refresh?` (boolean) and `tool?: { executable }` (absolute path) | `plan`: `{ buildSystemID, root, arguments, environment, workingDirectory, execution, optionFingerprint, output, decoder, executesProjectCode, mayUseNetwork }`; for a `provider` source `{ buildSystemID, root, provider: { method, params }, decoder, executesProjectCode, mayUseNetwork, optionFingerprint }`, where `method` is `lithe/build/model` or `lithe/build/dependencies` and `params` is `{ buildSystemID, root, options, optionArguments, environment, project?, refresh?, tool? }`; `refresh` appears only when `true` and `tool` only when the host sent it | | `build.taskPlan` | plan fields plus `task`, `project?`, `target?`, `modelTask?`, `userArguments?` | command `plan` with `arguments`, `environment`, `workingDirectory`, `execution`, and `optionFingerprint`; a provider task instead returns `provider: {method: "lithe/build/execute", params}` with effective options, selected task/entities, user arguments and effect metadata | -| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The deepest enclosing instance is selected by the working directory, then by the sole active workspace file field if the working directory is the workspace root and no instance contains it. A sole instance works without a path match. The working directory is preserved. `plugin.build.invalidSelection` when no instance can be selected or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | +| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The deepest enclosing instance is selected by the working directory, then by the resolved target of the sole active file field if it is a file inside the workspace, the working directory resolves lexically to the workspace root, and no instance contains that directory. A sole instance works without a path match. The working directory is preserved. `plugin.build.invalidSelection` when no instance can be selected or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | | `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is the deepest enclosing the working directory, or the only one. `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index f4bd9f0e..924ac4a5 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -31,9 +31,11 @@ use lithe_plugin_model::settings::{parse_localization_file, present, Localizatio use lithe_plugin_model::{PluginRejection, Validation}; use lithe_protocol::json_document::UniqueMap; use lithe_protocol::{CoreError, ErrorCode}; +use lithe_workspace::fs; use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::BTreeMap; +use std::io; use std::path::Path; /// Error code of a translation file Core did not apply. @@ -46,6 +48,8 @@ const INVALID_BEFORE_LAUNCH_TASK: &str = "plugin.build.invalidBeforeLaunchTask"; const MAX_PLUGINS: usize = 512; /// Most build-system instances one plan request may name. const MAX_INSTANCES: usize = 4_096; +const NO_MATCHING_INSTANCE: &str = + "The working directory is outside every project of this build system; choose one inside a project."; /// The installed plugins whose run configuration types and before-launch /// tasks the editor offers. @@ -442,9 +446,9 @@ pub(crate) struct RunConfigurationPlanRequest { /// `runConfig.launchPlan`. #[serde(default)] pub(crate) local_document: Option, - /// The detected instances of the build system, with their stored - /// options; the plan runs with the instance whose root holds the - /// working directory. + /// The detected instances of the build system, with their stored options. + /// Selection uses the working directory first and can fall back to the + /// run's file when the workspace root has no instance. pub(crate) instances: Vec, /// Absolute installed plugin directory, for `${pluginDir}`. #[serde(default)] @@ -624,17 +628,9 @@ fn declared_plan( .expect("launch values name declared fields"); field_arguments.push((id.clone(), field_value_arguments(field, value)?)); } - let file_directory = - if role.role == RunTypeRole::Configuration && launch.working_directory == "." { - sole_file_directory(workspace_root, declaration, &values) - } else { - None - }; - let instance = instance_of( - sources.instances, - &launch.working_directory, - file_directory.as_deref(), - )?; + let file_directory = (role.role == RunTypeRole::Configuration) + .then_some(|| sole_file_directory(workspace_root, declaration, &values)); + let instance = instance_of(sources.instances, &launch.working_directory, file_directory)?; let base = PlanBase { model_inputs: instance.model_inputs.clone(), root: instance.root.clone(), @@ -694,13 +690,14 @@ fn field_value_arguments( } } -/// A single effective file field identifies a project when the workspace -/// root does not identify one. Hidden fields are absent from `values`. +/// The workspace-relative parent of the sole active file's resolved target. +/// Resolving both paths keeps aliases inside the workspace usable and prevents +/// a link to an external file from choosing an instance. fn sole_file_directory( workspace_root: &Path, declaration: &RunTypeDeclaration, values: &[(String, DeclaredValue)], -) -> Option { +) -> io::Result> { let mut files = values.iter().filter_map(|(id, value)| { let DeclaredValue::Text(path) = value else { return None; @@ -711,16 +708,25 @@ fn sole_file_directory( .any(|field| field.id == *id && field.kind == RunFieldKind::File) .then_some(path) }); - let file = Path::new(files.next()?); - if files.next().is_some() { - return None; + let (Some(file), None) = (files.next(), files.next()) else { + return Ok(None); + }; + let workspace_root = fs::canonicalize(workspace_root)?; + let file = fs::canonicalize(file)?; + let Some(directory) = file + .parent() + .and_then(|parent| parent.strip_prefix(&workspace_root).ok()) + else { + return Ok(None); + }; + if !fs::is_file(&file)? { + return Ok(None); } - let directory = file.parent()?.strip_prefix(workspace_root).ok()?; - directory + let components = directory .iter() .map(|component| component.to_str()) - .collect::>>() - .map(|components| components.join("/")) + .collect::>>(); + Ok(components.and_then(|parts| decode::request_path(&parts.join("/"), "file directory").ok())) } /// Picks the deepest project that contains the working directory. When no @@ -730,7 +736,7 @@ fn sole_file_directory( fn instance_of<'a>( instances: &'a [RunTypeInstance], working_directory: &str, - file_directory: Option<&str>, + file_directory: Option io::Result>>, ) -> Validation<&'a RunTypeInstance> { if instances.is_empty() { return Err(invalid_selection( @@ -744,28 +750,33 @@ fn instance_of<'a>( .iter() .map(|instance| decode::request_path(&instance.root, "root")) .collect::>>()?; - let holding = [Some(working_directory), file_directory] - .into_iter() - .flatten() - .find_map(|directory| { - let directory = decode::request_path(directory, "working directory").ok()?; - roots - .iter() - .enumerate() - .filter(|(_, root)| decode::contains(root, &directory)) - .max_by_key(|(_, root)| { - if *root == "." { - 0 - } else { - root.split('/').count() - } - }) - .map(|(index, _)| &instances[index]) - }); - match (holding, instances) { - (Some(instance), _) | (None, [instance]) => Ok(instance), - (None, _) => Err(invalid_selection( - "The working directory is outside every project of this build system; choose one inside a project.", - )), + let holding = |directory: &str| { + roots + .iter() + .enumerate() + .filter(|(_, root)| decode::contains(root, directory)) + .max_by_key(|(_, root)| { + if *root == "." { + 0 + } else { + root.split('/').count() + } + }) + .map(|(index, _)| &instances[index]) + }; + let directory = decode::request_path(working_directory, "working directory").ok(); + match (directory.as_deref().and_then(holding), instances) { + (Some(instance), _) | (None, [instance]) => return Ok(instance), + (None, _) => {} + } + if let Some(resolve_file_directory) = + file_directory.filter(|_| directory.as_deref() == Some(".")) + { + let resolved = + resolve_file_directory().map_err(|_| invalid_selection(NO_MATCHING_INSTANCE))?; + if let Some(instance) = resolved.as_deref().and_then(holding) { + return Ok(instance); + } } + Err(invalid_selection(NO_MATCHING_INSTANCE)) } diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs index 9396f866..8f7bf01f 100644 --- a/rust/crates/core/src/tests/plugin_run_types.rs +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -3,7 +3,10 @@ //! their fields, and `build.runConfigurationPlan` expands a saved entry into //! the argv plan the host starts. -use super::support::{apply_run_changes, changed_run_document, temporary_root, Cleanup}; +use super::support::{ + apply_run_changes, changed_run_document, changed_run_paths, edit_plugin_run_document, + temporary_root, Cleanup, +}; use crate::execute_json; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -65,6 +68,23 @@ fn plan(root: &std::path::Path, manifest: Value, request: Value) -> Value { ) } +fn save_file_run(root: &std::path::Path, name: &str, directory: &str) -> Value { + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), + "values": { + "name": name, "workingDirectory": directory, + "field:runKind": "file", "field:file": "apps/worker/main.go", + }, + }), + ); + assert_eq!(saved["data"]["status"], "saved", "{saved}"); + apply_run_changes(root, &saved["data"]); + saved["data"].clone() +} + #[test] fn declared_types_follow_the_built_in_kinds_with_translated_text() { let plain = call( @@ -532,24 +552,12 @@ fn file_run_uses_its_project_when_the_workspace_root_has_no_instance() { ("default", "", "apps/worker"), ("explicit", "tools", "tools"), ] { - let saved = call( - "runConfig.saveConfiguration", - json!({ - "root": root, "provider": "build.run-type", "runType": run_type("build"), - "runTypePlugins": plugins(), - "values": { - "name": name, "workingDirectory": directory, - "field:runKind": "file", "field:file": "apps/worker/main.go", - }, - }), - ); - assert_eq!(saved["data"]["status"], "saved", "{saved}"); - apply_run_changes(&root, &saved["data"]); + let saved = save_file_run(&root, name, directory); let planned = plan( &root, manifest(), json!({ - "configurationId": saved["data"]["id"], + "configurationId": saved["id"], "instances": [{"root": "apps"}, {"root": "apps/worker"}, {"root": "tools"}], }), ); @@ -563,6 +571,85 @@ fn file_run_uses_its_project_when_the_workspace_root_has_no_instance() { } } +#[test] +fn file_run_accepts_an_equivalent_saved_workspace_root() { + let root = temporary_root("run-types-root-alias"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + fs::write(root.join("apps/worker/main.go"), "package main\n").unwrap(); + let saved = save_file_run(&root, "root alias", ""); + let plugin_document = changed_run_paths(&saved) + .into_iter() + .find(|path| path.ends_with(".toml")) + .expect("a declared run is saved in a plugin TOML document"); + edit_plugin_run_document(&root, &plugin_document, |document| { + document["configurations"][0]["cwd"] = json!("./"); + }); + + let planned = plan( + &root, + manifest(), + json!({ + "configurationId": saved["id"], + "instances": [{"root": "apps/worker"}, {"root": "tools"}], + }), + ); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], "apps/worker"); + assert_eq!(planned["data"]["plan"]["workingDirectory"], "./"); +} + +#[cfg(unix)] +fn plan_file_run_after_script_becomes_link(target: &str) -> Value { + let fixture = temporary_root("run-types-linked-file"); + let _cleanup = Cleanup(fixture.clone()); + let root = fixture.join("workspace"); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + let script = root.join("apps/worker/main.go"); + fs::write(&script, "package main\n").unwrap(); + let target = fixture.join(target); + fs::write(&target, "package main\n").unwrap(); + let saved = save_file_run(&root, "linked script", ""); + fs::remove_file(&script).unwrap(); + std::os::unix::fs::symlink(target, script).unwrap(); + + plan( + &root, + manifest(), + json!({ + "configurationId": saved["id"], + "instances": [ + {"root": "apps/worker", "options": {"tags": "worker"}}, + {"root": "tools", "options": {"tags": "tools"}}, + ], + }), + ) +} + +#[cfg(unix)] +#[test] +fn file_run_selects_the_project_of_its_link_target() { + let planned = plan_file_run_after_script_becomes_link("workspace/tools/main.go"); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], "tools"); + assert_eq!(planned["data"]["plan"]["workingDirectory"], "."); + assert_eq!(planned["data"]["plan"]["arguments"][1], "-tags"); + assert_eq!(planned["data"]["plan"]["arguments"][2], "tools"); +} + +#[cfg(unix)] +#[test] +fn file_run_cannot_infer_a_project_from_a_link_to_an_external_file() { + let planned = plan_file_run_after_script_becomes_link("outside.go"); + assert_eq!(planned["data"]["status"], "rejected", "{planned}"); + assert_eq!( + planned["data"]["error"]["code"], + "plugin.build.invalidSelection" + ); +} + #[test] fn a_type_without_program_arguments_stores_none() { let root = temporary_root("run-types-no-arguments"); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d7b1a638..ec6d0827 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3010,9 +3010,11 @@ the build system, `workspaceRoot`, the configuration ID and the detected instances of the build system with their stored options. Core picks the deepest instance whose root contains the configuration's working directory. When that directory is the workspace root and no instance contains it, Core -can instead use the deepest instance containing the sole active file field's -parent, if the file is inside the workspace. If neither path selects an -instance, a single detected instance still works. This choice does not change +can instead use the deepest instance containing the parent of the sole active +file field's resolved target, provided the target is a file inside the +workspace. Equivalent spellings of the workspace root, such as `./`, qualify +for this fallback. If neither path selects an instance, a single detected +instance still works. This choice does not change the working directory. Core returns a task plan: the global arguments, then the type's `arguments` with the field values, the instance's options and the program arguments, at the configuration's working directory, with its diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1d2775d2..a64a1d6c 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,可以用唯一生效的工作区内文件字段定位最深的构建实例。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。 +- [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,用唯一生效的文件字段解析后的工作区内目标定位最深的构建实例。`./` 等价于工作区根,指向工作区外的链接不参与定位。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。 - [#141](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/141),[@1lck](https://github.com/1lck),**`languageServers` 1**(API-25、API-29、API-31):语言服务器新增可选 `executesProjectCode`(不写按 `true`),启动请求新增 `projectCodeAllowed`(不写按未信任,[1lck/Lithe-IDEA#2208](https://github.com/1lck/Lithe-IDEA/issues/2208))。未信任的工作区里,`plugins.declarative.languageServerLaunchPlan` 和 `plugins.languageServers.decodeLaunch` 只给声明 `executesProjectCode: false` 的语言服务器计划;自带进程的构建提供者按 `buildSystems[].provider.executesProjectCode` 判断,共用语言服务器的跟随该服务器;VCS 提供者一律不给计划。拒绝码是新的 `plugin.launch.untrustedWorkspace`。插件后端和独立调试适配器不受影响。用 `executesProjectCode` 要声明 `requires.languageServers: 1`。没有新增宿主方法、通知或 SDK 版本。 - [#139](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/139),[@1lck](https://github.com/1lck),**`buildSystems` 2**(API-29):构建提供者的 `application` 运行声明(含 `entrypoints: true`)可以通过 `debug.configurationType` 复用已注册的连接调试器。`lithe/build/prepareRun` 复用原有 `launchOptions.debug`,入口运行仍不带 `target`。已有服务运行声明继续适用旧版本。没有新增 RPC 方法、通知或 SDK 版本。 - [#135](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/135),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`toolDefinitions` 0 内的行为修正(API-23):外部安装的 `executableLayouts` 文件链接到另一个文件名时,`toolchains.candidates` 的待探针路径和 `toolchains.resolve` 的 `executable` 改为规范主目录下的布局路径,不再是链接目标。rustup 把 `cargo`、`rust-analyzer` 链接到自身、按启动时的名字决定运行哪个工具,以前 Core 返回 `rustup`,版本探针失败。链接目标的类型、可执行位和越界检查不变;同名链接仍返回规范路径。没有新增字段、版本号、宿主方法、通知或 SDK 版本。