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: add validation step to confirm and attempt doctor fix

Vanalited893a1a24aaf
diff --git a/src-tauri/src/core/openclaw/commands.rs b/src-tauri/src/core/openclaw/commands.rs
index 7c10ceaae..6ad625fc7 100644
--- a/src-tauri/src/core/openclaw/commands.rs
+++ b/src-tauri/src/core/openclaw/commands.rs
@@ -584,6 +584,86 @@ async fn test_gateway_connection() -> Result<(), String> {
Ok(())
}
+/// Validate gateway auth via WebSocket handshake + RPC health check.
+async fn validate_gateway_auth() -> Result<(), String> {
+ let mut ws_stream = connect_to_gateway().await
+ .map_err(|e| format!("Gateway unreachable: {}", e))?;
+
+ gateway_handshake(&mut ws_stream).await
+ .map_err(|e| format!("Gateway auth failed: {}", e))?;
+
+ let health_id = next_request_id();
+ let health_request = serde_json::json!({
+ "type": "req",
+ "id": health_id,
+ "method": "health",
+ "params": {}
+ });
+
+ let health_json = serde_json::to_string(&health_request)
+ .map_err(|e| format!("Failed to serialize health request: {}", e))?;
+
+ ws_stream.send(Message::Text(health_json))
+ .await
+ .map_err(|e| format!("Failed to send health request: {}", e))?;
+
+ let timeout = tokio::time::Duration::from_secs(5);
+ let health_result = tokio::time::timeout(timeout, async {
+ while let Some(msg) = ws_stream.next().await {
+ match msg {
+ Ok(Message::Text(text)) => {
+ if let Ok(response) = serde_json::from_str::<GatewayResponse>(&text) {
+ if response.msg_type == "res" && response.id == health_id {
+ if response.ok {
+ return Ok(());
+ } else {
+ let error_msg = response.error
+ .map(|e| {
+ e.get("message")
+ .and_then(|m| m.as_str())
+ .map(String::from)
+ .unwrap_or_else(|| e.to_string())
+ })
+ .unwrap_or_else(|| "Health check rejected".to_string());
+ return Err(format!("Gateway health check failed: {}", error_msg));
+ }
+ }
+ }
+ }
+ Ok(Message::Close(_)) => return Err("Connection closed during health check".to_string()),
+ Err(e) => return Err(format!("WebSocket error during health check: {}", e)),
+ _ => {}
+ }
+ }
+ Err("Connection closed before health response".to_string())
+ }).await;
+
+ let _ = ws_stream.close(None).await;
+
+ match health_result {
+ Ok(inner) => inner,
+ Err(_) => Err("Gateway health check timed out".to_string()),
+ }
+}
+
+/// Auto-fix gateway config issues via `openclaw doctor --fix`.
+async fn run_doctor_fix() -> Result<(), String> {
+ let output = openclaw_command(&["doctor", "--fix"]).await
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await
+ .map_err(|e| format!("Failed to run openclaw doctor: {}", e))?;
+
+ if output.status.success() {
+ Ok(())
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ log::warn!("openclaw doctor --fix failed: {}", stderr);
+ Err(format!("Doctor fix failed: {}", stderr.trim()))
+ }
+}
+
/// Restart the gateway. Docker: `docker restart`. Direct process: stop → install → start
/// (launchd caches service args, so a plain `gateway restart` won't pick up config changes).
async fn restart_gateway_cli() -> Result<(), String> {
@@ -2087,7 +2167,62 @@ pub async fn openclaw_enable(
}
})?;
- // Step 6: Get final status
+ let gateway_wait = if is_docker { 60 } else { 15 };
+ if !wait_for_gateway_ready(gateway_wait).await {
+ return Err(serde_json::to_string(&EnableError {
+ code: EnableErrorCode::GatewayStartFailed,
+ message: "Gateway did not become responsive after starting.".to_string(),
+ recovery: vec![RecoveryOption {
+ label: "Retry".to_string(),
+ action: RecoveryAction::Retry,
+ description: "Try the setup again.".to_string(),
+ }],
+ })
+ .unwrap_or_else(|_| "Gateway not responsive".to_string()));
+ }
+
+ // Validate gateway auth + health (direct process only)
+ if !is_docker {
+ emit("validating", 85, "Validating configuration...", sandbox_info.as_deref());
+ steps_completed.push(EnableStep::ValidatingConfig);
+
+ match validate_gateway_auth().await {
+ Ok(()) => {}
+ Err(e) => {
+ log::warn!("Gateway validation failed: {}", e);
+ let _ = run_doctor_fix().await;
+ let _ = restart_gateway_cli().await;
+
+ if wait_for_gateway_ready(15).await {
+ if let Err(retry_err) = validate_gateway_auth().await {
+ return Err(serde_json::to_string(&EnableError {
+ code: EnableErrorCode::ValidationFailed,
+ message: format!("Validation failed after auto-fix: {}", retry_err),
+ recovery: vec![RecoveryOption {
+ label: "Retry".to_string(),
+ action: RecoveryAction::Retry,
+ description: "Try the setup again.".to_string(),
+ }],
+ })
+ .unwrap_or_else(|_| retry_err));
+ }
+ } else {
+ return Err(serde_json::to_string(&EnableError {
+ code: EnableErrorCode::ValidationFailed,
+ message: format!("Gateway did not recover after auto-fix: {}", e),
+ recovery: vec![RecoveryOption {
+ label: "Retry".to_string(),
+ action: RecoveryAction::Retry,
+ description: "Try the setup again.".to_string(),
+ }],
+ })
+ .unwrap_or_else(|_| e));
+ }
+ }
+ }
+ }
+
+ // Get final status
emit("complete", 100, "OpenClaw is ready!", sandbox_info.as_deref());
let final_status = openclaw_status(state).await?;
@@ -2279,14 +2414,19 @@ pub async fn openclaw_status(state: State<'_, OpenClawState>) -> Result<OpenClaw
})
}
-/// Restart the OpenClaw gateway via the sandbox abstraction.
+/// Restart the OpenClaw gateway. Blocks until the gateway is responsive.
#[tauri::command]
pub async fn openclaw_restart(state: State<'_, OpenClawState>) -> Result<(), String> {
- log::info!("Restarting OpenClaw gateway");
-
openclaw_stop(state.clone()).await?;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
- openclaw_start(state).await
+ openclaw_start(state).await?;
+
+ let max_wait = if is_docker_container_running().await { 60 } else { 15 };
+ if !wait_for_gateway_ready(max_wait).await {
+ return Err("Gateway did not become responsive after restart".to_string());
+ }
+
+ Ok(())
}
/// Get the OpenClaw configuration directory path
diff --git a/src-tauri/src/core/openclaw/models.rs b/src-tauri/src/core/openclaw/models.rs
index 08c3bef68..1eab056d8 100644
--- a/src-tauri/src/core/openclaw/models.rs
+++ b/src-tauri/src/core/openclaw/models.rs
@@ -549,6 +549,7 @@ pub enum EnableStep {
Installing,
Configuring,
Starting,
+ ValidatingConfig,
SyncingModels,
}
@@ -599,6 +600,7 @@ pub enum EnableErrorCode {
PortInUse,
ConfigWriteFailed,
GatewayStartFailed,
+ ValidationFailed,
}
/// A recovery option the user can take
diff --git a/web-app/src/containers/dialogs/EnableProgressDialog.tsx b/web-app/src/containers/dialogs/EnableProgressDialog.tsx
index 4c7ce3be7..f6cbcbde2 100644
--- a/web-app/src/containers/dialogs/EnableProgressDialog.tsx
+++ b/web-app/src/containers/dialogs/EnableProgressDialog.tsx
@@ -70,6 +70,7 @@ const STEP_LABELS: Record<string, string> = {
already_installed: 'OpenClaw installed',
configuring: 'Configuring',
starting: 'Starting gateway',
+ validating: 'Validating configuration',
syncing_models: 'Syncing models',
complete: 'Complete',
}
@@ -249,12 +250,16 @@ export function EnableProgressDialog({
}
}
+ const isDocker = sandboxInfo?.startsWith('Docker') ?? false
+
const allSteps = [
'checking_dependencies',
'checking_installation',
'installing',
'configuring',
'starting',
+ // Validation only runs for direct process, not Docker
+ ...(!isDocker ? ['validating'] : []),
'complete',
]
diff --git a/web-app/src/utils/openclaw.ts b/web-app/src/utils/openclaw.ts
index fd939a8b9..6953e5163 100644
--- a/web-app/src/utils/openclaw.ts
+++ b/web-app/src/utils/openclaw.ts
@@ -147,10 +147,7 @@ export async function ensureOpenClawHttpApi(): Promise<void> {
try {
const changed = await invoke<boolean>('openclaw_ensure_http_api')
if (changed) {
- console.log('[openclaw] Enabled HTTP chat completions endpoint, restarting gateway…')
await invoke('openclaw_restart')
- // Give the gateway a moment to become ready after restart
- await new Promise((resolve) => setTimeout(resolve, 2000))
}
httpApiEnsured = true
} catch {