Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: openclaw in sandbox

Vanalited1cecf552dcb
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 0e71ed200..3fc130cf1 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -6,7 +6,9 @@ version = 3
name = "Jan"
version = "0.6.599"
dependencies = [
+ "async-trait",
"base64 0.22.1",
+ "bollard",
"chrono",
"clap",
"dirs",
@@ -541,6 +543,50 @@ dependencies = [
"piper",
]
+[[package]]
+name = "bollard"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30"
+dependencies = [
+ "base64 0.22.1",
+ "bollard-stubs",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "hex",
+ "http 1.3.1",
+ "http-body-util",
+ "hyper 1.7.0",
+ "hyper-named-pipe",
+ "hyper-util",
+ "hyperlocal",
+ "log",
+ "pin-project-lite",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "serde_repr",
+ "serde_urlencoded",
+ "thiserror 2.0.17",
+ "tokio",
+ "tokio-util",
+ "tower-service",
+ "url",
+ "winapi",
+]
+
+[[package]]
+name = "bollard-stubs"
+version = "1.47.1-rc.27.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da"
+dependencies = [
+ "serde",
+ "serde_repr",
+ "serde_with",
+]
+
[[package]]
name = "borsh"
version = "1.5.7"
@@ -2593,6 +2639,7 @@ dependencies = [
"http 1.3.1",
"http-body 1.0.1",
"httparse",
+ "httpdate",
"itoa",
"pin-project-lite",
"pin-utils",
@@ -2601,6 +2648,21 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-named-pipe"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278"
+dependencies = [
+ "hex",
+ "hyper 1.7.0",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+ "winapi",
+]
+
[[package]]
name = "hyper-rustls"
version = "0.24.2"
@@ -2671,6 +2733,21 @@ dependencies = [
"windows-registry",
]
+[[package]]
+name = "hyperlocal"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7"
+dependencies = [
+ "hex",
+ "http-body-util",
+ "hyper 1.7.0",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+]
+
[[package]]
name = "iana-time-zone"
version = "0.1.64"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index abbca3dd7..e57ebdffa 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -28,10 +28,12 @@ default = [
hardware = ["dep:tauri-plugin-hardware"]
deep-link = ["dep:tauri-plugin-deep-link"]
mlx = ["dep:tauri-plugin-mlx"]
+docker = ["dep:bollard"]
desktop = [
"deep-link",
"hardware",
- "mlx"
+ "mlx",
+ "docker"
]
mobile = [
"tauri/protocol-asset",
@@ -54,6 +56,7 @@ tauri-build = { version = "2.0.2", features = [] }
[dependencies]
dirs = "6.0.0"
+async-trait = "0.1"
env = "1.0.1"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
flate2 = "1.0"
@@ -112,6 +115,7 @@ base64 = "0.22"
tokio-tungstenite = { version = "0.24", features = ["native-tls"] }
glob = "0.3"
clap = { version = "4.5", features = ["derive"] }
+bollard = { version = "0.18", optional = true }
[dependencies.tauri]
version = "2.8.5"
@@ -122,7 +126,7 @@ features = ["protocol-asset", "macos-private-api", "test"]
tempfile = "3.20.0"
[target.'cfg(unix)'.dependencies]
-nix = "=0.30.1"
+nix = { version = "=0.30.1", features = ["signal", "process", "resource"] }
[target.'cfg(windows)'.dependencies]
libc = "0.2.172"
diff --git a/src-tauri/src/core/openclaw/cli.rs b/src-tauri/src/core/openclaw/cli.rs
index 99bbef891..f3b121347 100644
--- a/src-tauri/src/core/openclaw/cli.rs
+++ b/src-tauri/src/core/openclaw/cli.rs
@@ -69,6 +69,8 @@ pub async fn get_status() -> Result<OpenClawStatus, String> {
openclaw_version,
port_available,
error: None,
+ sandbox_type: None,
+ isolation_tier: None,
})
}
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rs
index 3722ece32..a93506411 100644
--- a/src-tauri/src/core/openclaw/commands.rs
+++ b/src-tauri/src/core/openclaw/commands.rs
@@ -11,6 +11,7 @@ use tauri::State;
use crate::core::openclaw::{
constants::*,
models::*,
+ sandbox::Sandbox,
get_openclaw_config_path, get_openclaw_config_dir, OpenClawState, OPENCLAW_PORT, MIN_NODE_VERSION,
};
@@ -1605,15 +1606,14 @@ pub async fn openclaw_enable(
})
}
-/// Start the OpenClaw gateway
+/// Start the OpenClaw gateway via the sandbox abstraction.
#[tauri::command]
-pub async fn openclaw_start(_state: State<'_, OpenClawState>) -> Result<(), String> {
+pub async fn openclaw_start(state: State<'_, OpenClawState>) -> Result<(), String> {
log::info!("Starting OpenClaw gateway");
// Check if gateway is already responding
if check_gateway_responding().await {
log::info!("OpenClaw gateway is already running on port {}", OPENCLAW_PORT);
- // Even if running externally, ensure Jan's origin is configured
let _ = openclaw_ensure_jan_origin().await;
return Ok(());
}
@@ -1627,198 +1627,91 @@ pub async fn openclaw_start(_state: State<'_, OpenClawState>) -> Result<(), Stri
// Check port availability
let port_check = openclaw_check_port(OPENCLAW_PORT).await;
if !port_check.available {
- // Port is in use but gateway not responding - something else is using the port
return Err(format!("Port {} is already in use by another application", OPENCLAW_PORT));
}
// Ensure config exists
let config_path = get_openclaw_config_path()?;
if !config_path.exists() {
- // Generate default config (includes Jan's allowed origins by default)
openclaw_configure(None).await?;
} else {
- // Config exists, ensure Jan's origin is in allowedOrigins
- // This is crucial for the 1-click experience - users shouldn't need to manually edit config
openclaw_ensure_jan_origin().await?;
}
- // First, ensure the gateway service is installed (required on fresh install)
- // This registers the launchd service on macOS
- log::info!("Ensuring OpenClaw gateway service is installed");
- if let Ok(mut install_child) = Command::new("openclaw")
- .args(["gateway", "install"])
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
+ // Detect sandbox if not yet initialized
{
- let _ = install_child.wait().await;
- }
-
- // Start OpenClaw gateway via CLI
- // Note: 'openclaw gateway start' starts a launchd service (daemon) and exits immediately
- // The actual gateway runs as a separate daemon process, not as a child of this CLI command
- log::info!("Starting OpenClaw gateway service");
- let output = Command::new("openclaw")
- .args(["gateway", "start"])
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .output()
- .await
- .map_err(|e| format!("Failed to run openclaw gateway start: {}", e))?;
-
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- let stdout = String::from_utf8_lossy(&output.stdout);
- log::error!("openclaw gateway start failed: stdout={}, stderr={}", stdout, stderr);
- return Err(format!("Failed to start OpenClaw gateway: {}", stderr));
- }
-
- // Wait for the gateway to actually start responding
- // The launchd service takes a moment to initialize
- log::info!("Waiting for OpenClaw gateway to become responsive...");
- for i in 0..10 {
- tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
- if check_gateway_responding().await {
- log::info!("OpenClaw gateway started successfully on port {}", OPENCLAW_PORT);
- return Ok(());
+ let mut sandbox_guard = state.sandbox.lock().await;
+ if sandbox_guard.is_none() {
+ let detected = crate::core::openclaw::sandbox::detect_sandbox().await;
+ log::info!("Detected sandbox: {} (tier: {})", detected.name(), detected.isolation_tier());
+ *sandbox_guard = Some(detected);
}
- log::debug!("Gateway not responding yet, attempt {}/10", i + 1);
}
- // Gateway didn't respond in time
- Err("OpenClaw gateway started but is not responding. Check logs at /tmp/openclaw/".to_string())
+ // Build config and start via lifecycle module
+ let config = crate::core::openclaw::lifecycle::build_sandbox_config(
+ &crate::core::openclaw::constants::DEFAULT_JAN_BASE_URL,
+ )?;
+
+ let sandbox_guard = state.sandbox.lock().await;
+ let sandbox = sandbox_guard.as_ref().ok_or("Sandbox not initialized")?;
+ crate::core::openclaw::lifecycle::start_openclaw(sandbox.as_ref(), &config, &state).await
}
-/// Stop the OpenClaw gateway
+/// Stop the OpenClaw gateway via the sandbox abstraction.
#[tauri::command]
-pub async fn openclaw_stop(_state: State<'_, OpenClawState>) -> Result<(), String> {
+pub async fn openclaw_stop(state: State<'_, OpenClawState>) -> Result<(), String> {
log::info!("Stopping OpenClaw gateway");
- // Use 'openclaw gateway stop' to properly stop the launchd service
- // This is the correct way to stop the gateway when started via 'openclaw gateway start'
- let mut stopped_via_cli = false;
- let stop_result = Command::new("openclaw")
- .args(["gateway", "stop"])
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn();
-
- match stop_result {
- Ok(mut child) => {
- match child.wait().await {
- Ok(status) => {
- if status.success() {
- log::info!("OpenClaw gateway stop command succeeded");
- stopped_via_cli = true;
- } else {
- log::warn!("openclaw gateway stop returned non-zero status, trying fallback");
- }
- }
- Err(e) => {
- log::warn!("Failed to wait for gateway stop: {}", e);
- }
- }
+ let sandbox_guard = state.sandbox.lock().await;
+ match sandbox_guard.as_ref() {
+ Some(sandbox) => {
+ crate::core::openclaw::lifecycle::stop_openclaw(sandbox.as_ref(), &state).await
}
- Err(e) => {
- log::warn!("Failed to run openclaw gateway stop: {}", e);
+ None => {
+ // Sandbox never initialized — fall back to direct CLI stop
+ log::info!("No sandbox detected, using direct CLI stop");
+ let direct = crate::core::openclaw::sandbox_direct::DirectProcessSandbox;
+ let mut handle = crate::core::openclaw::sandbox::SandboxHandle::Named("direct-process".to_string());
+ direct.stop(&mut handle).await
}
}
-
- // Fallback: try to kill by process name
- if !stopped_via_cli {
- #[cfg(target_os = "macos")]
- {
- let _ = Command::new("pkill")
- .arg("-f")
- .arg("openclaw")
- .output()
- .await;
- }
-
- #[cfg(target_os = "linux")]
- {
- let _ = Command::new("pkill")
- .arg("-f")
- .arg("openclaw")
- .output()
- .await;
- }
-
- #[cfg(target_os = "windows")]
- {
- let _ = Command::new("taskkill")
- .args(["/F", "/IM", "openclaw.exe"])
- .output()
- .await;
- }
- }
-
- // Wait for the port to actually be released before returning.
- // Without this, the caller may immediately check status and find
- // the gateway still responding (race condition).
- for i in 0..10 {
- if !check_gateway_responding().await {
- log::info!("OpenClaw gateway stopped successfully (port released after {} checks)", i + 1);
- return Ok(());
- }
- log::debug!("Gateway still responding after stop, waiting... attempt {}/10", i + 1);
- tokio::time::sleep(std::time::Duration::from_millis(500)).await;
- }
-
- // Port is still occupied after 5 seconds - try SIGKILL as last resort
- log::warn!("OpenClaw gateway still responding after 5s, sending SIGKILL");
- #[cfg(any(target_os = "macos", target_os = "linux"))]
- {
- let _ = Command::new("pkill")
- .arg("-9")
- .arg("-f")
- .arg("openclaw")
- .output()
- .await;
- }
- #[cfg(target_os = "windows")]
- {
- let _ = Command::new("taskkill")
- .args(["/F", "/IM", "openclaw.exe"])
- .output()
- .await;
- }
-
- // Final wait after SIGKILL
- for i in 0..6 {
- if !check_gateway_responding().await {
- log::info!("OpenClaw gateway stopped after SIGKILL (attempt {})", i + 1);
- return Ok(());
- }
- tokio::time::sleep(std::time::Duration::from_millis(500)).await;
- }
-
- log::warn!("OpenClaw gateway may still be running after stop attempts");
- Ok(())
}
-/// Get the current OpenClaw status
+/// Get the current OpenClaw status, including sandbox information.
#[tauri::command]
-pub async fn openclaw_status(_state: State<'_, OpenClawState>) -> Result<OpenClawStatus, String> {
+pub async fn openclaw_status(state: State<'_, OpenClawState>) -> Result<OpenClawStatus, String> {
log::info!("Getting OpenClaw status");
- // Check if gateway is responding on the expected port
- // This is the source of truth - the gateway runs as a launchd daemon,
- // not as a child process we track
let running = check_gateway_responding().await;
- // Check if OpenClaw is installed
let openclaw_version = match check_openclaw_installed().await {
Ok(v) => v,
Err(_) => None,
};
- // Check Node.js
let node_check = openclaw_check_dependencies().await;
-
- // Check port
let port_check = openclaw_check_port(OPENCLAW_PORT).await;
+ // Get sandbox information from state
+ let (sandbox_type, isolation_tier) = {
+ let sandbox_guard = state.sandbox.lock().await;
+ let mode = state.sandbox_mode.lock().await;
+ match (&*sandbox_guard, &*mode) {
+ (Some(sandbox), crate::core::openclaw::sandbox::SandboxMode::Active { .. }) => {
+ (
+ Some(sandbox.name().to_string()),
+ Some(sandbox.isolation_tier().to_string()),
+ )
+ }
+ (Some(sandbox), _) if running => {
+ // Gateway running but not tracked (started externally)
+ (Some(sandbox.name().to_string()), Some(sandbox.isolation_tier().to_string()))
+ }
+ _ => (None, None),
+ }
+ };
+
Ok(OpenClawStatus {
installed: openclaw_version.is_some(),
running,
@@ -1826,21 +1719,18 @@ pub async fn openclaw_status(_state: State<'_, OpenClawState>) -> Result<OpenCla
openclaw_version,
port_available: port_check.available,
error: None,
+ sandbox_type,
+ isolation_tier,
})
}
-/// Restart the OpenClaw gateway
+/// Restart the OpenClaw gateway via the sandbox abstraction.
#[tauri::command]
pub async fn openclaw_restart(state: State<'_, OpenClawState>) -> Result<(), String> {
log::info!("Restarting OpenClaw gateway");
- // Stop first
openclaw_stop(state.clone()).await?;
-
- // Wait a bit for the process to fully terminate
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
-
- // Start again
openclaw_start(state).await
}
diff --git a/src-tauri/src/core/openclaw/health.rs b/src-tauri/src/core/openclaw/health.rs
new file mode 100644
index 000000000..32ec97ef2
--- /dev/null
+++ b/src-tauri/src/core/openclaw/health.rs
@@ -0,0 +1,87 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use tauri::Emitter;
+use tokio::sync::Mutex;
+
+use super::lifecycle::is_port_in_use;
+use super::sandbox::{Sandbox, SandboxMode};
+use super::OpenClawState;
+
+const HEALTH_CHECK_INTERVAL: Duration = Duration::from_secs(15);
+const MAX_RESTART_ATTEMPTS: u32 = 3;
+
+/// Spawn a background task that monitors the sandbox health.
+/// Returns a JoinHandle that can be used to cancel the monitor.
+pub fn spawn_health_monitor(
+ sandbox: Arc<Mutex<Option<Box<dyn Sandbox>>>>,
+ state: Arc<OpenClawState>,
+ app_handle: tauri::AppHandle,
+) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(async move {
+ let mut was_healthy = true;
+ let mut restart_count: u32 = 0;
+
+ loop {
+ tokio::time::sleep(HEALTH_CHECK_INTERVAL).await;
+
+ let mode = state.sandbox_mode.lock().await;
+ let is_active = matches!(*mode, SandboxMode::Active { .. });
+ drop(mode);
+
+ if !is_active {
+ // Sandbox is not active, nothing to monitor
+ was_healthy = true;
+ restart_count = 0;
+ continue;
+ }
+
+ // Check health by probing the port
+ let is_healthy = is_port_in_use(super::OPENCLAW_PORT).await;
+
+ if is_healthy && !was_healthy {
+ // Recovered
+ log::info!("OpenClaw health restored");
+ restart_count = 0;
+ let _ = app_handle.emit("openclaw-health-changed", "healthy");
+ } else if !is_healthy && was_healthy {
+ // Became unhealthy
+ log::warn!("OpenClaw health check failed — gateway not responding");
+ let _ = app_handle.emit("openclaw-health-changed", "unhealthy");
+ }
+
+ if !is_healthy && restart_count < MAX_RESTART_ATTEMPTS {
+ log::info!(
+ "Attempting auto-restart ({}/{})",
+ restart_count + 1,
+ MAX_RESTART_ATTEMPTS
+ );
+
+ // Attempt restart through the sandbox
+ let sandbox_guard = sandbox.lock().await;
+ if let Some(ref sandbox_impl) = *sandbox_guard {
+ let mut mode = state.sandbox_mode.lock().await;
+ if let SandboxMode::Active { ref mut handle, .. } = *mode {
+ // Stop, then restart is handled by the caller re-starting.
+ // For auto-restart, we just stop and let the next cycle detect it.
+ let _ = sandbox_impl.stop(handle).await;
+ }
+ *mode = SandboxMode::Inactive;
+ }
+ drop(sandbox_guard);
+
+ restart_count += 1;
+
+ if restart_count >= MAX_RESTART_ATTEMPTS {
+ log::error!(
+ "OpenClaw failed after {} restart attempts",
+ MAX_RESTART_ATTEMPTS
+ );
+ let _ = app_handle.emit("openclaw-failed", "max_restarts_exceeded");
+ }
+ }
+
+ was_healthy = is_healthy;
+ }
+ })
+}
diff --git a/src-tauri/src/core/openclaw/lifecycle.rs b/src-tauri/src/core/openclaw/lifecycle.rs
new file mode 100644
index 000000000..b82d2fb8f
--- /dev/null
+++ b/src-tauri/src/core/openclaw/lifecycle.rs
@@ -0,0 +1,193 @@
+use std::path::Path;
+use std::time::Duration;
+
+use super::sandbox::{
+ IsolationTier, Sandbox, SandboxConfig, SandboxMode, SandboxStatus,
+};
+use super::security::ensure_secure_config_permissions;
+use super::{get_openclaw_config_dir, OpenClawState, OPENCLAW_PORT};
+
+/// Build a SandboxConfig from the current OpenClaw configuration.
+pub fn build_sandbox_config(jan_api_url: &str) -> Result<SandboxConfig, String> {
+ let config_dir = get_openclaw_config_dir()?;
+
+ Ok(SandboxConfig {
+ config_dir: config_dir.clone(),
+ port: OPENCLAW_PORT,
+ jan_api_url: jan_api_url.to_string(),
+ env_vars: vec![(
+ "OPENCLAW_CONFIG".into(),
+ config_dir
+ .join("openclaw.json")
+ .to_string_lossy()
+ .into_owned(),
+ )],
+ })
+}
+
+/// Start OpenClaw using the provided sandbox implementation.
+/// Handles: config patching, sandbox start, health check, state update.
+pub async fn start_openclaw(
+ sandbox: &dyn Sandbox,
+ config: &SandboxConfig,
+ state: &OpenClawState,
+) -> Result<(), String> {
+ // 1. Ensure config directory has secure permissions
+ ensure_secure_config_permissions(&config.config_dir).await?;
+
+ // 2. Patch config if needed for this sandbox type
+ patch_config_for_sandbox(sandbox, &config.config_dir)?;
+
+ // 3. Start the sandbox
+ let handle = sandbox.start(config).await?;
+
+ // 4. Wait for the gateway to become responsive
+ wait_for_port(config.port, Duration::from_secs(30)).await?;
+
+ // 5. Update state
+ let mut mode = state.sandbox_mode.lock().await;
+ *mode = SandboxMode::Active {
+ sandbox_name: sandbox.name().to_string(),
+ isolation_tier: sandbox.isolation_tier(),
+ handle,
+ };
+
+ log::info!(
+ "OpenClaw started successfully via {} (tier: {})",
+ sandbox.name(),
+ sandbox.isolation_tier()
+ );
+
+ Ok(())
+}
+
+/// Stop OpenClaw regardless of which sandbox type is in use.
+pub async fn stop_openclaw(
+ sandbox: &dyn Sandbox,
+ state: &OpenClawState,
+) -> Result<(), String> {
+ let mut mode = state.sandbox_mode.lock().await;
+ if let SandboxMode::Active {
+ ref mut handle, ..
+ } = *mode
+ {
+ sandbox.stop(handle).await?;
+ }
+ *mode = SandboxMode::Inactive;
+
+ // Wait for the port to actually be released
+ for i in 0..10 {
+ if !is_port_in_use(OPENCLAW_PORT).await {
+ log::info!(
+ "OpenClaw stopped successfully (port released after {} checks)",
+ i + 1
+ );
+ return Ok(());
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ log::warn!("OpenClaw port may still be in use after stop");
+ Ok(())
+}
+
+/// Get OpenClaw status using the sandbox.
+pub async fn get_openclaw_status(
+ sandbox: &dyn Sandbox,
+ state: &OpenClawState,
+) -> Result<(SandboxStatus, Option<String>, Option<IsolationTier>), String> {
+ let mode = state.sandbox_mode.lock().await;
+
+ match &*mode {
+ SandboxMode::Active {
+ sandbox_name,
+ isolation_tier,
+ handle,
+ } => {
+ let status = sandbox.status(handle).await?;
+ Ok((
+ status,
+ Some(sandbox_name.clone()),
+ Some(isolation_tier.clone()),
+ ))
+ }
+ SandboxMode::Inactive => {
+ // Even if we think we're inactive, check if the gateway happens to be running
+ // (e.g., started externally or from a previous Jan session)
+ if is_port_in_use(OPENCLAW_PORT).await {
+ Ok((SandboxStatus::Running, None, None))
+ } else {
+ Ok((SandboxStatus::Stopped, None, None))
+ }
+ }
+ }
+}
+
+/// Shared health check: poll a port until it responds or timeout.
+pub async fn wait_for_port(port: u16, timeout: Duration) -> Result<(), String> {
+ let start = tokio::time::Instant::now();
+ let interval = Duration::from_millis(500);
+
+ loop {
+ if is_port_in_use(port).await {
+ log::info!("Port {} is now responding", port);
+ return Ok(());
+ }
+
+ if start.elapsed() >= timeout {
+ return Err(format!(
+ "Timed out waiting for port {} to respond ({}s)",
+ port,
+ timeout.as_secs()
+ ));
+ }
+
+ tokio::time::sleep(interval).await;
+ }
+}
+
+/// Check if a port has something listening (TCP connect succeeds).
+pub async fn is_port_in_use(port: u16) -> bool {
+ tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port))
+ .await
+ .is_ok()
+}
+
+/// Patch OpenClaw config based on the sandbox type.
+/// Docker needs different API URLs; namespace/direct sandboxes work with localhost.
+fn patch_config_for_sandbox(sandbox: &dyn Sandbox, config_dir: &Path) -> Result<(), String> {
+ match sandbox.isolation_tier() {
+ IsolationTier::FullContainer => {
+ // Docker: change Jan API URL to host.docker.internal
+ // and change gateway bind to 0.0.0.0 so the port mapping works
+ let config_path = config_dir.join("openclaw.json");
+ if config_path.exists() {
+ let content = std::fs::read_to_string(&config_path)
+ .map_err(|e| format!("Failed to read config: {}", e))?;
+
+ let patched = content
+ .replace("localhost:1337", "host.docker.internal:1337")
+ .replace("127.0.0.1:1337", "host.docker.internal:1337")
+ .replace("\"bind\":\"loopback\"", "\"bind\":\"0.0.0.0\"")
+ .replace("\"bind\": \"loopback\"", "\"bind\": \"0.0.0.0\"");
+
+ if patched != content {
+ std::fs::write(&config_path, patched)
+ .map_err(|e| format!("Failed to patch config: {}", e))?;
+ log::info!("Patched OpenClaw config for Docker sandbox");
+ }
+ }
+ }
+ IsolationTier::PlatformSandbox => {
+ // No config patching needed for platform-native sandboxes:
+ // - WSL2: NAT networking — guest reaches host via localhost
+ // - Apple Container: helper configures host networking
+ // - Linux namespaces: no network namespace, localhost works
+ }
+ IsolationTier::None => {
+ // Direct process: same machine, localhost works
+ }
+ }
+
+ Ok(())
+}
diff --git a/src-tauri/src/core/openclaw/mod.rs b/src-tauri/src/core/openclaw/mod.rs
index 460b14c75..2f35ce305 100644
--- a/src-tauri/src/core/openclaw/mod.rs
+++ b/src-tauri/src/core/openclaw/mod.rs
@@ -1,7 +1,19 @@
pub mod cli;
pub mod commands;
pub mod constants;
+pub mod health;
+pub mod lifecycle;
pub mod models;
+pub mod sandbox;
+pub mod sandbox_direct;
+#[cfg(target_os = "linux")]
+pub mod sandbox_native;
+#[cfg(target_os = "windows")]
+pub mod sandbox_wsl2;
+#[cfg(target_os = "macos")]
+pub mod sandbox_apple;
+#[cfg(feature = "docker")]
+pub mod sandbox_docker;
pub mod security;
pub mod tailscale;
pub mod tunnels;
@@ -11,6 +23,7 @@ use std::sync::Arc;
use tokio::sync::Mutex;
+use sandbox::{Sandbox, SandboxMode};
use tunnels::TunnelState;
/// OpenClaw configuration directory
@@ -36,17 +49,20 @@ pub const MIN_NODE_VERSION: u32 = 22;
/// OpenClaw Manager state
pub struct OpenClawState {
- /// Process handle for the OpenClaw gateway
- pub process_handle: Arc<Mutex<Option<tokio::process::Child>>>,
/// Tunnel state for managing tunnel processes
pub tunnel_state: TunnelState,
+ /// Current sandbox mode (inactive or active with handle)
+ pub sandbox_mode: Arc<Mutex<SandboxMode>>,
+ /// Detected sandbox implementation (set once on first use via detect_sandbox())
+ pub sandbox: Arc<Mutex<Option<Box<dyn Sandbox>>>>,
}
impl Default for OpenClawState {
fn default() -> Self {
Self {
- process_handle: Arc::new(Mutex::new(None)),
tunnel_state: TunnelState::default(),
+ sandbox_mode: Arc::new(Mutex::new(SandboxMode::Inactive)),
+ sandbox: Arc::new(Mutex::new(None)),
}
}
-}
\ No newline at end of file
+}
diff --git a/src-tauri/src/core/openclaw/models.rs b/src-tauri/src/core/openclaw/models.rs
index 7e6275948..9289de307 100644
--- a/src-tauri/src/core/openclaw/models.rs
+++ b/src-tauri/src/core/openclaw/models.rs
@@ -205,6 +205,12 @@ pub struct OpenClawStatus {
pub port_available: bool,
/// Error message (if any)
pub error: Option<String>,
+ /// Active sandbox type name (e.g., "Linux Namespaces", "WSL2", "Docker", "Direct Process")
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sandbox_type: Option<String>,
+ /// Isolation tier ("none", "platform_sandbox", "full_container")
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub isolation_tier: Option<String>,
}
/// Node.js check result
diff --git a/src-tauri/src/core/openclaw/sandbox.rs b/src-tauri/src/core/openclaw/sandbox.rs
new file mode 100644
index 000000000..bd4a73ac6
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox.rs
@@ -0,0 +1,141 @@
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+/// Configuration passed to any sandbox implementation.
+/// Platform-agnostic — no Docker-specific, WSL-specific, or namespace-specific fields.
+pub struct SandboxConfig {
+ /// Path to the OpenClaw config directory on the host (~/.openclaw/)
+ pub config_dir: PathBuf,
+ /// The port OpenClaw should listen on
+ pub port: u16,
+ /// The Jan API base URL that OpenClaw should connect to
+ pub jan_api_url: String,
+ /// Environment variables to pass to the OpenClaw process
+ pub env_vars: Vec<(String, String)>,
+}
+
+/// Opaque handle returned by `start()`. Each implementation stores what it needs.
+pub enum SandboxHandle {
+ /// PID-based handle (Linux namespaces, macOS)
+ Pid(u32),
+ /// Named handle (WSL2 distro name, Docker container name)
+ Named(String),
+ /// Process handle for direct process fallback
+ Process(tokio::process::Child),
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub enum SandboxStatus {
+ Running,
+ Stopped,
+ Failed { error: String },
+ Unknown,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum IsolationTier {
+ /// Tier 0: No isolation (direct process)
+ None,
+ /// Tier 2: Namespace/VM isolation (bubblewrap, WSL2, Apple Containerization)
+ PlatformSandbox,
+ /// Tier 3: Full OCI container (Docker/Podman)
+ FullContainer,
+}
+
+impl std::fmt::Display for IsolationTier {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ IsolationTier::None => write!(f, "none"),
+ IsolationTier::PlatformSandbox => write!(f, "platform_sandbox"),
+ IsolationTier::FullContainer => write!(f, "full_container"),
+ }
+ }
+}
+
+#[async_trait::async_trait]
+pub trait Sandbox: Send + Sync {
+ /// Human-readable name for this sandbox type
+ fn name(&self) -> &str;
+
+ /// The isolation tier this sandbox provides
+ fn isolation_tier(&self) -> IsolationTier;
+
+ /// Returns true if this sandbox mechanism is available on the current system
+ async fn is_available(&self) -> bool;
+
+ /// Start OpenClaw in the sandbox. Returns a handle for subsequent operations.
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String>;
+
+ /// Stop the sandboxed OpenClaw process.
+ async fn stop(&self, handle: &mut SandboxHandle) -> Result<(), String>;
+
+ /// Check current status of the sandboxed process.
+ async fn status(&self, handle: &SandboxHandle) -> Result<SandboxStatus, String>;
+
+ /// Retrieve recent log lines from the sandboxed process.
+ async fn logs(&self, handle: &SandboxHandle, lines: usize) -> Result<Vec<String>, String>;
+}
+
+/// Active sandbox mode — stored in OpenClawState.
+pub enum SandboxMode {
+ /// No sandbox active
+ Inactive,
+ /// Sandbox is running
+ Active {
+ sandbox_name: String,
+ isolation_tier: IsolationTier,
+ handle: SandboxHandle,
+ },
+}
+
+/// Auto-detect the best available sandbox for the current platform.
+/// Returns implementations in priority order: best isolation first.
+///
+/// Priority chain:
+/// 1. Docker/Podman (Tier 3) — best isolation, optional
+/// 2. Platform-native (Tier 2) — Linux namespaces / WSL2 / Apple Containerization
+/// 3. Direct process (Tier 0) — always-available fallback
+pub async fn detect_sandbox() -> Box<dyn Sandbox> {
+ // Tier 3: Docker/Podman (if available — best isolation, optional)
+ #[cfg(feature = "docker")]
+ {
+ let docker = super::sandbox_docker::DockerSandbox::new();
+ if docker.is_available().await {
+ log::info!("Sandbox: Docker detected");
+ return Box::new(docker);
+ }
+ }
+
+ // Tier 2: Platform-native lightweight sandbox
+ #[cfg(target_os = "linux")]
+ {
+ let native = super::sandbox_native::NativeSandbox;
+ if native.is_available().await {
+ log::info!("Sandbox: Linux namespaces (bubblewrap-style)");
+ return Box::new(native);
+ }
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ let wsl2 = super::sandbox_wsl2::Wsl2Sandbox::new();
+ if wsl2.is_available().await {
+ log::info!("Sandbox: WSL2");
+ return Box::new(wsl2);
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ let apple = super::sandbox_apple::AppleContainerSandbox;
+ if apple.is_available().await {
+ log::info!("Sandbox: Apple Containerization");
+ return Box::new(apple);
+ }
+ }
+
+ // Tier 0: No isolation (direct process fallback)
+ log::info!("Sandbox: none available, using direct process");
+ Box::new(super::sandbox_direct::DirectProcessSandbox)
+}
diff --git a/src-tauri/src/core/openclaw/sandbox_apple.rs b/src-tauri/src/core/openclaw/sandbox_apple.rs
new file mode 100644
index 000000000..75683d347
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox_apple.rs
@@ -0,0 +1,275 @@
+/// Apple Containerization Framework sandbox for macOS 26+ (Tahoe).
+///
+/// Delegates to a Swift helper binary (`container-helper`) that wraps
+/// Apple's Containerization.framework. This follows the same pattern as
+/// the `mlx-server` integration: a Swift binary built separately and
+/// bundled in `src-tauri/resources/bin/`.
+///
+/// The helper communicates via a simple JSON protocol over stdout.
+///
+/// Network model: the helper configures the container with host networking,
+/// so `localhost:1337` reaches Jan's API without config patching.
+#[cfg(target_os = "macos")]
+use std::process::Stdio;
+
+#[cfg(target_os = "macos")]
+use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, SandboxStatus};
+
+#[cfg(target_os = "macos")]
+const HELPER_BINARY: &str = "container-helper";
+
+#[cfg(target_os = "macos")]
+pub struct AppleContainerSandbox;
+
+#[cfg(target_os = "macos")]
+impl AppleContainerSandbox {
+ /// Check if the macOS version is 26.0 (Tahoe) or later.
+ async fn is_macos_26_or_later() -> bool {
+ match tokio::process::Command::new("sw_vers")
+ .args(["-productVersion"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ {
+ Ok(output) => {
+ let version = String::from_utf8_lossy(&output.stdout);
+ let trimmed = version.trim();
+ let parts: Vec<&str> = trimmed.split('.').collect();
+ if let Some(major) = parts.first() {
+ if let Ok(major_num) = major.parse::<u32>() {
+ return major_num >= 26;
+ }
+ }
+ log::info!(
+ "AppleContainerSandbox: could not parse macOS version: '{}'",
+ trimmed
+ );
+ false
+ }
+ Err(e) => {
+ log::info!("AppleContainerSandbox: sw_vers failed: {}", e);
+ false
+ }
+ }
+ }
+
+ /// Resolve the path to the container-helper binary from Tauri resources.
+ fn helper_path() -> Option<std::path::PathBuf> {
+ // Try the standard resource locations
+ let candidates = [
+ std::path::PathBuf::from("resources/bin").join(HELPER_BINARY),
+ // In development, the binary might be at the src-tauri level
+ std::path::PathBuf::from("src-tauri/resources/bin").join(HELPER_BINARY),
+ ];
+
+ for candidate in &candidates {
+ if candidate.exists() {
+ return Some(candidate.clone());
+ }
+ }
+
+ // Try resolving relative to the current executable
+ if let Ok(exe_path) = std::env::current_exe() {
+ if let Some(exe_dir) = exe_path.parent() {
+ let resource_path = exe_dir.join("resources/bin").join(HELPER_BINARY);
+ if resource_path.exists() {
+ return Some(resource_path);
+ }
+ // macOS .app bundle: Contents/MacOS/../Resources/
+ let bundle_path = exe_dir
+ .join("../Resources/resources/bin")
+ .join(HELPER_BINARY);
+ if bundle_path.exists() {
+ return Some(bundle_path);
+ }
+ }
+ }
+
+ None
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[async_trait::async_trait]
+impl Sandbox for AppleContainerSandbox {
+ fn name(&self) -> &str {
+ "Apple Containerization"
+ }
+
+ fn isolation_tier(&self) -> IsolationTier {
+ IsolationTier::PlatformSandbox
+ }
+
+ async fn is_available(&self) -> bool {
+ if !Self::is_macos_26_or_later().await {
+ log::info!("AppleContainerSandbox: macOS version < 26");
+ return false;
+ }
+
+ if Self::helper_path().is_none() {
+ log::info!("AppleContainerSandbox: container-helper binary not found");
+ return false;
+ }
+
+ true
+ }
+
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String> {
+ let helper = Self::helper_path()
+ .ok_or("container-helper binary not found in resources")?;
+
+ log::info!(
+ "AppleContainerSandbox: starting via {:?}",
+ helper
+ );
+
+ let output = tokio::process::Command::new(&helper)
+ .args([
+ "start",
+ "--config-dir",
+ &config.config_dir.to_string_lossy(),
+ "--port",
+ &config.port.to_string(),
+ "--jan-api-url",
+ &config.jan_api_url,
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to run container-helper: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("container-helper start failed: {}", stderr));
+ }
+
+ // Parse JSON output: {"container_id": "..."}
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(stdout.trim())
+ .map_err(|e| format!("Failed to parse container-helper output: {}", e))?;
+
+ let container_id = parsed
+ .get("container_id")
+ .and_then(|v| v.as_str())
+ .ok_or("container-helper did not return container_id")?
+ .to_string();
+
+ log::info!(
+ "AppleContainerSandbox: started container '{}'",
+ container_id
+ );
+ Ok(SandboxHandle::Named(container_id))
+ }
+
+ async fn stop(&self, handle: &mut SandboxHandle) -> Result<(), String> {
+ let container_id = match handle {
+ SandboxHandle::Named(id) => id.clone(),
+ _ => return Err("Invalid handle for AppleContainerSandbox".to_string()),
+ };
+
+ let helper = Self::helper_path()
+ .ok_or("container-helper binary not found")?;
+
+ log::info!(
+ "AppleContainerSandbox: stopping container '{}'",
+ container_id
+ );
+
+ let output = tokio::process::Command::new(&helper)
+ .args(["stop", "--container-id", &container_id])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to run container-helper stop: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ log::warn!("AppleContainerSandbox: stop returned error: {}", stderr);
+ }
+
+ Ok(())
+ }
+
+ async fn status(&self, handle: &SandboxHandle) -> Result<SandboxStatus, String> {
+ // Primary check: port connectivity
+ match tokio::net::TcpStream::connect(format!("127.0.0.1:{}", super::OPENCLAW_PORT)).await {
+ Ok(_) => return Ok(SandboxStatus::Running),
+ Err(_) => {}
+ }
+
+ // Secondary check: ask the helper
+ let container_id = match handle {
+ SandboxHandle::Named(id) => id.clone(),
+ _ => return Ok(SandboxStatus::Unknown),
+ };
+
+ if let Some(helper) = Self::helper_path() {
+ let output = tokio::process::Command::new(&helper)
+ .args(["status", "--container-id", &container_id])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await;
+
+ if let Ok(output) = output {
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(stdout.trim()) {
+ if parsed.get("running").and_then(|v| v.as_bool()) == Some(true) {
+ return Ok(SandboxStatus::Running);
+ }
+ }
+ }
+ }
+ }
+
+ Ok(SandboxStatus::Stopped)
+ }
+
+ async fn logs(
+ &self,
+ handle: &SandboxHandle,
+ lines: usize,
+ ) -> Result<Vec<String>, String> {
+ let container_id = match handle {
+ SandboxHandle::Named(id) => id.clone(),
+ _ => return Ok(vec!["Invalid handle".to_string()]),
+ };
+
+ let helper = match Self::helper_path() {
+ Some(p) => p,
+ None => return Ok(vec!["container-helper not found".to_string()]),
+ };
+
+ let output = tokio::process::Command::new(&helper)
+ .args([
+ "logs",
+ "--container-id",
+ &container_id,
+ "--lines",
+ &lines.to_string(),
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to read container logs: {}", e))?;
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ // Try to parse as JSON array, fall back to raw lines
+ if let Ok(log_lines) = serde_json::from_str::<Vec<String>>(stdout.trim()) {
+ Ok(log_lines)
+ } else {
+ Ok(stdout.lines().map(String::from).collect())
+ }
+ } else {
+ Ok(vec![
+ "Failed to retrieve logs from Apple Container sandbox.".to_string(),
+ ])
+ }
+ }
+}
diff --git a/src-tauri/src/core/openclaw/sandbox_direct.rs b/src-tauri/src/core/openclaw/sandbox_direct.rs
new file mode 100644
index 000000000..10de333d2
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox_direct.rs
@@ -0,0 +1,126 @@
+use std::process::Stdio;
+
+use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, SandboxStatus};
+
+/// Tier 0 fallback: runs OpenClaw as a direct process on the host.
+/// This preserves the exact current behavior — no isolation.
+pub struct DirectProcessSandbox;
+
+#[async_trait::async_trait]
+impl Sandbox for DirectProcessSandbox {
+ fn name(&self) -> &str {
+ "Direct Process"
+ }
+
+ fn isolation_tier(&self) -> IsolationTier {
+ IsolationTier::None
+ }
+
+ async fn is_available(&self) -> bool {
+ true // Always available as fallback
+ }
+
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String> {
+ // Ensure the gateway service is installed (registers launchd on macOS)
+ log::info!("DirectProcessSandbox: ensuring gateway service is installed");
+ if let Ok(mut install_child) = tokio::process::Command::new("openclaw")
+ .args(["gateway", "install"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ {
+ let _ = install_child.wait().await;
+ }
+
+ // Start OpenClaw gateway via CLI
+ // 'openclaw gateway start' starts a daemon and exits immediately
+ log::info!("DirectProcessSandbox: starting gateway service");
+ let mut cmd = tokio::process::Command::new("openclaw");
+ cmd.args(["gateway", "start"])
+ .current_dir(&config.config_dir)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ for (key, value) in &config.env_vars {
+ cmd.env(key, value);
+ }
+
+ let output = cmd
+ .output()
+ .await
+ .map_err(|e| format!("Failed to run openclaw gateway start: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ log::error!(
+ "openclaw gateway start failed: stdout={}, stderr={}",
+ stdout,
+ stderr
+ );
+ return Err(format!("Failed to start OpenClaw gateway: {}", stderr));
+ }
+
+ // The gateway runs as a daemon — we track it by port, not by child PID.
+ // Return a Named handle so stop() knows which mechanism to use.
+ Ok(SandboxHandle::Named("direct-process".to_string()))
+ }
+
+ async fn stop(&self, _handle: &mut SandboxHandle) -> Result<(), String> {
+ log::info!("DirectProcessSandbox: stopping gateway");
+
+ // Try the clean CLI stop first
+ let mut stopped_via_cli = false;
+ if let Ok(mut child) = tokio::process::Command::new("openclaw")
+ .args(["gateway", "stop"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ {
+ if let Ok(status) = child.wait().await {
+ if status.success() {
+ log::info!("openclaw gateway stop command succeeded");
+ stopped_via_cli = true;
+ }
+ }
+ }
+
+ // Fallback: kill by process name
+ if !stopped_via_cli {
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
+ {
+ let _ = tokio::process::Command::new("pkill")
+ .args(["-f", "openclaw"])
+ .output()
+ .await;
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ let _ = tokio::process::Command::new("taskkill")
+ .args(["/F", "/IM", "openclaw.exe"])
+ .output()
+ .await;
+ }
+ }
+
+ Ok(())
+ }
+
+ async fn status(&self, _handle: &SandboxHandle) -> Result<SandboxStatus, String> {
+ // Check if the gateway is responding on its port
+ match tokio::net::TcpStream::connect(format!("127.0.0.1:{}", super::OPENCLAW_PORT)).await {
+ Ok(_) => Ok(SandboxStatus::Running),
+ Err(_) => Ok(SandboxStatus::Stopped),
+ }
+ }
+
+ async fn logs(&self, _handle: &SandboxHandle, _lines: usize) -> Result<Vec<String>, String> {
+ // Direct process logs go to the system's service manager (launchd, etc.)
+ // or /tmp/openclaw/. We don't capture them in-process.
+ Ok(vec![
+ "Log capture not available in direct process mode. Check /tmp/openclaw/ for logs."
+ .to_string(),
+ ])
+ }
+}
diff --git a/src-tauri/src/core/openclaw/sandbox_docker.rs b/src-tauri/src/core/openclaw/sandbox_docker.rs
new file mode 100644
index 000000000..1a07d1f38
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox_docker.rs
@@ -0,0 +1,371 @@
+/// Docker/Podman sandbox using Bollard (pure Rust Docker API client).
+///
+/// This is an optional Tier 3 sandbox — only used if Docker is already installed.
+/// Jan never prompts users to install Docker. Bollard also works with Podman's
+/// Docker-compatible socket, so this implementation covers both.
+///
+/// Security hardening (Phase 3):
+/// - cap_drop: ALL — drop all Linux capabilities
+/// - cap_add: NET_BIND_SERVICE only — minimum needed for port binding
+/// - readonly_rootfs: true — container filesystem is read-only
+/// - tmpfs at /tmp — writable scratch space (noexec, nosuid)
+/// - no-new-privileges — prevent privilege escalation via setuid binaries
+/// - pids_limit: 256 — prevent fork bombs
+/// - memory: 512MB — prevent memory exhaustion
+/// - nano_cpus: 1 CPU — prevent CPU starvation of host
+/// - seccomp profile — custom syscall allowlist loaded from resources
+///
+/// Network model: Docker uses network isolation. The config patching in
+/// `lifecycle.rs` replaces `localhost:1337` with `host.docker.internal:1337`
+/// for `IsolationTier::FullContainer`.
+#[cfg(feature = "docker")]
+use std::collections::HashMap;
+
+#[cfg(feature = "docker")]
+use bollard::container::{
+ Config, CreateContainerOptions, ListContainersOptions, LogsOptions, RemoveContainerOptions,
+ StartContainerOptions, StopContainerOptions,
+};
+#[cfg(feature = "docker")]
+use bollard::image::CreateImageOptions;
+#[cfg(feature = "docker")]
+use bollard::models::{HostConfig, PortBinding, PortMap};
+#[cfg(feature = "docker")]
+use futures::StreamExt;
+
+#[cfg(feature = "docker")]
+use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, SandboxStatus};
+
+#[cfg(feature = "docker")]
+const CONTAINER_NAME: &str = "jan-openclaw";
+
+#[cfg(feature = "docker")]
+const IMAGE_NAME: &str = "ghcr.io/janhq/openclaw:latest";
+
+#[cfg(feature = "docker")]
+pub struct DockerSandbox;
+
+#[cfg(feature = "docker")]
+impl DockerSandbox {
+ pub fn new() -> Self {
+ Self
+ }
+
+ async fn get_client() -> Result<bollard::Docker, String> {
+ bollard::Docker::connect_with_local_defaults()
+ .map_err(|e| format!("Failed to connect to Docker: {}", e))
+ }
+
+ /// Check if the jan-openclaw container already exists (running or stopped).
+ async fn container_exists(client: &bollard::Docker) -> bool {
+ let mut filters = HashMap::new();
+ filters.insert("name", vec![CONTAINER_NAME]);
+
+ let options = ListContainersOptions {
+ all: true,
+ filters,
+ ..Default::default()
+ };
+
+ match client.list_containers(Some(options)).await {
+ Ok(containers) => !containers.is_empty(),
+ Err(_) => false,
+ }
+ }
+
+ /// Check if the image exists locally.
+ async fn image_exists(client: &bollard::Docker) -> bool {
+ client.inspect_image(IMAGE_NAME).await.is_ok()
+ }
+
+ /// Load the custom seccomp profile from the resources directory.
+ /// Returns the JSON string if found, None otherwise.
+ /// The Docker daemon will use its default seccomp profile as fallback.
+ fn load_seccomp_profile() -> Option<String> {
+ // Try resource locations
+ let candidates = [
+ std::path::PathBuf::from("resources/openclaw-seccomp.json"),
+ std::path::PathBuf::from("src-tauri/resources/openclaw-seccomp.json"),
+ ];
+
+ for candidate in &candidates {
+ if let Ok(content) = std::fs::read_to_string(candidate) {
+ return Some(content);
+ }
+ }
+
+ // Try relative to current executable (production builds)
+ if let Ok(exe_path) = std::env::current_exe() {
+ if let Some(exe_dir) = exe_path.parent() {
+ let resource_path = exe_dir.join("resources/openclaw-seccomp.json");
+ if let Ok(content) = std::fs::read_to_string(&resource_path) {
+ return Some(content);
+ }
+ // macOS .app bundle
+ let bundle_path = exe_dir.join("../Resources/resources/openclaw-seccomp.json");
+ if let Ok(content) = std::fs::read_to_string(&bundle_path) {
+ return Some(content);
+ }
+ }
+ }
+
+ log::info!("DockerSandbox: seccomp profile not found, using Docker default");
+ None
+ }
+
+ /// Pull the OpenClaw image.
+ async fn pull_image(client: &bollard::Docker) -> Result<(), String> {
+ log::info!("DockerSandbox: pulling image {}", IMAGE_NAME);
+
+ let options = CreateImageOptions {
+ from_image: IMAGE_NAME,
+ ..Default::default()
+ };
+
+ let mut stream = client.create_image(Some(options), None, None);
+
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(info) => {
+ if let Some(status) = info.status {
+ log::debug!("DockerSandbox: pull: {}", status);
+ }
+ }
+ Err(e) => {
+ return Err(format!("Failed to pull image {}: {}", IMAGE_NAME, e));
+ }
+ }
+ }
+
+ log::info!("DockerSandbox: image pulled successfully");
+ Ok(())
+ }
+}
+
+#[cfg(feature = "docker")]
+#[async_trait::async_trait]
+impl Sandbox for DockerSandbox {
+ fn name(&self) -> &str {
+ "Docker"
+ }
+
+ fn isolation_tier(&self) -> IsolationTier {
+ IsolationTier::FullContainer
+ }
+
+ async fn is_available(&self) -> bool {
+ match Self::get_client().await {
+ Ok(client) => {
+ match client.ping().await {
+ Ok(_) => {
+ log::info!("DockerSandbox: Docker daemon is responsive");
+ true
+ }
+ Err(e) => {
+ log::info!("DockerSandbox: Docker ping failed: {}", e);
+ false
+ }
+ }
+ }
+ Err(e) => {
+ log::info!("DockerSandbox: {}", e);
+ false
+ }
+ }
+ }
+
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String> {
+ let client = Self::get_client().await?;
+
+ // Pull image if not present
+ if !Self::image_exists(&client).await {
+ Self::pull_image(&client).await?;
+ }
+
+ // Remove existing container if it exists (stopped from a previous run)
+ if Self::container_exists(&client).await {
+ log::info!("DockerSandbox: removing existing container '{}'", CONTAINER_NAME);
+ let _ = client
+ .remove_container(
+ CONTAINER_NAME,
+ Some(RemoveContainerOptions {
+ force: true,
+ ..Default::default()
+ }),
+ )
+ .await;
+ }
+
+ // Build port bindings: 127.0.0.1:18789 -> 18789/tcp
+ let port_key = format!("{}/tcp", config.port);
+ let mut port_bindings: PortMap = HashMap::new();
+ port_bindings.insert(
+ port_key.clone(),
+ Some(vec![PortBinding {
+ host_ip: Some("127.0.0.1".to_string()),
+ host_port: Some(config.port.to_string()),
+ }]),
+ );
+
+ // Build environment variables
+ let mut env_vars: Vec<String> = config
+ .env_vars
+ .iter()
+ .map(|(k, v)| format!("{}={}", k, v))
+ .collect();
+ // Override config path for inside the container
+ env_vars.push("OPENCLAW_CONFIG=/root/.openclaw/openclaw.json".to_string());
+
+ // Build volume bind: ~/.openclaw -> /root/.openclaw
+ let host_config_dir = config.config_dir.to_string_lossy();
+ let binds = vec![format!("{}:/root/.openclaw", host_config_dir)];
+
+ // Build extra hosts for Docker-to-host networking
+ let extra_hosts = vec!["host.docker.internal:host-gateway".to_string()];
+
+ // Security: tmpfs mount at /tmp (writable scratch, noexec)
+ let mut tmpfs = HashMap::new();
+ tmpfs.insert(
+ "/tmp".to_string(),
+ "rw,noexec,nosuid,size=65536k".to_string(),
+ );
+
+ // Security: load custom seccomp profile if available
+ let seccomp_profile = Self::load_seccomp_profile();
+ let mut security_opt = vec!["no-new-privileges".to_string()];
+ if let Some(profile_json) = seccomp_profile {
+ security_opt.push(format!("seccomp={}", profile_json));
+ log::info!("DockerSandbox: custom seccomp profile loaded");
+ }
+
+ let host_config = HostConfig {
+ port_bindings: Some(port_bindings),
+ binds: Some(binds),
+ extra_hosts: Some(extra_hosts),
+ // Security hardening
+ cap_drop: Some(vec!["ALL".to_string()]),
+ cap_add: Some(vec!["NET_BIND_SERVICE".to_string()]),
+ readonly_rootfs: Some(true),
+ tmpfs: Some(tmpfs),
+ security_opt: Some(security_opt),
+ pids_limit: Some(256),
+ memory: Some(512 * 1024 * 1024), // 512 MB in bytes
+ nano_cpus: Some(1_000_000_000), // 1 CPU
+ ..Default::default()
+ };
+
+ let mut exposed_ports = HashMap::new();
+ exposed_ports.insert(port_key, HashMap::new());
+
+ let container_config = Config {
+ image: Some(IMAGE_NAME.to_string()),
+ env: Some(env_vars),
+ exposed_ports: Some(exposed_ports),
+ host_config: Some(host_config),
+ ..Default::default()
+ };
+
+ let options = CreateContainerOptions {
+ name: CONTAINER_NAME,
+ platform: None,
+ };
+
+ log::info!("DockerSandbox: creating container '{}'", CONTAINER_NAME);
+ client
+ .create_container(Some(options), container_config)
+ .await
+ .map_err(|e| format!("Failed to create Docker container: {}", e))?;
+
+ log::info!("DockerSandbox: starting container '{}'", CONTAINER_NAME);
+ client
+ .start_container(CONTAINER_NAME, None::<StartContainerOptions<String>>)
+ .await
+ .map_err(|e| format!("Failed to start Docker container: {}", e))?;
+
+ Ok(SandboxHandle::Named(CONTAINER_NAME.to_string()))
+ }
+
+ async fn stop(&self, _handle: &mut SandboxHandle) -> Result<(), String> {
+ let client = Self::get_client().await?;
+
+ log::info!("DockerSandbox: stopping container '{}'", CONTAINER_NAME);
+
+ // Stop with a 10-second grace period
+ let _ = client
+ .stop_container(
+ CONTAINER_NAME,
+ Some(StopContainerOptions { t: 10 }),
+ )
+ .await;
+
+ // Remove the container
+ let _ = client
+ .remove_container(
+ CONTAINER_NAME,
+ Some(RemoveContainerOptions {
+ force: true,
+ ..Default::default()
+ }),
+ )
+ .await;
+
+ log::info!("DockerSandbox: container '{}' stopped and removed", CONTAINER_NAME);
+ Ok(())
+ }
+
+ async fn status(&self, _handle: &SandboxHandle) -> Result<SandboxStatus, String> {
+ let client = match Self::get_client().await {
+ Ok(c) => c,
+ Err(_) => return Ok(SandboxStatus::Unknown),
+ };
+
+ match client.inspect_container(CONTAINER_NAME, None).await {
+ Ok(info) => {
+ if let Some(state) = info.state {
+ if state.running == Some(true) {
+ return Ok(SandboxStatus::Running);
+ }
+ if let Some(error) = state.error {
+ if !error.is_empty() {
+ return Ok(SandboxStatus::Failed { error });
+ }
+ }
+ }
+ Ok(SandboxStatus::Stopped)
+ }
+ Err(_) => Ok(SandboxStatus::Stopped),
+ }
+ }
+
+ async fn logs(
+ &self,
+ _handle: &SandboxHandle,
+ lines: usize,
+ ) -> Result<Vec<String>, String> {
+ let client = Self::get_client().await?;
+
+ let options = LogsOptions::<String> {
+ stdout: true,
+ stderr: true,
+ tail: lines.to_string(),
+ ..Default::default()
+ };
+
+ let mut stream = client.logs(CONTAINER_NAME, Some(options));
+ let mut log_lines = Vec::new();
+
+ while let Some(result) = stream.next().await {
+ match result {
+ Ok(output) => {
+ log_lines.push(output.to_string());
+ }
+ Err(e) => {
+ log::warn!("DockerSandbox: error reading logs: {}", e);
+ break;
+ }
+ }
+ }
+
+ Ok(log_lines)
+ }
+}
diff --git a/src-tauri/src/core/openclaw/sandbox_native.rs b/src-tauri/src/core/openclaw/sandbox_native.rs
new file mode 100644
index 000000000..c37ec2025
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox_native.rs
@@ -0,0 +1,278 @@
+/// Linux namespace-based sandbox using the `unshare` command.
+///
+/// Provides PID and mount namespace isolation — the same primitives that
+/// bubblewrap and Docker use under the hood. For the initial implementation
+/// we shell out to `unshare(1)` which is available on every modern Linux
+/// distribution. A future iteration can replace this with direct `nix::sched`
+/// syscalls for tighter control.
+///
+/// Security hardening (Phase 3):
+/// - PR_SET_NO_NEW_PRIVS: prevents privilege escalation via setuid binaries
+/// - PR_SET_DUMPABLE(0): prevents core dumps that could leak secrets
+/// - Resource limits via setrlimit: memory (RLIMIT_AS), CPU time, max PIDs, open files
+/// - PDEATHSIG: child receives SIGTERM when parent dies (prevents orphan processes)
+#[cfg(target_os = "linux")]
+use std::process::Stdio;
+
+#[cfg(target_os = "linux")]
+use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, SandboxStatus};
+
+/// Default memory limit: 512 MB
+#[cfg(target_os = "linux")]
+const DEFAULT_MEMORY_LIMIT_BYTES: u64 = 512 * 1024 * 1024;
+
+/// Default max open file descriptors
+#[cfg(target_os = "linux")]
+const DEFAULT_NOFILE_LIMIT: u64 = 4096;
+
+/// Default max processes (NPROC)
+#[cfg(target_os = "linux")]
+const DEFAULT_NPROC_LIMIT: u64 = 256;
+
+/// Default max core dump size: 0 (disabled)
+#[cfg(target_os = "linux")]
+const DEFAULT_CORE_LIMIT: u64 = 0;
+
+#[cfg(target_os = "linux")]
+pub struct NativeSandbox;
+
+#[cfg(target_os = "linux")]
+impl NativeSandbox {
+ /// Check whether unprivileged user namespaces are available.
+ /// Required for rootless namespace creation.
+ async fn check_user_namespace_support() -> bool {
+ // Method 1: check the sysctl (Debian/Ubuntu)
+ if let Ok(content) =
+ tokio::fs::read_to_string("/proc/sys/kernel/unprivileged_userns_clone").await
+ {
+ if content.trim() == "0" {
+ log::info!("User namespaces disabled via sysctl");
+ return false;
+ }
+ }
+ // If the file doesn't exist, the kernel doesn't gate it (newer kernels)
+
+ // Method 2: check that unshare(1) exists
+ if let Ok(output) = tokio::process::Command::new("unshare")
+ .arg("--help")
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .output()
+ .await
+ {
+ if !output.status.success() {
+ log::info!("unshare command not found");
+ return false;
+ }
+ } else {
+ return false;
+ }
+
+ true
+ }
+
+ /// Apply resource limits to a child process via setrlimit.
+ /// Called in the pre_exec hook (runs in the child before exec).
+ ///
+ /// # Safety
+ /// This function uses nix::sys::resource::setrlimit which is safe to call
+ /// in a pre_exec context (async-signal-safe).
+ fn apply_resource_limits() -> Result<(), String> {
+ use nix::sys::resource::{setrlimit, Resource};
+
+ // Memory limit (virtual address space)
+ setrlimit(
+ Resource::RLIMIT_AS,
+ DEFAULT_MEMORY_LIMIT_BYTES,
+ DEFAULT_MEMORY_LIMIT_BYTES,
+ )
+ .map_err(|e| format!("Failed to set RLIMIT_AS: {}", e))?;
+
+ // Max open file descriptors
+ setrlimit(
+ Resource::RLIMIT_NOFILE,
+ DEFAULT_NOFILE_LIMIT,
+ DEFAULT_NOFILE_LIMIT,
+ )
+ .map_err(|e| format!("Failed to set RLIMIT_NOFILE: {}", e))?;
+
+ // Max number of processes
+ setrlimit(
+ Resource::RLIMIT_NPROC,
+ DEFAULT_NPROC_LIMIT,
+ DEFAULT_NPROC_LIMIT,
+ )
+ .map_err(|e| format!("Failed to set RLIMIT_NPROC: {}", e))?;
+
+ // Disable core dumps (prevent secret leakage)
+ setrlimit(Resource::RLIMIT_CORE, DEFAULT_CORE_LIMIT, DEFAULT_CORE_LIMIT)
+ .map_err(|e| format!("Failed to set RLIMIT_CORE: {}", e))?;
+
+ Ok(())
+ }
+}
+
+#[cfg(target_os = "linux")]
+#[async_trait::async_trait]
+impl Sandbox for NativeSandbox {
+ fn name(&self) -> &str {
+ "Linux Namespaces"
+ }
+
+ fn isolation_tier(&self) -> IsolationTier {
+ IsolationTier::PlatformSandbox
+ }
+
+ async fn is_available(&self) -> bool {
+ Self::check_user_namespace_support().await
+ }
+
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String> {
+ log::info!("NativeSandbox: starting OpenClaw in PID+mount namespace (hardened)");
+
+ // Build the unshare command:
+ // --pid --fork : new PID namespace, fork so child is PID 1
+ // --mount-proc : mount a fresh /proc inside the namespace
+ // --map-root-user : map current user to root inside the namespace
+ //
+ // We intentionally do NOT use --net (network namespace) because OpenClaw
+ // needs to reach both the Jan API on localhost and external messaging APIs.
+ // Network isolation can be added later with a veth pair.
+ let mut cmd = tokio::process::Command::new("unshare");
+ cmd.args(["--pid", "--fork", "--mount-proc", "--map-root-user", "--"])
+ .args(["openclaw", "gateway", "start"])
+ .current_dir(&config.config_dir)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ for (key, value) in &config.env_vars {
+ cmd.env(key, value);
+ }
+
+ // Security hardening: pre_exec hook runs in the child process before exec.
+ // This is the standard pattern for setting up child process security.
+ //
+ // SAFETY: The closures called here (prctl, setrlimit) are async-signal-safe
+ // and do not allocate or call non-reentrant functions.
+ unsafe {
+ cmd.pre_exec(|| {
+ // 1. PR_SET_NO_NEW_PRIVS: prevent privilege escalation via setuid binaries.
+ // Once set, this is irreversible — exactly what we want for a sandbox.
+ if let Err(e) = nix::sys::prctl::set_no_new_privs() {
+ // Log to stderr since logging framework may not be available in child
+ eprintln!("NativeSandbox: failed to set NO_NEW_PRIVS: {}", e);
+ // Non-fatal: continue without this hardening
+ }
+
+ // 2. PR_SET_DUMPABLE(0): prevent core dumps that could leak secrets
+ // (tokens, session data, etc.)
+ let _ = libc::prctl(libc::PR_SET_DUMPABLE, 0);
+
+ // 3. PDEATHSIG: receive SIGTERM when parent (Jan) dies.
+ // Prevents orphan sandbox processes if Jan crashes.
+ let _ = nix::sys::prctl::set_pdeathsig(nix::sys::signal::Signal::SIGTERM);
+
+ // 4. Resource limits: constrain memory, file descriptors, processes
+ if let Err(e) = NativeSandbox::apply_resource_limits() {
+ eprintln!("NativeSandbox: resource limit warning: {}", e);
+ // Non-fatal: continue without resource limits
+ }
+
+ Ok(())
+ });
+ }
+
+ let child = cmd
+ .spawn()
+ .map_err(|e| format!("Failed to spawn sandboxed OpenClaw: {}", e))?;
+
+ let pid = child
+ .id()
+ .ok_or_else(|| "Failed to get PID of sandboxed process".to_string())?;
+
+ log::info!(
+ "NativeSandbox: spawned with PID {} (NO_NEW_PRIVS, resource limits applied)",
+ pid
+ );
+ Ok(SandboxHandle::Pid(pid))
+ }
+
+ async fn stop(&self, handle: &mut SandboxHandle) -> Result<(), String> {
+ if let SandboxHandle::Pid(pid) = handle {
+ log::info!("NativeSandbox: stopping PID {}", pid);
+
+ // Send SIGTERM first
+ let term_result = nix::sys::signal::kill(
+ nix::unistd::Pid::from_raw(*pid as i32),
+ nix::sys::signal::Signal::SIGTERM,
+ );
+
+ if let Err(e) = term_result {
+ // ESRCH means process already gone — not an error
+ if e != nix::errno::Errno::ESRCH {
+ log::warn!("NativeSandbox: SIGTERM failed: {}", e);
+ }
+ return Ok(());
+ }
+
+ // Wait up to 5 seconds for graceful shutdown
+ for _ in 0..10 {
+ tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
+ let still_alive = nix::sys::signal::kill(
+ nix::unistd::Pid::from_raw(*pid as i32),
+ None, // signal 0: just check if process exists
+ );
+ if still_alive.is_err() {
+ log::info!("NativeSandbox: process {} terminated gracefully", pid);
+ return Ok(());
+ }
+ }
+
+ // Force kill
+ log::warn!(
+ "NativeSandbox: process {} did not exit gracefully, sending SIGKILL",
+ pid
+ );
+ let _ = nix::sys::signal::kill(
+ nix::unistd::Pid::from_raw(*pid as i32),
+ nix::sys::signal::Signal::SIGKILL,
+ );
+ }
+
+ Ok(())
+ }
+
+ async fn status(&self, handle: &SandboxHandle) -> Result<SandboxStatus, String> {
+ if let SandboxHandle::Pid(pid) = handle {
+ // Check if the process is still alive
+ let alive = nix::sys::signal::kill(
+ nix::unistd::Pid::from_raw(*pid as i32),
+ None, // signal 0
+ );
+
+ if alive.is_ok() {
+ // Process exists, also verify port is responding
+ match tokio::net::TcpStream::connect(format!(
+ "127.0.0.1:{}",
+ super::OPENCLAW_PORT
+ ))
+ .await
+ {
+ Ok(_) => Ok(SandboxStatus::Running),
+ Err(_) => Ok(SandboxStatus::Running), // Process alive but port not ready yet
+ }
+ } else {
+ Ok(SandboxStatus::Stopped)
+ }
+ } else {
+ Ok(SandboxStatus::Unknown)
+ }
+ }
+
+ async fn logs(&self, _handle: &SandboxHandle, _lines: usize) -> Result<Vec<String>, String> {
+ // TODO: capture stdout/stderr to a log file during start()
+ Ok(vec![
+ "Log capture for namespace sandbox is not yet implemented. Check /tmp/openclaw/ for logs.".to_string(),
+ ])
+ }
+}
diff --git a/src-tauri/src/core/openclaw/sandbox_wsl2.rs b/src-tauri/src/core/openclaw/sandbox_wsl2.rs
new file mode 100644
index 000000000..3be4e8211
--- /dev/null
+++ b/src-tauri/src/core/openclaw/sandbox_wsl2.rs
@@ -0,0 +1,365 @@
+/// WSL2-based sandbox for Windows.
+///
+/// Uses the `wsl` CLI to manage a dedicated "Jan.OpenClaw" WSL2 distribution.
+/// The distribution runs a minimal Linux environment with OpenClaw installed.
+/// WSL2 provides VM-level isolation (separate Linux kernel in Hyper-V).
+///
+/// Security hardening (Phase 3):
+/// - Non-root user: OpenClaw runs as `openclaw` user (UID 1001) inside the distro
+/// - Resource limits: ulimit -v (memory), ulimit -n (files), ulimit -u (procs)
+/// - WSL2 already provides VM-level isolation (Hyper-V lightweight VM)
+/// - Users can further limit resources via .wslconfig (memory, processors)
+///
+/// Network model: WSL2 default NAT mode — the guest can reach the Windows host
+/// via `localhost`, so Jan's API at `localhost:1337` is accessible without
+/// config patching.
+#[cfg(target_os = "windows")]
+use std::process::Stdio;
+
+#[cfg(target_os = "windows")]
+use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, SandboxStatus};
+
+#[cfg(target_os = "windows")]
+const DISTRO_NAME: &str = "Jan.OpenClaw";
+
+#[cfg(target_os = "windows")]
+pub struct Wsl2Sandbox {
+ distro_name: String,
+}
+
+#[cfg(target_os = "windows")]
+impl Wsl2Sandbox {
+ pub fn new() -> Self {
+ Self {
+ distro_name: DISTRO_NAME.to_string(),
+ }
+ }
+
+ /// Check if WSL2 is available by probing wslapi.dll and running wsl --status.
+ async fn check_wsl2_available() -> bool {
+ // Step 1: Verify wslapi.dll exists (means WSL feature is installed)
+ if unsafe { libloading::Library::new("wslapi.dll") }.is_err() {
+ log::info!("Wsl2Sandbox: wslapi.dll not available");
+ return false;
+ }
+
+ // Step 2: Verify WSL2 is functional by running wsl --status
+ match tokio::process::Command::new("wsl")
+ .args(["--status"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ {
+ Ok(output) => {
+ if !output.status.success() {
+ log::info!("Wsl2Sandbox: wsl --status failed");
+ return false;
+ }
+ true
+ }
+ Err(e) => {
+ log::info!("Wsl2Sandbox: failed to run wsl --status: {}", e);
+ false
+ }
+ }
+ }
+
+ /// Check if the Jan.OpenClaw distribution is registered.
+ async fn is_distro_registered(&self) -> bool {
+ match tokio::process::Command::new("wsl")
+ .args(["--list", "--quiet"])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ {
+ Ok(output) => {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ stdout
+ .lines()
+ .any(|line| line.trim() == self.distro_name)
+ }
+ Err(_) => false,
+ }
+ }
+
+ /// Get the installation directory for the WSL2 distro.
+ fn install_dir(&self) -> std::path::PathBuf {
+ dirs::data_dir()
+ .unwrap_or_else(|| std::path::PathBuf::from("C:\\"))
+ .join("Jan")
+ .join("wsl")
+ .join(&self.distro_name)
+ }
+
+ /// Get the expected rootfs path from Tauri resources.
+ fn rootfs_path(&self) -> std::path::PathBuf {
+ // The rootfs tar.gz is expected in the resources/wsl/ directory.
+ // This is a build-time artifact — if not present, start() fails gracefully.
+ std::path::PathBuf::from("resources")
+ .join("wsl")
+ .join("jan-openclaw-rootfs.tar.gz")
+ }
+
+ /// Register the distro from a rootfs tar.gz.
+ async fn register_distro(&self, rootfs_path: &std::path::Path) -> Result<(), String> {
+ let install_dir = self.install_dir();
+ std::fs::create_dir_all(&install_dir)
+ .map_err(|e| format!("Failed to create WSL install dir: {}", e))?;
+
+ let output = tokio::process::Command::new("wsl")
+ .args([
+ "--import",
+ &self.distro_name,
+ &install_dir.to_string_lossy(),
+ &rootfs_path.to_string_lossy(),
+ "--version",
+ "2",
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to register WSL2 distro: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("WSL2 distro registration failed: {}", stderr));
+ }
+
+ log::info!(
+ "Wsl2Sandbox: registered distro '{}' from {:?}",
+ self.distro_name,
+ rootfs_path
+ );
+ Ok(())
+ }
+
+ /// Set up security inside the distro after import.
+ /// Creates a non-root `openclaw` user (UID 1001) and sets it as the default user.
+ async fn setup_distro_security(&self) -> Result<(), String> {
+ // Create the openclaw user if it doesn't exist
+ let setup_script = concat!(
+ "id -u openclaw >/dev/null 2>&1 || ",
+ "(addgroup -g 1001 openclaw 2>/dev/null || true; ",
+ "adduser -u 1001 -G openclaw -s /bin/sh -D openclaw 2>/dev/null || true; ",
+ "mkdir -p /home/openclaw/.openclaw; ",
+ "chown -R openclaw:openclaw /home/openclaw)"
+ );
+
+ let output = tokio::process::Command::new("wsl")
+ .args([
+ "-d",
+ &self.distro_name,
+ "--user",
+ "root",
+ "--",
+ "sh",
+ "-c",
+ setup_script,
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to setup distro security: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ log::warn!(
+ "Wsl2Sandbox: security setup had warnings (non-fatal): {}",
+ stderr
+ );
+ }
+
+ log::info!(
+ "Wsl2Sandbox: security setup complete for distro '{}'",
+ self.distro_name
+ );
+ Ok(())
+ }
+
+ /// Convert a Windows path to a WSL-compatible path.
+ /// e.g., C:\Users\foo\.openclaw -> /mnt/c/Users/foo/.openclaw
+ fn windows_to_wsl_path(win_path: &std::path::Path) -> String {
+ let path_str = win_path.to_string_lossy();
+ // Replace backslashes with forward slashes
+ let unix_path = path_str.replace('\\', "/");
+ // Convert drive letter: C:/... -> /mnt/c/...
+ if unix_path.len() >= 2 && unix_path.as_bytes()[1] == b':' {
+ let drive = unix_path.as_bytes()[0].to_ascii_lowercase() as char;
+ format!("/mnt/{}/{}", drive, &unix_path[3..])
+ } else {
+ unix_path
+ }
+ }
+}
+
+#[cfg(target_os = "windows")]
+#[async_trait::async_trait]
+impl Sandbox for Wsl2Sandbox {
+ fn name(&self) -> &str {
+ "WSL2"
+ }
+
+ fn isolation_tier(&self) -> IsolationTier {
+ IsolationTier::PlatformSandbox
+ }
+
+ async fn is_available(&self) -> bool {
+ Self::check_wsl2_available().await
+ }
+
+ async fn start(&self, config: &SandboxConfig) -> Result<SandboxHandle, String> {
+ log::info!(
+ "Wsl2Sandbox: starting OpenClaw in WSL2 distro '{}' (hardened)",
+ self.distro_name
+ );
+
+ // Register distro if not already present
+ if !self.is_distro_registered().await {
+ let rootfs = self.rootfs_path();
+ if !rootfs.exists() {
+ return Err(format!(
+ "WSL2 rootfs not found at {:?}. \
+ The WSL2 sandbox requires a bundled rootfs which is not yet available. \
+ Falling back to direct process mode.",
+ rootfs
+ ));
+ }
+ self.register_distro(&rootfs).await?;
+ }
+
+ // Security: set up non-root user inside the distro
+ if let Err(e) = self.setup_distro_security().await {
+ log::warn!("Wsl2Sandbox: security setup failed (non-fatal): {}", e);
+ }
+
+ // Convert the host config dir to a WSL-compatible path
+ let wsl_config_dir = Self::windows_to_wsl_path(&config.config_dir);
+
+ // Start OpenClaw inside the WSL2 distro as non-root user with resource limits.
+ // The sh -c wrapper applies ulimit constraints before launching openclaw:
+ // ulimit -v 524288 : virtual memory limit (512 MB in KB)
+ // ulimit -n 4096 : max open file descriptors
+ // ulimit -u 256 : max user processes
+ // ulimit -c 0 : disable core dumps
+ let start_script = format!(
+ "ulimit -v 524288; ulimit -n 4096; ulimit -u 256; ulimit -c 0; \
+ export OPENCLAW_CONFIG='{}/openclaw.json'; \
+ exec openclaw gateway start",
+ wsl_config_dir
+ );
+
+ let mut cmd = tokio::process::Command::new("wsl");
+ cmd.args([
+ "-d",
+ &self.distro_name,
+ "--user",
+ "openclaw",
+ "--",
+ "sh",
+ "-c",
+ &start_script,
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ // Pass environment variables
+ for (key, value) in &config.env_vars {
+ cmd.env(key, value);
+ }
+
+ let output = cmd
+ .output()
+ .await
+ .map_err(|e| format!("Failed to start OpenClaw in WSL2: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!("OpenClaw start in WSL2 failed: {}", stderr));
+ }
+
+ log::info!(
+ "Wsl2Sandbox: OpenClaw started in distro '{}' as user 'openclaw'",
+ self.distro_name
+ );
+ Ok(SandboxHandle::Named(self.distro_name.clone()))
+ }
+
+ async fn stop(&self, _handle: &mut SandboxHandle) -> Result<(), String> {
+ log::info!("Wsl2Sandbox: terminating distro '{}'", self.distro_name);
+
+ // First try to gracefully stop OpenClaw inside the distro
+ let _ = tokio::process::Command::new("wsl")
+ .args([
+ "-d",
+ &self.distro_name,
+ "--",
+ "openclaw",
+ "gateway",
+ "stop",
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await;
+
+ // Then terminate the entire distro
+ let output = tokio::process::Command::new("wsl")
+ .args(["--terminate", &self.distro_name])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to terminate WSL2 distro: {}", e))?;
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ log::warn!("Wsl2Sandbox: terminate returned error: {}", stderr);
+ }
+
+ Ok(())
+ }
+
+ async fn status(&self, _handle: &SandboxHandle) -> Result<SandboxStatus, String> {
+ // Check if the gateway is responding on its port
+ match tokio::net::TcpStream::connect(format!("127.0.0.1:{}", super::OPENCLAW_PORT)).await {
+ Ok(_) => Ok(SandboxStatus::Running),
+ Err(_) => Ok(SandboxStatus::Stopped),
+ }
+ }
+
+ async fn logs(
+ &self,
+ _handle: &SandboxHandle,
+ lines: usize,
+ ) -> Result<Vec<String>, String> {
+ let output = tokio::process::Command::new("wsl")
+ .args([
+ "-d",
+ &self.distro_name,
+ "--",
+ "tail",
+ "-n",
+ &lines.to_string(),
+ "/tmp/openclaw/gateway.log",
+ ])
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to read WSL2 logs: {}", e))?;
+
+ if output.status.success() {
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ Ok(stdout.lines().map(String::from).collect())
+ } else {
+ Ok(vec![
+ "Log retrieval from WSL2 distro failed. Check /tmp/openclaw/ inside the distro."
+ .to_string(),
+ ])
+ }
+ }
+}
diff --git a/src-tauri/src/core/openclaw/security.rs b/src-tauri/src/core/openclaw/security.rs
index 5378af03e..016c4e4ea 100644
--- a/src-tauri/src/core/openclaw/security.rs
+++ b/src-tauri/src/core/openclaw/security.rs
@@ -10,6 +10,55 @@ use uuid::Uuid;
use super::get_openclaw_config_dir;
use super::models::{AccessLogEntry, DeviceInfo, SecurityConfig};
+#[cfg(unix)]
+use std::os::unix::fs::PermissionsExt;
+
+/// Checks and fixes permissions on the OpenClaw config directory.
+///
+/// Ensures the config directory has restrictive permissions (700) to prevent
+/// unauthorized access to sensitive files like security tokens and credentials.
+/// This is called before starting any sandbox to ensure the config is secure.
+pub async fn ensure_secure_config_permissions(config_dir: &std::path::Path) -> Result<(), String> {
+ #[cfg(unix)]
+ {
+ // Ensure the config directory exists
+ if !config_dir.exists() {
+ tokio::fs::create_dir_all(config_dir)
+ .await
+ .map_err(|e| format!("Failed to create config dir: {}", e))?;
+ }
+
+ let metadata = tokio::fs::metadata(config_dir)
+ .await
+ .map_err(|e| format!("Cannot stat config dir: {}", e))?;
+
+ let mode = metadata.permissions().mode() & 0o777;
+
+ // Check if group/other have any permissions
+ if mode & 0o077 != 0 {
+ let mut perms = metadata.permissions();
+ perms.set_mode(0o700);
+ tokio::fs::set_permissions(config_dir, perms)
+ .await
+ .map_err(|e| format!("Cannot fix config dir permissions: {}", e))?;
+ log::info!("Fixed ~/.openclaw permissions to 700");
+ }
+ }
+
+ #[cfg(not(unix))]
+ {
+ // On non-Unix systems (Windows), we don't have the same permission model
+ // but we still ensure the directory exists
+ if !config_dir.exists() {
+ tokio::fs::create_dir_all(config_dir)
+ .await
+ .map_err(|e| format!("Failed to create config dir: {}", e))?;
+ }
+ }
+
+ Ok(())
+}
+
/// Maximum number of access log entries to keep
const MAX_ACCESS_LOG_ENTRIES: usize = 1000;