diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2a5454bc..0cd26863 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -4417,6 +4417,15 @@ script file, or a program or interpreter named by a path that is not a file, is Batch runs are `not_supported` outside Windows. +In a remote workspace (a request carrying `remoteWorkspace`) every +`runConfig.*` command reads and checks the host's files, and process runs are +planned for the host, which is Linux or macOS, so they never get a Windows +interpreter or a batch script even when the client is Windows. The plan's +`executable.path`, `arguments` and `inlineScript.path` are host paths, and +`inlineScriptBase` must name a host temporary directory, so the client starts +the process on the host without translating the plan. A host that cannot be +reached fails the request instead of reporting a file as missing. + `diagnostics.redactText` accepts `text` and returns `redacted` with credentials, tokens, and home-directory paths replaced by stable placeholders (`` for secrets, `` for a macOS/Linux `Users`/`home` path or a diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 8b135290..7fe12751 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -748,6 +748,7 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon fn has_remote_workspace_adapter(command: &str) -> bool { command.starts_with("git.") || command.starts_with("build.") + || command.starts_with("runConfig.") || matches!( command, "workspace.repositories" diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 8b2e82d6..c839fef6 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -159,6 +159,116 @@ fn remote_build_detects_host_models_normalizes_diagnostics_and_invalidates_sync( assert_eq!(std::fs::read_dir(placeholder).unwrap().count(), 0); } +/// Run configurations of a remote workspace are read from the host, checked +/// against the host's files, and planned with host paths, so the client starts +/// the process on the host without translating the plan. +#[test] +fn remote_run_configurations_resolve_and_plan_against_the_host() { + let host = HostFixture::new(); + let root = host.root.join("host"); + let placeholder = host.root.join("placeholder"); + std::fs::create_dir_all(root.join("scripts")).unwrap(); + std::fs::create_dir_all(root.join("web")).unwrap(); + std::fs::write( + root.join("scripts/build.sh"), + "#!/bin/bash -e\necho built\n", + ) + .unwrap(); + super::support::write_run_document( + &root, + ".lithe/run/configurations.yaml", + &json!({"version": 2, "configurations": [ + {"id": "user:build", "name": "build", "provider": "process.shell", + "confidence": "declared", "cwd": "web", + "extensions": {"process": {"script": "scripts/build.sh"}}}, + {"id": "user:inline", "name": "inline", "provider": "process.shell", + "confidence": "declared", "extensions": {"process": {"text": "echo hi\n"}}}, + {"id": "user:missing", "name": "missing", "provider": "process.shell", + "confidence": "declared", "extensions": {"process": {"script": "scripts/gone.sh"}}}, + ]}), + ); + + let resolved = host.request("runConfig.resolve", json!({"root": placeholder})); + let availability = |id: &str| { + resolved["configurations"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["id"] == id) + .unwrap_or_else(|| panic!("{id} missing from {resolved}"))["availability"] + .clone() + }; + // The documents exist only on the host; a runnable entry carries no + // availability. + assert!(availability("user:build").is_null(), "{resolved}"); + + // The script and its `#!` line are read on the host; every path in the + // plan is the host's. + let plan = host.request( + "runConfig.createLaunchPlan", + json!({"root": placeholder, "configurationId": "user:build"}), + ); + let script = root.join("scripts/build.sh"); + assert_eq!(plan["executable"], json!({"path": "/bin/bash"}), "{plan}"); + assert_eq!(plan["arguments"], json!(["-e", script]), "{plan}"); + assert_eq!(plan["workingDirectory"], "web", "{plan}"); + + // An inline script goes where the client asked, on the host. + let inline = host.request( + "runConfig.createLaunchPlan", + json!({"root": placeholder, "configurationId": "user:inline", + "inlineScriptBase": "/tmp/lithe-run-x/script"}), + ); + assert_eq!( + inline["inlineScript"]["path"], "/tmp/lithe-run-x/script.sh", + "{inline}" + ); + assert_eq!(inline["inlineScript"]["content"], "echo hi\n", "{inline}"); + + // A script missing on the host is refused before anything starts. + let response: Value = serde_json::from_str(&crate::execute_json( + &json!({ + "id": test_support::unique_id(), "command": "runConfig.createLaunchPlan", + "remoteWorkspace": {"sessionId": host.id, "localRoot": placeholder, "remoteRoot": root}, + "payload": {"root": placeholder, "configurationId": "user:missing"}, + }) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], false, "{response}"); + assert_eq!( + response["error"]["message"], "Script file was not found", + "{response}" + ); + + // The editor checks a working directory against the host's folders and + // saves through changes the client applies on the host. + let form = host.request( + "runConfig.editorForm", + json!({"root": placeholder, "configurationId": "user:build"}), + ); + let mut values = form["values"].as_object().unwrap().clone(); + values.insert("workingDirectory".into(), json!("nowhere")); + let refused = host.request( + "runConfig.saveConfiguration", + json!({"root": placeholder, "provider": "process.shell", + "configurationId": "user:build", "values": values}), + ); + assert_eq!( + refused["errors"], + json!([{"field": "workingDirectory", "code": "notFound"}]), + "{refused}" + ); + values.insert("workingDirectory".into(), json!("scripts")); + let saved = host.request( + "runConfig.saveConfiguration", + json!({"root": placeholder, "provider": "process.shell", + "configurationId": "user:build", "values": values}), + ); + assert_eq!(saved["status"], "saved", "{saved}"); + assert_eq!(std::fs::read_dir(placeholder).unwrap().count(), 0); +} + /// A remote root opened through a host symbolic link resolves outside the /// local placeholder; the empty-root boundary must ask the host, not the /// unmaterialized local projection, before scanning. diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index bb546f44..76ffec1a 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -10,10 +10,10 @@ use lithe_platform::paths::{ }; use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; +use lithe_workspace::fs; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; -use std::fs; use std::path::{Path, PathBuf}; mod arrangement; @@ -34,6 +34,18 @@ mod resolve; mod storage; mod validation; +/// The platform whose rules decide how a run's process starts: the +/// workspace host's when the workspace is remote, else this machine's. +/// Remote hosts are Linux or macOS, so a remote run never gets a Windows +/// interpreter or a batch script even when this machine is Windows. +pub(crate) fn run_platform() -> Platform { + if lithe_workspace::is_remote() { + Platform::Unix + } else { + Platform::HOST + } +} + pub use arrangement::{arrange, ArrangeRequest}; pub(crate) use arrangement::{valid_folder, Arrangement}; pub use before_launch::{ diff --git a/rust/crates/execution/src/configuration/declared.rs b/rust/crates/execution/src/configuration/declared.rs index 4e032f5e..ea1a554e 100644 --- a/rust/crates/execution/src/configuration/declared.rs +++ b/rust/crates/execution/src/configuration/declared.rs @@ -781,6 +781,8 @@ pub(crate) fn validate(configuration: &RunConfiguration) -> Result<(), CoreError #[cfg(test)] mod tests { use super::*; + // Fixtures live on this machine. + use std::fs; fn kind() -> DeclaredRunType { DeclaredRunType { diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index 502d6d9d..d82bf284 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -46,7 +46,7 @@ pub fn configuration_types(request: ConfigurationTypesRequest) -> Result Result { }); match editor { Editor::Process(kind) => { - if let Some(availability) = process::platform_availability(kind, Platform::HOST) { + if let Some(availability) = process::platform_availability(kind, run_platform()) { form["availability"] = json!(availability); } } @@ -672,7 +672,7 @@ fn header_fields(automatic_name: Option) -> Vec { /// The fields of `kind`'s editor, with automatic values for `draft`. fn fields(kind: Kind, root: &Path, draft: &Draft, choices: StepChoices) -> Vec { - let platform = Platform::HOST; + let platform = run_platform(); let options = draft.options(); let mut fields = header_fields(process::default_name(&options)); if kind.runs_script() { @@ -906,8 +906,8 @@ impl Common { let working_directory = match self.working_directory.trim() { "" | "." => ".".to_string(), value => normalize_working_directory(root, value).unwrap_or_else(|_| { - let target = process::file_path(root, value, Platform::HOST); - let code = if target.is_dir() { + let target = process::file_path(root, value, run_platform()); + let code = if fs::is_dir(&target).unwrap_or(false) { "outsideProject" } else { "notFound" @@ -1084,7 +1084,7 @@ impl Draft { "process", serde_json::to_value(&options).expect("process options encode"), ); - if let Ok(found) = process::field_errors(&configuration, Platform::HOST) { + if let Ok(found) = process::field_errors(&configuration, run_platform()) { for error in found { if error.code != "required" && !errors.iter().any(|known| known.field == error.field) @@ -1134,14 +1134,19 @@ fn stored_path( if let Some(code) = process::text_error(value, 4096) { return Err(code); } - let platform = Platform::HOST; + let platform = run_platform(); let absolute = lithe_platform::paths::is_absolute_path(value, platform); let path = if absolute { PathBuf::from(value) } else { root.join(value) }; - if (directory && !path.is_dir()) || (!directory && !path.is_file()) { + let found = if directory { + fs::is_dir(&path) + } else { + fs::is_file(&path) + }; + if !found.unwrap_or(false) { return Err("notFound"); } let canonical = fs::canonicalize(&path).map_err(|_| "notFound")?; diff --git a/rust/crates/execution/src/configuration/launch.rs b/rust/crates/execution/src/configuration/launch.rs index aeffe39f..754a6d4e 100644 --- a/rust/crates/execution/src/configuration/launch.rs +++ b/rust/crates/execution/src/configuration/launch.rs @@ -72,7 +72,40 @@ pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result Result { + assemble_launch_plan(request).map(host_paths) +} + +/// Replaces placeholder paths in `plan`'s executable, arguments and inline +/// script with the host paths they stand for; other values stay as they are. +fn host_paths(mut plan: Value) -> Value { + if !lithe_workspace::is_remote() { + return plan; + } + let host = |value: &mut Value| { + if let Some(text) = value.as_str() { + if let Some(mapped) = lithe_workspace::remote_path(Path::new(text)).to_str() { + *value = json!(mapped); + } + } + }; + if let Some(path) = plan.pointer_mut("/executable/path") { + host(path); + } + if let Some(arguments) = plan.get_mut("arguments").and_then(Value::as_array_mut) { + arguments.iter_mut().for_each(host); + } + if let Some(path) = plan.pointer_mut("/inlineScript/path") { + host(path); + } + plan +} + +fn assemble_launch_plan(request: LaunchPlanRequest) -> Result { let root = existing_root(&request.root)?; let layers = read_layers(&root, None, request.local_document)?; let resolved = resolve_layers(&root, &layers, None)?; @@ -90,7 +123,7 @@ pub fn create_launch_plan(request: LaunchPlanRequest) -> Result Result { normalize_project_directory(root, value).map_err(|error| { - if value.contains('$') && !root.join(value).is_dir() { + if value.contains('$') && !fs::is_dir(root.join(value)).unwrap_or(false) { CoreError::new( ErrorCode::InvalidRequest, "Working directory variables are not supported; use a path relative to the project", @@ -73,7 +73,7 @@ pub(crate) fn project_directory_exists(root: &Path, value: &str) -> bool { let Ok(canonical_target) = fs::canonicalize(root.join(value)) else { return false; }; - canonical_target.is_dir() && canonical_target.starts_with(canonical_root) + canonical_target.starts_with(canonical_root) && fs::is_dir(&canonical_target).unwrap_or(false) } /// Reads a sidecar document below `.lithe`, such as `project.json`, with the @@ -111,11 +111,15 @@ pub(crate) fn generated_ids(root: &Path) -> BTreeSet { pub(crate) fn existing_root(value: &str) -> Result { let path = PathBuf::from(value); - if !path.is_dir() { - return Err(CoreError::new( - ErrorCode::WorkspaceNotFound, - "Project root does not exist", - )); + match fs::is_dir(&path) { + Ok(true) => {} + Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), + Ok(false) | Err(_) => { + return Err(CoreError::new( + ErrorCode::WorkspaceNotFound, + "Project root does not exist", + )) + } } Ok(path) } diff --git a/rust/crates/execution/src/configuration/process.rs b/rust/crates/execution/src/configuration/process.rs index 267c13e8..9e83ed87 100644 --- a/rust/crates/execution/src/configuration/process.rs +++ b/rust/crates/execution/src/configuration/process.rs @@ -688,7 +688,7 @@ pub(crate) fn launch_plan( let (script, shebang) = match (options.script(), options.text()) { (Some(script), _) => { let file = file_path(root, script, platform); - if !file.is_file() { + if !fs::is_file(&file).unwrap_or(false) { return Err( CoreError::new(ErrorCode::InvalidRequest, "Script file was not found") .with_details(script), @@ -761,7 +761,9 @@ fn require_program( executable: &Executable, platform: Platform, ) -> Result<(), CoreError> { - if matches!(executable, Executable::Path(_)) && !file_path(root, value, platform).is_file() { + if matches!(executable, Executable::Path(_)) + && !fs::is_file(file_path(root, value, platform)).unwrap_or(false) + { return Err( CoreError::new(ErrorCode::InvalidRequest, "Program was not found").with_details(value), ); @@ -801,6 +803,8 @@ pub(crate) fn cmd_quote(argument: &str) -> String { #[cfg(test)] mod tests { use super::*; + // Fixtures live on this machine. + use std::fs; /// A fresh project directory, removed when dropped. struct Project(PathBuf); diff --git a/rust/crates/execution/src/configuration/resolve.rs b/rust/crates/execution/src/configuration/resolve.rs index f4de8d89..f6b75f6b 100644 --- a/rust/crates/execution/src/configuration/resolve.rs +++ b/rust/crates/execution/src/configuration/resolve.rs @@ -56,7 +56,7 @@ pub(crate) fn resolve_layers( } } let global_toolchain = local.get("toolchain").cloned(); - let platform = Platform::HOST; + let platform = run_platform(); for configuration in &mut configurations { configuration.plugin = layers .plugin_dependency(&configuration.id) diff --git a/rust/crates/execution/src/configuration/storage.rs b/rust/crates/execution/src/configuration/storage.rs index b9835bee..57e1569e 100644 --- a/rust/crates/execution/src/configuration/storage.rs +++ b/rust/crates/execution/src/configuration/storage.rs @@ -491,12 +491,14 @@ fn read_plugin_documents( let mut project = BTreeMap::new(); let mut local = BTreeMap::new(); let directory = root.join(".lithe").join(PLUGIN_DIRECTORY); - let Ok(entries) = fs::read_dir(&directory) else { - return Ok((project, local)); + let entries = match fs::read_dir(&directory) { + Ok(entries) => entries, + Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), + Err(_) => return Ok((project, local)), }; let mut names = entries .filter_map(Result::ok) - .filter(|entry| entry.path().is_file()) + .filter(|entry| fs::is_file(entry.path()).unwrap_or(false)) .filter_map(|entry| entry.file_name().into_string().ok()) .filter(|name| name.ends_with(".toml")) .collect::>(); @@ -582,6 +584,7 @@ pub(crate) fn read_file( let file = match fs::File::open(&path) { Ok(file) => file, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), Err(error) => { return Err(CoreError::new( ErrorCode::PermissionDenied, @@ -693,6 +696,8 @@ fn render_yaml(document: &Value) -> Result { #[cfg(test)] mod tests { use super::*; + // Fixtures live on this machine. + use std::fs; /// A temporary workspace, removed when dropped so a failing assertion /// does not leave it behind. diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index 86970692..5895baa9 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -113,7 +113,7 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result super::declared::validate(configuration)?; } if super::process::is_process_provider(&configuration.provider) { - super::process::validate(configuration, Platform::HOST)?; + super::process::validate(configuration, run_platform())?; } if invalid_native_relative_path(&configuration.cwd, Platform::HOST) { return Err(CoreError::new( diff --git a/rust/crates/execution/src/generated_layer.rs b/rust/crates/execution/src/generated_layer.rs index 472e6e81..b48f67e5 100644 --- a/rust/crates/execution/src/generated_layer.rs +++ b/rust/crates/execution/src/generated_layer.rs @@ -8,10 +8,10 @@ //! configurations a user saves are project documents. use super::configuration::RunConfigurationDocument; +use lithe_workspace::fs; #[cfg(any(test, feature = "test-support"))] use serde_json::Value; use std::collections::HashMap; -use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock};