From d2efc1e7d5dbffc72cbe31f862bcd477ce54881f Mon Sep 17 00:00:00 2001 From: YodonTan <239598511+YodonTan@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:04:14 +0800 Subject: [PATCH] fix(terminal): refresh PATH for new Windows sessions --- scripts/terminal-live-path.test.mjs | 67 ++++++ src/apps/cli/src/main.rs | 24 +- src/apps/desktop/src/api/terminal_api.rs | 23 +- src/apps/sdk-host/src/runtime.rs | 22 +- .../assembly/core/src/service/runtime/mod.rs | 11 +- .../services-core/src/managed_runtime.rs | 57 +++++ .../services/terminal/src/config/mod.rs | 4 + .../terminal/src/config/session_path.rs | 223 ++++++++++++++++++ .../services/terminal/src/config/types.rs | 107 ++++++++- .../services/terminal/src/pty/process.rs | 120 ++++++++++ .../services/terminal/src/session/manager.rs | 200 +++++++++++++++- 11 files changed, 828 insertions(+), 30 deletions(-) create mode 100644 scripts/terminal-live-path.test.mjs create mode 100644 src/crates/services/terminal/src/config/session_path.rs diff --git a/scripts/terminal-live-path.test.mjs b/scripts/terminal-live-path.test.mjs new file mode 100644 index 0000000000..50d683f680 --- /dev/null +++ b/scripts/terminal-live-path.test.mjs @@ -0,0 +1,67 @@ +// Static routing guards only: these do not establish live SSH/Peer/relay behavior. +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import test from 'node:test'; + +const read = path => fs.readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); +function between(source, start, end) { + const from = source.indexOf(start); + assert.notEqual(from, -1, `missing start marker: ${start}`); + const to = source.indexOf(end, from + start.length); + assert.notEqual(to, -1, `missing end marker: ${end}`); + return source.slice(from, to); +} + +for (const path of [ + 'src/apps/desktop/src/api/terminal_api.rs', + 'src/apps/cli/src/main.rs', + 'src/apps/sdk-host/src/runtime.rs', +]) { + test(`static host PATH initialization routing: ${path}`, () => { + const source = read(path); + const policy = between(source, 'if let Ok(runtime_manager) = RuntimeManager::new()', 'TerminalApi::new('); + const windows = between(policy, '#[cfg(windows)]', '#[cfg(not(windows))]'); + assert.match(windows, /runtime_manager\.terminal_path_entries\(\)/); + assert.match(windows, /set_session_path_entries\(/); + assert.doesNotMatch(windows, /merged_path_env|std::env::var|\.env\.insert/); + const other = policy.slice(policy.indexOf('#[cfg(not(windows))]')); + assert.match(other, /std::env::var\("PATH"\)\.ok\(\)/); + assert.match(other, /merged_path_env\(process_path\.as_deref\(\)\)/); + assert.match(other, /\.env\.insert\("PATH"\.to_string\(\), path\)/); + }); +} + +test('static local builder routing keeps normalization Windows-only and reads baseline per create', () => { + const source = read('src/crates/services/terminal/src/session/manager.rs'); + const create = between(source, '// The OS PATH is read here', '// Inject shell integration'); + assert.match(create, /#\[cfg\(windows\)\]\s*let baseline = session_path_baseline\(\)/); + assert.match(create, /env: self\.build_session_env\(env, baseline\.as_deref\(\)\)/); + const builder = between(source, ' fn build_session_env(', ' /// Inject shell integration scripts'); + const windows = between(builder, '#[cfg(windows)]', '#[cfg(not(windows))]'); + assert.match(windows, /request_path\.or\(config_path\)\.or_else/); + assert.match(windows, /compose_session_path/); + const other = builder.slice(builder.indexOf('#[cfg(not(windows))]')); + assert.match(builder, /let mut session_env = self\.config\.env\.clone\(\)/); + assert.match(other, /session_env\.extend\(request_env\)/); + assert.doesNotMatch(other, /compose_session_path|to_string_lossy|take_session_path_entries/); + assert.match(read('src/crates/services/terminal/src/config/mod.rs'), /#\[cfg\(windows\)\]\s*mod session_path;/); +}); + +test('static desktop remote branch returns before local init and never forwards environment', () => { + const source = read('src/apps/desktop/src/api/terminal_api.rs'); + const create = between(source, 'pub async fn terminal_create(', 'pub async fn terminal_get('); + const remote = between(create, 'if let Some(connection_id) = request', 'let api = state.get_or_init_api()'); + assert.match(remote, /return spawn_remote_pty_session\(/); + assert.doesNotMatch(remote, /request\.env|build_session_env|session_path_baseline|merged_path_env|set_session_path_entries/); + const spawn = between(source, 'async fn spawn_remote_pty_session(', '#[tauri::command]'); + assert.doesNotMatch(spawn, /request\.env|build_session_env|session_path_baseline|merged_path_env|set_session_path_entries/); + assert.match(spawn, /terminal_manager\s*\.create_session\(/); +}); + +test('static remote service ShellConfig keeps an empty local environment overlay', () => { + const source = read('src/crates/services/services-integrations/src/remote_ssh/remote_terminal.rs'); + const configs = [...source.matchAll(/let shell_config = ShellConfig\s*\{([\s\S]*?)\n\s*\};/g)]; + assert.ok(configs.length > 0, 'remote PTY shell configuration must remain visible'); + for (const [, config] of configs) assert.match(config, /env:\s*HashMap::new\(\)/); + assert.doesNotMatch(source, /build_session_env|session_path_baseline|set_session_path_entries|terminal_path_entries|merged_path_env/); +}); diff --git a/src/apps/cli/src/main.rs b/src/apps/cli/src/main.rs index c43e678be1..da628896b5 100644 --- a/src/apps/cli/src/main.rs +++ b/src/apps/cli/src/main.rs @@ -868,15 +868,23 @@ async fn initialize_terminal_service() { } } + // Windows refreshes the OS baseline per session; only directory anchors are + // snapshotted here (new managed installations require host restart). + // Other platforms retain their original process-PATH merge. if let Ok(runtime_manager) = RuntimeManager::new() { - let current_path = std::env::var("PATH").ok(); - if let Some(merged_path) = runtime_manager.merged_path_env(current_path.as_deref()) { - terminal_config - .env - .insert("PATH".to_string(), merged_path.clone()); - #[cfg(windows)] - { - terminal_config.env.insert("Path".to_string(), merged_path); + #[cfg(windows)] + { + let path_entries = runtime_manager.terminal_path_entries(); + terminal_config.set_session_path_entries( + path_entries.managed_prefix, + path_entries.platform_suffix, + ); + } + #[cfg(not(windows))] + { + let process_path = std::env::var("PATH").ok(); + if let Some(path) = runtime_manager.merged_path_env(process_path.as_deref()) { + terminal_config.env.insert("PATH".to_string(), path); } } } else { diff --git a/src/apps/desktop/src/api/terminal_api.rs b/src/apps/desktop/src/api/terminal_api.rs index c50b2b9cc5..dbc3dbf342 100644 --- a/src/apps/desktop/src/api/terminal_api.rs +++ b/src/apps/desktop/src/api/terminal_api.rs @@ -65,16 +65,23 @@ impl TerminalState { } } - // Prepend OpenBitFun-managed runtime dirs to PATH so Bash/Skill commands can - // run on machines without preinstalled dev tools. + // Windows refreshes the OS baseline per session; only directory anchors are + // snapshotted here (new managed installations require host restart). + // Other platforms retain their original process-PATH merge. if let Ok(runtime_manager) = RuntimeManager::new() { - let current_path = std::env::var("PATH").ok(); - if let Some(merged_path) = runtime_manager.merged_path_env(current_path.as_deref()) + #[cfg(windows)] { - config.env.insert("PATH".to_string(), merged_path.clone()); - #[cfg(windows)] - { - config.env.insert("Path".to_string(), merged_path); + let path_entries = runtime_manager.terminal_path_entries(); + config.set_session_path_entries( + path_entries.managed_prefix, + path_entries.platform_suffix, + ); + } + #[cfg(not(windows))] + { + let process_path = std::env::var("PATH").ok(); + if let Some(path) = runtime_manager.merged_path_env(process_path.as_deref()) { + config.env.insert("PATH".to_string(), path); } } } diff --git a/src/apps/sdk-host/src/runtime.rs b/src/apps/sdk-host/src/runtime.rs index ca27458f5a..c3c4ecbd6f 100644 --- a/src/apps/sdk-host/src/runtime.rs +++ b/src/apps/sdk-host/src/runtime.rs @@ -108,12 +108,24 @@ pub(crate) async fn initialize_terminal_service() { } } + // Windows refreshes the OS baseline per session; only directory anchors are + // snapshotted here (new managed installations require host restart). + // Other platforms retain their original process-PATH merge. if let Ok(runtime_manager) = RuntimeManager::new() { - let current_path = std::env::var("PATH").ok(); - if let Some(merged_path) = runtime_manager.merged_path_env(current_path.as_deref()) { - config.env.insert("PATH".to_string(), merged_path.clone()); - #[cfg(windows)] - config.env.insert("Path".to_string(), merged_path); + #[cfg(windows)] + { + let path_entries = runtime_manager.terminal_path_entries(); + config.set_session_path_entries( + path_entries.managed_prefix, + path_entries.platform_suffix, + ); + } + #[cfg(not(windows))] + { + let process_path = std::env::var("PATH").ok(); + if let Some(path) = runtime_manager.merged_path_env(process_path.as_deref()) { + config.env.insert("PATH".to_string(), path); + } } } else { tracing::warn!("Failed to initialize SDK Host terminal runtime PATH"); diff --git a/src/crates/assembly/core/src/service/runtime/mod.rs b/src/crates/assembly/core/src/service/runtime/mod.rs index b41e38a51e..26d35a18d2 100644 --- a/src/crates/assembly/core/src/service/runtime/mod.rs +++ b/src/crates/assembly/core/src/service/runtime/mod.rs @@ -9,7 +9,7 @@ use openbitfun_services_core::managed_runtime::ManagedRuntimeResolver; use std::path::{Path, PathBuf}; pub use openbitfun_services_core::managed_runtime::{ - ResolvedCommand, RuntimeCommandCapability, RuntimeSource, + ResolvedCommand, RuntimeCommandCapability, RuntimeSource, TerminalPathEntries, }; #[derive(Debug, Clone)] @@ -63,6 +63,11 @@ impl RuntimeManager { self.inner.managed_path_entries() } + /// PATH priority anchors for newly created terminal sessions. + pub fn terminal_path_entries(&self) -> TerminalPathEntries { + self.inner.terminal_path_entries() + } + pub fn merged_path_env(&self, existing_path: Option<&str>) -> Option { self.inner.merged_path_env(existing_path) } @@ -100,6 +105,10 @@ mod tests { .managed_path_entries() .iter() .any(|p| p == &node_bin)); + assert_eq!( + manager.terminal_path_entries().managed_prefix, + manager.managed_path_entries() + ); let _ = fs::remove_dir_all(root); } diff --git a/src/crates/services/services-core/src/managed_runtime.rs b/src/crates/services/services-core/src/managed_runtime.rs index 54e13c0611..da9e9dd293 100644 --- a/src/crates/services/services-core/src/managed_runtime.rs +++ b/src/crates/services/services-core/src/managed_runtime.rs @@ -38,6 +38,22 @@ pub struct RuntimeCommandCapability { pub resolved_path: Option, } +/// Initialization-time directory anchors for implicit local Windows terminal PATH. +/// +/// `managed_prefix` precedes the inherited custom increment and live OS baseline; +/// `platform_suffix` follows it. Explicit config/request PATH overrides this policy. +/// Unlike [`ManagedRuntimeResolver::merged_path_env`], this does not capture the +/// caller's full PATH. Hosts snapshot these directory sets at initialization: +/// managed runtime installations still require host restart; only the Windows OS +/// baseline is refreshed for each new session. Other platforms keep the legacy merge. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TerminalPathEntries { + /// OpenBitFun-managed runtime directories, highest priority. + pub managed_prefix: Vec, + /// Platform GUI extras the OS PATH does not carry, lowest priority. + pub platform_suffix: Vec, +} + #[derive(Debug, Clone)] pub struct ManagedRuntimeResolver { runtime_root: PathBuf, @@ -187,6 +203,17 @@ impl ManagedRuntimeResolver { .map(|v| v.to_string_lossy().to_string()) } + /// Directory anchors captured by Windows hosts at terminal initialization. + /// + /// This does not capture OS PATH. Only that baseline is refreshed per session; + /// new managed installations require restarting the host to refresh these sets. + pub fn terminal_path_entries(&self) -> TerminalPathEntries { + TerminalPathEntries { + managed_prefix: self.managed_path_entries(), + platform_suffix: system::platform_path_entries(), + } + } + fn resolve_system_command(&self, command: &str) -> Option { let check = system::check_command(command); if !check.exists { @@ -409,4 +436,34 @@ mod tests { let _ = fs::remove_dir_all(root); } + + #[test] + fn terminal_path_entries_carry_owner_policy_without_process_path() { + let root = temp_runtime_root(); + let node_bin = root.join("node").join("current").join("bin"); + let node_root = root.join("node").join("current"); + fs::create_dir_all(&node_bin).unwrap(); + fs::create_dir_all(&node_root).unwrap(); + + let manager = ManagedRuntimeResolver::new(root.clone()); + let entries = manager.terminal_path_entries(); + let platform_entries = system::platform_path_entries(); + + assert_eq!(entries.managed_prefix, manager.managed_path_entries()); + assert_eq!(entries.platform_suffix, platform_entries); + assert!(entries.managed_prefix.contains(&node_bin)); + assert!(entries.managed_prefix.contains(&node_root)); + + // Not a process PATH snapshot: entries are temp-root managed dirs or platform extras. + assert!( + entries.managed_prefix.iter().all(|path| path.starts_with(&root)) + && entries + .platform_suffix + .iter() + .all(|path| platform_entries.contains(path)), + "session path policy must not carry caller PATH entries" + ); + + let _ = fs::remove_dir_all(root); + } } diff --git a/src/crates/services/terminal/src/config/mod.rs b/src/crates/services/terminal/src/config/mod.rs index 7608f18e7c..76a58c2c70 100644 --- a/src/crates/services/terminal/src/config/mod.rs +++ b/src/crates/services/terminal/src/config/mod.rs @@ -1,5 +1,9 @@ //! Configuration types for the terminal module +#[cfg(windows)] +mod session_path; mod types; +#[cfg(windows)] +pub(crate) use session_path::*; pub use types::*; diff --git a/src/crates/services/terminal/src/config/session_path.rs b/src/crates/services/terminal/src/config/session_path.rs new file mode 100644 index 0000000000..c9b64f1380 --- /dev/null +++ b/src/crates/services/terminal/src/config/session_path.rs @@ -0,0 +1,223 @@ +//! Windows-only live PATH policy for newly created local terminal sessions. +//! +//! Explicit request PATH overrides explicit config PATH, both verbatim (even +//! empty/whitespace). Otherwise: managed prefix > inherited custom increment > +//! fresh OS baseline > platform suffix. Unix retains its original environment +//! overlay/inheritance semantics and never runs this normalization. +//! +//! The increment captures only parent-only directories at manager initialization. +//! A stale parent entry already deleted from the registry before initialization +//! is indistinguishable from custom input and remains until process restart. +//! Baseline additions, removals and ordering after initialization are live; +//! managed/platform directory sets are initialization snapshots, so installing +//! another managed runtime still requires restarting the host. + +use std::collections::{HashMap, HashSet}; +use std::ffi::{OsStr, OsString}; + +pub(crate) fn session_path_key() -> &'static str { + "Path" +} + +/// Reuse portable-pty's public Windows base environment (HKLM + HKCU, +/// including expansion and case-insensitive keys); do not duplicate its parser. +/// An explicitly empty value is a valid baseline. Missing PATH is reported, not +/// confused with empty; the builder falls back to parent inheritance on absence. +pub(crate) fn session_path_baseline() -> Option { + let builder = portable_pty::CommandBuilder::new("cmd.exe"); + let baseline = builder.get_env(session_path_key()).map(OsStr::to_os_string); + if baseline.is_none() { + log::warn!("Live terminal PATH baseline is unavailable; preserving parent environment"); + } + baseline +} + +/// Keep only the parent directories absent from the initialization baseline. +pub(crate) fn inherited_path_increment( + parent: Option<&OsStr>, + baseline: Option<&OsStr>, +) -> Vec { + // Without a baseline we cannot distinguish custom input from stale OS data. + let Some(baseline) = baseline else { + return Vec::new(); + }; + let mut os = PathAccumulator::default(); + os.push_paths(baseline); + let mut custom = PathAccumulator::default(); + if let Some(parent) = parent { + for path in std::env::split_paths(parent) { + let raw = path.to_string_lossy(); + let entry = trimmed_entry(&raw); + if !os.seen.contains(&identity_key(entry)) { + custom.push(entry); + } + } + } + custom.entries +} + +/// Compose only the implicit policy. Explicit config/request values never enter +/// this helper. `Some(empty)` must override stale parent PATH, while `None` +/// means the baseline is unavailable and leaves parent inheritance intact, +/// even when directory anchors exist (a partial overlay could hide OS tools). +pub(crate) fn compose_session_path( + managed_prefix: &[String], + inherited_entries: &[String], + baseline: Option<&OsStr>, + platform_suffix: &[String], +) -> Option { + // Without a baseline, a policy-only overlay would discard the parent's OS + // directories. Degrade to native inheritance rather than a partial PATH. + let baseline = baseline?; + let mut composed = PathAccumulator::default(); + composed.push_entries(managed_prefix); + composed.push_entries(inherited_entries); + composed.push_paths(baseline); + composed.push_entries(platform_suffix); + let joinable: Vec<&OsStr> = composed.entries.iter().filter_map(|entry| { + let entry = OsStr::new(entry); + if std::env::join_paths(std::iter::once(entry)).is_ok() { + Some(entry) + } else { + log::debug!("Dropping a session PATH entry that cannot be joined"); + None + } + }).collect(); + std::env::join_paths(joinable).ok() +} + +/// Remove all Windows PATH variants deterministically, preserving the chosen +/// value verbatim. Canonical `Path` wins, otherwise the last sorted key wins. +pub(crate) fn take_session_path_entries(env: &mut HashMap) -> Option { + let mut variants: Vec = env.keys() + .filter(|key| key.eq_ignore_ascii_case(session_path_key())) + .cloned().collect(); + variants.sort(); + let mut canonical = None; + let mut other = None; + for key in variants { + let value = env.remove(&key); + if key == session_path_key() { + canonical = value; + } else { + other = value; + } + } + canonical.or(other) +} + +#[derive(Default)] +struct PathAccumulator { + entries: Vec, + seen: HashSet, +} + +impl PathAccumulator { + fn push(&mut self, raw: &str) { + let entry = trimmed_entry(raw); + if !entry.is_empty() && self.seen.insert(identity_key(entry)) { + self.entries.push(entry.to_string()); + } + } + + fn push_paths(&mut self, value: &OsStr) { + for path in std::env::split_paths(value) { + self.push(&path.to_string_lossy()); + } + } + + fn push_entries(&mut self, entries: &[String]) { + for entry in entries { + self.push(entry); + } + } +} + +fn trimmed_entry(raw: &str) -> &str { + let mut value = raw.trim(); + loop { + let bytes = value.as_bytes(); + if bytes.len() < 2 { + break; + } + let quoted = (bytes[0] == b'"' && bytes[bytes.len() - 1] == b'"') + || (bytes[0] == b'\'' && bytes[bytes.len() - 1] == b'\''); + if !quoted { + break; + } + value = value[1..value.len() - 1].trim(); + } + value +} + +fn identity_key(entry: &str) -> String { + let trimmed = entry.trim_end_matches(['\\', '/']); + let bytes = trimmed.as_bytes(); + let drive_root = bytes.len() == 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; + if trimmed.is_empty() || drive_root { + entry.to_lowercase() + } else { + trimmed.to_lowercase() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn portable_pty_baseline_contract_allows_empty_or_missing() { + let builder = portable_pty::CommandBuilder::new("cmd.exe"); + assert_eq!(session_path_baseline(), builder.get_env("PATH").map(OsStr::to_os_string)); + } + + #[test] + fn inherited_increment_excludes_initial_baseline_but_retains_parent_only_entries() { + let baseline = OsStr::new("C:/os;C:/shared"); + let increment = inherited_path_increment(Some(OsStr::new("C:/custom;C:/OS;C:/shared")), Some(baseline)); + assert_eq!(increment, ["C:/custom"]); + assert!(inherited_path_increment(Some(baseline), None).is_empty()); + } + + #[test] + fn implicit_policy_normalizes_and_deduplicates_windows_entries() { + let path = compose_session_path( + &[" 'C:/managed/' ".into()], + &["c:/MANAGED".into(), "C:/custom".into()], + Some(OsStr::new("C:/custom;C:/os")), + &["C:/gui".into()], + ).unwrap(); + assert_eq!(path, OsString::from("C:/managed/;C:/custom;C:/os;C:/gui")); + } + + #[test] + fn explicit_values_preserve_blank_and_canonical_key_wins() { + for value in ["", " ", " C:/explicit "] { + let mut env = HashMap::from([ + ("PATH".into(), "C:/other".into()), + ("pAtH".into(), "C:/mixed".into()), + ("Path".into(), value.into()), + ]); + assert_eq!(take_session_path_entries(&mut env).as_deref(), Some(value)); + assert!(env.is_empty()); + } + } + + #[test] + fn empty_baseline_is_distinct_from_unavailable() { + assert_eq!(compose_session_path(&[], &[], Some(OsStr::new("")), &[]), Some(OsString::new())); + assert_eq!(compose_session_path(&[], &[], None, &[]), None); + } + + #[test] + fn drive_roots_and_drive_relative_entries_are_distinct() { + let value = compose_session_path(&[], &[], Some(OsStr::new("C:\\;\\;C:")), &[]).unwrap(); + assert_eq!(value, OsString::from("C:\\;\\;C:")); + } + + #[test] + fn invalid_implicit_entry_does_not_discard_the_baseline() { + let value = compose_session_path(&["C:/bad\"quote".into()], &[], Some(OsStr::new("C:/os")), &[]).unwrap(); + assert_eq!(value, OsString::from("C:/os")); + } +} diff --git a/src/crates/services/terminal/src/config/types.rs b/src/crates/services/terminal/src/config/types.rs index 5be592cb78..a26fb424f5 100644 --- a/src/crates/services/terminal/src/config/types.rs +++ b/src/crates/services/terminal/src/config/types.rs @@ -13,7 +13,12 @@ pub struct TerminalConfig { /// Default working directory pub default_cwd: Option, - /// Environment variables to set for all terminals + /// Environment variables to set for all terminals. + /// + /// An explicit PATH replaces the entire inherited/composed PATH verbatim, + /// including empty or whitespace values. Per-request PATH has final priority. + /// Windows variants are unified deterministically with canonical `Path` winning; + /// Unix keys and values retain their exact original overlay semantics. pub env: HashMap, /// Scrollback buffer size (lines) @@ -38,6 +43,42 @@ pub struct TerminalConfig { /// Persistent plain-text transcript settings for user-created terminal sessions. #[serde(default)] pub transcript: TerminalTranscriptConfig, + + /// Product-managed prefix for implicit PATH of new local Windows sessions. + /// + /// Used only without explicit config/request PATH, ahead of the inherited + /// custom increment and fresh OS baseline. This is an initialization snapshot; + /// newly installed managed runtimes require host restart, as before. Ignored + /// on other platforms, whose hosts retain their legacy merged PATH policy. + #[serde(default)] + pub managed_path_prefix: Vec, + + /// Initialization snapshot of platform extras appended after the live OS + /// baseline for implicit PATH of new local Windows sessions. Lowest priority; + /// ignored on other platforms. Runtime changes to this directory set require + /// host restart; only the OS baseline is refreshed on each session creation. + #[serde(default)] + pub platform_path_suffix: Vec, +} + +impl TerminalConfig { + /// Store the initialization snapshot for new local Windows sessions. + /// Hosts call this on Windows only; Unix native PATH inheritance is unchanged. + /// Directory sets are not refreshed when managed runtimes are installed. + pub fn set_session_path_entries( + &mut self, + managed_prefix: Vec, + platform_suffix: Vec, + ) { + self.managed_path_prefix = managed_prefix + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + self.platform_path_suffix = platform_suffix + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + } } impl Default for TerminalConfig { @@ -54,6 +95,8 @@ impl Default for TerminalConfig { default_cols: 80, default_rows: 24, transcript: TerminalTranscriptConfig::default(), + managed_path_prefix: Vec::new(), + platform_path_suffix: Vec::new(), } } } @@ -232,3 +275,65 @@ fn default_shell_executable() -> String { std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()) } } + +#[cfg(test)] +mod tests { + use super::TerminalConfig; + use std::path::PathBuf; + + #[test] + fn legacy_payload_without_session_path_policy_uses_empty_defaults() { + let mut legacy = TerminalConfig::default(); + legacy.env.insert("PATH".to_string(), " ".to_string()); + let mut payload = + serde_json::to_value(&legacy).expect("serialize terminal config"); + let object = payload + .as_object_mut() + .expect("terminal config serializes to an object"); + object.remove("managed_path_prefix"); + object.remove("platform_path_suffix"); + + let restored: TerminalConfig = + serde_json::from_value(payload).expect("deserialize legacy terminal config"); + + assert!(restored.managed_path_prefix.is_empty()); + assert!(restored.platform_path_suffix.is_empty()); + assert_eq!(restored.env, legacy.env); + let round_trip: TerminalConfig = serde_json::from_value( + serde_json::to_value(&restored).expect("serialize restored legacy config"), + ) + .expect("round trip legacy config"); + assert_eq!(round_trip.env, legacy.env); + } + + #[test] + fn session_path_policy_round_trips_through_json() { + let mut config = TerminalConfig::default(); + config.set_session_path_entries( + vec![ + PathBuf::from("/synthetic/managed/runtime"), + PathBuf::from("/synthetic/managed/node"), + ], + vec![PathBuf::from("/synthetic/platform/gui")], + ); + + assert_eq!( + config.managed_path_prefix, + vec![ + "/synthetic/managed/runtime".to_string(), + "/synthetic/managed/node".to_string() + ] + ); + assert_eq!( + config.platform_path_suffix, + vec!["/synthetic/platform/gui".to_string()] + ); + + let payload = serde_json::to_string(&config).expect("serialize terminal config"); + let restored: TerminalConfig = + serde_json::from_str(&payload).expect("deserialize terminal config"); + + assert_eq!(restored.managed_path_prefix, config.managed_path_prefix); + assert_eq!(restored.platform_path_suffix, config.platform_path_suffix); + } +} diff --git a/src/crates/services/terminal/src/pty/process.rs b/src/crates/services/terminal/src/pty/process.rs index 71b46c4a81..2e6168e4be 100644 --- a/src/crates/services/terminal/src/pty/process.rs +++ b/src/crates/services/terminal/src/pty/process.rs @@ -1000,4 +1000,124 @@ mod tests { assert!(started.elapsed() >= std::time::Duration::from_millis(150)); assert!(!spawned.controller.is_running()); } + + /// Absolute Windows system shell for tests that replace PATH completely. + /// + /// `CreateProcess` resolves a bare `cmd.exe` through the child environment, so a + /// test overlay without any system directory must pass the absolute path. + #[cfg(windows)] + fn absolute_windows_cmd() -> String { + std::env::var_os("SystemRoot") + .map(|root| std::path::PathBuf::from(root).join("System32").join("cmd.exe")) + .filter(|path| path.is_file()) + .or_else(|| { + std::env::var_os("COMSPEC") + .map(std::path::PathBuf::from) + .filter(|path| path.is_file()) + }) + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_else(|| "cmd.exe".to_string()) + } + + /// The overlay PATH must be the child's complete PATH: no inherited tail, no + /// duplicates. This is the second layer of the live-PATH design, so a stale + /// parent value can never leak past a freshly composed overlay. + #[tokio::test(flavor = "current_thread")] + async fn overlay_path_replaces_the_inherited_path_completely() { + const BEGIN: &str = "OBFPATHBEGIN"; + const END: &str = "OBFPATHEND"; + + let unique = std::process::id(); + let first = format!("/synthetic/overlay/first-{unique}"); + let second = format!("/synthetic/overlay/second-{unique}"); + let overlay = std::env::join_paths([first, second]) + .expect("join overlay PATH") + .to_string_lossy() + .into_owned(); + + #[cfg(windows)] + let (executable, args, shell_type) = ( + absolute_windows_cmd(), + vec![ + "/d".to_string(), + "/c".to_string(), + format!("echo {BEGIN}%PATH%{END}"), + ], + ShellType::Cmd, + ); + #[cfg(not(windows))] + let (executable, args, shell_type) = ( + "/bin/sh".to_string(), + vec![ + "-c".to_string(), + format!("printf '{BEGIN}%s{END}' \"$PATH\""), + ], + ShellType::Sh, + ); + + let mut env = std::collections::HashMap::new(); + let path_key = if cfg!(windows) { "Path" } else { "PATH" }; + env.insert(path_key.to_string(), overlay.clone()); + + let mut spawned = spawn_pty( + 5, + &ShellConfig { + executable, + args, + env, + ..ShellConfig::default() + }, + shell_type, + 200, + 24, + ) + .expect("spawn PATH overlay PTY"); + + let mut output = Vec::new(); + let result = tokio::time::timeout(std::time::Duration::from_secs(3), async { + while let Some(event) = spawned.events.recv().await { + match event { + PtyEvent::Data(data) => output.extend(data), + PtyEvent::Exit { exit_code } => return exit_code, + _ => {} + } + } + panic!("PTY event stream ended without an exit status"); + }) + .await; + + if result.is_err() { + spawned + .controller + .shutdown(true) + .await + .expect("clean up failed PATH overlay fixture"); + } + + let rendered = String::from_utf8_lossy(&output).into_owned(); + assert_eq!( + result.expect("PATH overlay child exit"), + Some(0), + "unexpected PATH child output: {rendered}" + ); + + let start = rendered + .find(BEGIN) + .unwrap_or_else(|| panic!("missing PATH begin marker in {rendered:?}")) + + BEGIN.len(); + let end = rendered + .find(END) + .unwrap_or_else(|| panic!("missing PATH end marker in {rendered:?}")); + assert_eq!( + &rendered[start..end], + overlay, + "child PATH must equal the overlay value exactly: {rendered:?}" + ); + + spawned + .controller + .shutdown(true) + .await + .expect("close exited PATH overlay PTY"); + } } diff --git a/src/crates/services/terminal/src/session/manager.rs b/src/crates/services/terminal/src/session/manager.rs index 8228298664..208edcc991 100644 --- a/src/crates/services/terminal/src/session/manager.rs +++ b/src/crates/services/terminal/src/session/manager.rs @@ -1,6 +1,7 @@ //! Session Manager - Manages terminal sessions lifecycle use std::collections::HashMap; +use std::ffi::OsStr; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; @@ -12,6 +13,11 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{mpsc, watch, RwLock}; use crate::config::{ShellConfig, TerminalConfig}; +#[cfg(windows)] +use crate::config::{ + compose_session_path, inherited_path_increment, session_path_baseline, session_path_key, + take_session_path_entries, +}; use crate::events::{TerminalEvent, TerminalEventEmitter}; use crate::pty::{ProcessProperty, PtyService, PtyServiceEvent}; use crate::shell::{ @@ -189,6 +195,16 @@ pub struct SessionManager { /// Persistent plain-text transcripts for manually created terminal sessions. transcript_recorder: Option, + + /// Host PATH entries that are not part of the live OS baseline. + /// + /// Captured once when the terminal service is initialized (hosts do this during + /// startup, but a lazily initialized host captures it at first terminal use) as + /// an increment, never as a full PATH: the live baseline is re-read for every + /// session so directories added to or removed from the machine or user PATH + /// after that point are honored. + #[cfg(windows)] + inherited_path_entries: Vec, } impl SessionManager { @@ -207,6 +223,15 @@ impl SessionManager { let output_taps = Arc::new(DashMap::new()); let transcript_recorder = TranscriptRecorder::from_config(&config.transcript); + // Only parent-only entries at initialization are custom. Already-stale + // parent entries cannot be distinguished and persist until host restart. + // Subsequent baseline additions/removals/reordering are read per session. + #[cfg(windows)] + let inherited_path_entries = inherited_path_increment( + std::env::var_os(session_path_key()).as_deref(), + session_path_baseline().as_deref(), + ); + let manager = Self { config, sessions: Arc::new(RwLock::new(HashMap::new())), @@ -220,6 +245,8 @@ impl SessionManager { output_taps, replay_watchers: Arc::new(DashMap::new()), transcript_recorder, + #[cfg(windows)] + inherited_path_entries, }; // Start event forwarding @@ -714,19 +741,21 @@ impl SessionManager { login: false, }); + // The OS PATH is read here, at session creation time, so a directory added + // to the machine or user PATH after the terminal service was initialized + // still reaches this child. + #[cfg(windows)] + let baseline = session_path_baseline(); + #[cfg(not(windows))] + let baseline: Option = None; let mut shell_config = ShellConfig { executable: shell_config_base.executable, args: shell_config_base.args, - env: self.config.env.clone(), + env: self.build_session_env(env, baseline.as_deref()), cwd: Some(cwd.clone()), login: shell_config_base.login, }; - // Add custom environment - if let Some(custom_env) = env { - shell_config.env.extend(custom_env); - } - // Inject shell integration if enabled and supported if enable_integration && shell_type.supports_integration() { self.inject_shell_integration(&mut shell_config, &shell_type, &nonce); @@ -816,6 +845,42 @@ impl SessionManager { .ok_or_else(|| TerminalError::Session("Session was removed".to_string())) } + /// Explicit config PATH retains its legacy whole-value override semantics; + /// request PATH wins. Only Windows composes implicit PATH from a fresh + /// baseline. Unix retains exact overlays and bare native inheritance. + fn build_session_env( + &self, + request_env: Option>, + _baseline: Option<&OsStr>, + ) -> HashMap { + let mut session_env = self.config.env.clone(); + #[cfg(windows)] + { + let mut request_env = request_env.unwrap_or_default(); + let config_path = take_session_path_entries(&mut session_env); + let request_path = take_session_path_entries(&mut request_env); + let path = request_path.or(config_path).or_else(|| { + compose_session_path( + &self.config.managed_path_prefix, + &self.inherited_path_entries, + _baseline, + &self.config.platform_path_suffix, + ).map(|path| path.to_string_lossy().into_owned()) + }); + if let Some(path) = path { + session_env.insert(session_path_key().to_string(), path); + } else { + debug!("No terminal PATH baseline or policy available; preserving parent environment"); + } + session_env.extend(request_env); + } + #[cfg(not(windows))] + if let Some(request_env) = request_env { + session_env.extend(request_env); + } + session_env + } + /// Inject shell integration scripts and environment variables fn inject_shell_integration( &self, @@ -1693,7 +1758,21 @@ impl Drop for SessionManager { #[cfg(test)] mod tests { - use super::{compute_stream_output_delta, CommandCompletionReason}; + use super::{compute_stream_output_delta, CommandCompletionReason, SessionManager}; + use crate::config::TerminalConfig; + use std::collections::HashMap; + use std::ffi::OsStr; + + /// Build a manager whose shell-integration scripts stay inside a temp directory. + /// + /// The temp directory is returned so it outlives the manager in the calling test. + fn test_manager(config: TerminalConfig) -> (tempfile::TempDir, SessionManager) { + let scripts_dir = tempfile::tempdir().expect("create temporary scripts dir"); + let mut config = config; + config.shell_integration.scripts_dir = Some(scripts_dir.path().to_path_buf()); + let manager = SessionManager::new(config); + (scripts_dir, manager) + } #[test] fn stream_output_delta_returns_utf8_suffix_without_cutting_chars() { @@ -1738,4 +1817,111 @@ mod tests { "\"timedOut\"" ); } + + #[cfg(windows)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_refreshes_baseline_add_remove_reorder_with_custom_prefix() { + let mut config = TerminalConfig::default(); + config.managed_path_prefix = vec!["C:/managed".into()]; + config.platform_path_suffix = vec!["C:/gui".into()]; + let (_scripts, mut manager) = test_manager(config); + manager.inherited_path_entries = crate::config::inherited_path_increment( + Some(OsStr::new("C:/custom;C:/one;C:/removed;C:/two")), + Some(OsStr::new("C:/one;C:/removed;C:/two")), + ); + let first = manager.build_session_env(None, Some(OsStr::new("C:/one;C:/removed;C:/two"))); + let second = manager.build_session_env(None, Some(OsStr::new("C:/two;C:/added;C:/one"))); + assert_eq!(first["Path"], "C:/managed;C:/custom;C:/one;C:/removed;C:/two;C:/gui"); + assert_eq!(second["Path"], "C:/managed;C:/custom;C:/two;C:/added;C:/one;C:/gui"); + } + + #[cfg(windows)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_config_path_overrides_policy_verbatim_including_empty() { + for value in ["", " ", " C:/explicit;C:/only "] { + let mut config = TerminalConfig::default(); + config.managed_path_prefix = vec!["C:/managed".into()]; + config.env.insert("PATH".into(), "C:/other".into()); + config.env.insert("pAtH".into(), "C:/mixed".into()); + config.env.insert("Path".into(), value.into()); + config.env.insert("CONFIG_ONLY".into(), "kept".into()); + let (_scripts, manager) = test_manager(config); + let result = manager.build_session_env(None, Some(OsStr::new("C:/os"))); + assert_eq!(result["Path"], value); + assert_eq!(result["CONFIG_ONLY"], "kept"); + assert_eq!(result.keys().filter(|key| key.eq_ignore_ascii_case("path")).count(), 1); + } + } + + #[cfg(windows)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_request_path_is_final_and_normalizes_all_variants() { + for value in ["", " ", "C:/request"] { + let mut config = TerminalConfig::default(); + config.env.insert("Path".into(), "C:/config".into()); + config.env.insert("SHARED".into(), "config".into()); + let (_scripts, manager) = test_manager(config); + let request = HashMap::from([ + ("PATH".into(), "C:/upper".into()), + ("pAtH".into(), "C:/mixed".into()), + ("Path".into(), value.into()), + ("SHARED".into(), "request".into()), + ]); + let result = manager.build_session_env(Some(request), Some(OsStr::new("C:/os"))); + assert_eq!(result["Path"], value); + assert_eq!(result["SHARED"], "request"); + assert_eq!(result.keys().filter(|key| key.eq_ignore_ascii_case("path")).count(), 1); + } + } + + #[cfg(windows)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_request_without_path_keeps_implicit_policy() { + let mut config = TerminalConfig::default(); + config.managed_path_prefix = vec!["C:/managed".into()]; + let (_scripts, mut manager) = test_manager(config); + manager.inherited_path_entries = vec!["C:/custom".into()]; + let request = HashMap::from([("EXTRA".into(), "kept".into())]); + let result = manager.build_session_env(Some(request), Some(OsStr::new("C:/os"))); + assert_eq!(result["Path"], "C:/managed;C:/custom;C:/os"); + assert_eq!(result["EXTRA"], "kept"); + } + + #[cfg(windows)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_empty_baseline_overrides_stale_parent_but_missing_does_not() { + let (_scripts, mut manager) = test_manager(TerminalConfig::default()); + manager.inherited_path_entries.clear(); + let result = manager.build_session_env(None, Some(OsStr::new(""))); + assert_eq!(result.get("Path").map(String::as_str), Some("")); + assert!(!manager.build_session_env(None, None).contains_key("Path")); + manager.config.managed_path_prefix = vec!["C:/managed".into()]; + manager.inherited_path_entries = vec!["C:/custom".into()]; + manager.config.platform_path_suffix = vec!["C:/gui".into()]; + assert!(!manager.build_session_env(None, None).contains_key("Path")); + } + + // Unix CI test: native non-UTF-8 inheritance must not become a lossy overlay. + #[cfg(unix)] + #[tokio::test(flavor = "current_thread")] + async fn build_session_env_unix_preserves_exact_overlay_and_bare_inheritance() { + use std::os::unix::ffi::OsStrExt; + let baseline = OsStr::from_bytes(b"/native/\xff: :/quoted/'name'"); + let mut config = TerminalConfig::default(); + config.managed_path_prefix = vec!["/ignored".into()]; + config.platform_path_suffix = vec!["/also-ignored".into()]; + let (_scripts, manager) = test_manager(config); + assert!(manager.build_session_env(None, Some(baseline)).is_empty()); + for value in ["", " ", " /legal whitespace :/literal/'quotes' "] { + let mut config = TerminalConfig::default(); + config.env.insert("PATH".into(), value.into()); + config.env.insert("Path".into(), "distinct-variable".into()); + let (_scripts, manager) = test_manager(config.clone()); + assert_eq!(manager.build_session_env(None, Some(baseline)), config.env); + let request = HashMap::from([("PATH".into(), " /request ".into())]); + let result = manager.build_session_env(Some(request), Some(baseline)); + assert_eq!(result["PATH"], " /request "); + assert_eq!(result["Path"], "distinct-variable"); + } + } }