Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/openclaw-rs/blob/main/tests/openclaw_tests.rs # openclaw-rs High-performance sovereign agent runtime in native Rust and Mojo for NVIDIA DGX Spark Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `openclaw-rs / tests / openclaw_tests.rs` 899 lines ยท 29500 bytes Raw Blame History 1 use axum::{ 2 body::Body, 3 http::{Request, StatusCode}, 4 }; 5 use futures_util::{SinkExt, StreamExt}; 6 use openclaw::{ 7 create_router, AgentEngine, Database, GatewayState, HeartbeatEngine, InferenceEngine, 8 MojoSimdBridge, SkillRegistry, VaultResolver, REDACTED_MARKER, 9 }; 10 use serde_json::Value; 11 use std::sync::Arc; 12 use std::time::Instant; 13 use tower::util::ServiceExt; 14 15 fn create_test_state() -> GatewayState { 16 let db = Arc::new(Database::open_in_memory().unwrap()); 17 let inference = Arc::new(InferenceEngine::new( 18 Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), 19 None, 20 )); 21 let heartbeat = Arc::new(HeartbeatEngine::with_inference( 22 60, 23 db.clone(), 24 inference.clone(), 25 )); 26 let skills = Arc::new(SkillRegistry::new()); 27 let agent = Arc::new(AgentEngine::new( 28 inference.clone(), 29 skills.clone(), 30 Some(db.clone()), 31 )); 32 33 GatewayState { 34 start_time: Instant::now(), 35 db, 36 inference, 37 heartbeat, 38 skills, 39 agent, 40 } 41 } 42 43 #[tokio::test] 44 async fn test_gateway_health_endpoint() { 45 let state = create_test_state(); 46 let app = create_router(state); 47 48 let response = app 49 .oneshot( 50 Request::builder() 51 .uri("/health") 52 .body(Body::empty()) 53 .unwrap(), 54 ) 55 .await 56 .unwrap(); 57 58 assert_eq!(response.status(), StatusCode::OK); 59 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 60 .await 61 .unwrap(); 62 let body: Value = serde_json::from_slice(&bytes).unwrap(); 63 assert_eq!(body["status"], "healthy"); 64 assert_eq!(body["engine"], "openclaw-rs/0.2.0"); 65 assert_eq!(body["database_mode"], "sqlite-wal"); 66 assert_eq!(body["zero_disk_secrets"], true); 67 } 68 69 #[tokio::test] 70 async fn test_gateway_openai_completions_endpoint() { 71 let state = create_test_state(); 72 let app = create_router(state); 73 74 let req_payload = serde_json::json!({ 75 "model": "atlas-lightning-omni", 76 "messages": [ 77 {"role": "system", "content": "You are OpenClaw."}, 78 {"role": "user", "content": "ping"} 79 ] 80 }); 81 82 let response = app 83 .oneshot( 84 Request::builder() 85 .method("POST") 86 .uri("/v1/chat/completions") 87 .header("Content-Type", "application/json") 88 .body(Body::from(req_payload.to_string())) 89 .unwrap(), 90 ) 91 .await 92 .unwrap(); 93 94 assert_eq!(response.status(), StatusCode::OK); 95 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 96 .await 97 .unwrap(); 98 let body: Value = serde_json::from_slice(&bytes).unwrap(); 99 assert_eq!(body["object"], "chat.completion"); 100 assert_eq!(body["choices"][0]["message"]["role"], "assistant"); 101 } 102 103 #[tokio::test] 104 async fn test_gateway_openai_multiturn_completions() { 105 let state = create_test_state(); 106 let app = create_router(state); 107 108 let req_payload = serde_json::json!({ 109 "model": "atlas-lightning-omni", 110 "messages": [ 111 {"role": "system", "content": "You are OpenClaw systems agent."}, 112 {"role": "user", "content": "List current memory status."}, 113 {"role": "assistant", "content": "All memory buffers nominal."}, 114 {"role": "user", "content": "Execute verification sweep."} 115 ] 116 }); 117 118 let response = app 119 .oneshot( 120 Request::builder() 121 .method("POST") 122 .uri("/v1/chat/completions") 123 .header("Content-Type", "application/json") 124 .body(Body::from(req_payload.to_string())) 125 .unwrap(), 126 ) 127 .await 128 .unwrap(); 129 130 assert_eq!(response.status(), StatusCode::OK); 131 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 132 .await 133 .unwrap(); 134 let body: Value = serde_json::from_slice(&bytes).unwrap(); 135 assert_eq!(body["object"], "chat.completion"); 136 assert_eq!(body["choices"][0]["finish_reason"], "stop"); 137 } 138 139 #[tokio::test] 140 async fn test_gateway_openai_streaming_endpoint() { 141 let state = create_test_state(); 142 let app = create_router(state); 143 144 let req_payload = serde_json::json!({ 145 "model": "atlas-lightning-omni", 146 "messages": [ 147 {"role": "user", "content": "stream tokens"} 148 ], 149 "stream": true 150 }); 151 152 let response = app 153 .oneshot( 154 Request::builder() 155 .method("POST") 156 .uri("/v1/chat/completions") 157 .header("Content-Type", "application/json") 158 .body(Body::from(req_payload.to_string())) 159 .unwrap(), 160 ) 161 .await 162 .unwrap(); 163 164 assert_eq!(response.status(), StatusCode::OK); 165 assert_eq!( 166 response.headers().get("content-type").unwrap(), 167 "text/event-stream" 168 ); 169 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 170 .await 171 .unwrap(); 172 let text = String::from_utf8_lossy(&bytes); 173 assert!(text.contains("data:")); 174 } 175 176 #[tokio::test] 177 async fn test_gateway_skills_endpoints() { 178 let state = create_test_state(); 179 let app = create_router(state.clone()); 180 181 // 1. List skills 182 let list_res = app 183 .oneshot( 184 Request::builder() 185 .uri("/api/v1/skills") 186 .body(Body::empty()) 187 .unwrap(), 188 ) 189 .await 190 .unwrap(); 191 192 assert_eq!(list_res.status(), StatusCode::OK); 193 let bytes = axum::body::to_bytes(list_res.into_body(), usize::MAX) 194 .await 195 .unwrap(); 196 let list: Value = serde_json::from_slice(&bytes).unwrap(); 197 let skills = list.as_array().unwrap(); 198 assert!(skills.iter().any(|s| s["name"] == "bash_eval")); 199 assert!(skills.iter().any(|s| s["name"] == "telemetry_ping")); 200 201 // 2. Execute skill 202 let app2 = create_router(state); 203 let exec_payload = serde_json::json!({ 204 "skill_name": "telemetry_ping", 205 "arguments": {} 206 }); 207 208 let exec_res = app2 209 .oneshot( 210 Request::builder() 211 .method("POST") 212 .uri("/api/v1/skills/execute") 213 .header("Content-Type", "application/json") 214 .body(Body::from(exec_payload.to_string())) 215 .unwrap(), 216 ) 217 .await 218 .unwrap(); 219 220 assert_eq!(exec_res.status(), StatusCode::OK); 221 let bytes2 = axum::body::to_bytes(exec_res.into_body(), usize::MAX) 222 .await 223 .unwrap(); 224 let result: Value = serde_json::from_slice(&bytes2).unwrap(); 225 assert_eq!(result["success"], true); 226 assert!(result["output"].as_str().unwrap().contains("healthy")); 227 } 228 229 #[tokio::test] 230 async fn test_gateway_shell_execution() { 231 let state = create_test_state(); 232 let app = create_router(state); 233 234 let req_payload = serde_json::json!({ 235 "command": "echo 'Sovereign OpenClaw native execution'" 236 }); 237 238 let response = app 239 .oneshot( 240 Request::builder() 241 .method("POST") 242 .uri("/api/v1/shell") 243 .header("Content-Type", "application/json") 244 .body(Body::from(req_payload.to_string())) 245 .unwrap(), 246 ) 247 .await 248 .unwrap(); 249 250 assert_eq!(response.status(), StatusCode::OK); 251 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 252 .await 253 .unwrap(); 254 let body: Value = serde_json::from_slice(&bytes).unwrap(); 255 assert_eq!(body["success"], true); 256 assert!(body["stdout"] 257 .as_str() 258 .unwrap() 259 .contains("Sovereign OpenClaw")); 260 } 261 262 #[tokio::test] 263 async fn test_gateway_task_creation_and_listing() { 264 let state = create_test_state(); 265 let app = create_router(state.clone()); 266 267 let req_payload = serde_json::json!({ 268 "task_type": "build_monitor", 269 "payload": "echo 'build nominal'" 270 }); 271 272 let response = app 273 .oneshot( 274 Request::builder() 275 .method("POST") 276 .uri("/api/v1/tasks") 277 .header("Content-Type", "application/json") 278 .body(Body::from(req_payload.to_string())) 279 .unwrap(), 280 ) 281 .await 282 .unwrap(); 283 284 assert_eq!(response.status(), StatusCode::OK); 285 286 let app2 = create_router(state); 287 let list_response = app2 288 .oneshot( 289 Request::builder() 290 .uri("/api/v1/tasks") 291 .body(Body::empty()) 292 .unwrap(), 293 ) 294 .await 295 .unwrap(); 296 297 assert_eq!(list_response.status(), StatusCode::OK); 298 let bytes = axum::body::to_bytes(list_response.into_body(), usize::MAX) 299 .await 300 .unwrap(); 301 let tasks: Value = serde_json::from_slice(&bytes).unwrap(); 302 assert_eq!(tasks.as_array().unwrap().len(), 1); 303 assert_eq!(tasks[0]["task_type"], "build_monitor"); 304 } 305 306 #[tokio::test] 307 async fn test_gateway_websocket_lifecycle() { 308 let state = create_test_state(); 309 let app = create_router(state); 310 311 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 312 let port = listener.local_addr().unwrap().port(); 313 314 tokio::spawn(async move { 315 axum::serve(listener, app).await.unwrap(); 316 }); 317 318 let ws_url = format!("ws://127.0.0.1:{}/ws", port); 319 let (mut ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await.unwrap(); 320 321 // 1. Welcome message 322 let msg = ws_stream.next().await.unwrap().unwrap(); 323 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 324 assert_eq!(val["type"], "welcome"); 325 assert_eq!(val["gateway"], "openclaw-rs"); 326 327 // 2. Ping / Pong 328 ws_stream 329 .send(tokio_tungstenite::tungstenite::Message::Text( 330 serde_json::json!({"type": "ping"}).to_string(), 331 )) 332 .await 333 .unwrap(); 334 335 let msg = ws_stream.next().await.unwrap().unwrap(); 336 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 337 assert_eq!(val["type"], "pong"); 338 339 // 3. Skills list over WebSocket 340 ws_stream 341 .send(tokio_tungstenite::tungstenite::Message::Text( 342 serde_json::json!({"type": "skills_list"}).to_string(), 343 )) 344 .await 345 .unwrap(); 346 347 let msg = ws_stream.next().await.unwrap().unwrap(); 348 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 349 assert_eq!(val["type"], "skills_list"); 350 assert!(!val["skills"].as_array().unwrap().is_empty()); 351 352 // 4. Skill execute over WebSocket 353 ws_stream 354 .send(tokio_tungstenite::tungstenite::Message::Text( 355 serde_json::json!({ 356 "type": "skill_exec", 357 "skill_name": "telemetry_ping", 358 "arguments": {} 359 }) 360 .to_string(), 361 )) 362 .await 363 .unwrap(); 364 365 let msg = ws_stream.next().await.unwrap().unwrap(); 366 let val: Value = serde_json::from_str(&msg.to_string()).unwrap(); 367 assert_eq!(val["type"], "skill_result"); 368 assert_eq!(val["response"]["success"], true); 369 } 370 371 #[tokio::test] 372 async fn test_mojo_simd_bridge_operations() { 373 let v1 = [1.0f32, 0.0, 0.0, 0.0]; 374 let v2 = [1.0f32, 0.0, 0.0, 0.0]; 375 let sim = MojoSimdBridge::cosine_similarity_4d(v1, v2); 376 assert!((sim - 1.0).abs() < 1e-4); 377 378 let tokens = [2.0f32, 4.0, 6.0, 8.0]; 379 let weights = [0.25f32, 0.25, 0.25, 0.25]; 380 let proj = MojoSimdBridge::token_projection(tokens, weights, 2.0); 381 assert!((proj - 7.0).abs() < 1e-4); 382 383 let entropy = MojoSimdBridge::token_entropy([0.5, 0.5, 0.0, 0.0]); 384 assert!(entropy < 0.0); 385 } 386 387 #[tokio::test] 388 async fn test_gateway_agent_run_endpoint() { 389 let state = create_test_state(); 390 let app = create_router(state); 391 392 let req_payload = serde_json::json!({ 393 "prompt": "Status and telemetry check", 394 "max_turns": 2 395 }); 396 397 let response = app 398 .oneshot( 399 Request::builder() 400 .method("POST") 401 .uri("/api/v1/agent/run") 402 .header("Content-Type", "application/json") 403 .body(Body::from(req_payload.to_string())) 404 .unwrap(), 405 ) 406 .await 407 .unwrap(); 408 409 assert_eq!(response.status(), StatusCode::OK); 410 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 411 .await 412 .unwrap(); 413 let body: Value = serde_json::from_slice(&bytes).unwrap(); 414 assert_eq!(body["status"], "completed"); 415 assert_eq!(body["prompt"], "Status and telemetry check"); 416 assert!(body["steps"].is_array()); 417 } 418 419 #[tokio::test] 420 async fn test_gateway_concurrent_requests_under_tokio_spawns() { 421 let state = create_test_state(); 422 let app = create_router(state); 423 424 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 425 let port = listener.local_addr().unwrap().port(); 426 427 tokio::spawn(async move { 428 axum::serve(listener, app).await.unwrap(); 429 }); 430 431 let client = reqwest::Client::new(); 432 let base_url = format!("http://127.0.0.1:{}", port); 433 434 let mut handles = Vec::new(); 435 for i in 0..30 { 436 let client_clone = client.clone(); 437 let base = base_url.clone(); 438 handles.push(tokio::spawn(async move { 439 match i % 4 { 440 0 => { 441 let res = client_clone.get(format!("{}/health", base)).send().await.unwrap(); 442 assert_eq!(res.status(), 200); 443 } 444 1 => { 445 let res = client_clone.get(format!("{}/v1/models", base)).send().await.unwrap(); 446 assert_eq!(res.status(), 200); 447 } 448 2 => { 449 let res = client_clone.get(format!("{}/api/v1/skills", base)).send().await.unwrap(); 450 assert_eq!(res.status(), 200); 451 } 452 _ => { 453 let payload = serde_json::json!({ 454 "model": "atlas-lightning-omni", 455 "messages": [{"role": "user", "content": "concurrent ping"}] 456 }); 457 let res = client_clone 458 .post(format!("{}/v1/chat/completions", base)) 459 .json(&payload) 460 .send() 461 .await 462 .unwrap(); 463 assert_eq!(res.status(), 200); 464 } 465 } 466 })); 467 } 468 469 for handle in handles { 470 handle.await.unwrap(); 471 } 472 } 473 474 #[tokio::test] 475 async fn test_gateway_completions_error_handling_and_validation() { 476 let state = create_test_state(); 477 478 // 1. Malformed JSON syntax 479 let app1 = create_router(state.clone()); 480 let malformed_res = app1 481 .oneshot( 482 Request::builder() 483 .method("POST") 484 .uri("/v1/chat/completions") 485 .header("Content-Type", "application/json") 486 .body(Body::from("{ \"model\": invalid_syntax")) 487 .unwrap(), 488 ) 489 .await 490 .unwrap(); 491 assert!( 492 malformed_res.status() == StatusCode::BAD_REQUEST 493 || malformed_res.status() == StatusCode::UNPROCESSABLE_ENTITY 494 ); 495 496 // 2. Missing required field 'messages' 497 let app2 = create_router(state.clone()); 498 let missing_field_payload = serde_json::json!({ 499 "model": "atlas-lightning-omni" 500 }); 501 let missing_field_res = app2 502 .oneshot( 503 Request::builder() 504 .method("POST") 505 .uri("/v1/chat/completions") 506 .header("Content-Type", "application/json") 507 .body(Body::from(missing_field_payload.to_string())) 508 .unwrap(), 509 ) 510 .await 511 .unwrap(); 512 assert_eq!(missing_field_res.status(), StatusCode::UNPROCESSABLE_ENTITY); 513 514 // 3. Empty messages array 515 let app3 = create_router(state.clone()); 516 let empty_messages_payload = serde_json::json!({ 517 "model": "atlas-lightning-omni", 518 "messages": [] 519 }); 520 let empty_res = app3 521 .oneshot( 522 Request::builder() 523 .method("POST") 524 .uri("/v1/chat/completions") 525 .header("Content-Type", "application/json") 526 .body(Body::from(empty_messages_payload.to_string())) 527 .unwrap(), 528 ) 529 .await 530 .unwrap(); 531 assert_eq!(empty_res.status(), StatusCode::BAD_REQUEST); 532 let bytes = axum::body::to_bytes(empty_res.into_body(), usize::MAX) 533 .await 534 .unwrap(); 535 let body: Value = serde_json::from_slice(&bytes).unwrap(); 536 assert_eq!(body["error"]["code"], "missing_required_parameter"); 537 538 // 4. Unsupported model 539 let app4 = create_router(state.clone()); 540 let unsupported_model_payload = serde_json::json!({ 541 "model": "unsupported-model-v999", 542 "messages": [{"role": "user", "content": "ping"}] 543 }); 544 let unsupported_res = app4 545 .oneshot( 546 Request::builder() 547 .method("POST") 548 .uri("/v1/chat/completions") 549 .header("Content-Type", "application/json") 550 .body(Body::from(unsupported_model_payload.to_string())) 551 .unwrap(), 552 ) 553 .await 554 .unwrap(); 555 assert_eq!(unsupported_res.status(), StatusCode::NOT_FOUND); 556 let bytes = axum::body::to_bytes(unsupported_res.into_body(), usize::MAX) 557 .await 558 .unwrap(); 559 let body: Value = serde_json::from_slice(&bytes).unwrap(); 560 assert_eq!(body["error"]["code"], "model_not_found"); 561 } 562 563 #[tokio::test] 564 async fn test_gateway_openai_streaming_formatting_and_terminal_chunk() { 565 let state = create_test_state(); 566 let app = create_router(state); 567 568 let payload = serde_json::json!({ 569 "model": "atlas-lightning-omni", 570 "messages": [{"role": "user", "content": "stream token check"}], 571 "stream": true 572 }); 573 574 let response = app 575 .oneshot( 576 Request::builder() 577 .method("POST") 578 .uri("/v1/chat/completions") 579 .header("Content-Type", "application/json") 580 .body(Body::from(payload.to_string())) 581 .unwrap(), 582 ) 583 .await 584 .unwrap(); 585 586 assert_eq!(response.status(), StatusCode::OK); 587 assert_eq!( 588 response.headers().get("content-type").unwrap(), 589 "text/event-stream" 590 ); 591 592 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 593 .await 594 .unwrap(); 595 let sse_text = String::from_utf8_lossy(&bytes); 596 597 // Split by double newline into SSE events 598 let events: Vec<&str> = sse_text 599 .split("\n\n") 600 .map(|s| s.trim()) 601 .filter(|s| !s.is_empty()) 602 .collect(); 603 604 assert!(events.len() >= 2); 605 606 // Verify first event is formatted chunk 607 let first_event = events[0]; 608 assert!(first_event.starts_with("data: ")); 609 let json_str = &first_event["data: ".len()..]; 610 let chunk_json: Value = serde_json::from_str(json_str).unwrap(); 611 assert_eq!(chunk_json["object"], "chat.completion.chunk"); 612 assert!(chunk_json["choices"][0]["delta"]["content"].is_string()); 613 614 // Verify last event is [DONE] 615 let last_event = events.last().unwrap(); 616 assert_eq!(*last_event, "data: [DONE]"); 617 } 618 619 #[tokio::test] 620 async fn test_gateway_agent_run_complex_payloads_and_edge_paths() { 621 let state = create_test_state(); 622 let app = create_router(state); 623 624 let complex_goal = "Execute sovereign diagnostics:\n1. Check local environment with \"quotes\" and { \"nested\": \"json\", \"value\": 42 }\n2. Inspect filesystem safety: prohibited 'find /' checks\n3. Emit unslop confirmation report"; 625 626 let payload = serde_json::json!({ 627 "prompt": complex_goal, 628 "system": "You are OpenClaw sovereign integration verifier.", 629 "max_turns": 3 630 }); 631 632 let response = app 633 .oneshot( 634 Request::builder() 635 .method("POST") 636 .uri("/api/v1/agent/run") 637 .header("Content-Type", "application/json") 638 .body(Body::from(payload.to_string())) 639 .unwrap(), 640 ) 641 .await 642 .unwrap(); 643 644 assert_eq!(response.status(), StatusCode::OK); 645 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) 646 .await 647 .unwrap(); 648 let body: Value = serde_json::from_slice(&bytes).unwrap(); 649 assert_eq!(body["status"], "completed"); 650 assert_eq!(body["prompt"], complex_goal); 651 assert!(body["turns_taken"].as_u64().unwrap() <= 3); 652 assert!(body["completed"].as_bool().unwrap()); 653 assert!(body["steps"].is_array()); 654 } 655 656 #[tokio::test] 657 async fn test_gateway_websocket_lifecycle_ping_pong_and_close() { 658 let state = create_test_state(); 659 let app = create_router(state); 660 661 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); 662 let port = listener.local_addr().unwrap().port(); 663 664 tokio::spawn(async move { 665 axum::serve(listener, app).await.unwrap(); 666 }); 667 668 let ws_url = format!("ws://127.0.0.1:{}/ws", port); 669 let (mut ws_stream, _) = tokio_tungstenite::connect_async(ws_url).await.unwrap(); 670 671 // 1. Welcome frame 672 let welcome_msg = ws_stream.next().await.unwrap().unwrap(); 673 let val: Value = serde_json::from_str(&welcome_msg.to_string()).unwrap(); 674 assert_eq!(val["type"], "welcome"); 675 676 // 2. Application Ping -> Pong 677 ws_stream 678 .send(tokio_tungstenite::tungstenite::Message::Text( 679 serde_json::json!({"type": "ping"}).to_string(), 680 )) 681 .await 682 .unwrap(); 683 let pong_msg = ws_stream.next().await.unwrap().unwrap(); 684 let pong_val: Value = serde_json::from_str(&pong_msg.to_string()).unwrap(); 685 assert_eq!(pong_val["type"], "pong"); 686 687 // 3. Native Tungstenite Ping frame -> expect native Pong frame 688 ws_stream 689 .send(tokio_tungstenite::tungstenite::Message::Ping(vec![9, 8, 7])) 690 .await 691 .unwrap(); 692 693 let pong_frame = ws_stream.next().await.unwrap().unwrap(); 694 assert!(pong_frame.is_pong()); 695 if let tokio_tungstenite::tungstenite::Message::Pong(data) = pong_frame { 696 assert_eq!(data, vec![9, 8, 7]); 697 } 698 699 // 4. Shell execution via WebSocket 700 ws_stream 701 .send(tokio_tungstenite::tungstenite::Message::Text( 702 serde_json::json!({ 703 "type": "shell", 704 "command": "echo 'ws_shell_ok'" 705 }) 706 .to_string(), 707 )) 708 .await 709 .unwrap(); 710 let shell_msg = ws_stream.next().await.unwrap().unwrap(); 711 let shell_val: Value = serde_json::from_str(&shell_msg.to_string()).unwrap(); 712 assert_eq!(shell_val["type"], "shell_output"); 713 assert!(shell_val["stdout"].as_str().unwrap().contains("ws_shell_ok")); 714 715 // 5. Clean connection close 716 ws_stream 717 .send(tokio_tungstenite::tungstenite::Message::Close(None)) 718 .await 719 .unwrap(); 720 } 721 722 #[tokio::test] 723 async fn test_gateway_submillisecond_health_latency_benchmark() { 724 let state = create_test_state(); 725 726 let app = create_router(state); 727 728 // Warm-up 729 for _ in 0..5 { 730 let _ = app 731 .clone() 732 .oneshot( 733 Request::builder() 734 .uri("/health") 735 .body(Body::empty()) 736 .unwrap(), 737 ) 738 .await 739 .unwrap(); 740 } 741 742 let iterations = 100; 743 let mut total_duration_micros: u128 = 0; 744 745 for _ in 0..iterations { 746 let start = Instant::now(); 747 let response = app 748 .clone() 749 .oneshot( 750 Request::builder() 751 .uri("/health") 752 .body(Body::empty()) 753 .unwrap(), 754 ) 755 .await 756 .unwrap(); 757 let elapsed = start.elapsed().as_micros(); 758 assert_eq!(response.status(), StatusCode::OK); 759 total_duration_micros += elapsed; 760 } 761 762 let avg_micros = total_duration_micros / iterations; 763 println!( 764 "Health endpoint latency benchmark: {} iterations, average = {} microseconds", 765 iterations, avg_micros 766 ); 767 assert!( 768 avg_micros < 1000, 769 "Health endpoint average latency must be sub-millisecond, got {} us", 770 avg_micros 771 ); 772 } 773 774 #[tokio::test] 775 async fn test_agent_multiturn_accumulation_and_error_recovery() { 776 let db = Arc::new(Database::open_in_memory().unwrap()); 777 let inference = Arc::new(InferenceEngine::new( 778 Some("http://127.0.0.1:9999/v1/chat/completions".to_string()), 779 None, 780 )); 781 let skills = Arc::new(SkillRegistry::new()); 782 let agent = AgentEngine::new(inference, skills.clone(), Some(db.clone())); 783 784 // Test execution with max_turns = 3 under local fallback 785 let result = agent 786 .execute_task("Run sequential diagnostic checks", None, 3) 787 .await 788 .unwrap(); 789 790 assert!(result.completed); 791 assert!(result.turns_taken >= 1); 792 assert!(!result.final_response.is_empty()); 793 794 // Verify DB recorded turn 795 let turns = db.list_recent_turns(5).unwrap(); 796 assert!(!turns.is_empty()); 797 assert_eq!(turns[0].prompt, "Run sequential diagnostic checks"); 798 } 799 800 #[test] 801 fn test_agent_token_budget_boundary_conditions() { 802 let mut msgs = vec![ 803 serde_json::json!({"role": "system", "content": "System prompt"}), 804 serde_json::json!({"role": "user", "content": "User initial request"}), 805 serde_json::json!({"role": "assistant", "content": "Step 1"}), 806 serde_json::json!({"role": "tool", "content": "Tool output 1"}), 807 serde_json::json!({"role": "assistant", "content": "Step 2"}), 808 serde_json::json!({"role": "tool", "content": "Tool output 2"}), 809 ]; 810 811 // Budget higher than tokens: no pruning 812 let p1 = AgentEngine::prune_context_window(&mut msgs, 5000); 813 assert!(!p1); 814 assert_eq!(msgs.len(), 6); 815 816 // Budget lower than tokens: prunes oldest intermediate turns first 817 let p2 = AgentEngine::prune_context_window(&mut msgs, 15); 818 assert!(p2); 819 assert_eq!(msgs.len(), 2); 820 assert_eq!(msgs[0]["role"], "system"); 821 assert_eq!(msgs[1]["role"], "user"); 822 823 // Boundary: length <= 2 cannot be pruned further 824 let p3 = AgentEngine::prune_context_window(&mut msgs, 0); 825 assert!(!p3); 826 assert_eq!(msgs.len(), 2); 827 } 828 829 #[test] 830 fn test_vault_streaming_redaction_and_zero_disk_keys() { 831 let vault = VaultResolver::new(); 832 vault.insert_cached("API_SECRET_KEY", "openclaw_sk_live_alpha9922"); 833 vault.insert_cached("DB_PASS", "postgres_master_secret_123"); 834 835 // Test streaming token chunks 836 let stream_chunks = vec![ 837 "data: {\"token\": \"Authentication header: Bearer \"}\n\n", 838 "data: {\"token\": \"openclaw_sk_live_alpha9922\"}\n\n", 839 "data: {\"token\": \" connected with postgres_master_secret_123\"}\n\n", 840 "data: [DONE]\n\n", 841 ]; 842 843 let mut redacted_chunks = Vec::new(); 844 for chunk in stream_chunks { 845 redacted_chunks.push(vault.redact_sensitive_text(chunk)); 846 } 847 848 assert!(!redacted_chunks[1].contains("openclaw_sk_live_alpha9922")); 849 assert!(redacted_chunks[1].contains(REDACTED_MARKER)); 850 assert!(!redacted_chunks[2].contains("postgres_master_secret_123")); 851 assert!(redacted_chunks[2].contains(REDACTED_MARKER)); 852 853 // Multi-line response redaction 854 let multiline = "Error log:\nAuth: openclaw_sk_live_alpha9922\nDB: postgres_master_secret_123\nStatus: nominal"; 855 let redacted_multi = vault.redact_sensitive_text(multiline); 856 assert!(!redacted_multi.contains("openclaw_sk_live_alpha9922")); 857 assert!(!redacted_multi.contains("postgres_master_secret_123")); 858 859 // Verify zero disk secrets written 860 assert!(!std::path::Path::new(".env").exists()); 861 assert!(!std::path::Path::new(".env.local").exists()); 862 assert!(!std::path::Path::new(".env.production").exists()); 863 } 864 865 #[test] 866 fn test_mojo_simd_mathematical_invariants_and_edge_cases() { 867 // Zero vectors 868 let zero = [0.0f32, 0.0, 0.0, 0.0]; 869 let non_zero = [1.0f32, 2.0, 3.0, 4.0]; 870 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(zero, non_zero), 0.0); 871 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(zero, zero), 0.0); 872 873 // Identical vectors 874 let v = [0.5f32, -0.5, 0.5, -0.5]; 875 let sim_ident = MojoSimdBridge::cosine_similarity_4d_fallback(v, v); 876 assert!((sim_ident - 1.0).abs() < 1e-4); 877 878 // Orthogonal vectors 879 let o1 = [1.0f32, 0.0, 0.0, 0.0]; 880 let o2 = [0.0f32, 1.0, 0.0, 0.0]; 881 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(o1, o2), 0.0); 882 883 // Opposite vectors 884 let opp = [-0.5f32, 0.5, -0.5, 0.5]; 885 let sim_opp = MojoSimdBridge::cosine_similarity_4d_fallback(v, opp); 886 assert!((sim_opp - (-1.0)).abs() < 1e-4); 887 888 // NaN and Inf handling 889 let nan_v = [f32::NAN, 1.0, 2.0, 3.0]; 890 let inf_v = [f32::INFINITY, 1.0, 2.0, 3.0]; 891 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(nan_v, non_zero), 0.0); 892 assert_eq!(MojoSimdBridge::cosine_similarity_4d_fallback(inf_v, non_zero), 0.0); 893 894 // Temperature scale boundaries 895 assert_eq!(MojoSimdBridge::temperature_scale_fallback(4.0, 0.0), 4.0); 896 assert_eq!(MojoSimdBridge::temperature_scale_fallback(4.0, f32::NAN), 0.0); 897 let normal_scaled = MojoSimdBridge::temperature_scale_fallback(8.0, 2.0); 898 assert!((normal_scaled - 4.0).abs() < 1e-4); 899 }