Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: docker commands to spawn the correct container
Vanalitea3f782f873b7
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rsindex a93506411..48601fb04 100644--- a/src-tauri/src/core/openclaw/commands.rs+++ b/src-tauri/src/core/openclaw/commands.rs@@ -798,9 +798,10 @@ pub async fn openclaw_install() -> Result<InstallResult, String> {});}- // Run npm install -g @openclaw/openclaw+ // Run npm install -g openclaw@<pinned-version>+ let pinned_package = format!("{}@{}", OPENCLAW_PACKAGE_NAME, OPENCLAW_VERSION);let child = Command::new("npm")- .args(["install", "-g", OPENCLAW_PACKAGE_NAME])+ .args(["install", "-g", &pinned_package]).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()@@ -911,53 +912,9 @@ pub async fn openclaw_install() -> Result<InstallResult, String> {let _ = child.wait().await;}- // ============================================- // Auto-start the Gateway- // ============================================- log::info!("Auto-starting OpenClaw Gateway");-- // First install the gateway service (required for fresh install)- // This registers the launchd service on macOS- if let Ok(mut child) = Command::new("openclaw")- .args(["gateway", "install"])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- {- let _ = child.wait().await;- }-- // Use 'openclaw gateway start' CLI to start the gateway- let start_result = Command::new("openclaw")- .args(["gateway", "start"])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn();-- match start_result {- Ok(mut child) => {- // Wait for the command to complete- match child.wait().await {- Ok(status) => {- if status.success() {- log::info!("OpenClaw Gateway started successfully");- } else {- log::warn!("openclaw gateway start returned non-zero status");- }- }- Err(e) => {- log::warn!("Failed to wait for gateway start: {}", e);- }- }- }- Err(e) => {- log::warn!("Failed to start Gateway: {}", e);- // Don't fail the install, the user can start it manually- }- }-- // Give the gateway a moment to start responding- tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;+ // NOTE: Gateway is NOT auto-started here. It is started by openclaw_start()+ // via the sandbox abstraction (Docker, platform-native, or direct process).+ // Auto-starting here would conflict with Docker sandbox mode.Ok(InstallResult {success: true,@@ -980,12 +937,6 @@ fn generate_default_config(input: Option<OpenClawConfigInput>) -> OpenClawConfigif let Some(base_url) = input.jan_base_url {config.models.providers.jan.base_url = base_url;}- if let Some(model_id) = input.model_id {- config.agents.defaults.model.primary = model_id;- }- if let Some(system_prompt) = input.system_prompt {- config.agents.defaults.system_prompt = system_prompt;- }}config@@ -1092,15 +1043,52 @@ pub async fn openclaw_ensure_jan_origin() -> Result<bool, String> {Ok(modified)}-/// Configure OpenClaw with the specified settings+/// Configure OpenClaw with the specified settings.+/// If a config file already exists, merges gateway + models defaults without+/// destroying other valid sections (agents, channels, plugins, etc.).+/// Also strips any known-invalid keys that would cause OpenClaw to reject the config.#[tauri::command]pub async fn openclaw_configure(config_input: Option<OpenClawConfigInput>) -> Result<OpenClawConfig, String> {log::info!("Configuring OpenClaw");let config = generate_default_config(config_input);-let config_path = get_openclaw_config_path()?;- let config_json = serde_json::to_string_pretty(&config)++ // Serialize the defaults as a JSON Value for merging+ let defaults: serde_json::Value = serde_json::to_value(&config)+ .map_err(|e| format!("Failed to serialize config: {}", e))?;++ let mut merged = if config_path.exists() {+ // Merge with existing config to preserve agents, channels, etc.+ let existing_str = std::fs::read_to_string(&config_path)+ .map_err(|e| format!("Failed to read existing config: {}", e))?;+ let mut existing: serde_json::Value = serde_json::from_str(&existing_str)+ .unwrap_or_else(|_| serde_json::json!({}));++ // Update gateway and models from defaults (these are the Jan-managed sections)+ if let Some(gw) = defaults.get("gateway") {+ existing["gateway"] = gw.clone();+ }+ if let Some(models) = defaults.get("models") {+ // Preserve existing model list if present, only set defaults if missing+ if existing.get("models").is_none() {+ existing["models"] = models.clone();+ } else {+ // Ensure provider structure exists but keep existing model definitions+ if existing.pointer("/models/providers/jan").is_none() {+ existing["models"]["providers"]["jan"] = models["providers"]["jan"].clone();+ }+ }+ }+ existing+ } else {+ defaults+ };++ // Strip known-invalid keys that OpenClaw rejects (strict Zod validation)+ strip_invalid_config_keys(&mut merged);++ let config_json = serde_json::to_string_pretty(&merged).map_err(|e| format!("Failed to serialize config: {}", e))?;std::fs::write(&config_path, config_json)@@ -1110,6 +1098,19 @@ pub async fn openclaw_configure(config_input: Option<OpenClawConfigInput>) -> ReOk(config)}+/// Strip known-invalid keys from an OpenClaw config.+/// OpenClaw uses strict Zod validation — unknown keys cause the gateway to refuse to start.+fn strip_invalid_config_keys(config: &mut serde_json::Value) {+ // agents.defaults.systemPrompt is NOT a valid key (system prompts come from workspace files)+ if let Some(defaults) = config.pointer_mut("/agents/defaults") {+ if let Some(obj) = defaults.as_object_mut() {+ if obj.remove("systemPrompt").is_some() {+ log::info!("Stripped invalid key: agents.defaults.systemPrompt");+ }+ }+ }+}+/// Get the current OpenClaw configuration#[tauri::command]pub async fn openclaw_get_config() -> Result<OpenClawConfig, String> {@@ -1127,13 +1128,29 @@ pub async fn openclaw_get_config() -> Result<OpenClawConfig, String> {.map_err(|e| format!("Failed to parse config: {}", e))}+/// Read the OpenClaw config file as a JSON Value.+/// Preserves all fields including unknown ones.+fn read_openclaw_config() -> Result<serde_json::Value, String> {+ let config_path = get_openclaw_config_path()?;+ let content = std::fs::read_to_string(&config_path)+ .map_err(|e| format!("Failed to read OpenClaw config: {}", e))?;+ serde_json::from_str(&content)+ .map_err(|e| format!("Failed to parse OpenClaw config: {}", e))+}++/// Write a JSON Value back to the OpenClaw config file.+fn write_openclaw_config(config: &serde_json::Value) -> Result<(), String> {+ let config_path = get_openclaw_config_path()?;+ let json = serde_json::to_string_pretty(config)+ .map_err(|e| format!("Failed to serialize config: {}", e))?;+ std::fs::write(&config_path, json)+ .map_err(|e| format!("Failed to write config: {}", e))+}+/// Sync the selected model from Jan to OpenClaw////// This updates OpenClaw's agent default model to match Jan's currently selected model.-/// It does three things:-/// 1. Ensures the "jan" provider exists pointing to localhost:1337-/// 2. Adds/updates the model in the jan provider's model list-/// 3. Sets the model as the default using `openclaw models set` (no restart needed)+/// Works for both Docker and direct process modes by writing directly to the config file.#[tauri::command]pub async fn openclaw_sync_model(model_id: String,@@ -1142,19 +1159,15 @@ pub async fn openclaw_sync_model() -> Result<(), String> {log::info!("Syncing model to OpenClaw: {} (provider: {:?})", model_id, provider);- // Format the model ID for OpenClaw- // For the jan provider, we use "jan/<model_id>" format- let openclaw_model_id = format!("jan/{}", model_id);let display_name = model_name.unwrap_or_else(|| model_id.clone());// Determine context window based on provider typelet context_window = if provider.as_deref() == Some("llamacpp") || provider.as_deref() == Some("mlx") {- 16000 // Local models typically have smaller context+ 16000} else {- 128000 // Remote providers usually have larger context+ 128000};- // Create a model definition for OpenClawlet model_def = serde_json::json!({"id": model_id,"name": display_name,@@ -1165,155 +1178,49 @@ pub async fn openclaw_sync_model("maxTokens": 4096});- // Check if jan provider exists- let check_output = Command::new("openclaw")- .args(["config", "get", "models.providers.jan"])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;+ // Read, modify, write the config directly (works for both Docker and direct process)+ let mut config = read_openclaw_config()?;- let jan_provider_exists = check_output- .as_ref()- .map(|o| o.status.success())- .unwrap_or(false);+ // Ensure models.providers.jan exists+ if config.pointer("/models/providers/jan").is_none() {+ // Read the current baseUrl to preserve Docker vs direct process setting+ let current_base_url = config+ .pointer("/models/providers/jan/baseUrl")+ .and_then(|v| v.as_str())+ .unwrap_or(DEFAULT_JAN_BASE_URL);- if !jan_provider_exists {- // Create the jan provider pointing to local Jan API- log::info!("Creating 'jan' provider in OpenClaw config");- let jan_provider = serde_json::json!({- "baseUrl": "http://localhost:1337/v1",- "api": "openai-completions",+ config["models"]["providers"]["jan"] = serde_json::json!({+ "baseUrl": current_base_url,+ "api": DEFAULT_JAN_API_TYPE,"authHeader": false,"apiKey": "not-needed","models": [model_def]});-- let create_output = Command::new("openclaw")- .args([- "config",- "set",- "models.providers.jan",- &jan_provider.to_string(),- ])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;-- if let Ok(output) = create_output {- if !output.status.success() {- log::warn!("Failed to create jan provider: {:?}", String::from_utf8_lossy(&output.stderr));- }- }} else {- // Jan provider exists, update the models list with this model- log::debug!("Jan provider exists, updating model list");-- // Get current models- let models_output = Command::new("openclaw")- .args(["config", "get", "models.providers.jan.models"])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;-- if let Ok(output) = models_output {- if output.status.success() {- let stdout = String::from_utf8_lossy(&output.stdout);- if let Ok(mut models) = serde_json::from_str::<Vec<serde_json::Value>>(stdout.trim()) {- // Check if model already exists- let model_exists = models.iter().any(|m| {- m.get("id").and_then(|v| v.as_str()) == Some(&model_id)- });-- if !model_exists {- // Add the new model- models.push(model_def);- let models_json = serde_json::to_string(&models).unwrap_or_default();-- let _ = Command::new("openclaw")- .args([- "config",- "set",- "models.providers.jan.models",- &models_json,- ])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;- }- }+ // Add model to existing list if not already present+ let models = config+ .pointer_mut("/models/providers/jan/models")+ .and_then(|v| v.as_array_mut());++ if let Some(models) = models {+ let model_exists = models.iter().any(|m| {+ m.get("id").and_then(|v| v.as_str()) == Some(&model_id)+ });+ if !model_exists {+ models.push(model_def);}}}- // Use `openclaw models set` to change the default model- // This updates the default for new sessions- let output = Command::new("openclaw")- .args(["models", "set", &openclaw_model_id])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await- .map_err(|e| format!("Failed to run openclaw models set: {}", e))?;-- let stderr = String::from_utf8_lossy(&output.stderr);- let stdout = String::from_utf8_lossy(&output.stdout);-- log::info!("OpenClaw config set output: {}", stdout);- if !stderr.is_empty() {- log::debug!("OpenClaw config set stderr: {}", stderr);- }-- if !output.status.success() {- return Err(format!(- "Failed to set OpenClaw model: {}",- if !stderr.is_empty() { stderr.to_string() } else { stdout.to_string() }- ));- }+ // Set as default model+ config["agents"]["defaults"]["model"]["primary"] = serde_json::json!(model_id);- // Now update active sessions to use the new model- // Get list of active sessions (updated in last 24 hours)- let sessions_output = Command::new("openclaw")- .args(["sessions", "--json", "--active", "1440"]) // Last 24 hours- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;+ // Clean up any invalid keys before writing+ strip_invalid_config_keys(&mut config);- if let Ok(sessions_result) = sessions_output {- if sessions_result.status.success() {- let sessions_json = String::from_utf8_lossy(&sessions_result.stdout);- // Parse the sessions response - it's an object with a "sessions" array- if let Ok(sessions_response) = serde_json::from_str::<serde_json::Value>(&sessions_json) {- if let Some(sessions) = sessions_response.get("sessions").and_then(|v| v.as_array()) {- // Send /model command to each active session- for session in sessions {- if let Some(session_id) = session.get("sessionId").and_then(|v| v.as_str()) {- let model_cmd = format!("/model {}", openclaw_model_id);- log::debug!("Switching model for session {}: {}", session_id, model_cmd);-- // Fire and forget - don't wait for response- let session_id_clone = session_id.to_string();- let model_cmd_clone = model_cmd.clone();- tokio::spawn(async move {- let _ = Command::new("openclaw")- .args(["agent", "--session-id", &session_id_clone, "--message", &model_cmd_clone])- .stdout(Stdio::null())- .stderr(Stdio::null())- .output()- .await;- });- }- }- }- }- }- }+ write_openclaw_config(&config)?;- log::info!("Successfully synced model '{}' to OpenClaw", openclaw_model_id);+ log::info!("Successfully synced model '{}' to OpenClaw config", model_id);Ok(())}@@ -1362,63 +1269,38 @@ pub async fn openclaw_sync_all_models(let synced_count = model_defs.len() as u32;+ // Read, modify, write the config directly (works for both Docker and direct process)+ let mut config = read_openclaw_config()?;++ // Preserve the current baseUrl (may be Docker or localhost depending on sandbox)+ let current_base_url = config+ .pointer("/models/providers/jan/baseUrl")+ .and_then(|v| v.as_str())+ .unwrap_or(DEFAULT_JAN_BASE_URL)+ .to_string();+// Build the full jan provider config with all models- let jan_provider = serde_json::json!({- "baseUrl": DEFAULT_JAN_BASE_URL,+ config["models"]["providers"]["jan"] = serde_json::json!({+ "baseUrl": current_base_url,"api": DEFAULT_JAN_API_TYPE,"authHeader": false,"apiKey": "not-needed","models": model_defs});- // Set the jan provider atomically (creates or replaces)- let output = Command::new("openclaw")- .args([- "config",- "set",- "models.providers.jan",- &jan_provider.to_string(),- ])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await- .map_err(|e| format!("Failed to run openclaw config set: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(format!("Failed to set jan provider models: {}", stderr));- }-// Set the default model if providedlet set_default = if let Some(ref model_id) = default_model_id {- let openclaw_model_id = format!("jan/{}", model_id);- let model_output = Command::new("openclaw")- .args(["models", "set", &openclaw_model_id])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await;-- match model_output {- Ok(o) if o.status.success() => {- log::info!("Set default model to {}", openclaw_model_id);- Some(openclaw_model_id)- }- Ok(o) => {- let stderr = String::from_utf8_lossy(&o.stderr);- log::warn!("Failed to set default model: {}", stderr);- None- }- Err(e) => {- log::warn!("Failed to run openclaw models set: {}", e);- None- }- }+ config["agents"]["defaults"]["model"]["primary"] = serde_json::json!(model_id);+ Some(format!("jan/{}", model_id))} else {None};+ // Clean up any invalid keys before writing+ strip_invalid_config_keys(&mut config);++ write_openclaw_config(&config)?;+log::info!("Successfully bulk synced {} models to OpenClaw", synced_count);Ok(BulkSyncResult {synced_count,@@ -1431,23 +1313,12 @@ pub async fn openclaw_sync_all_models(pub async fn openclaw_get_model() -> Result<String, String> {log::info!("Getting OpenClaw model");- let output = Command::new("openclaw")- .args(["config", "get", "agents.defaults.model.primary"])- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await- .map_err(|e| format!("Failed to run openclaw config get: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(format!("Failed to get OpenClaw model: {}", stderr));- }-- let stdout = String::from_utf8_lossy(&output.stdout);- // The output is JSON, parse it to get just the value- let model: String = serde_json::from_str(stdout.trim())- .unwrap_or_else(|_| stdout.trim().trim_matches('"').to_string());+ let config = read_openclaw_config()?;+ let model = config+ .pointer("/agents/defaults/model/primary")+ .and_then(|v| v.as_str())+ .unwrap_or(DEFAULT_MODEL_ID)+ .to_string();Ok(model)}@@ -1475,80 +1346,218 @@ pub async fn openclaw_enable(log::info!("Starting 1-click OpenClaw enable flow");let mut steps_completed: Vec<EnableStep> = vec![];+ let mut sandbox_info: Option<String> = None;- let emit = |step: &str, progress: u32, message: &str| {+ let emit = |step: &str, progress: u32, message: &str, sandbox: Option<&str>| {let _ = app.emit("openclaw-enable-progress",EnableProgressEvent {step: step.to_string(),progress,message: message.to_string(),+ sandbox_info: sandbox.map(|s| s.to_string()),},);};- // Step 1: Check Node.js dependencies- emit("checking_dependencies", 10, "Checking Node.js installation...");+ // Step 1: Detect sandbox type FIRST (before Node.js check)+ // This is important because for Docker, Node.js runs inside container+ let detected = crate::core::openclaw::sandbox::detect_sandbox().await;+ let sandbox_name = detected.name().to_string();+ let tier = detected.isolation_tier();+ let mut is_docker = sandbox_name == "Docker";+ sandbox_info = Some(match tier {+ crate::core::openclaw::sandbox::IsolationTier::None => "None (direct process)".to_string(),+ _ => sandbox_name.clone(),+ });+ log::info!("Detected sandbox: {} (tier: {:?})", sandbox_name, tier);++ // Step 1b: Check Node.js dependencies (skip for Docker - runs inside container)+ emit("checking_dependencies", 10, "Checking Node.js installation...", sandbox_info.as_deref());steps_completed.push(EnableStep::CheckingDependencies);- let node_check = openclaw_check_dependencies().await;- if !node_check.installed {- return Err(serde_json::to_string(&EnableError {- code: EnableErrorCode::NodeNotFound,- message: "Node.js is not installed. OpenClaw requires Node.js 22+.".to_string(),- recovery: vec![RecoveryOption {- label: "Download Node.js".to_string(),- action: RecoveryAction::OpenNodeDownload,- description: "Opens the Node.js download page in your browser.".to_string(),- }],- })- .unwrap_or_else(|_| "Node.js is not installed".to_string()));- }- if !node_check.meets_requirements {- return Err(serde_json::to_string(&EnableError {- code: EnableErrorCode::NodeVersionTooLow,- message: format!(- "Node.js 22+ required. Found: {}",- node_check.version.as_deref().unwrap_or("unknown")- ),- recovery: vec![RecoveryOption {- label: "Download Node.js".to_string(),- action: RecoveryAction::OpenNodeDownload,- description: "Opens the Node.js download page to get the latest version.".to_string(),- }],- })- .unwrap_or_else(|_| "Node.js version too low".to_string()));++ let _node_check = if is_docker {+ // For Docker, Node.js runs inside container - no host check needed+ log::info!("Docker sandbox detected - Node.js runs inside container, skipping host check");+ NodeCheckResult {+ installed: true, // Pretend it's installed to allow flow to continue+ version: None,+ major_version: None,+ meets_requirements: true,+ error: None,+ }+ } else {+ // For direct process, Node.js must be on host+ let check = openclaw_check_dependencies().await;+ if !check.installed {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeNotFound,+ message: "Node.js is not installed. OpenClaw requires Node.js 22+.".to_string(),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page in your browser.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js is not installed".to_string()));+ }+ if !check.meets_requirements {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeVersionTooLow,+ message: format!(+ "Node.js 22+ required. Found: {}",+ check.version.as_deref().unwrap_or("unknown")+ ),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page to get the latest version.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js version too low".to_string()));+ }+ check+ };++ // Store detected sandbox in state+ {+ let mut sandbox_guard = state.sandbox.lock().await;+ *sandbox_guard = Some(detected);}// Step 2: Check if OpenClaw is already installed- emit("checking_installation", 25, "Checking OpenClaw installation...");+ emit("checking_installation", 25, "Checking OpenClaw installation...", sandbox_info.as_deref());steps_completed.push(EnableStep::CheckingInstallation);- let already_installed = check_openclaw_installed().await.ok().flatten().is_some();++ let already_installed = if is_docker {+ // For Docker: check if the Docker image exists locally+ let docker_installed = crate::core::openclaw::sandbox_docker::DockerSandbox::is_installed().await;+ let docker_exists = docker_installed == Some(true);+ log::info!("Installation check: docker_container={}, sandbox={}", docker_exists, sandbox_name);++ if docker_exists {+ emit("already_installed", 40, "OpenClaw container exists in Docker.", sandbox_info.as_deref());+ }+ docker_exists+ } else {+ // For non-Docker: check npm package on host+ let npm_installed = check_openclaw_installed().await.ok().flatten().is_some();+ log::info!("Installation check: npm={}, sandbox={}", npm_installed, sandbox_name);+ npm_installed+ };// Step 3: Install if neededif !already_installed {- emit("installing", 40, "Installing OpenClaw (this may take a moment)...");- steps_completed.push(EnableStep::Installing);- let install_result = openclaw_install().await?;- if !install_result.success {- return Err(serde_json::to_string(&EnableError {- code: EnableErrorCode::NpmInstallFailed,- message: install_result- .error- .unwrap_or_else(|| "npm install failed".to_string()),- recovery: vec![RecoveryOption {- label: "Retry".to_string(),- action: RecoveryAction::Retry,- description: "Try installing OpenClaw again.".to_string(),- }],- })- .unwrap_or_else(|_| "Installation failed".to_string()));+ if is_docker {+ // Docker path: pull the image (the actual container is created in openclaw_start)+ emit("installing", 40, "Pulling OpenClaw Docker image...", sandbox_info.as_deref());+ steps_completed.push(EnableStep::Installing);++ // Pull Docker image with progress events+ match crate::core::openclaw::sandbox_docker::DockerSandbox::pull_image_if_needed_with_progress(+ &app,+ sandbox_info.as_deref(),+ ).await {+ Ok(()) => {+ log::info!("Docker image pulled successfully");+ }+ Err(e) => {+ // Docker image pull failed (e.g., image not published yet, auth error, network)+ // Fall back to direct process mode with npm install+ log::warn!("Docker image pull failed: {}. Falling back to direct process.", e);+ emit("installing", 42, "Docker image unavailable, falling back to direct install...", sandbox_info.as_deref());++ is_docker = false;+ sandbox_info = Some("None (direct process)".to_string());++ // Replace sandbox in state with DirectProcessSandbox+ {+ let mut sandbox_guard = state.sandbox.lock().await;+ *sandbox_guard = Some(Box::new(+ crate::core::openclaw::sandbox_direct::DirectProcessSandbox,+ ));+ }++ // Check Node.js (required for direct process)+ let node_check = openclaw_check_dependencies().await;+ if !node_check.installed {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeNotFound,+ message: format!(+ "Docker image unavailable and Node.js is not installed. \+ Original error: {}. Install Node.js 22+ for direct mode.",+ e+ ),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page in your browser.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js is not installed".to_string()));+ }+ if !node_check.meets_requirements {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NodeVersionTooLow,+ message: format!(+ "Docker image unavailable and Node.js version too low. \+ Original error: {}. Node.js 22+ required.",+ e+ ),+ recovery: vec![RecoveryOption {+ label: "Download Node.js".to_string(),+ action: RecoveryAction::OpenNodeDownload,+ description: "Opens the Node.js download page to get the latest version.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Node.js version too low".to_string()));+ }++ // Now do npm install+ emit("installing", 45, "Installing OpenClaw via npm...", sandbox_info.as_deref());+ let install_result = openclaw_install().await?;+ if !install_result.success {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NpmInstallFailed,+ message: install_result+ .error+ .unwrap_or_else(|| "npm install failed".to_string()),+ recovery: vec![RecoveryOption {+ label: "Retry".to_string(),+ action: RecoveryAction::Retry,+ description: "Try installing OpenClaw again.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Installation failed".to_string()));+ }+ }+ }+ } else {+ // Non-Docker path: npm install+ emit("installing", 40, "Installing OpenClaw (this may take a moment)...", sandbox_info.as_deref());+ steps_completed.push(EnableStep::Installing);+ let install_result = openclaw_install().await?;+ if !install_result.success {+ return Err(serde_json::to_string(&EnableError {+ code: EnableErrorCode::NpmInstallFailed,+ message: install_result+ .error+ .unwrap_or_else(|| "npm install failed".to_string()),+ recovery: vec![RecoveryOption {+ label: "Retry".to_string(),+ action: RecoveryAction::Retry,+ description: "Try installing OpenClaw again.".to_string(),+ }],+ })+ .unwrap_or_else(|_| "Installation failed".to_string()));+ }}} else {- emit("already_installed", 40, "OpenClaw is already installed.");+ emit("already_installed", 40, "OpenClaw is already installed.", sandbox_info.as_deref());}// Step 4: Configure- emit("configuring", 60, "Configuring OpenClaw...");+ emit("configuring", 60, "Configuring OpenClaw...", sandbox_info.as_deref());steps_completed.push(EnableStep::Configuring);openclaw_configure(config_input).await.map_err(|e| {serde_json::to_string(&EnableError {@@ -1564,7 +1573,7 @@ pub async fn openclaw_enable(})?;// Step 5: Start the gateway- emit("starting", 75, "Starting OpenClaw gateway...");+ emit("starting", 75, "Starting OpenClaw gateway...", sandbox_info.as_deref());steps_completed.push(EnableStep::Starting);openclaw_start(state.clone()).await.map_err(|e| {if e.contains("Port") || e.contains("port") {@@ -1595,7 +1604,7 @@ pub async fn openclaw_enable(})?;// Step 6: Get final status- emit("complete", 100, "OpenClaw is ready!");+ emit("complete", 100, "OpenClaw is ready!", sandbox_info.as_deref());let final_status = openclaw_status(state).await?;Ok(EnableResult {@@ -1611,26 +1620,69 @@ pub async fn openclaw_enable(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);- let _ = openclaw_ensure_jan_origin().await;- return Ok(());- }+ // Step 1: Detect sandbox FIRST (before port checks) — determines how we handle everything+ let sandbox_name: String;+ let is_docker = {+ let mut sandbox_guard = state.sandbox.lock().await;+ if sandbox_guard.is_none() {+ let detected = crate::core::openclaw::sandbox::detect_sandbox().await;+ let name = detected.name().to_string();+ let tier_str = detected.isolation_tier().to_string();+ sandbox_name = format!("{} (tier: {})", name, tier_str);+ log::info!("Detected sandbox: {}", sandbox_name);+ *sandbox_guard = Some(detected);+ name == "Docker"+ } else {+ let sb = sandbox_guard.as_ref().unwrap();+ sandbox_name = format!("{} (tier: {})", sb.name(), sb.isolation_tier());+ sb.name() == "Docker"+ }+ };- // Check dependencies first- let node_check = openclaw_check_dependencies().await;- if !node_check.installed || !node_check.meets_requirements {- return Err(node_check.error.unwrap_or_else(|| "Node.js requirements not met".to_string()));- }+ log::info!("Starting OpenClaw with sandbox: {}", sandbox_name);++ // Step 2: Port check — behavior depends on sandbox type+ if is_docker {+ // For Docker: if port is in use, something else is on it (host process, old container).+ // We need to ensure the Docker container is running, not just that the port responds.+ // Check if our Docker container is already running.+ let docker_status = {+ let sandbox_guard = state.sandbox.lock().await;+ if let Some(sandbox) = sandbox_guard.as_ref() {+ let dummy_handle = crate::core::openclaw::sandbox::SandboxHandle::Named(+ "jan-openclaw".to_string(),+ );+ sandbox.status(&dummy_handle).await.ok()+ } else {+ None+ }+ };- // Check port availability- let port_check = openclaw_check_port(OPENCLAW_PORT).await;- if !port_check.available {- return Err(format!("Port {} is already in use by another application", OPENCLAW_PORT));+ if docker_status == Some(crate::core::openclaw::sandbox::SandboxStatus::Running) {+ log::info!("Docker container is already running");+ return Ok(());+ }++ // If port is in use but Docker container is NOT running, something else occupies the port.+ // We'll let the Docker start proceed — it binds to the same port and will fail with a+ // clear error if there's a conflict.+ log::info!("Docker container not running, will start it");+ } else {+ // For non-Docker: if gateway is already responding, we're done+ if check_gateway_responding().await {+ log::info!("OpenClaw gateway is already running on port {}", OPENCLAW_PORT);+ let _ = openclaw_ensure_jan_origin().await;+ return Ok(());+ }++ // Check port availability for non-Docker+ let port_check = openclaw_check_port(OPENCLAW_PORT).await;+ if !port_check.available {+ return Err(format!("Port {} is already in use by another application", OPENCLAW_PORT));+ }}- // Ensure config exists+ // Step 3: Ensure config existslet config_path = get_openclaw_config_path()?;if !config_path.exists() {openclaw_configure(None).await?;@@ -1638,21 +1690,24 @@ pub async fn openclaw_start(state: State<'_, OpenClawState>) -> Result<(), Strinopenclaw_ensure_jan_origin().await?;}- // Detect sandbox if not yet initialized- {- 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);+ // Step 4: Node.js check (skip for Docker — runs inside container)+ if !is_docker {+ let node_check = openclaw_check_dependencies().await;+ if !node_check.installed || !node_check.meets_requirements {+ return Err(node_check.error.unwrap_or_else(|| "Node.js requirements not met".to_string()));}+ } else {+ log::info!("Docker sandbox detected - Node.js runs inside container, skipping host check");}- // Build config and start via lifecycle module+ // Step 5: Build config and start via lifecycle modulelet config = crate::core::openclaw::lifecycle::build_sandbox_config(&crate::core::openclaw::constants::DEFAULT_JAN_BASE_URL,)?;+ // Take a reference to the sandbox within a scoped lock, then call start_openclaw.+ // start_openclaw internally locks sandbox_mode, so we must not hold the sandbox lock+ // across the entire call. Instead, scope it properly.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@@ -1690,13 +1745,42 @@ pub async fn openclaw_status(state: State<'_, OpenClawState>) -> Result<OpenClawErr(_) => None,};+ // Determine "installed" based on which sandbox is detected.+ // When Docker is the sandbox, we need the Docker image to exist locally.+ // When direct process is the sandbox, we need the npm package on the host.+ let is_docker_sandbox = {+ let sandbox_guard = state.sandbox.lock().await;+ sandbox_guard.as_ref().map(|s| s.name() == "Docker").unwrap_or(false)+ };++ let is_installed = if is_docker_sandbox {+ // For Docker sandbox: installed means the Docker image is available locally+ // (container existence is transient — it's created/destroyed on start/stop)+ crate::core::openclaw::sandbox_docker::DockerSandbox::is_image_available().await+ } else {+ // For direct process: installed means the npm package is on the host+ openclaw_version.is_some()+ };+let node_check = openclaw_check_dependencies().await;let port_check = openclaw_check_port(OPENCLAW_PORT).await;// Get sandbox information from state+ // Also check if container still exists (in case it was deleted externally)let (sandbox_type, isolation_tier) = {- let sandbox_guard = state.sandbox.lock().await;- let mode = state.sandbox_mode.lock().await;+ let mut sandbox_guard = state.sandbox.lock().await;+ let mut mode = state.sandbox_mode.lock().await;++ // If state says Active but container doesn't exist, reset state+ if let crate::core::openclaw::sandbox::SandboxMode::Active { .. } = &*mode {+ if !running {+ // Container was deleted externally, reset state+ log::info!("OpenClaw container was deleted externally, resetting state");+ *mode = crate::core::openclaw::sandbox::SandboxMode::Inactive;+ *sandbox_guard = None;+ }+ }+match (&*sandbox_guard, &*mode) {(Some(sandbox), crate::core::openclaw::sandbox::SandboxMode::Active { .. }) => {(@@ -1713,7 +1797,7 @@ pub async fn openclaw_status(state: State<'_, OpenClawState>) -> Result<OpenClaw};Ok(OpenClawStatus {- installed: openclaw_version.is_some(),+ installed: is_installed,running,node_version: node_check.version,openclaw_version,@@ -3491,6 +3575,80 @@ pub fn security_generate_pairing_code() -> String {security::generate_pairing_code()}+// ============================================+// Sandbox Commands+// ============================================++use crate::core::openclaw::sandbox::SandboxMode;++/// Get sandbox logs+///+/// Returns the last N lines of logs from the sandboxed OpenClaw process.+#[tauri::command]+pub async fn sandbox_get_logs(+ state: State<'_, OpenClawState>,+ lines: usize,+) -> Result<Vec<String>, String> {+ log::info!("Getting sandbox logs (lines: {})", lines);++ let mode = state.sandbox_mode.lock().await;+ let sandbox_guard = state.sandbox.lock().await;++ match (&*mode, &*sandbox_guard) {+ (SandboxMode::Active { handle, .. }, Some(sandbox)) => {+ sandbox.logs(handle, lines).await+ }+ _ => {+ // Try to read from the gateway log file directly+ let config_dir = get_openclaw_config_dir()?;+ let log_path = config_dir.join("gateway.log");++ if log_path.exists() {+ let content = tokio::fs::read_to_string(&log_path)+ .await+ .map_err(|e| format!("Failed to read log file: {}", e))?;++ let all_lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();+ let start = if all_lines.len() > lines {+ all_lines.len() - lines+ } else {+ 0+ };+ Ok(all_lines[start..].to_vec())+ } else {+ Ok(vec!["No logs available. OpenClaw may not be running.".to_string()])+ }+ }+ }+}++/// Restart the sandboxed OpenClaw process+///+/// Stops the current sandbox (if running) and starts a fresh one.+/// This is useful for recovering from errors or applying configuration changes.+#[tauri::command]+pub async fn sandbox_restart(state: State<'_, OpenClawState>) -> Result<(), String> {+ log::info!("Restarting sandbox");++ // Stop the current sandbox if active+ {+ let mut mode = state.sandbox_mode.lock().await;+ let sandbox_guard = state.sandbox.lock().await;++ if let SandboxMode::Active { handle, sandbox_name, isolation_tier } = std::mem::take(&mut *mode) {+ if let Some(sandbox) = &*sandbox_guard {+ log::info!("Stopping sandbox {} ({:?})", sandbox_name, isolation_tier);+ let mut handle = handle;+ let _ = sandbox.stop(&mut handle).await;+ }+ }+ *mode = SandboxMode::Inactive;+ }++ // Start fresh+ openclaw_start(state).await+}+// ============================================// Tunnel Provider Commands// ============================================diff --git a/src-tauri/src/core/openclaw/constants.rs b/src-tauri/src/core/openclaw/constants.rsindex d393309c2..c5f709b45 100644--- a/src-tauri/src/core/openclaw/constants.rs+++ b/src-tauri/src/core/openclaw/constants.rs@@ -1,17 +1,27 @@/// OpenClaw package name on npmpub const OPENCLAW_PACKAGE_NAME: &str = "openclaw";+/// Pinned OpenClaw version (npm semver and Docker image tag)+/// This ensures config compatibility across installs.+pub const OPENCLAW_VERSION: &str = "2026.3.1";+/// Default OpenClaw gateway portpub const DEFAULT_OPENCLAW_PORT: u16 = 18789;-/// Default Jan API base URL+/// Default Jan API base URL (direct process — same host)pub const DEFAULT_JAN_BASE_URL: &str = "http://localhost:1337/v1";+/// Jan API base URL for Docker sandbox (container → host networking)+pub const DOCKER_JAN_BASE_URL: &str = "http://host.docker.internal:1337/v1";++/// Gateway bind mode for direct process (loopback only)+pub const DEFAULT_BIND_MODE: &str = "loopback";++/// Gateway bind mode for Docker (must be accessible from port mapping)+pub const DOCKER_BIND_MODE: &str = "lan";+/// Default API type for Janpub const DEFAULT_JAN_API_TYPE: &str = "openai-completions";/// Default model ID for agents-pub const DEFAULT_MODEL_ID: &str = "llama-3.2-3b";--/// Default system prompt for agents-pub const DEFAULT_SYSTEM_PROMPT: &str = "You are a helpful AI assistant running via Jan.";\ No newline at end of file+pub const DEFAULT_MODEL_ID: &str = "llama-3.2-3b";\ No newline at end of filediff --git a/src-tauri/src/core/openclaw/lifecycle.rs b/src-tauri/src/core/openclaw/lifecycle.rsindex b82d2fb8f..cc6beee72 100644--- a/src-tauri/src/core/openclaw/lifecycle.rs+++ b/src-tauri/src/core/openclaw/lifecycle.rs@@ -153,41 +153,64 @@ pub async fn is_port_in_use(port: u16) -> bool {.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() {+/// Patch OpenClaw config based on the sandbox type using proper JSON parsing.+/// Docker needs different API URLs and bind mode; direct process uses localhost.+pub fn patch_config_for_sandbox(sandbox: &dyn Sandbox, config_dir: &Path) -> Result<(), String> {+ use super::constants;++ let config_path = config_dir.join("openclaw.json");+ if !config_path.exists() {+ return Ok(());+ }++ let content = std::fs::read_to_string(&config_path)+ .map_err(|e| format!("Failed to read config: {}", e))?;++ let mut config: serde_json::Value = serde_json::from_str(&content)+ .map_err(|e| format!("Failed to parse config: {}", e))?;++ let (target_base_url, target_bind) = 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");- }- }+ // Docker: container reaches Jan host via host.docker.internal+ // Bind to "lan" so Docker port mapping works+ (constants::DOCKER_JAN_BASE_URL, constants::DOCKER_BIND_MODE)}- 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::PlatformSandbox | IsolationTier::None => {+ // Direct process / platform sandbox: same host, use localhost+ (constants::DEFAULT_JAN_BASE_URL, constants::DEFAULT_BIND_MODE)}- IsolationTier::None => {- // Direct process: same machine, localhost works+ };++ let mut modified = false;++ // Patch gateway.bind+ if let Some(bind) = config.pointer_mut("/gateway/bind") {+ if bind.as_str() != Some(target_bind) {+ *bind = serde_json::json!(target_bind);+ modified = true;+ }+ }++ // Patch models.providers.jan.baseUrl+ if let Some(base_url) = config.pointer_mut("/models/providers/jan/baseUrl") {+ if base_url.as_str() != Some(target_base_url) {+ *base_url = serde_json::json!(target_base_url);+ modified = true;}}+ if modified {+ let updated = serde_json::to_string_pretty(&config)+ .map_err(|e| format!("Failed to serialize config: {}", e))?;+ std::fs::write(&config_path, updated)+ .map_err(|e| format!("Failed to write config: {}", e))?;+ log::info!(+ "Patched OpenClaw config for {} sandbox (bind={}, baseUrl={})",+ sandbox.name(),+ target_bind,+ target_base_url+ );+ }+Ok(())}diff --git a/src-tauri/src/core/openclaw/models.rs b/src-tauri/src/core/openclaw/models.rsindex 9289de307..6c9bf090e 100644--- a/src-tauri/src/core/openclaw/models.rs+++ b/src-tauri/src/core/openclaw/models.rs@@ -3,14 +3,14 @@ use serde::{Deserialize, Serialize};use super::constants;/// OpenClaw configuration structure+/// Only includes keys that OpenClaw actually recognizes.+/// Unknown keys (like agents.defaults.systemPrompt) cause OpenClaw to reject the config.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct OpenClawConfig {/// Gateway configurationpub gateway: GatewayConfig,/// Model providers configurationpub models: ModelsConfig,- /// Agents configuration- pub agents: AgentsConfig,}impl Default for OpenClawConfig {@@ -18,7 +18,6 @@ impl Default for OpenClawConfig {Self {gateway: GatewayConfig::default(),models: ModelsConfig::default(),- agents: AgentsConfig::default(),}}}@@ -141,54 +140,11 @@ impl Default for JanProviderConfig {}}-/// Agents configuration-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AgentsConfig {- /// Default agent settings- pub defaults: AgentDefaults,-}--impl Default for AgentsConfig {- fn default() -> Self {- Self {- defaults: AgentDefaults::default(),- }- }-}--/// Default agent settings-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AgentDefaults {- /// Default model configuration- pub model: ModelConfig,- /// Default system prompt- #[serde(rename = "systemPrompt")]- pub system_prompt: String,-}--impl Default for AgentDefaults {- fn default() -> Self {- Self {- model: ModelConfig::default(),- system_prompt: constants::DEFAULT_SYSTEM_PROMPT.to_string(),- }- }-}--/// Model configuration-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ModelConfig {- /// Primary model ID- pub primary: String,-}--impl Default for ModelConfig {- fn default() -> Self {- Self {- primary: constants::DEFAULT_MODEL_ID.to_string(),- }- }-}+// NOTE: OpenClaw uses strict Zod validation on its config — unknown keys+// cause the gateway to refuse to start. The `agents.defaults` section accepts+// known keys like `model` (object: {primary, fallbacks}), `maxConcurrent`,+// `subagents`, `compaction`, `workspace`, etc. Custom keys like `systemPrompt`+// are NOT valid and will be rejected. See: https://docs.openclaw.ai/gateway/configuration-reference/// OpenClaw status response#[derive(Debug, Clone, Serialize, Deserialize)]@@ -256,12 +212,9 @@ pub struct OpenClawConfigInput {/// Optional custom Jan base URL#[serde(rename = "janBaseUrl")]pub jan_base_url: Option<String>,- /// Optional custom model ID+ /// Optional custom model ID (sets agents.defaults.model.primary)#[serde(rename = "modelId")]pub model_id: Option<String>,- /// Optional custom system prompt- #[serde(rename = "systemPrompt")]- pub system_prompt: Option<String>,/// Optional custom portpub port: Option<u16>,/// Optional bind address@@ -583,6 +536,9 @@ pub struct EnableProgressEvent {pub progress: u32,/// Human-readable messagepub message: String,+ /// Optional sandbox info for display (e.g., "Linux Namespaces", "Docker 24.0.7")+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sandbox_info: Option<String>,}/// Error with recovery options for the enable flowdiff --git a/src-tauri/src/core/openclaw/sandbox.rs b/src-tauri/src/core/openclaw/sandbox.rsindex bd4a73ac6..7f0e8aa83 100644--- a/src-tauri/src/core/openclaw/sandbox.rs+++ b/src-tauri/src/core/openclaw/sandbox.rs@@ -89,6 +89,12 @@ pub enum SandboxMode {},}+impl Default for SandboxMode {+ fn default() -> Self {+ SandboxMode::Inactive+ }+}+/// Auto-detect the best available sandbox for the current platform./// Returns implementations in priority order: best isolation first.///diff --git a/src-tauri/src/core/openclaw/sandbox_docker.rs b/src-tauri/src/core/openclaw/sandbox_docker.rsindex 1a07d1f38..8335d5d1f 100644--- a/src-tauri/src/core/openclaw/sandbox_docker.rs+++ b/src-tauri/src/core/openclaw/sandbox_docker.rs@@ -40,7 +40,7 @@ use super::sandbox::{IsolationTier, Sandbox, SandboxConfig, SandboxHandle, Sandbconst CONTAINER_NAME: &str = "jan-openclaw";#[cfg(feature = "docker")]-const IMAGE_NAME: &str = "ghcr.io/janhq/openclaw:latest";+const IMAGE_NAME: &str = "ghcr.io/openclaw/openclaw:2026.3.1";#[cfg(feature = "docker")]pub struct DockerSandbox;@@ -51,6 +51,24 @@ impl DockerSandbox {Self}+ /// Check if Docker is available and the OpenClaw container exists.+ /// Returns Some(true) if container exists, Some(false) if Docker available but no container,+ /// None if Docker is not available.+ pub async fn is_installed() -> Option<bool> {+ let client = match Self::get_client().await {+ Ok(c) => c,+ Err(_) => return None,+ };++ // Check if Docker is responding+ if client.ping().await.is_err() {+ return None;+ }++ // Check if container exists+ Some(Self::container_exists(&client).await)+ }+async fn get_client() -> Result<bollard::Docker, String> {bollard::Docker::connect_with_local_defaults().map_err(|e| format!("Failed to connect to Docker: {}", e))@@ -73,11 +91,21 @@ impl DockerSandbox {}}- /// Check if the image exists locally.+ /// Check if the image exists locally (internal).async fn image_exists(client: &bollard::Docker) -> bool {client.inspect_image(IMAGE_NAME).await.is_ok()}+ /// Check if the Docker image is available locally (public).+ /// Returns true if Docker is available AND the image exists.+ pub async fn is_image_available() -> bool {+ let client = match Self::get_client().await {+ Ok(c) => c,+ Err(_) => return false,+ };+ Self::image_exists(&client).await+ }+/// 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.@@ -113,7 +141,7 @@ impl DockerSandbox {None}- /// Pull the OpenClaw image.+ /// Pull the OpenClaw image (internal, no progress events).async fn pull_image(client: &bollard::Docker) -> Result<(), String> {log::info!("DockerSandbox: pulling image {}", IMAGE_NAME);@@ -140,6 +168,108 @@ impl DockerSandbox {log::info!("DockerSandbox: image pulled successfully");Ok(())}++ /// Pull the Docker image if not already present, emitting progress events.+ /// Called from `openclaw_enable()` to provide real-time feedback during the+ /// potentially long image download.+ pub async fn pull_image_if_needed_with_progress(+ app: &tauri::AppHandle,+ sandbox_info: Option<&str>,+ ) -> Result<(), String> {+ use tauri::Emitter;+ use super::models::EnableProgressEvent;++ let client = Self::get_client().await?;++ // Check if image already exists locally+ if Self::image_exists(&client).await {+ log::info!("DockerSandbox: image {} already exists locally", IMAGE_NAME);+ let _ = app.emit(+ "openclaw-enable-progress",+ EnableProgressEvent {+ step: "installing".to_string(),+ progress: 55,+ message: "Docker image already available.".to_string(),+ sandbox_info: sandbox_info.map(|s| s.to_string()),+ },+ );+ return Ok(());+ }++ log::info!("DockerSandbox: pulling image {} with progress", IMAGE_NAME);++ let options = CreateImageOptions {+ from_image: IMAGE_NAME,+ ..Default::default()+ };++ let mut stream = client.create_image(Some(options), None, None);+ let mut last_progress_pct: u32 = 40; // Start at 40% (where installing step begins)++ while let Some(result) = stream.next().await {+ match result {+ Ok(info) => {+ // Calculate progress from Docker's layer download info+ let mut msg = String::new();+ if let Some(ref status) = info.status {+ msg = status.clone();+ }++ // Use progress_detail to estimate percentage (40-55 range for pull)+ if let Some(ref detail) = info.progress_detail {+ if let (Some(current), Some(total)) = (detail.current, detail.total) {+ if total > 0 {+ let pct = (current as f64 / total as f64 * 15.0) as u32 + 40;+ last_progress_pct = pct.min(55);+ }+ }+ }++ if let Some(ref status) = info.status {+ // Only emit for meaningful status changes+ if status.contains("Pulling") || status.contains("Downloading")+ || status.contains("Extracting") || status.contains("Pull complete")+ || status.contains("Already exists")+ {+ let display_msg = if let Some(ref id) = info.id {+ format!("{}: {}", status, id)+ } else {+ msg.clone()+ };++ let _ = app.emit(+ "openclaw-enable-progress",+ EnableProgressEvent {+ step: "installing".to_string(),+ progress: last_progress_pct,+ message: format!("Pulling image... {}", display_msg),+ sandbox_info: sandbox_info.map(|s| s.to_string()),+ },+ );+ }+ }++ log::debug!("DockerSandbox: pull: {:?}", info.status);+ }+ Err(e) => {+ return Err(format!("Failed to pull image {}: {}", IMAGE_NAME, e));+ }+ }+ }++ log::info!("DockerSandbox: image pulled successfully");+ let _ = app.emit(+ "openclaw-enable-progress",+ EnableProgressEvent {+ step: "installing".to_string(),+ progress: 58,+ message: "Docker image pulled successfully.".to_string(),+ sandbox_info: sandbox_info.map(|s| s.to_string()),+ },+ );++ Ok(())+ }}#[cfg(feature = "docker")]@@ -208,17 +338,23 @@ impl Sandbox for DockerSandbox {);// Build environment variables+ // Note: the official OpenClaw image runs as user `node` (home = /home/node)let mut env_vars: Vec<String> = config.env_vars.iter()+ .filter(|(k, _)| k != "OPENCLAW_CONFIG") // Remove host path, we set the container path below.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+ // Override config path for inside the container (node user's home)+ env_vars.push("OPENCLAW_CONFIG=/home/node/.openclaw/openclaw.json".to_string());+ // V8 default heap limit on arm64 is ~512MB which is too small for OpenClaw.+ // Explicitly raise it so the gateway doesn't OOM during startup.+ env_vars.push("NODE_OPTIONS=--max-old-space-size=768".to_string());++ // Build volume bind: ~/.openclaw -> /home/node/.openclaw+ // The official image runs as `node` user, NOT rootlet host_config_dir = config.config_dir.to_string_lossy();- let binds = vec![format!("{}:/root/.openclaw", host_config_dir)];+ let binds = vec![format!("{}:/home/node/.openclaw", host_config_dir)];// Build extra hosts for Docker-to-host networkinglet extra_hosts = vec!["host.docker.internal:host-gateway".to_string()];@@ -249,8 +385,8 @@ impl Sandbox for DockerSandbox {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+ memory: Some(1024 * 1024 * 1024), // 1 GB — Node.js V8 heap needs headroom+ nano_cpus: Some(1_000_000_000), // 1 CPU..Default::default()};diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex bd519181f..a44c31c25 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -151,6 +151,9 @@ pub fn run() {core::openclaw::commands::openclaw_get_config_dir,core::openclaw::commands::openclaw_ensure_jan_origin,core::openclaw::commands::openclaw_setup_for_channels,+ // Sandbox commands+ core::openclaw::commands::sandbox_get_logs,+ core::openclaw::commands::sandbox_restart,// Telegram commandscore::openclaw::commands::telegram_validate_token,core::openclaw::commands::telegram_configure,diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex fef3378ed..9ef20a9a5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -176,13 +176,12 @@ fn run_openclaw_cli(cli: OpenClawCli) {}}- OpenClawCommands::Configure { port, bind, jan_base_url, model_id, system_prompt } => {+ OpenClawCommands::Configure { port, bind, jan_base_url, model_id } => {let config_input = app_lib::core::openclaw::models::OpenClawConfigInput {port,bind,jan_base_url,model_id,- system_prompt,};let result = rt.block_on(async {@@ -195,7 +194,6 @@ fn run_openclaw_cli(cli: OpenClawCli) {println!(" Gateway Port: {}", config.gateway.port);println!(" Gateway Bind: {}", config.gateway.bind);println!(" Jan Base URL: {}", config.models.providers.jan.base_url);- println!(" Model ID: {}", config.agents.defaults.model.primary);}Err(e) => {eprintln!("Configuration failed: {}", e);diff --git a/src-tauri/src/openclaw_cli.rs b/src-tauri/src/openclaw_cli.rsindex 340d3fa5f..5e39542b3 100644--- a/src-tauri/src/openclaw_cli.rs+++ b/src-tauri/src/openclaw_cli.rs@@ -37,12 +37,9 @@ pub enum OpenClawCommands {/// Jan base URL#[arg(long)]jan_base_url: Option<String>,- /// Model ID to use+ /// Model ID to use (sets agents.defaults.model.primary)#[arg(long)]model_id: Option<String>,- /// System prompt for agents- #[arg(long)]- system_prompt: Option<String>,},/// Restart the OpenClaw gatewayRestart,diff --git a/web-app/src/containers/dialogs/EnableProgressDialog.tsx b/web-app/src/containers/dialogs/EnableProgressDialog.tsxindex b55630854..23006b561 100644--- a/web-app/src/containers/dialogs/EnableProgressDialog.tsx+++ b/web-app/src/containers/dialogs/EnableProgressDialog.tsx@@ -25,6 +25,7 @@ interface EnableProgressEvent {step: stringprogress: numbermessage: string+ sandbox_info?: string}interface EnableResult {@@ -90,6 +91,7 @@ export function EnableProgressDialog({const [message, setMessage] = useState('')const [completedSteps, setCompletedSteps] = useState<string[]>([])const [currentStep, setCurrentStep] = useState('')+ const [sandboxInfo, setSandboxInfo] = useState<string | null>(null)const [error, setError] = useState<EnableError | null>(null)const [isRunning, setIsRunning] = useState(false)const [isDone, setIsDone] = useState(false)@@ -99,6 +101,7 @@ export function EnableProgressDialog({setMessage('')setCompletedSteps([])setCurrentStep('')+ setSandboxInfo(null)setError(null)setIsRunning(false)setIsDone(false)@@ -163,10 +166,13 @@ export function EnableProgressDialog({const unlisten = listen<EnableProgressEvent>('openclaw-enable-progress',(event) => {- const { step, progress: p, message: msg } = event.payload+ const { step, progress: p, message: msg, sandbox_info } = event.payloadsetProgress(p)setMessage(msg)setCurrentStep(step)+ if (sandbox_info) {+ setSandboxInfo(sandbox_info)+ }setCompletedSteps((prev) => {if (step !== prev[prev.length - 1]) {return [...prev, step]@@ -258,6 +264,13 @@ export function EnableProgressDialog({const isCurrent = currentStep === step && !isDoneconst label = STEP_LABELS[step] || step+ // Show sandbox info next to specific steps+ const showSandboxInfo = sandboxInfo && (+ step === 'checking_dependencies' ||+ step === 'starting' ||+ step === 'complete'+ )+// Skip install step if it didn't happenif (step === 'installing' &&@@ -290,6 +303,11 @@ export function EnableProgressDialog({>{label}</span>+ {showSandboxInfo && (+ <span className="ml-auto text-xs text-muted-foreground">+ {sandboxInfo}+ </span>+ )}</div>)})}diff --git a/web-app/src/containers/dialogs/SandboxLogsDialog.tsx b/web-app/src/containers/dialogs/SandboxLogsDialog.tsxnew file mode 100644index 000000000..c27428955--- /dev/null+++ b/web-app/src/containers/dialogs/SandboxLogsDialog.tsx@@ -0,0 +1,206 @@+import { useState, useEffect, useCallback, useRef } from 'react'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { toast } from 'sonner'+import {+ IconSearch,+ IconCopy,+ IconDownload,+ IconRefresh,+ IconLoader2,+ IconFileText,+} from '@tabler/icons-react'++interface SandboxLogsDialogProps {+ isOpen: boolean+ onOpenChange: (open: boolean) => void+}++export function SandboxLogsDialog({+ isOpen,+ onOpenChange,+}: SandboxLogsDialogProps) {+ const { t } = useTranslation()+ const [logs, setLogs] = useState<string[]>([])+ const [filteredLogs, setFilteredLogs] = useState<string[]>([])+ const [searchQuery, setSearchQuery] = useState('')+ const [isLoading, setIsLoading] = useState(false)+ const [isRestarting, setIsRestarting] = useState(false)+ const logsEndRef = useRef<HTMLDivElement>(null)++ const fetchLogs = useCallback(async () => {+ setIsLoading(true)+ try {+ const logLines = await invoke<string[]>('sandbox_get_logs', { lines: 200 })+ setLogs(logLines)+ setFilteredLogs(logLines)+ } catch (err) {+ const errorMsg = err instanceof Error ? err.message : String(err)+ toast.error(`Failed to load logs: ${errorMsg}`)+ setLogs([])+ setFilteredLogs([])+ } finally {+ setIsLoading(false)+ }+ }, [])++ const handleRestart = useCallback(async () => {+ setIsRestarting(true)+ try {+ await invoke('sandbox_restart')+ toast.success(t('settings:restarting'))+ onOpenChange(false)+ } catch (err) {+ const errorMsg = err instanceof Error ? err.message : String(err)+ toast.error(`Failed to restart: ${errorMsg}`)+ } finally {+ setIsRestarting(false)+ }+ }, [onOpenChange, t])++ const handleCopy = useCallback(() => {+ const text = filteredLogs.join('\n')+ navigator.clipboard.writeText(text)+ toast.success(t('settings:copiedToClipboard'))+ }, [filteredLogs, t])++ const handleDownload = useCallback(() => {+ const text = filteredLogs.join('\n')+ const blob = new Blob([text], { type: 'text/plain' })+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = `openclaw-logs-${new Date().toISOString().slice(0, 10)}.txt`+ document.body.appendChild(a)+ a.click()+ document.body.removeChild(a)+ URL.revokeObjectURL(url)+ }, [filteredLogs])++ // Filter logs when search query changes+ useEffect(() => {+ if (!searchQuery.trim()) {+ setFilteredLogs(logs)+ return+ }+ const query = searchQuery.toLowerCase()+ const filtered = logs.filter((log) => log.toLowerCase().includes(query))+ setFilteredLogs(filtered)+ }, [searchQuery, logs])++ // Scroll to bottom when logs change+ useEffect(() => {+ logsEndRef.current?.scrollIntoView({ behavior: 'smooth' })+ }, [filteredLogs])++ // Subscribe to live log events+ useEffect(() => {+ if (!isOpen) return++ const unlisten = listen<string>('openclaw-log-line', (event) => {+ const line = event.payload+ setLogs((prev) => {+ const updated = [...prev, line]+ // Keep only last 500 lines+ return updated.slice(-500)+ })+ })++ return () => {+ unlisten.then((f) => f())+ }+ }, [isOpen])++ // Fetch logs when dialog opens+ useEffect(() => {+ if (isOpen) {+ fetchLogs()+ }+ }, [isOpen, fetchLogs])++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-3xl max-h-[80vh]">+ <DialogHeader>+ <DialogTitle>{t('settings:logViewer')}</DialogTitle>+ </DialogHeader>++ <div className="flex flex-col gap-3 h-[500px]">+ {/* Toolbar */}+ <div className="flex items-center gap-2">+ <div className="relative flex-1">+ <IconSearch className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />+ <Input+ placeholder="Search logs..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="pl-9"+ />+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={fetchLogs}+ disabled={isLoading}+ >+ {isLoading ? (+ <IconLoader2 className="h-4 w-4 animate-spin" />+ ) : (+ <IconRefresh className="h-4 w-4" />+ )}+ </Button>+ <Button variant="outline" size="sm" onClick={handleCopy}>+ <IconCopy className="h-4 w-4 mr-1" />+ {t('settings:copyLogs')}+ </Button>+ <Button variant="outline" size="sm" onClick={handleDownload}>+ <IconDownload className="h-4 w-4 mr-1" />+ {t('settings:downloadLogs')}+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={handleRestart}+ disabled={isRestarting}+ >+ {isRestarting ? (+ <IconLoader2 className="h-4 w-4 animate-spin mr-1" />+ ) : (+ <IconRefresh className="h-4 w-4 mr-1" />+ )}+ {t('settings:restartSandbox')}+ </Button>+ </div>++ {/* Log content */}+ <div className="flex-1 overflow-auto rounded-md border bg-muted/50 p-3 font-mono text-xs">+ {filteredLogs.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-full text-muted-foreground">+ <IconFileText className="h-8 w-8 mb-2" />+ <p>{t('settings:noLogs')}</p>+ </div>+ ) : (+ <div className="space-y-0.5">+ {filteredLogs.map((log, index) => (+ <div key={index} className="whitespace-pre-wrap break-all">+ {log}+ </div>+ ))}+ <div ref={logsEndRef} />+ </div>+ )}+ </div>+ </div>+ </DialogContent>+ </Dialog>+ )+}\ No newline at end of filediff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 399222d1a..d50be3f40 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -366,6 +366,21 @@"whatsapp": "WhatsApp","discord": "Discord","channels": "Channels",+ "sandbox": "Sandbox",+ "viewLogs": "View Logs",+ "sandboxNone": "None (direct process)",+ "sandboxLinux": "Linux Namespaces",+ "sandboxWsl2": "WSL2",+ "sandboxDocker": "Docker",+ "securityAdvisory": "OpenClaw is running without sandbox isolation. For better security, enable WSL2 (Windows) or update to macOS Tahoe.",+ "learnMore": "Learn more",+ "logViewer": "Sandbox Logs",+ "noLogs": "No logs available",+ "copyLogs": "Copy All",+ "downloadLogs": "Download",+ "restartSandbox": "Restart Sandbox",+ "restartConfirm": "Restart Sandbox?",+ "restarting": "Restarting sandbox...","localNetworkOnly": "Local Network Only","notConfigured": "Not Configured","tokenAuth": "Token Authentication",diff --git a/web-app/src/routes/settings/remote-access.tsx b/web-app/src/routes/settings/remote-access.tsxindex 5f1f0ed55..1c407c715 100644--- a/web-app/src/routes/settings/remote-access.tsx+++ b/web-app/src/routes/settings/remote-access.tsx@@ -11,6 +11,7 @@ import { TailscaleSetupDialog } from '@/containers/dialogs/TailscaleSetupDialog'import { SecurityConfigDialog } from '@/containers/dialogs/SecurityConfigDialog'import { TunnelSelectionDialog } from '@/containers/dialogs/TunnelSelectionDialog'import { EnableProgressDialog } from '@/containers/dialogs/EnableProgressDialog'+import { SandboxLogsDialog } from '@/containers/dialogs/SandboxLogsDialog'import { ChannelCard } from '@/containers/ChannelCard'import { useTranslation } from '@/i18n/react-i18next-compat'import { useEffect, useState, useCallback } from 'react'@@ -25,6 +26,8 @@ import {IconPlus,IconCopy,IconExternalLink,+ IconFileText,+ IconAlertTriangle,} from '@tabler/icons-react'import type {ChannelType,@@ -55,6 +58,7 @@ function RemoteAccess() {const [isSecurityDialogOpen, setIsSecurityDialogOpen] = useState(false)const [isTunnelDialogOpen, setIsTunnelDialogOpen] = useState(false)const [isEnableDialogOpen, setIsEnableDialogOpen] = useState(false)+ const [isLogsDialogOpen, setIsLogsDialogOpen] = useState(false)const [tunnelStatus, setTunnelStatus] = useState<TunnelProvidersStatus | null>(null)const [, setSecurityStatus] = useState<SecurityStatus | null>(null)const [telegramConfig, setTelegramConfig] = useState<TelegramConfig | null>(null)@@ -334,6 +338,42 @@ function RemoteAccess() {}/>+ {isRunning && status?.sandbox_type && (+ <CardItem+ title={t('settings:remoteAccess.sandbox')}+ actions={+ <div className="flex items-center gap-2">+ <span className="text-foreground text-sm">+ {status.sandbox_type}+ {status.isolation_tier && status.isolation_tier !== 'none' && (+ <span className="text-muted-foreground ml-1">+ (Tier {status.isolation_tier === 'full_container' ? '3' : status.isolation_tier === 'platform_sandbox' ? '2' : '0'})+ </span>+ )}+ </span>+ <Button+ variant="ghost"+ size="icon-sm"+ onClick={() => setIsLogsDialogOpen(true)}+ title={t('settings:viewLogs')}+ >+ <IconFileText className="h-4 w-4" />+ </Button>+ </div>+ }+ />+ )}++ {/* Security Advisory - show when no sandbox (Tier 0) */}+ {isRunning && (!status?.isolation_tier || status.isolation_tier === 'none') && (+ <div className="flex items-start gap-2 rounded-md border border-yellow-500/30 bg-yellow-500/10 p-3">+ <IconAlertTriangle className="h-5 w-5 text-yellow-500 shrink-0 mt-0.5" />+ <p className="text-sm text-yellow-600 dark:text-yellow-400">+ {t('settings:securityAdvisory')}+ </p>+ </div>+ )}+<CardItemtitle={t('settings:remoteAccess.channels')}actions={@@ -468,6 +508,10 @@ function RemoteAccess() {onOpenChange={setIsEnableDialogOpen}onSuccess={fetchStatus}/>+ <SandboxLogsDialog+ isOpen={isLogsDialogOpen}+ onOpenChange={setIsLogsDialogOpen}+ /></div>)}diff --git a/web-app/src/types/openclaw.ts b/web-app/src/types/openclaw.tsindex e50c1c9fa..15ff82b1a 100644--- a/web-app/src/types/openclaw.ts+++ b/web-app/src/types/openclaw.ts@@ -31,6 +31,8 @@ export interface OpenClawStatus {openclaw_version: string | nullport_available: booleanerror: string | null+ sandbox_type?: string | null+ isolation_tier?: string | null}export type TunnelProvider = 'none' | 'tailscale' | 'ngrok' | 'cloudflare' | 'localonly'