| 1 | use super::*; |
| 2 | use crate::bridge::*; |
| 3 | use crate::config_rpc::*; |
| 4 | use crate::http::*; |
| 5 | use crate::stdio::*; |
| 6 | use crate::turns::*; |
| 7 | use axum::body::{Body, to_bytes}; |
| 8 | use axum::extract::{Path as AxumPath, Query}; |
| 9 | use axum::extract::{Request, State}; |
| 10 | use axum::http::header; |
| 11 | use axum::response::{IntoResponse, Response}; |
| 12 | use axum::routing::{get, post}; |
| 13 | use axum::{Json, Router}; |
| 14 | use codewhale_protocol::{AppRequest, PromptRequest, PromptResponse}; |
| 15 | use std::collections::HashMap; |
| 16 | use std::collections::VecDeque; |
| 17 | use std::fs; |
| 18 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 19 | use tower::ServiceExt; |
| 20 | |
| 21 | #[tokio::test] |
| 22 | async fn control_framing_accepts_exact_limit_crlf_and_preserves_next_frame() { |
| 23 | let mut input = vec![b'x'; MAX_RUNTIME_IMAGE_BODY_BYTES]; |
| 24 | input.extend_from_slice(b"\r\nnext\n"); |
| 25 | let mut reader = BoundedLines::new(BufReader::with_capacity(8192, input.as_slice())); |
| 26 | assert_eq!( |
| 27 | reader.next_line().await.unwrap().unwrap().len(), |
| 28 | MAX_RUNTIME_IMAGE_BODY_BYTES |
| 29 | ); |
| 30 | assert_eq!(reader.next_line().await.unwrap().as_deref(), Some("next")); |
| 31 | assert!(reader.next_line().await.unwrap().is_none()); |
| 32 | } |
| 33 | |
| 34 | #[tokio::test] |
| 35 | async fn control_framing_rejects_non_utf8_and_keeps_eof_line_contract() { |
| 36 | let mut invalid = BoundedLines::new(BufReader::new(&b"\xff\n"[..])); |
| 37 | assert_eq!( |
| 38 | invalid.next_line().await.unwrap_err().kind(), |
| 39 | std::io::ErrorKind::InvalidData |
| 40 | ); |
| 41 | let mut eof = BoundedLines::new(BufReader::new(&b"last\r"[..])); |
| 42 | assert_eq!(eof.next_line().await.unwrap().as_deref(), Some("last\r")); |
| 43 | assert!(eof.next_line().await.unwrap().is_none()); |
| 44 | } |
| 45 | |
| 46 | #[test] |
| 47 | fn retained_control_queue_refuses_exhaustion_without_admitting_more_work() { |
| 48 | let mut pending = VecDeque::new(); |
| 49 | let mut bytes = 0; |
| 50 | for _ in 0..64 { |
| 51 | queue_stdio_work( |
| 52 | &mut pending, |
| 53 | &mut bytes, |
| 54 | PendingStdioWork::Response(json!({})), |
| 55 | 2, |
| 56 | ) |
| 57 | .unwrap(); |
| 58 | } |
| 59 | let before = bytes; |
| 60 | assert!( |
| 61 | queue_stdio_work( |
| 62 | &mut pending, |
| 63 | &mut bytes, |
| 64 | PendingStdioWork::Response(json!({})), |
| 65 | 2 |
| 66 | ) |
| 67 | .is_err() |
| 68 | ); |
| 69 | assert_eq!(pending.len(), 64); |
| 70 | assert_eq!(bytes, before); |
| 71 | let mut pending = VecDeque::new(); |
| 72 | let mut bytes = 0; |
| 73 | assert!( |
| 74 | queue_stdio_work( |
| 75 | &mut pending, |
| 76 | &mut bytes, |
| 77 | PendingStdioWork::Response(json!({})), |
| 78 | MAX_RUNTIME_IMAGE_BODY_BYTES |
| 79 | ) |
| 80 | .is_err() |
| 81 | ); |
| 82 | assert!(pending.is_empty()); |
| 83 | assert_eq!(bytes, 0); |
| 84 | } |
| 85 | |
| 86 | #[tokio::test] |
| 87 | async fn captured_owner_bridge_is_retained_and_never_spawns_a_replacement() { |
| 88 | install_test_crypto_provider(); |
| 89 | let tmp = tempfile::tempdir().unwrap(); |
| 90 | let config = tmp.path().join("config.toml"); |
| 91 | fs::write(&config, "").unwrap(); |
| 92 | let mut state = build_state(Some(config), None).unwrap(); |
| 93 | state.captured_owner = Some(codewhale_protocol::RuntimeOwnerReceipt { |
| 94 | version: 1, |
| 95 | data_dir: tmp.path().join("runtime"), |
| 96 | execution_scope: "fixture".into(), |
| 97 | lease_generation: "fixture".into(), |
| 98 | pid: std::process::id(), |
| 99 | process_start: "fixture".into(), |
| 100 | principal: "fixture".into(), |
| 101 | socket_path: tmp.path().join("owner.sock"), |
| 102 | config_path: state.config_path.clone(), |
| 103 | }); |
| 104 | let captured = Arc::new(Mutex::new(RuntimeBridge { |
| 105 | base_url: "http://127.0.0.1:1".into(), |
| 106 | client: codewhale_release::tls::reqwest_client(), |
| 107 | auth_token: None, |
| 108 | child: None, |
| 109 | last_seq_by_thread: HashMap::new(), |
| 110 | })); |
| 111 | *state.runtime_bridge.lock().await = Some(captured.clone()); |
| 112 | invalidate_runtime_bridge(&state).await; |
| 113 | let live = acquire_runtime_bridge(&state).await.unwrap(); |
| 114 | assert!(Arc::ptr_eq(&live, &captured)); |
| 115 | *state.runtime_bridge.lock().await = None; |
| 116 | let refused = acquire_runtime_bridge(&state).await; |
| 117 | assert!(refused.is_err()); |
| 118 | } |
| 119 | |
| 120 | #[tokio::test] |
| 121 | async fn unbound_frontend_refuses_turn_without_creating_a_runtime_owner() { |
| 122 | install_test_crypto_provider(); |
| 123 | let (state, _temporary) = capability_test_state(); |
| 124 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 125 | let refused = dispatch_stdio_request( |
| 126 | &state, |
| 127 | "prompt/request", |
| 128 | json!({"allowed_tools": [], "prompt":"must not dispatch"}), |
| 129 | ) |
| 130 | .await |
| 131 | .expect_err("no captured owner can execute this prompt"); |
| 132 | assert_eq!(refused.wire.code, RUNTIME_UNAVAILABLE_CODE); |
| 133 | assert!(refused.wire.message.contains("refusing another owner")); |
| 134 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 135 | assert!(state.runtime_thread_map.lock().await.is_empty()); |
| 136 | assert!(state.in_flight_turns.lock().await.is_empty()); |
| 137 | } |
| 138 | |
| 139 | #[test] |
| 140 | fn captured_bridge_diagnostics_redact_private_authentication() { |
| 141 | let mut bridge = RuntimeBridge::from_base_url_for_test("http://127.0.0.1:1".into()); |
| 142 | bridge.auth_token = Some("private-bridge-token-must-stay-in-memory".into()); |
| 143 | let diagnostic = format!("{bridge:?}"); |
| 144 | assert!(!diagnostic.contains("private-bridge-token")); |
| 145 | assert!(diagnostic.contains("authenticated: true")); |
| 146 | } |
| 147 | |
| 148 | #[tokio::test] |
| 149 | async fn full_control_queue_keeps_interrupt_priority_and_guest_shutdown_refusal() { |
| 150 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 151 | async fn interrupted(State(count): State<Arc<AtomicUsize>>) -> StatusCode { |
| 152 | count.fetch_add(1, Ordering::SeqCst); |
| 153 | StatusCode::OK |
| 154 | } |
| 155 | install_test_crypto_provider(); |
| 156 | let count = Arc::new(AtomicUsize::new(0)); |
| 157 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 158 | let address = listener.local_addr().unwrap(); |
| 159 | let app = Router::new() |
| 160 | .route( |
| 161 | "/v1/threads/runtime/turns/turn/interrupt", |
| 162 | post(interrupted), |
| 163 | ) |
| 164 | .with_state(count.clone()); |
| 165 | let server = tokio::spawn(async move { |
| 166 | axum::serve(listener, app).await.unwrap(); |
| 167 | }); |
| 168 | let (state, _root) = capability_test_state(); |
| 169 | let register_turn = || InFlightTurn { |
| 170 | owner: TurnExecutionOwner::HistoricalHttp { |
| 171 | base_url: format!("http://{address}"), |
| 172 | auth_token: None, |
| 173 | }, |
| 174 | runtime_thread_id: "runtime".into(), |
| 175 | turn_id: "turn".into(), |
| 176 | connection: None, |
| 177 | }; |
| 178 | state |
| 179 | .in_flight_turns |
| 180 | .lock() |
| 181 | .await |
| 182 | .insert("client".into(), register_turn()); |
| 183 | let mut pending = VecDeque::new(); |
| 184 | let mut bytes = 0; |
| 185 | for _ in 0..64 { |
| 186 | queue_stdio_work( |
| 187 | &mut pending, |
| 188 | &mut bytes, |
| 189 | PendingStdioWork::Response(json!({})), |
| 190 | 2, |
| 191 | ) |
| 192 | .unwrap(); |
| 193 | } |
| 194 | let guest = StdioLoopPolicy { |
| 195 | transport: AppTransport::Socket, |
| 196 | shutdown: ShutdownAuthority::Denied, |
| 197 | }; |
| 198 | assert!( |
| 199 | handle_line_during_turn( |
| 200 | &state, |
| 201 | r#"{"id":1,"method":"shutdown","params":{}}"#, |
| 202 | &mut pending, |
| 203 | &mut bytes, |
| 204 | guest, |
| 205 | None |
| 206 | ) |
| 207 | .await |
| 208 | .is_err() |
| 209 | ); |
| 210 | assert_eq!( |
| 211 | count.load(Ordering::SeqCst), |
| 212 | 0, |
| 213 | "guest must not interrupt before its denied shutdown" |
| 214 | ); |
| 215 | assert!( |
| 216 | handle_line_during_turn( |
| 217 | &state, |
| 218 | r#"{"id":2,"method":"thread/interrupt","params":{"thread_id":"client"}}"#, |
| 219 | &mut pending, |
| 220 | &mut bytes, |
| 221 | guest, |
| 222 | None |
| 223 | ) |
| 224 | .await |
| 225 | .is_err() |
| 226 | ); |
| 227 | assert_eq!( |
| 228 | count.load(Ordering::SeqCst), |
| 229 | 1, |
| 230 | "interrupt acts before its overloaded reply queue" |
| 231 | ); |
| 232 | assert!( |
| 233 | state.in_flight_turns.lock().await.is_empty(), |
| 234 | "a successful interrupt retires the turn registration" |
| 235 | ); |
| 236 | state |
| 237 | .in_flight_turns |
| 238 | .lock() |
| 239 | .await |
| 240 | .insert("client".into(), register_turn()); |
| 241 | let owner = StdioLoopPolicy { |
| 242 | transport: AppTransport::Socket, |
| 243 | shutdown: ShutdownAuthority::Granted, |
| 244 | }; |
| 245 | assert!( |
| 246 | handle_line_during_turn( |
| 247 | &state, |
| 248 | r#"{"id":3,"method":"shutdown","params":{}}"#, |
| 249 | &mut pending, |
| 250 | &mut bytes, |
| 251 | owner, |
| 252 | None |
| 253 | ) |
| 254 | .await |
| 255 | .is_err() |
| 256 | ); |
| 257 | assert_eq!( |
| 258 | count.load(Ordering::SeqCst), |
| 259 | 2, |
| 260 | "authorized shutdown retains immediate interrupt priority" |
| 261 | ); |
| 262 | assert_eq!(pending.len(), 64); |
| 263 | server.abort(); |
| 264 | } |
| 265 | |
| 266 | #[tokio::test] |
| 267 | async fn bound_owner_config_reload_uses_private_auth_and_preserves_rejected_owner() { |
| 268 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 269 | #[derive(Clone)] |
| 270 | struct ReloadFixture { |
| 271 | count: Arc<AtomicUsize>, |
| 272 | refuse: Arc<AtomicBool>, |
| 273 | } |
| 274 | async fn reload( |
| 275 | State(fixture): State<ReloadFixture>, |
| 276 | headers: axum::http::HeaderMap, |
| 277 | ) -> Response { |
| 278 | assert_eq!( |
| 279 | headers.get(header::AUTHORIZATION).unwrap(), |
| 280 | "Bearer private-reload-fixture" |
| 281 | ); |
| 282 | fixture.count.fetch_add(1, Ordering::SeqCst); |
| 283 | if fixture.refuse.load(Ordering::SeqCst) { |
| 284 | StatusCode::BAD_REQUEST.into_response() |
| 285 | } else { |
| 286 | Json(json!({"message":"fixture config reloaded"})).into_response() |
| 287 | } |
| 288 | } |
| 289 | install_test_crypto_provider(); |
| 290 | let fixture = ReloadFixture { |
| 291 | count: Arc::new(AtomicUsize::new(0)), |
| 292 | refuse: Arc::new(AtomicBool::new(false)), |
| 293 | }; |
| 294 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 295 | let address = listener.local_addr().unwrap(); |
| 296 | let app = Router::new() |
| 297 | .route("/v1/config/reload", post(reload)) |
| 298 | .with_state(fixture.clone()); |
| 299 | let server = tokio::spawn(async move { |
| 300 | axum::serve(listener, app).await.unwrap(); |
| 301 | }); |
| 302 | let (mut state, root) = capability_test_state(); |
| 303 | state.captured_owner = Some(codewhale_protocol::RuntimeOwnerReceipt { |
| 304 | version: 1, |
| 305 | data_dir: root.path().join("runtime"), |
| 306 | execution_scope: "fixture".into(), |
| 307 | lease_generation: "fixture".into(), |
| 308 | pid: std::process::id(), |
| 309 | process_start: "fixture".into(), |
| 310 | principal: "fixture".into(), |
| 311 | socket_path: root.path().join("owner.sock"), |
| 312 | config_path: state.config_path.clone(), |
| 313 | }); |
| 314 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{address}")); |
| 315 | bridge.auth_token = Some("private-reload-fixture".into()); |
| 316 | let captured = Arc::new(Mutex::new(bridge)); |
| 317 | *state.runtime_bridge.lock().await = Some(captured.clone()); |
| 318 | install_mock_native_services(&mut state).await; |
| 319 | propagate_config(&state).await.unwrap(); |
| 320 | assert_eq!(fixture.count.load(Ordering::SeqCst), 1); |
| 321 | fixture.refuse.store(true, Ordering::SeqCst); |
| 322 | assert!( |
| 323 | propagate_config(&state) |
| 324 | .await |
| 325 | .unwrap_err() |
| 326 | .to_string() |
| 327 | .contains("config saved") |
| 328 | ); |
| 329 | assert_eq!(fixture.count.load(Ordering::SeqCst), 2); |
| 330 | assert!(Arc::ptr_eq( |
| 331 | state.runtime_bridge.lock().await.as_ref().unwrap(), |
| 332 | &captured |
| 333 | )); |
| 334 | server.abort(); |
| 335 | } |
| 336 | |
| 337 | fn app_with_config(auth_token: Option<&str>) -> (Router, tempfile::TempDir) { |
| 338 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 339 | let config_path = tmp.path().join("config.toml"); |
| 340 | fs::write(&config_path, "api_key = \"sk-deepseek-secret\"\n").expect("write config"); |
| 341 | let state = build_state( |
| 342 | Some(config_path), |
| 343 | auth_token.map(std::string::ToString::to_string), |
| 344 | ) |
| 345 | .expect("state"); |
| 346 | (app_router(state, &[]), tmp) |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn build_state_keeps_resolved_explicit_config_path() { |
| 351 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 352 | let config_dir = tmp.path().join("config-dir"); |
| 353 | fs::create_dir_all(&config_dir).expect("config dir"); |
| 354 | let config_path = config_dir.join("config.toml"); |
| 355 | fs::write(&config_path, "api_key = \"sk-deepseek-secret\"\n").expect("write config"); |
| 356 | |
| 357 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 358 | |
| 359 | assert_eq!( |
| 360 | state.config_path.as_deref(), |
| 361 | Some( |
| 362 | config_path |
| 363 | .canonicalize() |
| 364 | .expect("canonical config") |
| 365 | .as_path() |
| 366 | ) |
| 367 | ); |
| 368 | } |
| 369 | |
| 370 | async fn response_body_json(response: Response) -> Value { |
| 371 | let bytes = to_bytes(response.into_body(), usize::MAX) |
| 372 | .await |
| 373 | .expect("body bytes"); |
| 374 | serde_json::from_slice(&bytes).expect("json response") |
| 375 | } |
| 376 | |
| 377 | #[tokio::test] |
| 378 | async fn http_app_routes_require_bearer_token_when_auth_enabled() { |
| 379 | let (app, _tmp) = app_with_config(Some("test-token")); |
| 380 | let response = app |
| 381 | .oneshot( |
| 382 | Request::builder() |
| 383 | .method(Method::POST) |
| 384 | .uri("/app") |
| 385 | .header(header::CONTENT_TYPE, "application/json") |
| 386 | .body(Body::from( |
| 387 | serde_json::to_vec(&AppRequest::ConfigGet { |
| 388 | key: "api_key".to_string(), |
| 389 | }) |
| 390 | .expect("request json"), |
| 391 | )) |
| 392 | .expect("request"), |
| 393 | ) |
| 394 | .await |
| 395 | .expect("response"); |
| 396 | |
| 397 | assert_eq!(response.status(), StatusCode::UNAUTHORIZED); |
| 398 | } |
| 399 | |
| 400 | #[tokio::test] |
| 401 | async fn http_config_get_redacts_sensitive_values_after_auth() { |
| 402 | let (app, _tmp) = app_with_config(Some("test-token")); |
| 403 | let response = app |
| 404 | .oneshot( |
| 405 | Request::builder() |
| 406 | .method(Method::POST) |
| 407 | .uri("/app") |
| 408 | .header(header::AUTHORIZATION, "Bearer test-token") |
| 409 | .header(header::CONTENT_TYPE, "application/json") |
| 410 | .body(Body::from( |
| 411 | serde_json::to_vec(&AppRequest::ConfigGet { |
| 412 | key: "api_key".to_string(), |
| 413 | }) |
| 414 | .expect("request json"), |
| 415 | )) |
| 416 | .expect("request"), |
| 417 | ) |
| 418 | .await |
| 419 | .expect("response"); |
| 420 | |
| 421 | assert_eq!(response.status(), StatusCode::OK); |
| 422 | let body = response_body_json(response).await; |
| 423 | assert_eq!(body["data"]["value"], "sk-d***cret"); |
| 424 | } |
| 425 | |
| 426 | /// Every route `Capabilities` advertises must reach a handler. A POST |
| 427 | /// with an empty JSON body is enough: a registered handler answers with |
| 428 | /// its own status (200, or 422 for a body it rejects), while a path with |
| 429 | /// no handler answers 404 and a wrong method 405. |
| 430 | #[tokio::test] |
| 431 | async fn every_advertised_route_has_a_handler() { |
| 432 | let (_app, tmp) = app_with_config(Some("test-token")); |
| 433 | let state = build_state(Some(tmp.path().join("config.toml")), None).expect("state"); |
| 434 | let caps = process_app_request(&state, AppRequest::Capabilities, AppTransport::Http).await; |
| 435 | let advertised: Vec<String> = |
| 436 | serde_json::from_value(caps.data["routes"].clone()).expect("routes list"); |
| 437 | assert_eq!(advertised, ADVERTISED_ROUTES); |
| 438 | |
| 439 | for route in &advertised { |
| 440 | let mut status = StatusCode::METHOD_NOT_ALLOWED; |
| 441 | for method in [Method::POST, Method::GET] { |
| 442 | let (app, _tmp) = app_with_config(Some("test-token")); |
| 443 | let body = if method == Method::POST { |
| 444 | Body::from("{}") |
| 445 | } else { |
| 446 | Body::empty() |
| 447 | }; |
| 448 | status = app |
| 449 | .oneshot( |
| 450 | Request::builder() |
| 451 | .method(method) |
| 452 | .uri(route.as_str()) |
| 453 | .header(header::AUTHORIZATION, "Bearer test-token") |
| 454 | .header(header::CONTENT_TYPE, "application/json") |
| 455 | .body(body) |
| 456 | .expect("request"), |
| 457 | ) |
| 458 | .await |
| 459 | .expect("response") |
| 460 | .status(); |
| 461 | if status != StatusCode::METHOD_NOT_ALLOWED { |
| 462 | break; |
| 463 | } |
| 464 | } |
| 465 | assert!( |
| 466 | status != StatusCode::NOT_FOUND |
| 467 | && status != StatusCode::METHOD_NOT_ALLOWED |
| 468 | && !status.is_server_error(), |
| 469 | "advertised route {route} has no working handler: {status}" |
| 470 | ); |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | /// `/tool` ran calls against an empty tool registry under an approval |
| 475 | /// mapping of its own. It is gone from both the router and the |
| 476 | /// advertised list; tools run only inside Engine turns. |
| 477 | #[tokio::test] |
| 478 | async fn tool_route_is_not_served_or_advertised() { |
| 479 | let (app, tmp) = app_with_config(Some("test-token")); |
| 480 | let response = app |
| 481 | .oneshot( |
| 482 | Request::builder() |
| 483 | .method(Method::POST) |
| 484 | .uri("/tool") |
| 485 | .header(header::AUTHORIZATION, "Bearer test-token") |
| 486 | .header(header::CONTENT_TYPE, "application/json") |
| 487 | .body(Body::from( |
| 488 | r#"{"call":{"name":"exec_shell","payload":{"type":"local_shell","command":["true"]}}}"#, |
| 489 | )) |
| 490 | .expect("request"), |
| 491 | ) |
| 492 | .await |
| 493 | .expect("response"); |
| 494 | assert_eq!(response.status(), StatusCode::NOT_FOUND); |
| 495 | |
| 496 | let state = build_state(Some(tmp.path().join("config.toml")), None).expect("state"); |
| 497 | let caps = process_app_request(&state, AppRequest::Capabilities, AppTransport::Http).await; |
| 498 | let advertised = caps.data["routes"].as_array().expect("routes list"); |
| 499 | assert!(!advertised.iter().any(|route| route == "/tool")); |
| 500 | } |
| 501 | |
| 502 | #[tokio::test] |
| 503 | async fn mcp_startup_route_cannot_start_a_parallel_pool() { |
| 504 | let (app, tmp) = app_with_config(Some("test-token")); |
| 505 | let response = app |
| 506 | .oneshot( |
| 507 | Request::builder() |
| 508 | .method(Method::POST) |
| 509 | .uri("/mcp/startup") |
| 510 | .header(header::AUTHORIZATION, "Bearer test-token") |
| 511 | .body(Body::empty()) |
| 512 | .expect("request"), |
| 513 | ) |
| 514 | .await |
| 515 | .expect("response"); |
| 516 | assert_eq!(response.status(), StatusCode::NOT_FOUND); |
| 517 | |
| 518 | let state = build_state(Some(tmp.path().join("config.toml")), None).expect("state"); |
| 519 | let caps = process_app_request(&state, AppRequest::Capabilities, AppTransport::Http).await; |
| 520 | assert!( |
| 521 | !caps.data["routes"] |
| 522 | .as_array() |
| 523 | .expect("routes") |
| 524 | .iter() |
| 525 | .any(|route| route == "/mcp/startup") |
| 526 | ); |
| 527 | assert!( |
| 528 | !caps.data["events"] |
| 529 | .as_array() |
| 530 | .expect("events") |
| 531 | .iter() |
| 532 | .any(|event| event == "mcp_startup_update" || event == "mcp_startup_complete") |
| 533 | ); |
| 534 | } |
| 535 | |
| 536 | #[tokio::test] |
| 537 | async fn cors_does_not_allow_arbitrary_origins() { |
| 538 | let (app, _tmp) = app_with_config(Some("test-token")); |
| 539 | let response = app |
| 540 | .oneshot( |
| 541 | Request::builder() |
| 542 | .method(Method::GET) |
| 543 | .uri("/healthz") |
| 544 | .header(header::ORIGIN, "https://attacker.example") |
| 545 | .body(Body::empty()) |
| 546 | .expect("request"), |
| 547 | ) |
| 548 | .await |
| 549 | .expect("response"); |
| 550 | |
| 551 | assert_eq!(response.status(), StatusCode::OK); |
| 552 | assert!( |
| 553 | response |
| 554 | .headers() |
| 555 | .get(header::ACCESS_CONTROL_ALLOW_ORIGIN) |
| 556 | .is_none() |
| 557 | ); |
| 558 | } |
| 559 | |
| 560 | #[tokio::test] |
| 561 | async fn config_reload_refreshes_runtime_config_from_disk() { |
| 562 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 563 | let config_path = tmp.path().join("config.toml"); |
| 564 | fs::write( |
| 565 | &config_path, |
| 566 | "api_key = \"sk-deepseek-secret\"\nmodel = \"deepseek-chat\"\n", |
| 567 | ) |
| 568 | .expect("write config"); |
| 569 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 570 | { |
| 571 | let runtime = state.runtime.read().await; |
| 572 | assert_eq!(runtime.config.model.as_deref(), Some("deepseek-chat")); |
| 573 | } |
| 574 | |
| 575 | fs::write( |
| 576 | &config_path, |
| 577 | "api_key = \"sk-deepseek-secret\"\nmodel = \"deepseek-reasoner\"\n", |
| 578 | ) |
| 579 | .expect("rewrite config"); |
| 580 | |
| 581 | // ConfigReload must re-read the file and push it into the live |
| 582 | // Runtime without a restart. |
| 583 | let response = process_app_request(&state, AppRequest::ConfigReload, AppTransport::Stdio).await; |
| 584 | assert!(response.ok, "reload should succeed"); |
| 585 | assert_eq!(response.data["reloaded"], true); |
| 586 | |
| 587 | // The shared config lock reflects the new model. |
| 588 | { |
| 589 | let cfg = state.config.read().await; |
| 590 | assert_eq!(cfg.model.as_deref(), Some("deepseek-reasoner")); |
| 591 | } |
| 592 | // The live Runtime reflects the new model. |
| 593 | { |
| 594 | let runtime = state.runtime.read().await; |
| 595 | assert_eq!(runtime.config.model.as_deref(), Some("deepseek-reasoner")); |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | #[tokio::test] |
| 600 | async fn config_set_propagates_to_runtime_config() { |
| 601 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 602 | let config_path = tmp.path().join("config.toml"); |
| 603 | fs::write( |
| 604 | &config_path, |
| 605 | "api_key = \"sk-deepseek-secret\"\nmodel = \"deepseek-chat\"\n", |
| 606 | ) |
| 607 | .expect("write config"); |
| 608 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 609 | |
| 610 | // Set a new model via the API. |
| 611 | let response = process_app_request( |
| 612 | &state, |
| 613 | AppRequest::ConfigSet { |
| 614 | key: "model".to_string(), |
| 615 | value: "deepseek-reasoner".to_string(), |
| 616 | }, |
| 617 | AppTransport::Stdio, |
| 618 | ) |
| 619 | .await; |
| 620 | assert!(response.ok, "set should succeed"); |
| 621 | |
| 622 | // Live runtime sees the new model. |
| 623 | { |
| 624 | let runtime = state.runtime.read().await; |
| 625 | assert_eq!(runtime.config.model.as_deref(), Some("deepseek-reasoner")); |
| 626 | } |
| 627 | // The on-disk file was persisted. |
| 628 | let persisted = fs::read_to_string(&config_path).expect("read config"); |
| 629 | assert!(persisted.contains("deepseek-reasoner")); |
| 630 | } |
| 631 | |
| 632 | /// A bridge stand-in with no child process: this test only cares about |
| 633 | /// whether the cache slot survives, not about talking to a runtime. |
| 634 | fn sentinel_bridge() -> SharedRuntimeBridge { |
| 635 | Arc::new(Mutex::new(RuntimeBridge { |
| 636 | base_url: "http://127.0.0.1:0".to_string(), |
| 637 | client: codewhale_release::tls::reqwest_client(), |
| 638 | auth_token: None, |
| 639 | child: None, |
| 640 | last_seq_by_thread: HashMap::new(), |
| 641 | })) |
| 642 | } |
| 643 | |
| 644 | #[tokio::test] |
| 645 | async fn failed_config_set_keeps_the_stdio_bridge() { |
| 646 | crate::install_test_crypto_provider(); |
| 647 | // #4737: `set_value` rejects an invalid value before assigning, so the |
| 648 | // request is a no-op — but `apply_config_update` ran anyway and |
| 649 | // invalidated the cached bridge, dropping the child runtime along with |
| 650 | // its thread map. A single bad value orphaned every in-flight stdio |
| 651 | // thread, behind a response that correctly reported `ok: false`. |
| 652 | // |
| 653 | // Only `set_value` is exercised: an unknown key lands in `extras` and |
| 654 | // succeeds, and `unset_value` has no failing input today, so its |
| 655 | // identical guard has nothing to assert against. |
| 656 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 657 | let config_path = tmp.path().join("config.toml"); |
| 658 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 659 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 660 | let bridge = sentinel_bridge(); |
| 661 | *state.runtime_bridge.lock().await = Some(bridge.clone()); |
| 662 | state |
| 663 | .runtime_thread_map |
| 664 | .lock() |
| 665 | .await |
| 666 | .insert("stdio-1".to_string(), "runtime-1".to_string()); |
| 667 | |
| 668 | let disk_before = fs::read(&config_path).unwrap(); |
| 669 | let config_before = serde_json::to_value(&*state.config.read().await).unwrap(); |
| 670 | let runtime_before = serde_json::to_value(&state.runtime.read().await.config).unwrap(); |
| 671 | let token = ["sk-live-", "Z7qX4mNb2Vc9Lk3PwR8t"].concat(); |
| 672 | for (key, value) in [ |
| 673 | ("telemetry", "not-a-bool"), |
| 674 | ("approval_policy", "bogus"), |
| 675 | ("sandbox_mode", "full"), |
| 676 | ("verbosity", "quiet"), |
| 677 | ("approval_policy", token.as_str()), |
| 678 | ("sandbox_mode", token.as_str()), |
| 679 | ("verbosity", token.as_str()), |
| 680 | ] { |
| 681 | let response = process_app_request( |
| 682 | &state, |
| 683 | AppRequest::ConfigSet { |
| 684 | key: key.into(), |
| 685 | value: value.into(), |
| 686 | }, |
| 687 | AppTransport::Stdio, |
| 688 | ) |
| 689 | .await; |
| 690 | assert!(!response.ok, "invalid {key} must fail"); |
| 691 | assert!(response.data["error"].is_string(), "refusal detail"); |
| 692 | let rendered = serde_json::to_string(&response).unwrap(); |
| 693 | assert!( |
| 694 | !rendered.contains(&token), |
| 695 | "credential must not enter diagnostics or the echoed value" |
| 696 | ); |
| 697 | assert_eq!( |
| 698 | response.data["value"].as_str(), |
| 699 | Some(if value == token { "[redacted]" } else { value }) |
| 700 | ); |
| 701 | assert_eq!(fs::read(&config_path).unwrap(), disk_before); |
| 702 | assert_eq!( |
| 703 | serde_json::to_value(&*state.config.read().await).unwrap(), |
| 704 | config_before |
| 705 | ); |
| 706 | assert_eq!( |
| 707 | serde_json::to_value(&state.runtime.read().await.config).unwrap(), |
| 708 | runtime_before |
| 709 | ); |
| 710 | assert!( |
| 711 | state |
| 712 | .runtime_bridge |
| 713 | .lock() |
| 714 | .await |
| 715 | .as_ref() |
| 716 | .is_some_and(|cached| Arc::ptr_eq(cached, &bridge)), |
| 717 | "the same bridge must survive a failed config/set", |
| 718 | ); |
| 719 | assert_eq!( |
| 720 | state |
| 721 | .runtime_thread_map |
| 722 | .lock() |
| 723 | .await |
| 724 | .get("stdio-1") |
| 725 | .map(String::as_str), |
| 726 | Some("runtime-1"), |
| 727 | "the live thread map must be intact", |
| 728 | ); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | #[tokio::test] |
| 733 | async fn successful_config_set_still_invalidates_the_stdio_bridge() { |
| 734 | crate::install_test_crypto_provider(); |
| 735 | // The other half of #4737: a mutation that *did* happen must still |
| 736 | // rebuild the bridge, or the runtime keeps serving the old config. |
| 737 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 738 | let config_path = tmp.path().join("config.toml"); |
| 739 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 740 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 741 | *state.runtime_bridge.lock().await = Some(sentinel_bridge()); |
| 742 | |
| 743 | let response = process_app_request( |
| 744 | &state, |
| 745 | AppRequest::ConfigSet { |
| 746 | key: "model".to_string(), |
| 747 | value: "deepseek-reasoner".to_string(), |
| 748 | }, |
| 749 | AppTransport::Stdio, |
| 750 | ) |
| 751 | .await; |
| 752 | assert!(response.ok, "valid set should succeed: {response:?}"); |
| 753 | assert_eq!(response.data["value"], "deepseek-reasoner"); |
| 754 | assert!( |
| 755 | state.runtime_bridge.lock().await.is_none(), |
| 756 | "a successful config change must invalidate the cached bridge", |
| 757 | ); |
| 758 | } |
| 759 | |
| 760 | #[tokio::test] |
| 761 | async fn config_update_keeps_the_stdio_thread_mapping() { |
| 762 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 763 | thread_control::resolve(&state, "canonical-1", true) |
| 764 | .await |
| 765 | .unwrap(); |
| 766 | let bridge = state.runtime_bridge.lock().await.clone().unwrap(); |
| 767 | let response = process_app_request(&state, AppRequest::ConfigReload, AppTransport::Stdio).await; |
| 768 | assert!(response.ok, "captured owner reload failed: {response:?}"); |
| 769 | assert!( |
| 770 | state |
| 771 | .runtime_bridge |
| 772 | .lock() |
| 773 | .await |
| 774 | .as_ref() |
| 775 | .is_some_and(|captured| Arc::ptr_eq(captured, &bridge)), |
| 776 | "reload keeps the already captured owner" |
| 777 | ); |
| 778 | let result = dispatch_stdio_request( |
| 779 | &state, |
| 780 | "thread/message", |
| 781 | json!({"thread_id":"canonical-1","allowed_tools": [], "input":"next"}), |
| 782 | ) |
| 783 | .await |
| 784 | .unwrap(); |
| 785 | assert_eq!(result.result["status"], "accepted"); |
| 786 | server.abort(); |
| 787 | } |
| 788 | |
| 789 | #[tokio::test] |
| 790 | async fn thread_message_on_an_unknown_thread_is_not_found() { |
| 791 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 792 | let error = dispatch_stdio_request( |
| 793 | &state, |
| 794 | "thread/message", |
| 795 | json!({"thread_id":"never-created","allowed_tools": [], "input":"hello"}), |
| 796 | ) |
| 797 | .await |
| 798 | .unwrap_err(); |
| 799 | assert_eq!(error.wire.code, THREAD_NOT_FOUND_CODE); |
| 800 | let error = run_http_thread_message( |
| 801 | &state, |
| 802 | "never-created".into(), |
| 803 | "hello".into(), |
| 804 | Some(Vec::new()), |
| 805 | Vec::new(), |
| 806 | None, |
| 807 | ) |
| 808 | .await |
| 809 | .unwrap_err(); |
| 810 | assert_eq!(error.wire.code, THREAD_NOT_FOUND_CODE); |
| 811 | assert!(state.runtime_thread_map.lock().await.is_empty()); |
| 812 | assert!(state.in_flight_turns.lock().await.is_empty()); |
| 813 | server.abort(); |
| 814 | } |
| 815 | |
| 816 | #[tokio::test] |
| 817 | async fn thread_runtime_link_survives_an_app_server_restart() { |
| 818 | let (state, tmp, server) = thread_control::compatibility_fixture().await; |
| 819 | let workspace = state.frontend_workspace.clone().unwrap(); |
| 820 | let owner = state.captured_owner.clone(); |
| 821 | let store = state.runtime.read().await.state_store().clone(); |
| 822 | let mut metadata = codewhale_state::ThreadMetadata { |
| 823 | cwd: workspace.clone(), |
| 824 | ..test_client_metadata("client-1") |
| 825 | }; |
| 826 | metadata.model_provider = "fixture-account".into(); |
| 827 | restore_test_thread_archive(&store, &metadata); |
| 828 | dispatch_stdio_request( |
| 829 | &state, |
| 830 | "thread/message", |
| 831 | json!({"thread_id":"client-1","allowed_tools": [], "input":"first"}), |
| 832 | ) |
| 833 | .await |
| 834 | .unwrap(); |
| 835 | let receipt = store |
| 836 | .get_canonical_runtime_link("client-1", owner.as_ref().unwrap()) |
| 837 | .unwrap() |
| 838 | .unwrap(); |
| 839 | let bridge = state.runtime_bridge.lock().await.clone(); |
| 840 | let native = state.owner_frontend.clone(); |
| 841 | drop(state); |
| 842 | let mut restarted = build_state(Some(tmp.path().join("config.toml")), None).unwrap(); |
| 843 | restarted.captured_owner = owner; |
| 844 | restarted.owner_frontend = native; |
| 845 | restarted.frontend_workspace = Some(workspace); |
| 846 | *restarted.runtime_bridge.lock().await = bridge; |
| 847 | assert!(restarted.runtime_thread_map.lock().await.is_empty()); |
| 848 | dispatch_stdio_request( |
| 849 | &restarted, |
| 850 | "thread/message", |
| 851 | json!({"thread_id":"client-1","allowed_tools": [], "input":"second"}), |
| 852 | ) |
| 853 | .await |
| 854 | .unwrap(); |
| 855 | assert!(restarted.runtime_thread_map.lock().await.is_empty()); |
| 856 | assert_eq!( |
| 857 | store |
| 858 | .get_canonical_runtime_link("client-1", restarted.captured_owner.as_ref().unwrap()) |
| 859 | .unwrap() |
| 860 | .unwrap(), |
| 861 | receipt |
| 862 | ); |
| 863 | server.abort(); |
| 864 | } |
| 865 | |
| 866 | #[tokio::test] |
| 867 | async fn unreceipted_cache_cannot_replace_the_native_thread_receipt() { |
| 868 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 869 | let store = state.runtime.read().await.state_store().clone(); |
| 870 | restore_test_thread_archive( |
| 871 | &store, |
| 872 | &codewhale_state::ThreadMetadata { |
| 873 | cwd: state.frontend_workspace.clone().unwrap(), |
| 874 | ..test_client_metadata("client-1") |
| 875 | }, |
| 876 | ); |
| 877 | state |
| 878 | .runtime_thread_map |
| 879 | .lock() |
| 880 | .await |
| 881 | .insert("client-1".into(), "unreceipted-cache".into()); |
| 882 | dispatch_stdio_request( |
| 883 | &state, |
| 884 | "thread/message", |
| 885 | json!({"thread_id":"client-1","allowed_tools": [], "input":"hello"}), |
| 886 | ) |
| 887 | .await |
| 888 | .unwrap(); |
| 889 | let receipt = store |
| 890 | .get_canonical_runtime_link("client-1", state.captured_owner.as_ref().unwrap()) |
| 891 | .unwrap() |
| 892 | .unwrap(); |
| 893 | assert_eq!(receipt.runtime_thread_id, "canonical-1"); |
| 894 | assert_eq!( |
| 895 | store |
| 896 | .get_runtime_thread_link("client-1") |
| 897 | .unwrap() |
| 898 | .as_deref(), |
| 899 | Some("canonical-1") |
| 900 | ); |
| 901 | assert_eq!( |
| 902 | state |
| 903 | .runtime_thread_map |
| 904 | .lock() |
| 905 | .await |
| 906 | .get("client-1") |
| 907 | .map(String::as_str), |
| 908 | Some("unreceipted-cache") |
| 909 | ); |
| 910 | server.abort(); |
| 911 | } |
| 912 | |
| 913 | #[tokio::test] |
| 914 | async fn a_thread_messaged_after_a_restart_starts_in_its_stored_workspace() { |
| 915 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 916 | let workspace = state.frontend_workspace.clone().unwrap(); |
| 917 | let store = state.runtime.read().await.state_store().clone(); |
| 918 | restore_test_thread_archive( |
| 919 | &store, |
| 920 | &codewhale_state::ThreadMetadata { |
| 921 | cwd: workspace.clone(), |
| 922 | ..test_client_metadata("client-1") |
| 923 | }, |
| 924 | ); |
| 925 | assert!(state.stdio_thread_hints.lock().await.is_empty()); |
| 926 | dispatch_stdio_request( |
| 927 | &state, |
| 928 | "thread/message", |
| 929 | json!({"thread_id":"client-1","allowed_tools": [], "input":"hello"}), |
| 930 | ) |
| 931 | .await |
| 932 | .unwrap(); |
| 933 | assert_eq!( |
| 934 | thread_control::resolve(&state, "client-1", true) |
| 935 | .await |
| 936 | .unwrap() |
| 937 | .1, |
| 938 | workspace |
| 939 | ); |
| 940 | assert_eq!( |
| 941 | store.get_thread("client-1").unwrap().unwrap().cwd, |
| 942 | workspace |
| 943 | ); |
| 944 | server.abort(); |
| 945 | } |
| 946 | |
| 947 | #[tokio::test] |
| 948 | async fn a_link_to_a_runtime_thread_that_is_gone_is_replaced() { |
| 949 | // Keep the historical case identity. Missing owner checkpoints now |
| 950 | // refuse; replacing them with an empty conversation loses history. |
| 951 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 952 | let store = state.runtime.read().await.state_store().clone(); |
| 953 | restore_test_thread_archive( |
| 954 | &store, |
| 955 | &codewhale_state::ThreadMetadata { |
| 956 | cwd: state.frontend_workspace.clone().unwrap(), |
| 957 | ..test_client_metadata("client-1") |
| 958 | }, |
| 959 | ); |
| 960 | rusqlite::Connection::open(store.db_path()).unwrap().execute( |
| 961 | "INSERT INTO thread_runtime_links(thread_id,runtime_thread_id,created_at) VALUES('client-1','thr_gone',1)", [] |
| 962 | ).unwrap(); |
| 963 | let before = store.snapshot_legacy_thread_history("client-1").unwrap(); |
| 964 | let error = dispatch_stdio_request( |
| 965 | &state, |
| 966 | "thread/message", |
| 967 | json!({"thread_id":"client-1","allowed_tools": [], "input":"hello"}), |
| 968 | ) |
| 969 | .await |
| 970 | .unwrap_err(); |
| 971 | assert_eq!(error.wire.code, THREAD_NOT_FOUND_CODE); |
| 972 | assert_eq!( |
| 973 | store |
| 974 | .get_runtime_thread_link("client-1") |
| 975 | .unwrap() |
| 976 | .as_deref(), |
| 977 | Some("thr_gone") |
| 978 | ); |
| 979 | assert!( |
| 980 | store |
| 981 | .get_canonical_runtime_link("client-1", state.captured_owner.as_ref().unwrap()) |
| 982 | .unwrap() |
| 983 | .is_none() |
| 984 | ); |
| 985 | assert_eq!( |
| 986 | serde_json::to_value(store.snapshot_legacy_thread_history("client-1").unwrap()).unwrap(), |
| 987 | serde_json::to_value(before).unwrap() |
| 988 | ); |
| 989 | assert!(state.in_flight_turns.lock().await.is_empty()); |
| 990 | server.abort(); |
| 991 | } |
| 992 | |
| 993 | #[tokio::test] |
| 994 | async fn restored_thread_link_retries_validation_after_a_transient_failure() { |
| 995 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 996 | let store = state.runtime.read().await.state_store().clone(); |
| 997 | restore_test_thread_archive( |
| 998 | &store, |
| 999 | &codewhale_state::ThreadMetadata { |
| 1000 | cwd: state.frontend_workspace.clone().unwrap(), |
| 1001 | ..test_client_metadata("client-1") |
| 1002 | }, |
| 1003 | ); |
| 1004 | thread_control::resolve(&state, "client-1", true) |
| 1005 | .await |
| 1006 | .unwrap(); |
| 1007 | let receipt = store |
| 1008 | .get_canonical_runtime_link("client-1", state.captured_owner.as_ref().unwrap()) |
| 1009 | .unwrap(); |
| 1010 | let bridge = state.runtime_bridge.lock().await.take(); |
| 1011 | let first = acquire_live_runtime_bridge(&state) |
| 1012 | .await |
| 1013 | .expect_err("transient connection refused"); |
| 1014 | assert_eq!(first.wire.code, RUNTIME_UNAVAILABLE_CODE); |
| 1015 | *state.runtime_bridge.lock().await = bridge; |
| 1016 | dispatch_stdio_request( |
| 1017 | &state, |
| 1018 | "thread/message", |
| 1019 | json!({"thread_id":"client-1","allowed_tools": [], "input":"retry"}), |
| 1020 | ) |
| 1021 | .await |
| 1022 | .unwrap(); |
| 1023 | assert_eq!( |
| 1024 | store |
| 1025 | .get_canonical_runtime_link("client-1", state.captured_owner.as_ref().unwrap()) |
| 1026 | .unwrap(), |
| 1027 | receipt |
| 1028 | ); |
| 1029 | server.abort(); |
| 1030 | } |
| 1031 | |
| 1032 | #[cfg(unix)] |
| 1033 | fn dead_bridge(base_url: &str) -> RuntimeBridge { |
| 1034 | let mut child = Command::new("true").spawn().expect("spawn fixture child"); |
| 1035 | child.wait().expect("fixture child exits"); |
| 1036 | let mut bridge = RuntimeBridge::from_base_url_for_test(base_url.to_string()); |
| 1037 | bridge.child = Some(child); |
| 1038 | bridge |
| 1039 | } |
| 1040 | |
| 1041 | #[cfg(unix)] |
| 1042 | #[tokio::test] |
| 1043 | async fn a_dead_runtime_child_is_replaced_by_a_live_one() { |
| 1044 | crate::install_test_crypto_provider(); |
| 1045 | // A crashed or killed child stayed cached, so every later turn failed |
| 1046 | // against it until the app-server restarted. |
| 1047 | let (state, _tmp) = capability_test_state(); |
| 1048 | let dead = Arc::new(Mutex::new(dead_bridge("http://dead.invalid"))); |
| 1049 | *state.runtime_bridge.lock().await = Some(dead.clone()); |
| 1050 | |
| 1051 | let starts = std::sync::atomic::AtomicUsize::new(0); |
| 1052 | let bridge = acquire_live_runtime_bridge_with(&state, || { |
| 1053 | starts.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 1054 | async { |
| 1055 | Ok(RuntimeBridge::from_base_url_for_test( |
| 1056 | "http://live.invalid".to_string(), |
| 1057 | )) |
| 1058 | } |
| 1059 | }) |
| 1060 | .await |
| 1061 | .expect("a live replacement is returned"); |
| 1062 | assert_eq!(bridge.base_url, "http://live.invalid"); |
| 1063 | drop(bridge); |
| 1064 | assert_eq!(starts.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 1065 | let slot = state.runtime_bridge.lock().await; |
| 1066 | let cached = slot.as_ref().expect("the replacement is cached"); |
| 1067 | assert!(!Arc::ptr_eq(cached, &dead), "the dead bridge is evicted"); |
| 1068 | assert_eq!(cached.lock().await.base_url, "http://live.invalid"); |
| 1069 | } |
| 1070 | |
| 1071 | #[cfg(unix)] |
| 1072 | #[tokio::test] |
| 1073 | async fn a_runtime_child_that_dies_on_respawn_is_reported_after_one_retry() { |
| 1074 | crate::install_test_crypto_provider(); |
| 1075 | let (state, _tmp) = capability_test_state(); |
| 1076 | *state.runtime_bridge.lock().await = |
| 1077 | Some(Arc::new(Mutex::new(dead_bridge("http://dead.invalid")))); |
| 1078 | |
| 1079 | let starts = std::sync::atomic::AtomicUsize::new(0); |
| 1080 | let err = acquire_live_runtime_bridge_with(&state, || { |
| 1081 | starts.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 1082 | async { Ok(dead_bridge("http://dead-again.invalid")) } |
| 1083 | }) |
| 1084 | .await |
| 1085 | .expect_err("a child that exits at once is not handed out"); |
| 1086 | assert_eq!(err.wire.code, RUNTIME_UNAVAILABLE_CODE); |
| 1087 | assert!( |
| 1088 | err.wire.message.contains("exited immediately"), |
| 1089 | "{}", |
| 1090 | err.wire.message |
| 1091 | ); |
| 1092 | assert_eq!( |
| 1093 | starts.load(std::sync::atomic::Ordering::SeqCst), |
| 1094 | 1, |
| 1095 | "respawned exactly once", |
| 1096 | ); |
| 1097 | assert!( |
| 1098 | state.runtime_bridge.lock().await.is_none(), |
| 1099 | "no dead bridge stays cached", |
| 1100 | ); |
| 1101 | } |
| 1102 | |
| 1103 | #[tokio::test] |
| 1104 | async fn config_set_keeps_edits_saved_by_other_processes() { |
| 1105 | // Persisting used to write the startup snapshot back over a freshly |
| 1106 | // loaded store, erasing edits another process (the TUI, `login`) |
| 1107 | // had saved since. |
| 1108 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1109 | let config_path = tmp.path().join("config.toml"); |
| 1110 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1111 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1112 | fs::write( |
| 1113 | &config_path, |
| 1114 | "model = \"deepseek-chat\"\ntelemetry = true\n", |
| 1115 | ) |
| 1116 | .expect("external edit"); |
| 1117 | |
| 1118 | let response = process_app_request( |
| 1119 | &state, |
| 1120 | AppRequest::ConfigSet { |
| 1121 | key: "model".to_string(), |
| 1122 | value: "deepseek-reasoner".to_string(), |
| 1123 | }, |
| 1124 | AppTransport::Stdio, |
| 1125 | ) |
| 1126 | .await; |
| 1127 | assert!(response.ok, "set should succeed: {response:?}"); |
| 1128 | let persisted = fs::read_to_string(&config_path).expect("read config"); |
| 1129 | assert!(persisted.contains("deepseek-reasoner"), "{persisted}"); |
| 1130 | assert!( |
| 1131 | persisted.contains("telemetry = true"), |
| 1132 | "the external edit must survive: {persisted}" |
| 1133 | ); |
| 1134 | assert_eq!( |
| 1135 | state.config.read().await.telemetry, |
| 1136 | Some(true), |
| 1137 | "the live config reflects what was saved", |
| 1138 | ); |
| 1139 | } |
| 1140 | |
| 1141 | #[tokio::test(flavor = "current_thread")] |
| 1142 | async fn config_store_work_does_not_block_the_runtime() { |
| 1143 | let (state, _tmp) = capability_test_state(); |
| 1144 | let (started_tx, started_rx) = tokio::sync::oneshot::channel(); |
| 1145 | let (resume_tx, resume_rx) = std::sync::mpsc::channel(); |
| 1146 | let update_state = state.clone(); |
| 1147 | let update = tokio::spawn(async move { |
| 1148 | update_config_store(&update_state, move |store| { |
| 1149 | started_tx |
| 1150 | .send(()) |
| 1151 | .map_err(|_| anyhow!("configuration test caller disappeared"))?; |
| 1152 | // Simulate a stalled file/store operation. The only Tokio |
| 1153 | // thread must remain free to send the resume signal. |
| 1154 | resume_rx |
| 1155 | .recv_timeout(Duration::from_secs(3)) |
| 1156 | .context("configuration store work blocked the runtime")?; |
| 1157 | store.config.model = Some("deepseek-reasoner".to_string()); |
| 1158 | Ok(()) |
| 1159 | }) |
| 1160 | .await |
| 1161 | }); |
| 1162 | tokio::time::timeout(Duration::from_secs(5), started_rx) |
| 1163 | .await |
| 1164 | .expect("the store operation started") |
| 1165 | .expect("start signal"); |
| 1166 | resume_tx |
| 1167 | .send(()) |
| 1168 | .expect("Tokio must run while the store operation is waiting"); |
| 1169 | update |
| 1170 | .await |
| 1171 | .expect("configuration task joined") |
| 1172 | .expect("configuration update finished"); |
| 1173 | assert_eq!( |
| 1174 | state.config.read().await.model.as_deref(), |
| 1175 | Some("deepseek-reasoner") |
| 1176 | ); |
| 1177 | } |
| 1178 | |
| 1179 | #[tokio::test] |
| 1180 | async fn config_set_reports_a_failed_load() { |
| 1181 | crate::install_test_crypto_provider(); |
| 1182 | // Persisting failures were logged and swallowed: the reply said ok |
| 1183 | // while disk (and so every future turn) kept the old value. |
| 1184 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1185 | let config_path = tmp.path().join("config.toml"); |
| 1186 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1187 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1188 | *state.runtime_bridge.lock().await = Some(sentinel_bridge()); |
| 1189 | fs::write(&config_path, "model = [unterminated\n").expect("corrupt config"); |
| 1190 | |
| 1191 | let response = process_app_request( |
| 1192 | &state, |
| 1193 | AppRequest::ConfigSet { |
| 1194 | key: "model".to_string(), |
| 1195 | value: "deepseek-reasoner".to_string(), |
| 1196 | }, |
| 1197 | AppTransport::Stdio, |
| 1198 | ) |
| 1199 | .await; |
| 1200 | assert!(!response.ok, "an unsaved change must not report ok"); |
| 1201 | assert!(response.data["error"].is_string()); |
| 1202 | assert_eq!( |
| 1203 | app_response_status(&response), |
| 1204 | StatusCode::INTERNAL_SERVER_ERROR, |
| 1205 | "a config file the server cannot read is a server fault", |
| 1206 | ); |
| 1207 | assert_eq!( |
| 1208 | state.config.read().await.model.as_deref(), |
| 1209 | Some("deepseek-chat"), |
| 1210 | "nothing is propagated when the load fails", |
| 1211 | ); |
| 1212 | assert!( |
| 1213 | state.runtime_bridge.lock().await.is_some(), |
| 1214 | "a failed load must not tear down the bridge", |
| 1215 | ); |
| 1216 | } |
| 1217 | |
| 1218 | #[cfg(unix)] |
| 1219 | #[tokio::test] |
| 1220 | async fn config_set_reports_a_failed_save() { |
| 1221 | use std::os::unix::fs::PermissionsExt as _; |
| 1222 | crate::install_test_crypto_provider(); |
| 1223 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1224 | let config_dir = tmp.path().join("cfg"); |
| 1225 | fs::create_dir(&config_dir).expect("config dir"); |
| 1226 | let config_path = config_dir.join("config.toml"); |
| 1227 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1228 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1229 | *state.runtime_bridge.lock().await = Some(sentinel_bridge()); |
| 1230 | fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o500)).expect("read-only"); |
| 1231 | if fs::write(config_dir.join("probe"), "").is_ok() { |
| 1232 | // Running as a user that ignores directory permissions (root); |
| 1233 | // the save cannot be made to fail this way. |
| 1234 | fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o700)).ok(); |
| 1235 | return; |
| 1236 | } |
| 1237 | |
| 1238 | let set = |key: &str, value: &str| AppRequest::ConfigSet { |
| 1239 | key: key.to_string(), |
| 1240 | value: value.to_string(), |
| 1241 | }; |
| 1242 | let response = process_app_request( |
| 1243 | &state, |
| 1244 | set("model", "deepseek-reasoner"), |
| 1245 | AppTransport::Stdio, |
| 1246 | ) |
| 1247 | .await; |
| 1248 | let rejected = |
| 1249 | process_app_request(&state, set("telemetry", "not-a-bool"), AppTransport::Stdio).await; |
| 1250 | fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o700)).expect("restore"); |
| 1251 | |
| 1252 | assert!(!response.ok, "an unsaved change must not report ok"); |
| 1253 | let error = response.data["error"].as_str().expect("error message"); |
| 1254 | assert!(error.starts_with("failed to save config"), "{error}"); |
| 1255 | assert_eq!( |
| 1256 | app_response_status(&response), |
| 1257 | StatusCode::INTERNAL_SERVER_ERROR, |
| 1258 | "a failed save is a server fault, not a bad request", |
| 1259 | ); |
| 1260 | assert!(!rejected.ok); |
| 1261 | assert_eq!( |
| 1262 | app_response_status(&rejected), |
| 1263 | StatusCode::BAD_REQUEST, |
| 1264 | "an invalid value is still the caller's mistake", |
| 1265 | ); |
| 1266 | assert_eq!( |
| 1267 | fs::read_to_string(&config_path).expect("read config"), |
| 1268 | "model = \"deepseek-chat\"\n", |
| 1269 | ); |
| 1270 | assert_eq!( |
| 1271 | state.config.read().await.model.as_deref(), |
| 1272 | Some("deepseek-chat"), |
| 1273 | "nothing is propagated when the save fails", |
| 1274 | ); |
| 1275 | assert!( |
| 1276 | state.runtime_bridge.lock().await.is_some(), |
| 1277 | "a failed save must not tear down the bridge", |
| 1278 | ); |
| 1279 | } |
| 1280 | |
| 1281 | #[tokio::test] |
| 1282 | async fn a_saved_config_change_still_propagates_when_the_caller_goes_away() { |
| 1283 | crate::install_test_crypto_provider(); |
| 1284 | // Once the file was written, a request future dropped before the |
| 1285 | // propagation (an HTTP client disconnect) left disk ahead of the live |
| 1286 | // runtime and the cached bridge until a reload or restart. |
| 1287 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1288 | let config_path = tmp.path().join("config.toml"); |
| 1289 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1290 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1291 | *state.runtime_bridge.lock().await = Some(sentinel_bridge()); |
| 1292 | |
| 1293 | // A concurrent reader holds the runtime, so the set |
| 1294 | // saves to disk and then waits to propagate. |
| 1295 | let runtime_reader = state.runtime.read().await; |
| 1296 | let request = process_app_request( |
| 1297 | &state, |
| 1298 | AppRequest::ConfigSet { |
| 1299 | key: "model".to_string(), |
| 1300 | value: "deepseek-reasoner".to_string(), |
| 1301 | }, |
| 1302 | AppTransport::Http, |
| 1303 | ); |
| 1304 | // Long enough for the save to reach disk on a slow runner: 200 ms was |
| 1305 | // not, once, on hosted Windows. |
| 1306 | assert!( |
| 1307 | tokio::time::timeout(Duration::from_secs(2), request) |
| 1308 | .await |
| 1309 | .is_err(), |
| 1310 | "the set waits for the runtime", |
| 1311 | ); |
| 1312 | assert!( |
| 1313 | fs::read_to_string(&config_path) |
| 1314 | .expect("read config") |
| 1315 | .contains("deepseek-reasoner"), |
| 1316 | "the change was saved before the caller went away", |
| 1317 | ); |
| 1318 | drop(runtime_reader); |
| 1319 | |
| 1320 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1321 | while state.runtime_bridge.lock().await.is_some() { |
| 1322 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 1323 | } |
| 1324 | }) |
| 1325 | .await |
| 1326 | .expect("the saved change still invalidates the bridge"); |
| 1327 | assert_eq!( |
| 1328 | state.runtime.read().await.config.model.as_deref(), |
| 1329 | Some("deepseek-reasoner"), |
| 1330 | ); |
| 1331 | assert_eq!( |
| 1332 | state.config.read().await.model.as_deref(), |
| 1333 | Some("deepseek-reasoner"), |
| 1334 | ); |
| 1335 | } |
| 1336 | |
| 1337 | #[tokio::test] |
| 1338 | async fn config_reload_reads_disk_after_the_earlier_queued_write() { |
| 1339 | let tmp = tempfile::tempdir().unwrap(); |
| 1340 | let config_path = tmp.path().join("config.toml"); |
| 1341 | fs::write(&config_path, "model = \"deepseek-chat\"\n").unwrap(); |
| 1342 | let state = build_state(Some(config_path.clone()), None).unwrap(); |
| 1343 | let reader = state.config.read().await; |
| 1344 | let set_state = state.clone(); |
| 1345 | let set = tokio::spawn(async move { |
| 1346 | process_app_request( |
| 1347 | &set_state, |
| 1348 | AppRequest::ConfigSet { |
| 1349 | key: "model".into(), |
| 1350 | value: "deepseek-reasoner".into(), |
| 1351 | }, |
| 1352 | AppTransport::Http, |
| 1353 | ) |
| 1354 | .await |
| 1355 | }); |
| 1356 | // Tokio's writer-preferring lock rejects new readers only once the |
| 1357 | // first writer is queued. Keep the original reader until reload has |
| 1358 | // also been polled, deterministically reproducing the stale-load race. |
| 1359 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1360 | while state.config.try_read().is_ok() { |
| 1361 | tokio::task::yield_now().await; |
| 1362 | } |
| 1363 | }) |
| 1364 | .await |
| 1365 | .unwrap(); |
| 1366 | let mut reload = Box::pin(process_app_request( |
| 1367 | &state, |
| 1368 | AppRequest::ConfigReload, |
| 1369 | AppTransport::Http, |
| 1370 | )); |
| 1371 | std::future::poll_fn(|cx| { |
| 1372 | assert!(std::future::Future::poll(reload.as_mut(), cx).is_pending()); |
| 1373 | std::task::Poll::Ready(()) |
| 1374 | }) |
| 1375 | .await; |
| 1376 | drop(reader); |
| 1377 | let (set, reload) = |
| 1378 | tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(set, reload) }) |
| 1379 | .await |
| 1380 | .expect("both queued operations finish"); |
| 1381 | assert!(set.unwrap().ok); |
| 1382 | assert!(reload.ok); |
| 1383 | assert_eq!( |
| 1384 | state.config.read().await.model.as_deref(), |
| 1385 | Some("deepseek-reasoner") |
| 1386 | ); |
| 1387 | assert_eq!( |
| 1388 | state.runtime.read().await.config.model.as_deref(), |
| 1389 | Some("deepseek-reasoner") |
| 1390 | ); |
| 1391 | assert_eq!( |
| 1392 | ConfigStore::load(Some(config_path)) |
| 1393 | .unwrap() |
| 1394 | .config |
| 1395 | .model |
| 1396 | .as_deref(), |
| 1397 | Some("deepseek-reasoner") |
| 1398 | ); |
| 1399 | } |
| 1400 | |
| 1401 | #[tokio::test] |
| 1402 | async fn config_reload_finishes_propagation_when_the_caller_goes_away() { |
| 1403 | crate::install_test_crypto_provider(); |
| 1404 | let tmp = tempfile::tempdir().unwrap(); |
| 1405 | let config_path = tmp.path().join("config.toml"); |
| 1406 | fs::write(&config_path, "model = \"deepseek-chat\"\n").unwrap(); |
| 1407 | let state = build_state(Some(config_path.clone()), None).unwrap(); |
| 1408 | *state.runtime_bridge.lock().await = Some(sentinel_bridge()); |
| 1409 | fs::write(&config_path, "model = \"deepseek-reasoner\"\n").unwrap(); |
| 1410 | let reader = state.runtime.read().await; |
| 1411 | let mut reload = Box::pin(process_app_request( |
| 1412 | &state, |
| 1413 | AppRequest::ConfigReload, |
| 1414 | AppTransport::Http, |
| 1415 | )); |
| 1416 | std::future::poll_fn(|cx| { |
| 1417 | assert!(std::future::Future::poll(reload.as_mut(), cx).is_pending()); |
| 1418 | std::task::Poll::Ready(()) |
| 1419 | }) |
| 1420 | .await; |
| 1421 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1422 | while state.config.read().await.model.as_deref() != Some("deepseek-reasoner") { |
| 1423 | tokio::task::yield_now().await; |
| 1424 | } |
| 1425 | }) |
| 1426 | .await |
| 1427 | .unwrap(); |
| 1428 | drop(reload); |
| 1429 | drop(reader); |
| 1430 | tokio::time::timeout(Duration::from_secs(5), async { |
| 1431 | while state.runtime_bridge.lock().await.is_some() { |
| 1432 | tokio::task::yield_now().await; |
| 1433 | } |
| 1434 | }) |
| 1435 | .await |
| 1436 | .expect("reload propagation outlives its caller"); |
| 1437 | assert_eq!( |
| 1438 | state.runtime.read().await.config.model.as_deref(), |
| 1439 | Some("deepseek-reasoner") |
| 1440 | ); |
| 1441 | assert_eq!( |
| 1442 | fs::read_to_string(config_path).unwrap(), |
| 1443 | "model = \"deepseek-reasoner\"\n", |
| 1444 | "reload must not rewrite the file" |
| 1445 | ); |
| 1446 | } |
| 1447 | |
| 1448 | #[tokio::test] |
| 1449 | async fn config_unset_propagates_to_runtime_config() { |
| 1450 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1451 | let config_path = tmp.path().join("config.toml"); |
| 1452 | fs::write( |
| 1453 | &config_path, |
| 1454 | "api_key = \"sk-deepseek-secret\"\nmodel = \"deepseek-chat\"\n", |
| 1455 | ) |
| 1456 | .expect("write config"); |
| 1457 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1458 | |
| 1459 | // Sanity: runtime starts with the on-disk model. |
| 1460 | { |
| 1461 | let runtime = state.runtime.read().await; |
| 1462 | assert_eq!(runtime.config.model.as_deref(), Some("deepseek-chat")); |
| 1463 | } |
| 1464 | |
| 1465 | // Unset the model via the API. This walks a separate code path |
| 1466 | // from ConfigSet (unset_value + update_config), so it needs its |
| 1467 | // own regression coverage. |
| 1468 | let response = process_app_request( |
| 1469 | &state, |
| 1470 | AppRequest::ConfigUnset { |
| 1471 | key: "model".to_string(), |
| 1472 | }, |
| 1473 | AppTransport::Stdio, |
| 1474 | ) |
| 1475 | .await; |
| 1476 | assert!(response.ok, "unset should succeed"); |
| 1477 | |
| 1478 | // Live runtime sees the cleared model. |
| 1479 | { |
| 1480 | let runtime = state.runtime.read().await; |
| 1481 | assert!(runtime.config.model.is_none()); |
| 1482 | } |
| 1483 | // Shared config lock agrees. |
| 1484 | { |
| 1485 | let cfg = state.config.read().await; |
| 1486 | assert!(cfg.model.is_none()); |
| 1487 | } |
| 1488 | // The on-disk file no longer carries the model value. |
| 1489 | let persisted = fs::read_to_string(&config_path).expect("read config"); |
| 1490 | assert!(!persisted.contains("deepseek-chat")); |
| 1491 | } |
| 1492 | |
| 1493 | #[tokio::test] |
| 1494 | async fn config_reload_returns_error_when_disk_config_is_invalid() { |
| 1495 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1496 | let config_path = tmp.path().join("config.toml"); |
| 1497 | fs::write( |
| 1498 | &config_path, |
| 1499 | "api_key = \"sk-deepseek-secret\"\nmodel = \"deepseek-chat\"\n", |
| 1500 | ) |
| 1501 | .expect("write config"); |
| 1502 | let state = build_state(Some(config_path.clone()), None).expect("state"); |
| 1503 | |
| 1504 | // Corrupt the on-disk config so ConfigStore::load fails to parse. |
| 1505 | fs::write(&config_path, "api_key = \"unterminated\n").expect("corrupt config"); |
| 1506 | |
| 1507 | let response = process_app_request(&state, AppRequest::ConfigReload, AppTransport::Stdio).await; |
| 1508 | assert!(!response.ok, "reload of corrupt config must fail"); |
| 1509 | let err = response.data["error"] |
| 1510 | .as_str() |
| 1511 | .expect("error message present") |
| 1512 | .to_string(); |
| 1513 | assert!( |
| 1514 | err.contains("failed to load config"), |
| 1515 | "error should mention load failure, got: {err}" |
| 1516 | ); |
| 1517 | |
| 1518 | // Live state is untouched: the early-return on load error must |
| 1519 | // not have clobbered runtime.config or state.config. |
| 1520 | { |
| 1521 | let runtime = state.runtime.read().await; |
| 1522 | assert_eq!(runtime.config.model.as_deref(), Some("deepseek-chat")); |
| 1523 | } |
| 1524 | { |
| 1525 | let cfg = state.config.read().await; |
| 1526 | assert_eq!(cfg.model.as_deref(), Some("deepseek-chat")); |
| 1527 | } |
| 1528 | } |
| 1529 | |
| 1530 | async fn seed_test_bridge(state: &AppState) -> SharedRuntimeBridge { |
| 1531 | let bridge = Arc::new(Mutex::new(RuntimeBridge::from_base_url_for_test( |
| 1532 | "http://127.0.0.1:9".to_string(), |
| 1533 | ))); |
| 1534 | *state.runtime_bridge.lock().await = Some(bridge.clone()); |
| 1535 | bridge |
| 1536 | } |
| 1537 | |
| 1538 | #[tokio::test] |
| 1539 | async fn config_set_invalidates_cached_stdio_bridge() { |
| 1540 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1541 | let config_path = tmp.path().join("config.toml"); |
| 1542 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1543 | let state = build_state(Some(config_path), None).expect("state"); |
| 1544 | seed_test_bridge(&state).await; |
| 1545 | |
| 1546 | let response = process_app_request( |
| 1547 | &state, |
| 1548 | AppRequest::ConfigSet { |
| 1549 | key: "model".to_string(), |
| 1550 | value: "deepseek-reasoner".to_string(), |
| 1551 | }, |
| 1552 | AppTransport::Stdio, |
| 1553 | ) |
| 1554 | .await; |
| 1555 | assert!(response.ok, "set should succeed"); |
| 1556 | |
| 1557 | // The cached bridge child must be dropped so the next stdio request |
| 1558 | // spawns a fresh runtime that reads the persisted config. |
| 1559 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 1560 | } |
| 1561 | |
| 1562 | #[tokio::test] |
| 1563 | async fn config_reload_invalidates_cached_stdio_bridge() { |
| 1564 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1565 | let config_path = tmp.path().join("config.toml"); |
| 1566 | fs::write(&config_path, "model = \"deepseek-chat\"\n").expect("write config"); |
| 1567 | let state = build_state(Some(config_path), None).expect("state"); |
| 1568 | seed_test_bridge(&state).await; |
| 1569 | |
| 1570 | let response = process_app_request(&state, AppRequest::ConfigReload, AppTransport::Stdio).await; |
| 1571 | assert!(response.ok, "reload should succeed"); |
| 1572 | |
| 1573 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 1574 | } |
| 1575 | |
| 1576 | #[tokio::test] |
| 1577 | async fn stdio_bridge_invalidation_not_blocked_by_in_flight_turn() { |
| 1578 | let (state, _tmp) = capability_test_state(); |
| 1579 | let bridge = seed_test_bridge(&state).await; |
| 1580 | |
| 1581 | // Simulate a long streaming turn holding the inner bridge lock. |
| 1582 | let _in_flight = bridge.lock().await; |
| 1583 | |
| 1584 | // Invalidation only touches the cache slot, so it must complete |
| 1585 | // without waiting for the in-flight turn to release the bridge. |
| 1586 | tokio::time::timeout(Duration::from_secs(1), invalidate_runtime_bridge(&state)) |
| 1587 | .await |
| 1588 | .expect("invalidation must not wait on bridge traffic"); |
| 1589 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 1590 | } |
| 1591 | |
| 1592 | #[tokio::test] |
| 1593 | async fn runtime_read_paths_run_concurrently() { |
| 1594 | // Tool/status/mcp handlers take read guards; two must coexist so a |
| 1595 | // long-running tool call cannot serialize unrelated requests. With |
| 1596 | // the old `Mutex<Runtime>` this pattern would deadlock. |
| 1597 | let (state, _tmp) = capability_test_state(); |
| 1598 | let first = state.runtime.read().await; |
| 1599 | let second = state.runtime.read().await; |
| 1600 | assert_eq!(first.config.provider, second.config.provider); |
| 1601 | } |
| 1602 | |
| 1603 | #[tokio::test] |
| 1604 | async fn health_probes_advertise_legacy_deepseek_service_name() { |
| 1605 | // External probes still key off the DeepSeek-era service name; both |
| 1606 | // transports must serve it from the single compat shim. |
| 1607 | let (app, _tmp) = app_with_config(None); |
| 1608 | let response = app |
| 1609 | .oneshot( |
| 1610 | Request::builder() |
| 1611 | .method(Method::GET) |
| 1612 | .uri("/healthz") |
| 1613 | .body(Body::empty()) |
| 1614 | .expect("request"), |
| 1615 | ) |
| 1616 | .await |
| 1617 | .expect("response"); |
| 1618 | let body = response_body_json(response).await; |
| 1619 | assert_eq!(body["service"], legacy_deepseek_compat::SERVICE_NAME); |
| 1620 | assert_eq!(body["service"], "deepseek-app-server"); |
| 1621 | |
| 1622 | let (state, _tmp) = capability_test_state(); |
| 1623 | let stdio = dispatch_stdio_request(&state, "healthz", json!({})) |
| 1624 | .await |
| 1625 | .expect("stdio healthz"); |
| 1626 | assert_eq!( |
| 1627 | stdio.result["service"], |
| 1628 | legacy_deepseek_compat::SERVICE_NAME |
| 1629 | ); |
| 1630 | } |
| 1631 | |
| 1632 | #[test] |
| 1633 | fn non_loopback_bind_without_auth_fails_fast() { |
| 1634 | let options = AppServerOptions { |
| 1635 | listen: "0.0.0.0:8787".parse().expect("socket addr"), |
| 1636 | config_path: None, |
| 1637 | auth_token: None, |
| 1638 | insecure_no_auth: false, |
| 1639 | cors_origins: Vec::new(), |
| 1640 | }; |
| 1641 | |
| 1642 | let err = resolve_auth_token(&options).expect_err("non-loopback generated auth should fail"); |
| 1643 | assert!(err.to_string().contains("without explicit auth token")); |
| 1644 | } |
| 1645 | |
| 1646 | #[tokio::test] |
| 1647 | async fn stdio_transport_redacts_config_get_secrets() { |
| 1648 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1649 | let config_path = tmp.path().join("config.toml"); |
| 1650 | fs::write(&config_path, "").expect("write config"); |
| 1651 | let state = build_state(Some(config_path), None).expect("state"); |
| 1652 | { |
| 1653 | let mut cfg = state.config.write().await; |
| 1654 | cfg.providers.deepseek.api_key = Some("sk-deepseek-secret".to_string()); |
| 1655 | } |
| 1656 | |
| 1657 | let response = process_app_request( |
| 1658 | &state, |
| 1659 | AppRequest::ConfigGet { |
| 1660 | key: "api_key".to_string(), |
| 1661 | }, |
| 1662 | AppTransport::Stdio, |
| 1663 | ) |
| 1664 | .await; |
| 1665 | |
| 1666 | assert_eq!(response.data["value"], "sk-d***cret"); |
| 1667 | } |
| 1668 | |
| 1669 | #[tokio::test] |
| 1670 | async fn stdio_thread_goal_methods_refuse_execution_and_read_existing_goal() { |
| 1671 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 1672 | let capabilities = dispatch_stdio_request(&state, "thread/capabilities", json!({})) |
| 1673 | .await |
| 1674 | .unwrap(); |
| 1675 | assert_eq!(capabilities.result["goal_execution"], false); |
| 1676 | assert!( |
| 1677 | !capabilities.result["methods"] |
| 1678 | .as_array() |
| 1679 | .unwrap() |
| 1680 | .iter() |
| 1681 | .any(|method| method == "thread/goal/set") |
| 1682 | ); |
| 1683 | let started = |
| 1684 | dispatch_stdio_request(&state, "thread/start", json!({"operationKey":"goal-start"})) |
| 1685 | .await |
| 1686 | .unwrap(); |
| 1687 | let id = started.result["thread"]["id"].as_str().unwrap(); |
| 1688 | let set = dispatch_stdio_request( |
| 1689 | &state, |
| 1690 | "thread/goal/set", |
| 1691 | json!({"thread_id":id,"objective":"Release 0.10.1","token_budget":59000}), |
| 1692 | ) |
| 1693 | .await |
| 1694 | .unwrap_err(); |
| 1695 | assert_eq!( |
| 1696 | set.wire.data.unwrap()["error"], |
| 1697 | "interactive_execution_unsupported" |
| 1698 | ); |
| 1699 | let (endpoint, token) = { |
| 1700 | let shared = state.runtime_bridge.lock().await.clone().unwrap(); |
| 1701 | let bridge = shared.lock().await; |
| 1702 | (bridge.base_url.clone(), bridge.auth_token.clone().unwrap()) |
| 1703 | }; |
| 1704 | codewhale_release::tls::reqwest_client() |
| 1705 | .put(format!("{endpoint}/v1/threads/{id}/goal")) |
| 1706 | .bearer_auth(token) |
| 1707 | .json(&json!({"objective":"Release 0.10.1","token_budget":59000})) |
| 1708 | .send() |
| 1709 | .await |
| 1710 | .unwrap() |
| 1711 | .error_for_status() |
| 1712 | .unwrap(); |
| 1713 | let got = dispatch_stdio_request(&state, "thread/goal/get", json!({"thread_id":id})) |
| 1714 | .await |
| 1715 | .unwrap(); |
| 1716 | assert_eq!(got.result["goal"]["token_budget"], 59000); |
| 1717 | let cleared = dispatch_stdio_request(&state, "thread/goal/clear", json!({"thread_id":id})) |
| 1718 | .await |
| 1719 | .unwrap(); |
| 1720 | assert_eq!(cleared.result["status"], "cleared"); |
| 1721 | assert_eq!(cleared.result["data"]["cleared"], true); |
| 1722 | server.abort(); |
| 1723 | } |
| 1724 | |
| 1725 | #[tokio::test] |
| 1726 | async fn stdio_resume_of_missing_thread_fails_without_clobbering_the_hint() { |
| 1727 | let (state, tmp, server) = thread_control::compatibility_fixture().await; |
| 1728 | let workspace = tmp.path().join("ws"); |
| 1729 | state.stdio_thread_hints.lock().await.insert( |
| 1730 | "ghost-thread".into(), |
| 1731 | RuntimeThreadHint { |
| 1732 | model: Some("fixture-model".into()), |
| 1733 | workspace: Some(workspace.clone()), |
| 1734 | }, |
| 1735 | ); |
| 1736 | for method in ["thread/resume", "thread/fork"] { |
| 1737 | let error = dispatch_stdio_request( |
| 1738 | &state, |
| 1739 | method, |
| 1740 | json!({"thread_id":"ghost-thread","operation_key":format!("{method}-missing")}), |
| 1741 | ) |
| 1742 | .await |
| 1743 | .unwrap_err(); |
| 1744 | assert_eq!(error.wire.code, THREAD_NOT_FOUND_CODE); |
| 1745 | assert!(error.wire.message.contains("ghost-thread")); |
| 1746 | } |
| 1747 | let hints = state.stdio_thread_hints.lock().await; |
| 1748 | assert_eq!( |
| 1749 | hints["ghost-thread"].model.as_deref(), |
| 1750 | Some("fixture-model") |
| 1751 | ); |
| 1752 | assert_eq!(hints["ghost-thread"].workspace.as_ref(), Some(&workspace)); |
| 1753 | server.abort(); |
| 1754 | } |
| 1755 | |
| 1756 | #[tokio::test] |
| 1757 | async fn stdio_archive_of_missing_thread_fails_instead_of_reporting_success() { |
| 1758 | let (state, _tmp, server) = thread_control::compatibility_fixture().await; |
| 1759 | for method in ["thread/archive", "thread/unarchive"] { |
| 1760 | let error = dispatch_stdio_request(&state, method, json!({"thread_id":"ghost-thread"})) |
| 1761 | .await |
| 1762 | .unwrap_err(); |
| 1763 | assert_eq!(error.wire.code, THREAD_NOT_FOUND_CODE); |
| 1764 | assert!(error.wire.message.contains("ghost-thread")); |
| 1765 | } |
| 1766 | server.abort(); |
| 1767 | } |
| 1768 | |
| 1769 | fn sse_frame(event: &str, payload: Value) -> String { |
| 1770 | format!("event: {event}\ndata: {payload}\n\n") |
| 1771 | } |
| 1772 | struct RuntimeInterruptFixture { |
| 1773 | signal: tokio::sync::Notify, |
| 1774 | calls: std::sync::atomic::AtomicUsize, |
| 1775 | fail_first: bool, |
| 1776 | terminal_race: bool, |
| 1777 | workspace: std::path::PathBuf, |
| 1778 | } |
| 1779 | |
| 1780 | /// A runtime whose turn never ends on its own — only an interrupt stops |
| 1781 | /// it. That is the shape of the runaway turn this protects against. |
| 1782 | async fn spawn_uninterruptible_until_asked_runtime( |
| 1783 | owner_router: Router, |
| 1784 | fail_first: bool, |
| 1785 | terminal_race: bool, |
| 1786 | workspace: std::path::PathBuf, |
| 1787 | ) -> ( |
| 1788 | String, |
| 1789 | Arc<RuntimeInterruptFixture>, |
| 1790 | tokio::task::JoinHandle<()>, |
| 1791 | ) { |
| 1792 | use axum::body::Body; |
| 1793 | use axum::extract::Path as AxumPath; |
| 1794 | |
| 1795 | let interrupted = Arc::new(RuntimeInterruptFixture { |
| 1796 | signal: tokio::sync::Notify::new(), |
| 1797 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 1798 | fail_first, |
| 1799 | terminal_race, |
| 1800 | workspace, |
| 1801 | }); |
| 1802 | |
| 1803 | async fn create_turn(AxumPath(thread_id): AxumPath<String>) -> Json<Value> { |
| 1804 | Json(json!({ "turn": { "id": "turn_runaway", "thread_id": thread_id } })) |
| 1805 | } |
| 1806 | async fn create_thread() -> Json<Value> { |
| 1807 | Json(json!({ "id": "thr_runaway" })) |
| 1808 | } |
| 1809 | async fn interrupt( |
| 1810 | State(notify): State<Arc<RuntimeInterruptFixture>>, |
| 1811 | AxumPath((_thread_id, _turn_id)): AxumPath<(String, String)>, |
| 1812 | ) -> (StatusCode, Json<Value>) { |
| 1813 | let count = notify |
| 1814 | .calls |
| 1815 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 1816 | + 1; |
| 1817 | if notify.fail_first && count == 1 { |
| 1818 | return ( |
| 1819 | StatusCode::SERVICE_UNAVAILABLE, |
| 1820 | Json(json!({"error":"fixture interrupt uncertainty"})), |
| 1821 | ); |
| 1822 | } |
| 1823 | notify.signal.notify_one(); |
| 1824 | (StatusCode::OK, Json(json!({ "ok": true }))) |
| 1825 | } |
| 1826 | async fn get_thread( |
| 1827 | State(fixture): State<Arc<RuntimeInterruptFixture>>, |
| 1828 | AxumPath(thread_id): AxumPath<String>, |
| 1829 | ) -> Json<Value> { |
| 1830 | Json(json!({ |
| 1831 | "thread":{"id":thread_id,"created_at":"2026-10-02T00:00:00Z", |
| 1832 | "updated_at":"2026-10-02T00:00:01Z","model":"fixture-model", |
| 1833 | "model_provider":"custom","model_provider_id":"fixture-account", |
| 1834 | "workspace":fixture.workspace,"archived":false}, |
| 1835 | "turns":[{"id":"turn_runaway","thread_id":thread_id, |
| 1836 | "status":if fixture.terminal_race {"completed"} else {"in_progress"}}], |
| 1837 | })) |
| 1838 | } |
| 1839 | async fn thread_events( |
| 1840 | State(notify): State<Arc<RuntimeInterruptFixture>>, |
| 1841 | AxumPath(thread_id): AxumPath<String>, |
| 1842 | ) -> ([(header::HeaderName, &'static str); 1], Body) { |
| 1843 | // Hold the event response open until something interrupts the |
| 1844 | // turn. Nothing else can end it, which is the point. |
| 1845 | notify.signal.notified().await; |
| 1846 | let body = [ |
| 1847 | sse_frame( |
| 1848 | "item.delta", |
| 1849 | json!({ |
| 1850 | "seq": 1, |
| 1851 | "thread_id": thread_id, "turn_id": "turn_runaway", |
| 1852 | "payload": { "kind": "agent_message", "delta": "thinking" } |
| 1853 | }), |
| 1854 | ), |
| 1855 | sse_frame( |
| 1856 | "turn.completed", |
| 1857 | json!({ |
| 1858 | "seq": 2, |
| 1859 | "thread_id": thread_id, "turn_id": "turn_runaway", |
| 1860 | "payload": { "turn": { "id": "turn_runaway", "thread_id": thread_id, "status": "interrupted" } } |
| 1861 | }), |
| 1862 | ), |
| 1863 | ] |
| 1864 | .concat(); |
| 1865 | ( |
| 1866 | [(header::CONTENT_TYPE, "text/event-stream")], |
| 1867 | Body::from(body), |
| 1868 | ) |
| 1869 | } |
| 1870 | |
| 1871 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 1872 | .await |
| 1873 | .expect("bind test listener"); |
| 1874 | let addr = listener.local_addr().expect("listener addr"); |
| 1875 | let app = Router::new() |
| 1876 | .route("/v1/threads", post(create_thread)) |
| 1877 | .route("/v1/threads/{thread_id}", get(get_thread)) |
| 1878 | .route("/v1/threads/{thread_id}/turns", post(create_turn)) |
| 1879 | .route( |
| 1880 | "/v1/threads/{thread_id}/turns/{turn_id}/interrupt", |
| 1881 | post(interrupt), |
| 1882 | ) |
| 1883 | .route("/v1/threads/{thread_id}/events", get(thread_events)) |
| 1884 | .with_state(interrupted.clone()) |
| 1885 | .fallback_service(owner_router); |
| 1886 | let server = tokio::spawn(async move { |
| 1887 | axum::serve(listener, app) |
| 1888 | .await |
| 1889 | .expect("serve test runtime"); |
| 1890 | }); |
| 1891 | (format!("http://{addr}"), interrupted, server) |
| 1892 | } |
| 1893 | |
| 1894 | #[tokio::test] |
| 1895 | async fn interrupt_stops_a_turn_that_would_otherwise_stream_forever() { |
| 1896 | for (method, failure_kind) in [ |
| 1897 | ("thread/message", "interrupt"), |
| 1898 | ("thread/message", "reader_error"), |
| 1899 | ("thread/message", "outer_cancel"), |
| 1900 | ("thread/request", "reader_error"), |
| 1901 | ("thread/request", "outer_cancel"), |
| 1902 | ("prompt/request", "reader_error"), |
| 1903 | ("prompt/request", "outer_cancel"), |
| 1904 | ("prompt/run", "reader_error"), |
| 1905 | ("prompt/run", "outer_cancel"), |
| 1906 | ("thread/message", "uncertain_recovery"), |
| 1907 | ("thread/message", "terminal_race"), |
| 1908 | ] { |
| 1909 | let (mut state, _tmp, owner_router) = thread_control::compatibility_router(); |
| 1910 | let (base_url, observed_interrupts, server) = spawn_uninterruptible_until_asked_runtime( |
| 1911 | owner_router, |
| 1912 | matches!(failure_kind, "uncertain_recovery" | "terminal_race"), |
| 1913 | failure_kind == "terminal_race", |
| 1914 | _tmp.path().to_owned(), |
| 1915 | ) |
| 1916 | .await; |
| 1917 | seed_client_thread(&state, "thr_a").await; |
| 1918 | *state.runtime_bridge.lock().await = Some(Arc::new(Mutex::new( |
| 1919 | RuntimeBridge::from_base_url_for_test(base_url), |
| 1920 | ))); |
| 1921 | install_mock_native_services(&mut state).await; |
| 1922 | |
| 1923 | let (client, server_side) = tokio::io::duplex(16 * 1024); |
| 1924 | let (client_reader, mut client_writer) = tokio::io::split(client); |
| 1925 | |
| 1926 | let loop_state = state.clone(); |
| 1927 | let loop_handle = tokio::spawn(async move { |
| 1928 | let (rx, tx) = tokio::io::split(server_side); |
| 1929 | run_stdio_loop( |
| 1930 | &loop_state, |
| 1931 | BoundedLines::new(BufReader::new(rx)), |
| 1932 | tx, |
| 1933 | StdioLoopPolicy::process_stdio(), |
| 1934 | None::<()>, |
| 1935 | ) |
| 1936 | .await |
| 1937 | }); |
| 1938 | |
| 1939 | client_writer.write_all(b"{\"id\":\"initialize\",\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"fixture\",\"version\":\"1\"}}}\n{\"method\":\"initialized\"}\n").await.expect("initialize connection"); |
| 1940 | |
| 1941 | // Start the runaway turn. |
| 1942 | let params = match method { |
| 1943 | "thread/request" => { |
| 1944 | json!({"kind":"message","thread_id":"thr_a","input":"go","allowed_tools":[]}) |
| 1945 | } |
| 1946 | "prompt/request" | "prompt/run" => { |
| 1947 | json!({"thread_id":"thr_a","prompt":"go","allowed_tools":[]}) |
| 1948 | } |
| 1949 | _ => json!({"thread_id":"thr_a","input":"go","allowed_tools":[]}), |
| 1950 | }; |
| 1951 | client_writer |
| 1952 | .write_all(format!("{}\n", json!({"id":1,"method":method,"params":params})).as_bytes()) |
| 1953 | .await |
| 1954 | .expect("send native request"); |
| 1955 | |
| 1956 | // Wait until the turn is genuinely in flight before cancelling, so the |
| 1957 | // test exercises mid-stream cancellation rather than a race. |
| 1958 | let mut lines = BufReader::new(client_reader); |
| 1959 | let mut output = String::new(); |
| 1960 | tokio::time::timeout(Duration::from_secs(10), async { |
| 1961 | loop { |
| 1962 | let mut line = String::new(); |
| 1963 | assert!( |
| 1964 | tokio::io::AsyncBufReadExt::read_line(&mut lines, &mut line) |
| 1965 | .await |
| 1966 | .expect("native output") |
| 1967 | > 0 |
| 1968 | ); |
| 1969 | let started = serde_json::from_str::<Value>(&line).expect("native frame")["type"] |
| 1970 | == "response_start"; |
| 1971 | output.push_str(&line); |
| 1972 | if started { |
| 1973 | break; |
| 1974 | } |
| 1975 | } |
| 1976 | }) |
| 1977 | .await |
| 1978 | .expect("native turn must establish its exact claim before cancellation"); |
| 1979 | |
| 1980 | if failure_kind == "outer_cancel" { |
| 1981 | loop_handle.abort(); |
| 1982 | assert!(loop_handle.await.unwrap_err().is_cancelled()); |
| 1983 | tokio::time::timeout(Duration::from_secs(20), async { |
| 1984 | loop { |
| 1985 | if observed_interrupts |
| 1986 | .calls |
| 1987 | .load(std::sync::atomic::Ordering::SeqCst) |
| 1988 | == 1 |
| 1989 | && state.in_flight_turns.lock().await.is_empty() |
| 1990 | { |
| 1991 | break; |
| 1992 | } |
| 1993 | tokio::task::yield_now().await; |
| 1994 | } |
| 1995 | }) |
| 1996 | .await |
| 1997 | .expect("one owned cleanup must outlive its canceled observer"); |
| 1998 | } else { |
| 1999 | if failure_kind != "interrupt" { |
| 2000 | client_writer |
| 2001 | .write_all(&[0xff, b'\n']) |
| 2002 | .await |
| 2003 | .expect("send invalid UTF-8"); |
| 2004 | } else { |
| 2005 | client_writer |
| 2006 | .write_all( |
| 2007 | b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"thread/interrupt\",\ |
| 2008 | \"params\":{\"thread_id\":\"thr_a\"}}\n", |
| 2009 | ) |
| 2010 | .await |
| 2011 | .expect("send thread/interrupt"); |
| 2012 | client_writer |
| 2013 | .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"shutdown\"}\n") |
| 2014 | .await |
| 2015 | .expect("send shutdown"); |
| 2016 | } |
| 2017 | let finished = tokio::time::timeout(Duration::from_secs(20), loop_handle) |
| 2018 | .await |
| 2019 | .expect("the loop must exit rather than hang on the runaway turn") |
| 2020 | .expect("join loop"); |
| 2021 | if failure_kind != "interrupt" { |
| 2022 | let error = finished.unwrap_err(); |
| 2023 | assert!(format!("{error:#}").contains("control frame is not UTF-8")); |
| 2024 | assert_eq!( |
| 2025 | observed_interrupts |
| 2026 | .calls |
| 2027 | .load(std::sync::atomic::Ordering::SeqCst), |
| 2028 | 1 |
| 2029 | ); |
| 2030 | if failure_kind == "uncertain_recovery" { |
| 2031 | assert!(format!("{error:#}").contains("unconfirmed")); |
| 2032 | assert_eq!( |
| 2033 | state |
| 2034 | .in_flight_turns |
| 2035 | .lock() |
| 2036 | .await |
| 2037 | .get("thr_a") |
| 2038 | .unwrap() |
| 2039 | .turn_id, |
| 2040 | "turn_runaway" |
| 2041 | ); |
| 2042 | assert!( |
| 2043 | interrupt_stdio_turn(&state, "thr_a", None) |
| 2044 | .await |
| 2045 | .expect("explicit recovery interrupt") |
| 2046 | ); |
| 2047 | assert_eq!( |
| 2048 | observed_interrupts |
| 2049 | .calls |
| 2050 | .load(std::sync::atomic::Ordering::SeqCst), |
| 2051 | 2 |
| 2052 | ); |
| 2053 | } |
| 2054 | } else { |
| 2055 | finished.expect("loop result"); |
| 2056 | } |
| 2057 | assert!(state.in_flight_turns.lock().await.is_empty()); |
| 2058 | } |
| 2059 | |
| 2060 | lines |
| 2061 | .read_to_string(&mut output) |
| 2062 | .await |
| 2063 | .expect("read stdio output"); |
| 2064 | |
| 2065 | let responses: Vec<Value> = output |
| 2066 | .lines() |
| 2067 | .filter_map(|line| serde_json::from_str::<Value>(line).ok()) |
| 2068 | .collect(); |
| 2069 | let by_id = |id: u64| { |
| 2070 | responses |
| 2071 | .iter() |
| 2072 | .find(|value| value["id"] == json!(id)) |
| 2073 | .unwrap_or_else(|| panic!("no response for id {id} in {output}")) |
| 2074 | .clone() |
| 2075 | }; |
| 2076 | |
| 2077 | if failure_kind == "interrupt" { |
| 2078 | // The turn ended as interrupted rather than running to completion. |
| 2079 | assert!( |
| 2080 | by_id(1)["error"].is_object(), |
| 2081 | "the interrupted turn should report an error, got: {}", |
| 2082 | by_id(1) |
| 2083 | ); |
| 2084 | assert_eq!(by_id(2)["result"]["interrupted"], json!(true)); |
| 2085 | assert_eq!(by_id(3)["result"]["status"], json!("stopped")); |
| 2086 | } else { |
| 2087 | assert!( |
| 2088 | responses |
| 2089 | .iter() |
| 2090 | .all(|response| response.get("id") != Some(&json!(1))) |
| 2091 | ); |
| 2092 | } |
| 2093 | |
| 2094 | server.abort(); |
| 2095 | let _ = server.await; |
| 2096 | } |
| 2097 | } |
| 2098 | |
| 2099 | #[tokio::test] |
| 2100 | async fn interrupting_an_idle_thread_is_not_an_error() { |
| 2101 | let (state, _tmp) = capability_test_state(); |
| 2102 | let response = dispatch_stdio_request( |
| 2103 | &state, |
| 2104 | "thread/interrupt", |
| 2105 | json!({ "thread_id": "thr_nothing_running" }), |
| 2106 | ) |
| 2107 | .await |
| 2108 | .expect("interrupt dispatch"); |
| 2109 | assert_eq!(response.result["interrupted"], json!(false)); |
| 2110 | } |
| 2111 | |
| 2112 | #[tokio::test] |
| 2113 | async fn output_cap_bridge_checks_support_before_creation_and_forwards_each_surface() { |
| 2114 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 2115 | #[derive(Clone)] |
| 2116 | struct Fixture { |
| 2117 | supported: Arc<AtomicBool>, |
| 2118 | created: Arc<AtomicUsize>, |
| 2119 | requests: Arc<Mutex<Vec<Value>>>, |
| 2120 | } |
| 2121 | async fn info(State(f): State<Fixture>, headers: axum::http::HeaderMap) -> Json<Value> { |
| 2122 | assert_eq!( |
| 2123 | headers.get(header::AUTHORIZATION).unwrap(), |
| 2124 | "Bearer fixture-output-cap" |
| 2125 | ); |
| 2126 | Json(json!({"capabilities":{"turn_output_token_limit":f.supported.load(Ordering::SeqCst)}})) |
| 2127 | } |
| 2128 | async fn providers() -> Json<Value> { |
| 2129 | Json( |
| 2130 | json!({"current":"custom","current_provider_id":"fixture-route","providers":[{"id":"custom","model_provider_id":"fixture-route","default_model":"fixture-model"}]}), |
| 2131 | ) |
| 2132 | } |
| 2133 | async fn models( |
| 2134 | axum::extract::Query(query): axum::extract::Query<HashMap<String, String>>, |
| 2135 | ) -> Json<Value> { |
| 2136 | assert_eq!( |
| 2137 | query.get("model_provider_id").map(String::as_str), |
| 2138 | Some("fixture-route") |
| 2139 | ); |
| 2140 | Json( |
| 2141 | json!({"provider":"custom","model_provider_id":"fixture-route","total":2,"models":[{"id":"fixture-model","output_token_limit":"supported"},{"id":"uncapped-transport","output_token_limit":"unsupported"}]}), |
| 2142 | ) |
| 2143 | } |
| 2144 | async fn create_thread(State(f): State<Fixture>) -> Json<Value> { |
| 2145 | let n = f.created.fetch_add(1, Ordering::SeqCst); |
| 2146 | Json(json!({"id":format!("thr_cap_{n}")})) |
| 2147 | } |
| 2148 | async fn create_turn( |
| 2149 | State(f): State<Fixture>, |
| 2150 | AxumPath(thread_id): AxumPath<String>, |
| 2151 | Json(body): Json<Value>, |
| 2152 | ) -> Json<Value> { |
| 2153 | f.requests.lock().await.push(body); |
| 2154 | Json(json!({"turn":{"id":"turn_cap","thread_id":thread_id}})) |
| 2155 | } |
| 2156 | async fn events( |
| 2157 | State(f): State<Fixture>, |
| 2158 | AxumPath(thread_id): AxumPath<String>, |
| 2159 | ) -> impl IntoResponse { |
| 2160 | let seq = f.requests.lock().await.len(); |
| 2161 | ( |
| 2162 | [(header::CONTENT_TYPE, "text/event-stream")], |
| 2163 | sse_frame( |
| 2164 | "turn.completed", |
| 2165 | json!({ |
| 2166 | "seq":seq,"thread_id":thread_id,"turn_id":"turn_cap","payload":{"turn":{"id":"turn_cap","thread_id":thread_id,"status":"completed"}} |
| 2167 | }), |
| 2168 | ), |
| 2169 | ) |
| 2170 | } |
| 2171 | let fixture = Fixture { |
| 2172 | supported: Arc::new(AtomicBool::new(false)), |
| 2173 | created: Arc::new(AtomicUsize::new(0)), |
| 2174 | requests: Arc::new(Mutex::new(Vec::new())), |
| 2175 | }; |
| 2176 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2177 | let addr = listener.local_addr().unwrap(); |
| 2178 | let (mut state, _tmp, owner_router) = thread_control::compatibility_router(); |
| 2179 | let router = Router::new() |
| 2180 | .route("/v1/runtime/info", get(info)) |
| 2181 | .route("/v1/providers", get(providers)) |
| 2182 | .route("/v1/providers/custom/models", get(models)) |
| 2183 | .route("/v1/threads", post(create_thread)) |
| 2184 | .route("/v1/threads/{id}/turns", post(create_turn)) |
| 2185 | .route("/v1/threads/{id}/events", get(events)) |
| 2186 | .with_state(fixture.clone()) |
| 2187 | .fallback_service(owner_router); |
| 2188 | let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); |
| 2189 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{addr}")); |
| 2190 | bridge.auth_token = Some("fixture-output-cap".into()); |
| 2191 | *state.runtime_bridge.lock().await = Some(Arc::new(Mutex::new(bridge))); |
| 2192 | install_mock_native_services(&mut state).await; |
| 2193 | let result = dispatch_stdio_request( |
| 2194 | &state, |
| 2195 | "prompt/run", |
| 2196 | json!({"allowed_tools": [], "prompt":"review","maxOutputTokens":1500}), |
| 2197 | ) |
| 2198 | .await; |
| 2199 | assert!( |
| 2200 | result |
| 2201 | .unwrap_err() |
| 2202 | .wire |
| 2203 | .message |
| 2204 | .contains("does not support") |
| 2205 | ); |
| 2206 | assert_eq!(fixture.created.load(Ordering::SeqCst), 0); |
| 2207 | assert!(fixture.requests.lock().await.is_empty()); |
| 2208 | fixture.supported.store(true, Ordering::SeqCst); |
| 2209 | for model in ["auto", "uncapped-transport", "unknown-model"] { |
| 2210 | assert!( |
| 2211 | dispatch_stdio_request( |
| 2212 | &state, |
| 2213 | "prompt/run", |
| 2214 | json!({"allowed_tools": [], "prompt":"review","model":model,"maxOutputTokens":1500}) |
| 2215 | ) |
| 2216 | .await |
| 2217 | .is_err() |
| 2218 | ); |
| 2219 | } |
| 2220 | assert_eq!(fixture.created.load(Ordering::SeqCst), 0); |
| 2221 | for thread_id in ["stdio-cap", "request-cap", "http-cap"] { |
| 2222 | seed_client_thread(&state, thread_id).await; |
| 2223 | } |
| 2224 | for (method, params) in [ |
| 2225 | ( |
| 2226 | "prompt/run", |
| 2227 | json!({"allowed_tools": [], "prompt":"review","maxOutputTokens":1500}), |
| 2228 | ), |
| 2229 | ( |
| 2230 | "thread/message", |
| 2231 | json!({"thread_id":"stdio-cap","allowed_tools": [], "input":"review","maxOutputTokens":1500}), |
| 2232 | ), |
| 2233 | ( |
| 2234 | "thread/request", |
| 2235 | json!({"kind":"message","thread_id":"request-cap","allowed_tools": [], "input":"review","maxOutputTokens":1500}), |
| 2236 | ), |
| 2237 | ] { |
| 2238 | dispatch_stdio_request(&state, method, params) |
| 2239 | .await |
| 2240 | .expect("existing app-server caller forwards allowance"); |
| 2241 | } |
| 2242 | run_http_thread_message( |
| 2243 | &state, |
| 2244 | "http-cap".into(), |
| 2245 | "review".into(), |
| 2246 | Some(Vec::new()), |
| 2247 | Vec::new(), |
| 2248 | std::num::NonZeroU32::new(1500), |
| 2249 | ) |
| 2250 | .await |
| 2251 | .unwrap(); |
| 2252 | let requests = fixture.requests.lock().await.clone(); |
| 2253 | assert_eq!(requests.len(), 4); |
| 2254 | assert!( |
| 2255 | requests |
| 2256 | .iter() |
| 2257 | .all(|request| request["maxOutputTokens"] == 1500) |
| 2258 | ); |
| 2259 | let count = fixture.created.load(Ordering::SeqCst); |
| 2260 | for invalid in [ |
| 2261 | json!(0), |
| 2262 | json!(-1), |
| 2263 | json!(1.5), |
| 2264 | json!("1500"), |
| 2265 | json!(4_294_967_296u64), |
| 2266 | ] { |
| 2267 | assert!( |
| 2268 | dispatch_stdio_request( |
| 2269 | &state, |
| 2270 | "prompt/run", |
| 2271 | json!({"allowed_tools": [], "prompt":"review","maxOutputTokens":invalid}) |
| 2272 | ) |
| 2273 | .await |
| 2274 | .is_err() |
| 2275 | ); |
| 2276 | } |
| 2277 | assert_eq!(fixture.created.load(Ordering::SeqCst), count); |
| 2278 | assert_eq!(fixture.requests.lock().await.len(), 4); |
| 2279 | server.abort(); |
| 2280 | let _ = server.await; |
| 2281 | } |
| 2282 | |
| 2283 | #[tokio::test] |
| 2284 | async fn stdio_runtime_bridge_streams_response_delta_events() { |
| 2285 | async fn create_turn(AxumPath(thread_id): AxumPath<String>) -> Json<Value> { |
| 2286 | Json(json!({ |
| 2287 | "thread": { "id": thread_id }, |
| 2288 | "turn": { "id": "turn_test" }, |
| 2289 | })) |
| 2290 | } |
| 2291 | |
| 2292 | async fn thread_events( |
| 2293 | AxumPath(thread_id): AxumPath<String>, |
| 2294 | Query(query): Query<HashMap<String, String>>, |
| 2295 | ) -> ([(header::HeaderName, &'static str); 1], String) { |
| 2296 | assert_eq!(thread_id, "thr_test"); |
| 2297 | assert_eq!(query.get("since_seq").map(String::as_str), Some("0")); |
| 2298 | |
| 2299 | let body = [ |
| 2300 | sse_frame( |
| 2301 | "item.delta", |
| 2302 | json!({ |
| 2303 | "seq": 1, |
| 2304 | "turn_id": "turn_test", |
| 2305 | "payload": { |
| 2306 | "kind": "agent_message", |
| 2307 | "delta": "hello" |
| 2308 | } |
| 2309 | }), |
| 2310 | ), |
| 2311 | sse_frame( |
| 2312 | "turn.completed", |
| 2313 | json!({ |
| 2314 | "seq": 2, |
| 2315 | "turn_id": "turn_test", |
| 2316 | "payload": { |
| 2317 | "turn": { |
| 2318 | "status": "completed" |
| 2319 | } |
| 2320 | } |
| 2321 | }), |
| 2322 | ), |
| 2323 | ] |
| 2324 | .concat(); |
| 2325 | |
| 2326 | ([(header::CONTENT_TYPE, "text/event-stream")], body) |
| 2327 | } |
| 2328 | |
| 2329 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 2330 | .await |
| 2331 | .expect("bind test listener"); |
| 2332 | let addr = listener.local_addr().expect("listener addr"); |
| 2333 | let app = Router::new() |
| 2334 | .route("/v1/threads/{thread_id}/turns", post(create_turn)) |
| 2335 | .route("/v1/threads/{thread_id}/events", get(thread_events)); |
| 2336 | |
| 2337 | let server = tokio::spawn(async move { |
| 2338 | axum::serve(listener, app) |
| 2339 | .await |
| 2340 | .expect("serve test runtime"); |
| 2341 | }); |
| 2342 | |
| 2343 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{addr}")); |
| 2344 | let (mut reader, mut writer) = tokio::io::duplex(4096); |
| 2345 | |
| 2346 | let result = bridge |
| 2347 | .message_thread( |
| 2348 | "thr_test", |
| 2349 | RuntimeTurnInput { |
| 2350 | input: "hello", |
| 2351 | images: &[], |
| 2352 | max_output_tokens: None, |
| 2353 | expected_workspace: None, |
| 2354 | cancellation: None, |
| 2355 | }, |
| 2356 | &mut writer, |
| 2357 | None, |
| 2358 | None, |
| 2359 | ) |
| 2360 | .await |
| 2361 | .expect("message_thread should succeed"); |
| 2362 | drop(writer); |
| 2363 | |
| 2364 | let mut stdout = Vec::new(); |
| 2365 | reader |
| 2366 | .read_to_end(&mut stdout) |
| 2367 | .await |
| 2368 | .expect("read stdio output"); |
| 2369 | server.abort(); |
| 2370 | let _ = server.await; |
| 2371 | |
| 2372 | let lines: Vec<Value> = String::from_utf8(stdout) |
| 2373 | .expect("utf8 output") |
| 2374 | .lines() |
| 2375 | .map(|line| serde_json::from_str(line).expect("json line")) |
| 2376 | .collect(); |
| 2377 | |
| 2378 | assert_eq!( |
| 2379 | result.get("status").and_then(Value::as_str), |
| 2380 | Some("accepted") |
| 2381 | ); |
| 2382 | assert_eq!( |
| 2383 | result.pointer("/data/turn_id").and_then(Value::as_str), |
| 2384 | Some("turn_test") |
| 2385 | ); |
| 2386 | assert_eq!(bridge.last_seq_by_thread.get("thr_test"), Some(&2)); |
| 2387 | |
| 2388 | let event_types: Vec<&str> = lines |
| 2389 | .iter() |
| 2390 | .map(|line| { |
| 2391 | line.get("type") |
| 2392 | .and_then(Value::as_str) |
| 2393 | .expect("event type") |
| 2394 | }) |
| 2395 | .collect(); |
| 2396 | assert_eq!( |
| 2397 | event_types, |
| 2398 | vec!["response_start", "response_delta", "response_end"] |
| 2399 | ); |
| 2400 | assert_eq!(lines[1]["delta"], "hello"); |
| 2401 | } |
| 2402 | |
| 2403 | #[tokio::test] |
| 2404 | async fn native_stdio_recovers_lost_admission_and_cleans_up_disconnected_callers() { |
| 2405 | #[derive(Clone, Default)] |
| 2406 | struct Fixture { |
| 2407 | starts: Arc<Mutex<Vec<(String, String)>>>, |
| 2408 | lookups: Arc<Mutex<Vec<(String, String)>>>, |
| 2409 | interrupts: Arc<Mutex<Vec<(String, String)>>>, |
| 2410 | started: Arc<tokio::sync::Notify>, |
| 2411 | interrupted: Arc<tokio::sync::Notify>, |
| 2412 | finish_start: Arc<tokio::sync::Notify>, |
| 2413 | pending_reads: Arc<std::sync::atomic::AtomicUsize>, |
| 2414 | } |
| 2415 | |
| 2416 | async fn start( |
| 2417 | State(f): State<Fixture>, |
| 2418 | AxumPath(thread): AxumPath<String>, |
| 2419 | Json(body): Json<Value>, |
| 2420 | ) -> StatusCode { |
| 2421 | let key = body["operation_key"].as_str().unwrap().to_owned(); |
| 2422 | assert!(uuid::Uuid::parse_str(&key).is_ok()); |
| 2423 | f.starts.lock().await.push((thread.clone(), key)); |
| 2424 | f.started.notify_one(); |
| 2425 | if thread == "cancel" || thread == "drop" { |
| 2426 | f.finish_start.notified().await; |
| 2427 | } |
| 2428 | if thread.starts_with("refused") { |
| 2429 | StatusCode::FORBIDDEN |
| 2430 | } else { |
| 2431 | StatusCode::SERVICE_UNAVAILABLE |
| 2432 | } |
| 2433 | } |
| 2434 | async fn lookup( |
| 2435 | State(f): State<Fixture>, |
| 2436 | AxumPath(identity): AxumPath<(String, String)>, |
| 2437 | ) -> Response { |
| 2438 | assert!(f.starts.lock().await.contains(&identity)); |
| 2439 | if identity.0 == "drop" { |
| 2440 | match f |
| 2441 | .pending_reads |
| 2442 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 2443 | { |
| 2444 | 0 => return StatusCode::NOT_FOUND.into_response(), |
| 2445 | 1 => return StatusCode::CONFLICT.into_response(), |
| 2446 | _ => {} |
| 2447 | } |
| 2448 | } |
| 2449 | f.lookups.lock().await.push(identity.clone()); |
| 2450 | if identity.0 == "refused" { |
| 2451 | return StatusCode::NOT_FOUND.into_response(); |
| 2452 | } |
| 2453 | let thread = if identity.0 == "mismatch" { |
| 2454 | "somewhere-else" |
| 2455 | } else { |
| 2456 | &identity.0 |
| 2457 | }; |
| 2458 | Json(json!({"thread_id":thread,"id":"ours","effective_model":"fixture"})).into_response() |
| 2459 | } |
| 2460 | async fn interrupt( |
| 2461 | State(f): State<Fixture>, |
| 2462 | AxumPath(identity): AxumPath<(String, String)>, |
| 2463 | ) -> Json<Value> { |
| 2464 | f.interrupts.lock().await.push(identity); |
| 2465 | f.interrupted.notify_one(); |
| 2466 | Json(json!({"interrupted":true})) |
| 2467 | } |
| 2468 | async fn events(AxumPath(thread): AxumPath<String>) -> impl IntoResponse { |
| 2469 | let frames = ["another-turn", "ours"].map(|id| sse_frame("turn.completed", json!({ |
| 2470 | "thread_id":thread,"turn_id":id,"payload":{"turn":{"id":id,"thread_id":thread,"status":"completed"}} |
| 2471 | }))).join(""); |
| 2472 | ([(header::CONTENT_TYPE, "text/event-stream")], frames) |
| 2473 | } |
| 2474 | let f = Fixture::default(); |
| 2475 | let router = Router::new() |
| 2476 | .route("/v1/threads/{id}/turns", post(start)) |
| 2477 | .route("/v1/threads/{id}/turn-operations/{key}", get(lookup)) |
| 2478 | .route("/v1/threads/{id}/turns/{turn}/interrupt", post(interrupt)) |
| 2479 | .route("/v1/threads/{id}/events", get(events)) |
| 2480 | .with_state(f.clone()); |
| 2481 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 2482 | let addr = listener.local_addr().unwrap(); |
| 2483 | let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); |
| 2484 | let owner = Arc::new(MockRuntimeFrontend { |
| 2485 | stalled_subscription: None, |
| 2486 | bridge: Arc::new(Mutex::new(RuntimeBridge::from_base_url_for_test(format!( |
| 2487 | "http://{addr}" |
| 2488 | )))), |
| 2489 | }); |
| 2490 | let subscription_started = Arc::new(tokio::sync::Notify::new()); |
| 2491 | let stalled = Arc::new(MockRuntimeFrontend { |
| 2492 | stalled_subscription: Some(subscription_started.clone()), |
| 2493 | bridge: owner.bridge.clone(), |
| 2494 | }); |
| 2495 | let token = tokio_util::sync::CancellationToken::new(); |
| 2496 | let cancellation = token.clone(); |
| 2497 | let pending = tokio::spawn(async move { |
| 2498 | message_native_thread( |
| 2499 | stalled, |
| 2500 | "no-subscription", |
| 2501 | RuntimeTurnInput { |
| 2502 | input: "hello", |
| 2503 | images: &[], |
| 2504 | max_output_tokens: None, |
| 2505 | expected_workspace: None, |
| 2506 | cancellation: Some(&cancellation), |
| 2507 | }, |
| 2508 | &mut tokio::io::sink(), |
| 2509 | None, |
| 2510 | None, |
| 2511 | None, |
| 2512 | ) |
| 2513 | .await |
| 2514 | }); |
| 2515 | tokio::time::timeout(Duration::from_secs(5), subscription_started.notified()) |
| 2516 | .await |
| 2517 | .unwrap(); |
| 2518 | token.cancel(); |
| 2519 | let error = tokio::time::timeout(Duration::from_secs(5), pending) |
| 2520 | .await |
| 2521 | .unwrap() |
| 2522 | .unwrap() |
| 2523 | .unwrap_err(); |
| 2524 | assert!(error.to_string().contains("before native turn admission")); |
| 2525 | assert!(f.starts.lock().await.is_empty()); |
| 2526 | for thread in [ |
| 2527 | "observe", |
| 2528 | "refused", |
| 2529 | "refused-after-start", |
| 2530 | "mismatch", |
| 2531 | "cancel", |
| 2532 | "drop", |
| 2533 | ] { |
| 2534 | let token = tokio_util::sync::CancellationToken::new(); |
| 2535 | let cloned = token.clone(); |
| 2536 | let owner = owner.clone(); |
| 2537 | let task = tokio::spawn(async move { |
| 2538 | message_native_thread( |
| 2539 | owner, |
| 2540 | thread, |
| 2541 | RuntimeTurnInput { |
| 2542 | input: "hello", |
| 2543 | images: &[], |
| 2544 | max_output_tokens: None, |
| 2545 | expected_workspace: None, |
| 2546 | cancellation: Some(&cloned), |
| 2547 | }, |
| 2548 | &mut tokio::io::sink(), |
| 2549 | None, |
| 2550 | None, |
| 2551 | None, |
| 2552 | ) |
| 2553 | .await |
| 2554 | }); |
| 2555 | tokio::time::timeout(Duration::from_secs(5), f.started.notified()) |
| 2556 | .await |
| 2557 | .unwrap(); |
| 2558 | match thread { |
| 2559 | "observe" => assert_eq!(task.await.unwrap().unwrap()["data"]["turn_id"], "ours"), |
| 2560 | "refused" | "refused-after-start" => { |
| 2561 | if thread == "refused-after-start" { |
| 2562 | tokio::time::timeout(Duration::from_secs(5), f.interrupted.notified()) |
| 2563 | .await |
| 2564 | .unwrap(); |
| 2565 | } |
| 2566 | let error = task.await.unwrap().unwrap_err(); |
| 2567 | assert_eq!( |
| 2568 | error.downcast_ref::<RuntimeOwnerFailure>().unwrap().status, |
| 2569 | 403 |
| 2570 | ); |
| 2571 | } |
| 2572 | "mismatch" => assert!( |
| 2573 | format!("{:#}", task.await.unwrap().unwrap_err()) |
| 2574 | .contains("another thread identity") |
| 2575 | ), |
| 2576 | _ => { |
| 2577 | if thread == "drop" { |
| 2578 | task.abort(); |
| 2579 | assert!(task.await.unwrap_err().is_cancelled()); |
| 2580 | } else { |
| 2581 | token.cancel(); |
| 2582 | assert!( |
| 2583 | format!("{:#}", task.await.unwrap().unwrap_err()) |
| 2584 | .contains("canceled during native turn admission") |
| 2585 | ); |
| 2586 | } |
| 2587 | assert!(f.lookups.lock().await.iter().all(|(id, _)| id != thread)); |
| 2588 | f.finish_start.notify_one(); |
| 2589 | tokio::time::timeout(Duration::from_secs(5), f.interrupted.notified()) |
| 2590 | .await |
| 2591 | .unwrap(); |
| 2592 | } |
| 2593 | } |
| 2594 | } |
| 2595 | let starts = f.starts.lock().await; |
| 2596 | assert_eq!(starts.len(), 6); |
| 2597 | assert_eq!( |
| 2598 | starts |
| 2599 | .iter() |
| 2600 | .map(|(_, key)| key) |
| 2601 | .collect::<std::collections::HashSet<_>>() |
| 2602 | .len(), |
| 2603 | 6 |
| 2604 | ); |
| 2605 | assert_eq!(*starts, *f.lookups.lock().await); |
| 2606 | assert_eq!( |
| 2607 | *f.interrupts.lock().await, |
| 2608 | [ |
| 2609 | ("refused-after-start".into(), "ours".into()), |
| 2610 | ("cancel".into(), "ours".into()), |
| 2611 | ("drop".into(), "ours".into()) |
| 2612 | ] |
| 2613 | ); |
| 2614 | server.abort(); |
| 2615 | } |
| 2616 | |
| 2617 | /// Audit R03-05: a stream that breaks before `turn.completed` must not |
| 2618 | /// report `response_end` ahead of the error, and must not leave the |
| 2619 | /// runtime turn running with nothing able to interrupt it. |
| 2620 | #[tokio::test] |
| 2621 | async fn stdio_runtime_bridge_interrupts_a_turn_whose_stream_breaks() { |
| 2622 | static INTERRUPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 2623 | |
| 2624 | async fn create_turn(AxumPath(thread_id): AxumPath<String>) -> Json<Value> { |
| 2625 | Json(json!({ |
| 2626 | "thread": { "id": thread_id }, |
| 2627 | "turn": { "id": "turn_broken" }, |
| 2628 | })) |
| 2629 | } |
| 2630 | |
| 2631 | async fn thread_events() -> ([(header::HeaderName, &'static str); 1], String) { |
| 2632 | // One delta, then the stream ends without `turn.completed`. |
| 2633 | let body = sse_frame( |
| 2634 | "item.delta", |
| 2635 | json!({ |
| 2636 | "seq": 1, |
| 2637 | "turn_id": "turn_broken", |
| 2638 | "payload": { "kind": "agent_message", "delta": "partial" } |
| 2639 | }), |
| 2640 | ); |
| 2641 | ([(header::CONTENT_TYPE, "text/event-stream")], body) |
| 2642 | } |
| 2643 | |
| 2644 | async fn interrupt(AxumPath((thread_id, turn_id)): AxumPath<(String, String)>) -> Json<Value> { |
| 2645 | assert_eq!(thread_id, "thr_broken"); |
| 2646 | assert_eq!(turn_id, "turn_broken"); |
| 2647 | INTERRUPTED.store(true, std::sync::atomic::Ordering::SeqCst); |
| 2648 | Json(json!({ "interrupted": true })) |
| 2649 | } |
| 2650 | |
| 2651 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 2652 | .await |
| 2653 | .expect("bind test listener"); |
| 2654 | let addr = listener.local_addr().expect("listener addr"); |
| 2655 | let app = Router::new() |
| 2656 | .route("/v1/threads/{thread_id}/turns", post(create_turn)) |
| 2657 | .route("/v1/threads/{thread_id}/events", get(thread_events)) |
| 2658 | .route( |
| 2659 | "/v1/threads/{thread_id}/turns/{turn_id}/interrupt", |
| 2660 | post(interrupt), |
| 2661 | ); |
| 2662 | let server = tokio::spawn(async move { |
| 2663 | axum::serve(listener, app) |
| 2664 | .await |
| 2665 | .expect("serve test runtime"); |
| 2666 | }); |
| 2667 | |
| 2668 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{addr}")); |
| 2669 | let (mut reader, mut writer) = tokio::io::duplex(4096); |
| 2670 | let result = bridge |
| 2671 | .message_thread( |
| 2672 | "thr_broken", |
| 2673 | RuntimeTurnInput { |
| 2674 | input: "hello", |
| 2675 | images: &[], |
| 2676 | max_output_tokens: None, |
| 2677 | expected_workspace: None, |
| 2678 | cancellation: None, |
| 2679 | }, |
| 2680 | &mut writer, |
| 2681 | None, |
| 2682 | None, |
| 2683 | ) |
| 2684 | .await; |
| 2685 | drop(writer); |
| 2686 | let mut stdout = Vec::new(); |
| 2687 | reader |
| 2688 | .read_to_end(&mut stdout) |
| 2689 | .await |
| 2690 | .expect("read stdio output"); |
| 2691 | server.abort(); |
| 2692 | let _ = server.await; |
| 2693 | |
| 2694 | assert!(result.is_err(), "a broken stream is an error"); |
| 2695 | let event_types: Vec<String> = String::from_utf8(stdout) |
| 2696 | .expect("utf8 output") |
| 2697 | .lines() |
| 2698 | .map(|line| { |
| 2699 | serde_json::from_str::<Value>(line).expect("json line")["type"] |
| 2700 | .as_str() |
| 2701 | .expect("event type") |
| 2702 | .to_string() |
| 2703 | }) |
| 2704 | .collect(); |
| 2705 | assert_eq!(event_types, vec!["response_start", "response_delta"]); |
| 2706 | assert!( |
| 2707 | INTERRUPTED.load(std::sync::atomic::Ordering::SeqCst), |
| 2708 | "the orphaned runtime turn was not interrupted" |
| 2709 | ); |
| 2710 | } |
| 2711 | |
| 2712 | #[tokio::test] |
| 2713 | async fn stdio_runtime_bridge_applies_thread_start_hints() { |
| 2714 | async fn create_thread(Json(body): Json<Value>) -> Json<Value> { |
| 2715 | assert_eq!(body["model"], "deepseek-v4"); |
| 2716 | assert_eq!(body["workspace"], "/tmp/codewhale-stdio"); |
| 2717 | Json(json!({ |
| 2718 | "id": "thr_runtime", |
| 2719 | "model": body["model"].clone(), |
| 2720 | "workspace": body["workspace"].clone(), |
| 2721 | })) |
| 2722 | } |
| 2723 | |
| 2724 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 2725 | .await |
| 2726 | .expect("bind test listener"); |
| 2727 | let addr = listener.local_addr().expect("listener addr"); |
| 2728 | let app = Router::new().route("/v1/threads", post(create_thread)); |
| 2729 | |
| 2730 | let server = tokio::spawn(async move { |
| 2731 | axum::serve(listener, app) |
| 2732 | .await |
| 2733 | .expect("serve test runtime"); |
| 2734 | }); |
| 2735 | |
| 2736 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{addr}")); |
| 2737 | let mut thread_map = HashMap::new(); |
| 2738 | let runtime_id = bridge |
| 2739 | .ensure_runtime_thread( |
| 2740 | &mut thread_map, |
| 2741 | "legacy_thread", |
| 2742 | Some(RuntimeThreadHint { |
| 2743 | model: Some("deepseek-v4".to_string()), |
| 2744 | workspace: Some(PathBuf::from("/tmp/codewhale-stdio")), |
| 2745 | }), |
| 2746 | ) |
| 2747 | .await |
| 2748 | .expect("runtime thread"); |
| 2749 | server.abort(); |
| 2750 | let _ = server.await; |
| 2751 | |
| 2752 | assert_eq!(runtime_id, "thr_runtime"); |
| 2753 | assert_eq!( |
| 2754 | thread_map.get("legacy_thread").map(String::as_str), |
| 2755 | Some("thr_runtime") |
| 2756 | ); |
| 2757 | } |
| 2758 | |
| 2759 | // ── prompt routing runs a real turn ──────────────────────────────── |
| 2760 | // |
| 2761 | // `/prompt`, `prompt/request` and `prompt/run` used to return HTTP 200 |
| 2762 | // with a stringified echo of the caller's own routing metadata, having |
| 2763 | // called no model at all. These stand up the in-crate stub runtime and |
| 2764 | // assert the response is what the model streamed — not an echo — and |
| 2765 | // that an unreachable runtime is an explicit typed failure. |
| 2766 | |
| 2767 | /// Prompts the stub runtime was actually asked to run. |
| 2768 | type StubPrompts = Arc<Mutex<Vec<String>>>; |
| 2769 | |
| 2770 | /// A minimal but honest runtime: it creates threads, starts turns, and |
| 2771 | /// streams `agent_message` deltas followed by `turn.completed`. |
| 2772 | async fn spawn_stub_runtime( |
| 2773 | owner_router: Option<Router>, |
| 2774 | ) -> (String, StubPrompts, tokio::task::JoinHandle<()>) { |
| 2775 | async fn create_thread(Json(body): Json<Value>) -> Json<Value> { |
| 2776 | Json(json!({ |
| 2777 | "id": "thr_stub", |
| 2778 | "model": body["model"].as_str().unwrap_or("stub-model-v1"), |
| 2779 | })) |
| 2780 | } |
| 2781 | |
| 2782 | async fn create_turn( |
| 2783 | State(prompts): State<StubPrompts>, |
| 2784 | AxumPath(thread_id): AxumPath<String>, |
| 2785 | Json(body): Json<Value>, |
| 2786 | ) -> Json<Value> { |
| 2787 | prompts |
| 2788 | .lock() |
| 2789 | .await |
| 2790 | .push(body["prompt"].as_str().unwrap_or_default().to_string()); |
| 2791 | Json(json!({ |
| 2792 | "thread": { "id": thread_id, "model": "stub-model-v1" }, |
| 2793 | "turn": { "id": "turn_stub", "thread_id": thread_id }, |
| 2794 | })) |
| 2795 | } |
| 2796 | |
| 2797 | async fn thread_events( |
| 2798 | AxumPath(thread_id): AxumPath<String>, |
| 2799 | ) -> ([(header::HeaderName, &'static str); 1], String) { |
| 2800 | let body = [ |
| 2801 | sse_frame( |
| 2802 | "item.delta", |
| 2803 | json!({ |
| 2804 | "seq": 1, |
| 2805 | "thread_id": thread_id, "turn_id": "turn_stub", |
| 2806 | "payload": { "kind": "agent_message", "delta": "the answer" } |
| 2807 | }), |
| 2808 | ), |
| 2809 | sse_frame( |
| 2810 | "item.delta", |
| 2811 | json!({ |
| 2812 | "seq": 2, |
| 2813 | "thread_id": thread_id, "turn_id": "turn_stub", |
| 2814 | "payload": { "kind": "agent_message", "delta": " is 4" } |
| 2815 | }), |
| 2816 | ), |
| 2817 | sse_frame( |
| 2818 | "turn.completed", |
| 2819 | json!({ |
| 2820 | "seq": 3, |
| 2821 | "thread_id": thread_id, "turn_id": "turn_stub", |
| 2822 | "payload": { "turn": { "id": "turn_stub", "thread_id": thread_id, "status": "completed" } } |
| 2823 | }), |
| 2824 | ), |
| 2825 | ] |
| 2826 | .concat(); |
| 2827 | ([(header::CONTENT_TYPE, "text/event-stream")], body) |
| 2828 | } |
| 2829 | |
| 2830 | let prompts: StubPrompts = Arc::new(Mutex::new(Vec::new())); |
| 2831 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 2832 | .await |
| 2833 | .expect("bind stub runtime"); |
| 2834 | let addr = listener.local_addr().expect("listener addr"); |
| 2835 | let app = Router::new() |
| 2836 | .route("/v1/threads", post(create_thread)) |
| 2837 | .route("/v1/threads/{thread_id}/turns", post(create_turn)) |
| 2838 | .route("/v1/threads/{thread_id}/events", get(thread_events)) |
| 2839 | .with_state(prompts.clone()); |
| 2840 | let app = match owner_router { |
| 2841 | Some(owner) => app.fallback_service(owner), |
| 2842 | None => app, |
| 2843 | }; |
| 2844 | let server = tokio::spawn(async move { |
| 2845 | let _ = axum::serve(listener, app).await; |
| 2846 | }); |
| 2847 | (format!("http://{addr}"), prompts, server) |
| 2848 | } |
| 2849 | |
| 2850 | async fn seed_bridge_at(state: &mut AppState, base_url: String) -> SharedRuntimeBridge { |
| 2851 | let bridge = Arc::new(Mutex::new(RuntimeBridge::from_base_url_for_test(base_url))); |
| 2852 | *state.runtime_bridge.lock().await = Some(bridge.clone()); |
| 2853 | install_mock_native_services(state).await; |
| 2854 | bridge |
| 2855 | } |
| 2856 | |
| 2857 | #[tokio::test] |
| 2858 | async fn prompt_request_executes_a_genuine_model_turn() { |
| 2859 | let (mut state, _tmp) = capability_test_state(); |
| 2860 | let (base_url, prompts, server) = spawn_stub_runtime(None).await; |
| 2861 | seed_bridge_at(&mut state, base_url).await; |
| 2862 | |
| 2863 | let (mut reader, mut writer) = tokio::io::duplex(4096); |
| 2864 | let dispatched = dispatch_stdio_request_with_writer( |
| 2865 | &state, |
| 2866 | &mut writer, |
| 2867 | "prompt/request", |
| 2868 | json!({ "allowed_tools": [], "prompt": "what is 2+2" }), |
| 2869 | AppTransport::Stdio, |
| 2870 | None, |
| 2871 | None, |
| 2872 | ) |
| 2873 | .await |
| 2874 | .expect("prompt/request dispatch"); |
| 2875 | drop(writer); |
| 2876 | |
| 2877 | let response: PromptResponse = |
| 2878 | serde_json::from_value(dispatched.result).expect("prompt response"); |
| 2879 | |
| 2880 | // The model's words, not a restatement of the request. |
| 2881 | assert_eq!(response.output, "the answer is 4"); |
| 2882 | assert!( |
| 2883 | !response.output.contains("what is 2+2"), |
| 2884 | "prompt echo leaked into the output: {}", |
| 2885 | response.output |
| 2886 | ); |
| 2887 | assert_eq!(response.model, "stub-model-v1"); |
| 2888 | assert_eq!( |
| 2889 | prompts.lock().await.as_slice(), |
| 2890 | ["what is 2+2".to_string()], |
| 2891 | "the prompt must reach the runtime's turn endpoint" |
| 2892 | ); |
| 2893 | |
| 2894 | // Real streaming frames, not three canned ones. |
| 2895 | let deltas: Vec<String> = response |
| 2896 | .events |
| 2897 | .iter() |
| 2898 | .filter_map(|event| match event { |
| 2899 | EventFrame::ResponseDelta { delta, .. } => Some(delta.clone()), |
| 2900 | _ => None, |
| 2901 | }) |
| 2902 | .collect(); |
| 2903 | assert_eq!(deltas, vec!["the answer".to_string(), " is 4".to_string()]); |
| 2904 | assert!(matches!( |
| 2905 | response.events.first(), |
| 2906 | Some(EventFrame::ResponseStart { .. }) |
| 2907 | )); |
| 2908 | assert!(matches!( |
| 2909 | response.events.last(), |
| 2910 | Some(EventFrame::ResponseEnd { .. }) |
| 2911 | )); |
| 2912 | |
| 2913 | // The stdio transport sees the same turn stream `thread/message` emits. |
| 2914 | let mut stdout = Vec::new(); |
| 2915 | reader.read_to_end(&mut stdout).await.expect("read stdout"); |
| 2916 | let stdout = String::from_utf8(stdout).expect("utf8 stdout"); |
| 2917 | assert!( |
| 2918 | stdout.contains("\"type\":\"response_delta\"") && stdout.contains("the answer"), |
| 2919 | "stdio prompt turn must stream its deltas, got: {stdout}" |
| 2920 | ); |
| 2921 | |
| 2922 | // A prompt without a thread_id must not leave a mapping behind. |
| 2923 | assert!( |
| 2924 | state.runtime_thread_map.lock().await.is_empty(), |
| 2925 | "one-shot prompt threads must not accumulate in the map" |
| 2926 | ); |
| 2927 | |
| 2928 | server.abort(); |
| 2929 | let _ = server.await; |
| 2930 | } |
| 2931 | |
| 2932 | #[tokio::test] |
| 2933 | async fn prompt_without_a_reachable_runtime_fails_explicitly() { |
| 2934 | let (mut state, _tmp) = capability_test_state(); |
| 2935 | // Port 9 (discard) refuses immediately: no runtime is listening. |
| 2936 | seed_bridge_at(&mut state, "http://127.0.0.1:9".to_string()).await; |
| 2937 | |
| 2938 | let err = dispatch_stdio_request( |
| 2939 | &state, |
| 2940 | "prompt/run", |
| 2941 | json!({ "allowed_tools": [], "prompt": "hello" }), |
| 2942 | ) |
| 2943 | .await |
| 2944 | .expect_err("a prompt with no reachable runtime must fail, not echo"); |
| 2945 | assert_eq!(err.wire.code, RUNTIME_UNAVAILABLE_CODE); |
| 2946 | |
| 2947 | let (status, Json(body)) = http_error_from_jsonrpc(err); |
| 2948 | assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); |
| 2949 | assert_eq!(body["error"]["code"], "runtime_unavailable"); |
| 2950 | assert!( |
| 2951 | body.get("output").is_none(), |
| 2952 | "a failure must not be shaped like a PromptResponse: {body}" |
| 2953 | ); |
| 2954 | } |
| 2955 | |
| 2956 | #[tokio::test] |
| 2957 | async fn empty_prompt_is_rejected_before_any_runtime_work() { |
| 2958 | let (state, _tmp) = capability_test_state(); |
| 2959 | let err = dispatch_stdio_request( |
| 2960 | &state, |
| 2961 | "prompt/request", |
| 2962 | json!({ "allowed_tools": [], "prompt": " " }), |
| 2963 | ) |
| 2964 | .await |
| 2965 | .expect_err("an empty prompt must be rejected"); |
| 2966 | assert_eq!(err.wire.code, -32602); |
| 2967 | assert!( |
| 2968 | state.runtime_bridge.lock().await.is_none(), |
| 2969 | "a rejected prompt must not start a runtime" |
| 2970 | ); |
| 2971 | } |
| 2972 | |
| 2973 | #[tokio::test] |
| 2974 | async fn http_thread_message_runs_the_turn_instead_of_queueing_it() { |
| 2975 | let (mut state, _tmp, owner_router) = thread_control::compatibility_router(); |
| 2976 | seed_client_thread(&state, "thr_http").await; |
| 2977 | let (base_url, prompts, server) = spawn_stub_runtime(Some(owner_router)).await; |
| 2978 | seed_bridge_at(&mut state, base_url).await; |
| 2979 | |
| 2980 | let response = run_http_thread_message( |
| 2981 | &state, |
| 2982 | "thr_http".to_string(), |
| 2983 | "go".to_string(), |
| 2984 | Some(Vec::new()), |
| 2985 | Vec::new(), |
| 2986 | None, |
| 2987 | ) |
| 2988 | .await |
| 2989 | .expect("http thread message"); |
| 2990 | |
| 2991 | assert_eq!(response.status, "completed"); |
| 2992 | assert_eq!(response.thread_id, "thr_http"); |
| 2993 | assert_eq!(response.data["turn_id"], "turn_stub"); |
| 2994 | assert_eq!(prompts.lock().await.as_slice(), ["go".to_string()]); |
| 2995 | assert!( |
| 2996 | response |
| 2997 | .events |
| 2998 | .iter() |
| 2999 | .any(|event| matches!(event, EventFrame::ResponseDelta { .. })), |
| 3000 | "a completed turn must carry the deltas it streamed" |
| 3001 | ); |
| 3002 | |
| 3003 | server.abort(); |
| 3004 | let _ = server.await; |
| 3005 | } |
| 3006 | |
| 3007 | #[tokio::test] |
| 3008 | async fn http_thread_message_without_a_runtime_is_a_typed_error() { |
| 3009 | let (mut state, _tmp, _owner_router) = thread_control::compatibility_router(); |
| 3010 | seed_client_thread(&state, "thr_http").await; |
| 3011 | seed_bridge_at(&mut state, "http://127.0.0.1:9".to_string()).await; |
| 3012 | |
| 3013 | let err = run_http_thread_message( |
| 3014 | &state, |
| 3015 | "thr_http".to_string(), |
| 3016 | "go".to_string(), |
| 3017 | Some(Vec::new()), |
| 3018 | Vec::new(), |
| 3019 | None, |
| 3020 | ) |
| 3021 | .await |
| 3022 | .expect_err("no runtime means no turn"); |
| 3023 | assert_eq!(err.wire.code, RUNTIME_UNAVAILABLE_CODE); |
| 3024 | } |
| 3025 | |
| 3026 | #[tokio::test] |
| 3027 | async fn submit_user_input_refuses_instead_of_claiming_resolution() { |
| 3028 | let (state, _tmp) = capability_test_state(); |
| 3029 | for (method, params) in [ |
| 3030 | ( |
| 3031 | "thread/goal/set", |
| 3032 | json!({"thread_id":"unknown","objective":"must not start"}), |
| 3033 | ), |
| 3034 | ( |
| 3035 | "thread/request", |
| 3036 | json!({"kind":"goal_set","thread_id":"unknown","objective":"must not start"}), |
| 3037 | ), |
| 3038 | ] { |
| 3039 | let error = dispatch_stdio_request(&state, method, params) |
| 3040 | .await |
| 3041 | .unwrap_err(); |
| 3042 | let (status, Json(body)) = http_error_from_jsonrpc(error); |
| 3043 | assert_eq!(status, StatusCode::BAD_REQUEST); |
| 3044 | assert_eq!( |
| 3045 | body["error"]["data"]["error"], |
| 3046 | "interactive_execution_unsupported" |
| 3047 | ); |
| 3048 | assert!(state.runtime_thread_map.lock().await.is_empty()); |
| 3049 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 3050 | } |
| 3051 | for tools in [Value::Null, json!(["shell"])] { |
| 3052 | for (method, params) in [ |
| 3053 | ( |
| 3054 | "thread/message", |
| 3055 | json!({"thread_id":"unknown","input":"do work","allowed_tools":tools}), |
| 3056 | ), |
| 3057 | ( |
| 3058 | "thread/request", |
| 3059 | json!({"kind":"message","thread_id":"unknown","input":"do work","allowed_tools":tools}), |
| 3060 | ), |
| 3061 | ( |
| 3062 | "prompt/run", |
| 3063 | json!({"prompt":"do work","allowed_tools":tools}), |
| 3064 | ), |
| 3065 | ( |
| 3066 | "prompt/request", |
| 3067 | json!({"prompt":"do work","allowed_tools":tools}), |
| 3068 | ), |
| 3069 | ] { |
| 3070 | let error = dispatch_stdio_request(&state, method, params) |
| 3071 | .await |
| 3072 | .unwrap_err(); |
| 3073 | assert_eq!(error.wire.code, -32602); |
| 3074 | assert_eq!( |
| 3075 | error.wire.data.unwrap()["error"], |
| 3076 | "interactive_execution_unsupported" |
| 3077 | ); |
| 3078 | } |
| 3079 | let error = run_http_thread_message( |
| 3080 | &state, |
| 3081 | "unknown".into(), |
| 3082 | "do work".into(), |
| 3083 | serde_json::from_value(tools).unwrap(), |
| 3084 | Vec::new(), |
| 3085 | None, |
| 3086 | ) |
| 3087 | .await |
| 3088 | .unwrap_err(); |
| 3089 | assert_eq!( |
| 3090 | error.wire.data.unwrap()["error"], |
| 3091 | "interactive_execution_unsupported" |
| 3092 | ); |
| 3093 | assert!(state.runtime_thread_map.lock().await.is_empty()); |
| 3094 | assert!(state.runtime_bridge.lock().await.is_none()); |
| 3095 | } |
| 3096 | let response = process_app_request( |
| 3097 | &state, |
| 3098 | AppRequest::SubmitUserInput { |
| 3099 | request_id: "user-input-1".to_string(), |
| 3100 | answers: Vec::new(), |
| 3101 | }, |
| 3102 | AppTransport::Stdio, |
| 3103 | ) |
| 3104 | .await; |
| 3105 | |
| 3106 | assert!(!response.ok, "this transport cannot deliver the answer"); |
| 3107 | assert_eq!(response.data["error"], "user_input_reply_unsupported"); |
| 3108 | assert!( |
| 3109 | response.data.get("resolved").is_none(), |
| 3110 | "nothing was resolved: {}", |
| 3111 | response.data |
| 3112 | ); |
| 3113 | assert!( |
| 3114 | response.data["message"] |
| 3115 | .as_str() |
| 3116 | .expect("message") |
| 3117 | .contains("/v1/user-input/"), |
| 3118 | "the refusal must name the transport that can accept the answer" |
| 3119 | ); |
| 3120 | assert!( |
| 3121 | !response.data["message"] |
| 3122 | .as_str() |
| 3123 | .expect("message") |
| 3124 | .contains(" "), |
| 3125 | "the refusal must not expose source-formatting whitespace" |
| 3126 | ); |
| 3127 | } |
| 3128 | |
| 3129 | // ── capability drift guard ───────────────────────────────────────── |
| 3130 | // |
| 3131 | // The stdio `capabilities` method is the benchmark/SDK contract: external |
| 3132 | // harnesses probe it (without spending model tokens) to learn what the |
| 3133 | // app-server can do. Pin the advertised method set so any change forces a |
| 3134 | // deliberate update here, in the dispatcher, and in docs/RUNTIME_API.md. |
| 3135 | |
| 3136 | /// Methods advertised by the top-level `capabilities` probe, in order. |
| 3137 | const EXPECTED_CAPABILITY_METHODS: &[&str] = &[ |
| 3138 | "healthz", |
| 3139 | "thread/capabilities", |
| 3140 | "thread/request", |
| 3141 | "thread/create", |
| 3142 | "thread/start", |
| 3143 | "thread/resume", |
| 3144 | "thread/fork", |
| 3145 | "thread/list", |
| 3146 | "thread/loaded/list", |
| 3147 | "thread/read", |
| 3148 | "thread/name/set", |
| 3149 | "thread/set_name", |
| 3150 | "thread/goal/get", |
| 3151 | "thread/goal/clear", |
| 3152 | "thread/archive", |
| 3153 | "thread/unarchive", |
| 3154 | "thread/message", |
| 3155 | "thread/interrupt", |
| 3156 | "app/capabilities", |
| 3157 | "app/request", |
| 3158 | "app/config/get", |
| 3159 | "app/config/set", |
| 3160 | "app/config/unset", |
| 3161 | "app/config/list", |
| 3162 | "app/config/reload", |
| 3163 | "app/models", |
| 3164 | "app/thread_loaded_list", |
| 3165 | "prompt/capabilities", |
| 3166 | "prompt/request", |
| 3167 | "prompt/run", |
| 3168 | "shutdown", |
| 3169 | ]; |
| 3170 | |
| 3171 | fn capability_test_state() -> (AppState, tempfile::TempDir) { |
| 3172 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 3173 | let config_path = tmp.path().join("config.toml"); |
| 3174 | fs::write(&config_path, "").expect("write config"); |
| 3175 | let state = build_state(Some(config_path), None).expect("state"); |
| 3176 | (state, tmp) |
| 3177 | } |
| 3178 | |
| 3179 | /// Persist a client thread under a fixed id, as `thread/create` would, |
| 3180 | /// so `thread/message` accepts it. |
| 3181 | fn test_client_metadata(thread_id: &str) -> codewhale_state::ThreadMetadata { |
| 3182 | codewhale_state::ThreadMetadata { |
| 3183 | id: thread_id.to_string(), |
| 3184 | rollout_path: None, |
| 3185 | preview: String::new(), |
| 3186 | ephemeral: false, |
| 3187 | model_provider: "deepseek".to_string(), |
| 3188 | created_at: 1, |
| 3189 | updated_at: 1, |
| 3190 | status: codewhale_state::ThreadStatus::Idle, |
| 3191 | path: None, |
| 3192 | cwd: PathBuf::from("/tmp/codewhale"), |
| 3193 | cli_version: "0.0.0-test".to_string(), |
| 3194 | source: codewhale_state::SessionSource::Api, |
| 3195 | name: None, |
| 3196 | sandbox_policy: None, |
| 3197 | approval_mode: None, |
| 3198 | archived: false, |
| 3199 | archived_at: None, |
| 3200 | git_sha: None, |
| 3201 | git_branch: None, |
| 3202 | git_origin_url: None, |
| 3203 | memory_mode: None, |
| 3204 | current_leaf_id: None, |
| 3205 | } |
| 3206 | } |
| 3207 | |
| 3208 | fn restore_test_thread_archive(store: &StateStore, metadata: &codewhale_state::ThreadMetadata) { |
| 3209 | store |
| 3210 | .restore_legacy_thread_archive(&codewhale_state::LegacyThreadArchive { |
| 3211 | thread: metadata.clone(), |
| 3212 | messages: Vec::new(), |
| 3213 | goal: None, |
| 3214 | checkpoints: Vec::new(), |
| 3215 | }) |
| 3216 | .expect("restore absent historical fixture"); |
| 3217 | } |
| 3218 | |
| 3219 | async fn seed_client_thread(state: &AppState, thread_id: &str) { |
| 3220 | let mut metadata = test_client_metadata(thread_id); |
| 3221 | if let Some(workspace) = state.frontend_workspace.as_ref() { |
| 3222 | metadata.cwd = workspace.clone(); |
| 3223 | } |
| 3224 | let store = state.runtime.read().await.state_store().clone(); |
| 3225 | restore_test_thread_archive(&store, &metadata); |
| 3226 | } |
| 3227 | |
| 3228 | #[tokio::test] |
| 3229 | async fn capabilities_method_set_is_stable() { |
| 3230 | let (state, _tmp) = capability_test_state(); |
| 3231 | let caps = dispatch_stdio_request(&state, "capabilities", json!({})) |
| 3232 | .await |
| 3233 | .expect("capabilities dispatch"); |
| 3234 | assert_eq!(caps.result["framing"], "jsonl"); |
| 3235 | let methods: Vec<String> = caps.result["methods"] |
| 3236 | .as_array() |
| 3237 | .expect("methods array") |
| 3238 | .iter() |
| 3239 | .map(|m| m.as_str().expect("method string").to_string()) |
| 3240 | .collect(); |
| 3241 | assert_eq!( |
| 3242 | methods, EXPECTED_CAPABILITY_METHODS, |
| 3243 | "app-server stdio capability set drifted; update the dispatcher, this \ |
| 3244 | snapshot, and docs/RUNTIME_API.md together" |
| 3245 | ); |
| 3246 | } |
| 3247 | |
| 3248 | /// The socket transport advertises the `daemon/attach` handshake right |
| 3249 | /// after `healthz`; the stdio pin above must stay untouched by it. |
| 3250 | #[tokio::test] |
| 3251 | async fn socket_transport_advertises_daemon_attach() { |
| 3252 | let (state, _tmp) = capability_test_state(); |
| 3253 | let mut sink = tokio::io::sink(); |
| 3254 | let caps = dispatch_stdio_request_with_writer( |
| 3255 | &state, |
| 3256 | &mut sink, |
| 3257 | "capabilities", |
| 3258 | json!({}), |
| 3259 | AppTransport::Socket, |
| 3260 | None, |
| 3261 | None, |
| 3262 | ) |
| 3263 | .await |
| 3264 | .expect("capabilities dispatch"); |
| 3265 | let expected_transport = if cfg!(windows) { |
| 3266 | "named-pipe" |
| 3267 | } else { |
| 3268 | "unix-socket" |
| 3269 | }; |
| 3270 | assert_eq!(caps.result["transport"], json!(expected_transport)); |
| 3271 | assert_eq!(caps.result["framing"], "websocket-text"); |
| 3272 | let methods: Vec<String> = caps.result["methods"] |
| 3273 | .as_array() |
| 3274 | .expect("methods array") |
| 3275 | .iter() |
| 3276 | .map(|m| m.as_str().expect("method string").to_string()) |
| 3277 | .collect(); |
| 3278 | let mut expected: Vec<String> = EXPECTED_CAPABILITY_METHODS |
| 3279 | .iter() |
| 3280 | .map(|m| m.to_string()) |
| 3281 | .collect(); |
| 3282 | expected.insert(1, daemon_socket::ATTACH_METHOD.to_string()); |
| 3283 | assert_eq!(methods, expected); |
| 3284 | } |
| 3285 | |
| 3286 | #[tokio::test] |
| 3287 | async fn every_advertised_capability_is_dispatchable() { |
| 3288 | let (state, _tmp) = capability_test_state(); |
| 3289 | // Empty params: methods may fail validation (-32602), but none may report |
| 3290 | // method-not-found (-32601). Required fields (e.g. PromptRequest.prompt) |
| 3291 | // make the prompt routes fail at parse time, so no model tokens are spent. |
| 3292 | for method in EXPECTED_CAPABILITY_METHODS { |
| 3293 | if let Err(err) = dispatch_stdio_request(&state, method, json!({})).await { |
| 3294 | assert_ne!( |
| 3295 | err.wire.code, |
| 3296 | DispatchError::method_not_found(method).wire.code, |
| 3297 | "advertised capability `{method}` is not dispatchable" |
| 3298 | ); |
| 3299 | } |
| 3300 | } |
| 3301 | } |
| 3302 | |
| 3303 | // ── resolve_auth_token ───────────────────────────────────────────── |
| 3304 | |
| 3305 | #[test] |
| 3306 | fn auth_token_empty_string_fails() { |
| 3307 | let options = AppServerOptions { |
| 3308 | listen: "127.0.0.1:0".parse().expect("addr"), |
| 3309 | config_path: None, |
| 3310 | auth_token: Some(" ".to_string()), |
| 3311 | insecure_no_auth: false, |
| 3312 | cors_origins: Vec::new(), |
| 3313 | }; |
| 3314 | let err = resolve_auth_token(&options).expect_err("empty token should fail"); |
| 3315 | assert!(err.to_string().contains("cannot be empty")); |
| 3316 | } |
| 3317 | |
| 3318 | #[test] |
| 3319 | fn auth_token_generated_when_none_provided() { |
| 3320 | let options = AppServerOptions { |
| 3321 | listen: "127.0.0.1:0".parse().expect("addr"), |
| 3322 | config_path: None, |
| 3323 | auth_token: None, |
| 3324 | insecure_no_auth: false, |
| 3325 | cors_origins: Vec::new(), |
| 3326 | }; |
| 3327 | let token = resolve_auth_token(&options).unwrap(); |
| 3328 | assert!(token.is_some()); |
| 3329 | assert!(token.unwrap().starts_with("cwapp_")); |
| 3330 | } |
| 3331 | |
| 3332 | #[test] |
| 3333 | fn runtime_child_endpoint_must_be_a_reported_loopback_port() { |
| 3334 | let ok = parse_runtime_endpoint("Runtime API listening on http://127.0.0.1:49152\r\n") |
| 3335 | .expect("loopback endpoint"); |
| 3336 | assert_eq!(ok.port(), 49152); |
| 3337 | for bad in [ |
| 3338 | "Runtime API listening on http://127.0.0.1:0", |
| 3339 | "Runtime API listening on http://10.0.0.5:7878", |
| 3340 | "Runtime API listening on http://[::1]:7878", |
| 3341 | "Runtime API listening on http://example.com:80", |
| 3342 | "Runtime API listening on http://127.0.0.1:80/redirect", |
| 3343 | "listening on http://127.0.0.1:7878", |
| 3344 | "", |
| 3345 | ] { |
| 3346 | assert!(parse_runtime_endpoint(bad).is_err(), "{bad:?}"); |
| 3347 | } |
| 3348 | |
| 3349 | let mut first_line_only: &[u8] = |
| 3350 | b"Runtime API listening on http://127.0.0.1:5000\nRuntime API listening on http://127.0.0.1:6000\n"; |
| 3351 | assert_eq!( |
| 3352 | read_runtime_ready_line(&mut first_line_only).unwrap(), |
| 3353 | "Runtime API listening on http://127.0.0.1:5000" |
| 3354 | ); |
| 3355 | let mut closed: &[u8] = b"Runtime API listening on http://127.0.0.1:5000"; |
| 3356 | assert!(read_runtime_ready_line(&mut closed).is_err(), "no newline"); |
| 3357 | let oversized = vec![b'a'; RUNTIME_READY_MAX_BYTES + 1]; |
| 3358 | assert!(read_runtime_ready_line(&mut oversized.as_slice()).is_err()); |
| 3359 | } |
| 3360 | |
| 3361 | #[test] |
| 3362 | fn runtime_bridge_command_keeps_auth_token_out_of_argv() { |
| 3363 | // FR001-C001: runtime auth token must not appear on the child argv |
| 3364 | // (visible via local `ps`); pass it via env instead. |
| 3365 | let token = "cwrt_unit_test_secret_token_not_for_argv"; |
| 3366 | let cmd = RuntimeBridge::runtime_command(None, token).expect("command"); |
| 3367 | let argv: Vec<String> = cmd |
| 3368 | .get_args() |
| 3369 | .map(|a| a.to_string_lossy().into_owned()) |
| 3370 | .collect(); |
| 3371 | assert!( |
| 3372 | argv.windows(2).any(|pair| pair == ["--port", "0"]), |
| 3373 | "the child picks and reports its own port: {argv:?}" |
| 3374 | ); |
| 3375 | assert!( |
| 3376 | !argv |
| 3377 | .iter() |
| 3378 | .any(|a| a.contains(token) || a == "--auth-token"), |
| 3379 | "auth token must not be present in child argv: {argv:?}" |
| 3380 | ); |
| 3381 | let envs: Vec<(String, String)> = cmd |
| 3382 | .get_envs() |
| 3383 | .filter_map(|(k, v)| { |
| 3384 | Some(( |
| 3385 | k.to_string_lossy().into_owned(), |
| 3386 | v?.to_string_lossy().into_owned(), |
| 3387 | )) |
| 3388 | }) |
| 3389 | .collect(); |
| 3390 | assert!( |
| 3391 | envs.iter() |
| 3392 | .any(|(k, v)| k == "CODEWHALE_RUNTIME_TOKEN" && v == token), |
| 3393 | "token must be carried via CODEWHALE_RUNTIME_TOKEN: {envs:?}" |
| 3394 | ); |
| 3395 | assert!( |
| 3396 | envs.iter() |
| 3397 | .any(|(k, v)| k == "DEEPSEEK_RUNTIME_TOKEN" && v == token), |
| 3398 | "legacy alias DEEPSEEK_RUNTIME_TOKEN must also carry the token: {envs:?}" |
| 3399 | ); |
| 3400 | } |
| 3401 | |
| 3402 | #[test] |
| 3403 | fn generated_auth_status_does_not_render_token() { |
| 3404 | let rendered = app_server_auth_status_lines(false).join("\n"); |
| 3405 | |
| 3406 | assert!(!rendered.contains("Authorization: Bearer")); |
| 3407 | assert!(rendered.contains("not printed")); |
| 3408 | assert!(rendered.contains("CODEWHALE_APP_SERVER_TOKEN")); |
| 3409 | } |
| 3410 | |
| 3411 | #[test] |
| 3412 | fn auth_token_explicit_is_preserved() { |
| 3413 | let options = AppServerOptions { |
| 3414 | listen: "127.0.0.1:0".parse().expect("addr"), |
| 3415 | config_path: None, |
| 3416 | auth_token: Some("my-secret".to_string()), |
| 3417 | insecure_no_auth: false, |
| 3418 | cors_origins: Vec::new(), |
| 3419 | }; |
| 3420 | let token = resolve_auth_token(&options).unwrap(); |
| 3421 | assert_eq!(token.as_deref(), Some("my-secret")); |
| 3422 | } |
| 3423 | |
| 3424 | #[test] |
| 3425 | fn auth_token_explicit_allows_non_loopback_bind() { |
| 3426 | let options = AppServerOptions { |
| 3427 | listen: "0.0.0.0:8787".parse().expect("socket addr"), |
| 3428 | config_path: None, |
| 3429 | auth_token: Some("my-secret".to_string()), |
| 3430 | insecure_no_auth: false, |
| 3431 | cors_origins: Vec::new(), |
| 3432 | }; |
| 3433 | let token = resolve_auth_token(&options).unwrap(); |
| 3434 | assert_eq!(token.as_deref(), Some("my-secret")); |
| 3435 | } |
| 3436 | |
| 3437 | #[test] |
| 3438 | fn insecure_no_auth_on_loopback_returns_none() { |
| 3439 | let options = AppServerOptions { |
| 3440 | listen: "127.0.0.1:0".parse().expect("addr"), |
| 3441 | config_path: None, |
| 3442 | auth_token: None, |
| 3443 | insecure_no_auth: true, |
| 3444 | cors_origins: Vec::new(), |
| 3445 | }; |
| 3446 | let token = resolve_auth_token(&options).unwrap(); |
| 3447 | assert!(token.is_none()); |
| 3448 | } |
| 3449 | |
| 3450 | #[test] |
| 3451 | fn insecure_no_auth_on_non_loopback_fails_fast() { |
| 3452 | let options = AppServerOptions { |
| 3453 | listen: "0.0.0.0:8787".parse().expect("socket addr"), |
| 3454 | config_path: None, |
| 3455 | auth_token: None, |
| 3456 | insecure_no_auth: true, |
| 3457 | cors_origins: Vec::new(), |
| 3458 | }; |
| 3459 | |
| 3460 | let err = resolve_auth_token(&options).expect_err("non-loopback unauth should fail"); |
| 3461 | assert!( |
| 3462 | err.to_string() |
| 3463 | .contains("refusing unauthenticated app-server bind") |
| 3464 | ); |
| 3465 | } |
| 3466 | |
| 3467 | // ── cors_layer ───────────────────────────────────────────────────── |
| 3468 | |
| 3469 | #[test] |
| 3470 | fn cors_layer_includes_default_origins() { |
| 3471 | let layer = cors_layer(&[]); |
| 3472 | // Just verify it doesn't panic and creates successfully |
| 3473 | let _ = layer; |
| 3474 | } |
| 3475 | |
| 3476 | #[test] |
| 3477 | fn cors_layer_adds_extra_origins() { |
| 3478 | let extras = vec!["https://example.com".to_string()]; |
| 3479 | let layer = cors_layer(&extras); |
| 3480 | let _ = layer; |
| 3481 | } |
| 3482 | |
| 3483 | #[test] |
| 3484 | fn cors_layer_skips_empty_origins() { |
| 3485 | let extras = vec!["".to_string(), " ".to_string()]; |
| 3486 | let layer = cors_layer(&extras); |
| 3487 | let _ = layer; |
| 3488 | } |
| 3489 | |
| 3490 | // ── JsonRpc helpers ──────────────────────────────────────────────── |
| 3491 | |
| 3492 | #[test] |
| 3493 | fn params_or_object_returns_object_for_null() { |
| 3494 | let result = params_or_object(Value::Null); |
| 3495 | assert_eq!(result, json!({})); |
| 3496 | } |
| 3497 | |
| 3498 | #[test] |
| 3499 | fn params_or_object_passthrough_for_non_null() { |
| 3500 | let input = json!({"key": "value"}); |
| 3501 | let result = params_or_object(input.clone()); |
| 3502 | assert_eq!(result, input); |
| 3503 | } |
| 3504 | |
| 3505 | #[test] |
| 3506 | fn jsonrpc_result_format() { |
| 3507 | let result = jsonrpc_result(RequestId::Integer(1), json!({"ok": true})); |
| 3508 | assert!(result.get("jsonrpc").is_none()); |
| 3509 | assert_eq!(result["id"], 1); |
| 3510 | assert_eq!(result["result"]["ok"], true); |
| 3511 | } |
| 3512 | |
| 3513 | #[test] |
| 3514 | fn jsonrpc_result_string_id() { |
| 3515 | let result = jsonrpc_result(RequestId::String("string-request".into()), json!(null)); |
| 3516 | assert_eq!(result["id"], "string-request"); |
| 3517 | assert!(result["result"].is_null()); |
| 3518 | } |
| 3519 | |
| 3520 | #[test] |
| 3521 | fn jsonrpc_error_format() { |
| 3522 | let err = jsonrpc_error(RequestId::Integer(2), DispatchError::internal("oops")); |
| 3523 | assert!(err.get("jsonrpc").is_none()); |
| 3524 | assert_eq!(err["id"], 2); |
| 3525 | assert_eq!(err["error"]["code"], -32603); |
| 3526 | assert_eq!(err["error"]["message"], "oops"); |
| 3527 | } |
| 3528 | |
| 3529 | #[test] |
| 3530 | fn jsonrpc_error_codes() { |
| 3531 | assert_eq!(DispatchError::invalid_request("").wire.code, -32600); |
| 3532 | assert_eq!(DispatchError::method_not_found("x").wire.code, -32601); |
| 3533 | assert_eq!(DispatchError::invalid_params("").wire.code, -32602); |
| 3534 | assert_eq!(DispatchError::internal("").wire.code, -32603); |
| 3535 | } |
| 3536 | |
| 3537 | // ── AppServerOptions ─────────────────────────────────────────────── |
| 3538 | |
| 3539 | #[test] |
| 3540 | fn app_server_options_debug_does_not_leak_token() { |
| 3541 | let options = AppServerOptions { |
| 3542 | listen: "127.0.0.1:8080".parse().expect("addr"), |
| 3543 | config_path: None, |
| 3544 | auth_token: Some("secret-token".to_string()), |
| 3545 | insecure_no_auth: false, |
| 3546 | cors_origins: vec!["https://example.com".to_string()], |
| 3547 | }; |
| 3548 | let debug = format!("{options:?}"); |
| 3549 | assert!(!debug.contains("secret-token")); |
| 3550 | assert!(debug.contains("<redacted>")); |
| 3551 | assert!(debug.contains("8080")); |
| 3552 | } |
| 3553 | |
| 3554 | // ── Default CORS origins ────────────────────────────────────────── |
| 3555 | |
| 3556 | #[test] |
| 3557 | fn default_cors_origins_include_common_dev_ports() { |
| 3558 | assert!(DEFAULT_CORS_ORIGINS.contains(&"http://localhost:3000")); |
| 3559 | assert!(DEFAULT_CORS_ORIGINS.contains(&"http://localhost:5173")); |
| 3560 | assert!(!DEFAULT_CORS_ORIGINS.iter().any(|o| o.starts_with("tauri:"))); |
| 3561 | } |
| 3562 | #[tokio::test] |
| 3563 | async fn runtime_image_daemon_bridge_checks_transport_and_forwards_exact_wire() { |
| 3564 | async fn capture( |
| 3565 | State(seen): State<Arc<Mutex<Vec<Value>>>>, |
| 3566 | Json(body): Json<Value>, |
| 3567 | ) -> (StatusCode, Json<Value>) { |
| 3568 | seen.lock().await.push(body); |
| 3569 | ( |
| 3570 | StatusCode::BAD_REQUEST, |
| 3571 | Json(json!({"error":"fixture stops before an Engine"})), |
| 3572 | ) |
| 3573 | } |
| 3574 | for supported in [false, true] { |
| 3575 | let seen = Arc::new(Mutex::new(Vec::new())); |
| 3576 | let app = Router::new() |
| 3577 | .route( |
| 3578 | "/v1/runtime/info", |
| 3579 | get(move || async move { |
| 3580 | Json(json!({"capabilities":{"turn_image_inputs":supported}})) |
| 3581 | }), |
| 3582 | ) |
| 3583 | .route("/v1/threads/{id}/turns", post(capture)) |
| 3584 | .with_state(seen.clone()); |
| 3585 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 3586 | let addr = listener.local_addr().unwrap(); |
| 3587 | let server = tokio::spawn(async move { |
| 3588 | axum::serve(listener, app).await.unwrap(); |
| 3589 | }); |
| 3590 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{addr}")); |
| 3591 | let images = vec![RuntimeImageInput { |
| 3592 | mime: "image/png".into(), |
| 3593 | data_base64: "fixture-bytes-validated-by-Core".into(), |
| 3594 | }]; |
| 3595 | let mut writer = tokio::io::sink(); |
| 3596 | assert!( |
| 3597 | bridge |
| 3598 | .message_thread( |
| 3599 | "thr_fixture", |
| 3600 | RuntimeTurnInput { |
| 3601 | input: "look", |
| 3602 | images: &images, |
| 3603 | max_output_tokens: None, |
| 3604 | expected_workspace: None, |
| 3605 | cancellation: None, |
| 3606 | }, |
| 3607 | &mut writer, |
| 3608 | None, |
| 3609 | None |
| 3610 | ) |
| 3611 | .await |
| 3612 | .is_err() |
| 3613 | ); |
| 3614 | let requests = seen.lock().await; |
| 3615 | assert_eq!(requests.len(), usize::from(supported)); |
| 3616 | if supported { |
| 3617 | assert_eq!( |
| 3618 | requests[0], |
| 3619 | json!({"allowed_tools": [], "prompt":"look","images":images}) |
| 3620 | ); |
| 3621 | } |
| 3622 | server.abort(); |
| 3623 | } |
| 3624 | } |
| 3625 | |
| 3626 | #[test] |
| 3627 | fn runtime_image_daemon_all_input_families_preserve_images() { |
| 3628 | let image = json!({"mime":"image/png","dataBase64":"AQ=="}); |
| 3629 | let thread: ThreadMessageParams = serde_json::from_value( |
| 3630 | json!({"thread_id":"thr_fixture","allowed_tools": [], "input":"look","images":[image.clone()]}), |
| 3631 | ) |
| 3632 | .unwrap(); |
| 3633 | let prompt: PromptRequest = serde_json::from_value( |
| 3634 | json!({"allowed_tools": [], "prompt":"look","images":[image.clone()]}), |
| 3635 | ) |
| 3636 | .unwrap(); |
| 3637 | let generic: ThreadRequest = serde_json::from_value( |
| 3638 | json!({"kind":"message","thread_id":"thr_fixture","allowed_tools": [], "input":"look","images":[image]}), |
| 3639 | ) |
| 3640 | .unwrap(); |
| 3641 | assert_eq!(thread.images, prompt.images); |
| 3642 | let ThreadRequest::Message { images, .. } = generic else { |
| 3643 | panic!("message"); |
| 3644 | }; |
| 3645 | assert_eq!(thread.images, images); |
| 3646 | assert!(matches!( |
| 3647 | parse_stdio_line(&" ".repeat(MAX_RUNTIME_IMAGE_BODY_BYTES + 1)), |
| 3648 | ParsedStdioLine::Ignored |
| 3649 | )); |
| 3650 | } |
| 3651 | |
| 3652 | #[tokio::test] |
| 3653 | async fn stdio_initialize_gates_requests_and_notifications_never_mint_calls() { |
| 3654 | let (state, _tmp) = capability_test_state(); |
| 3655 | let input = concat!( |
| 3656 | "{\"method\":\"initialized\"}\n", |
| 3657 | "{\"id\":0,\"method\":\"healthz\"}\n", |
| 3658 | "{\"id\":\"init\",\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"fixture\",\"version\":\"1\"}}}\n", |
| 3659 | "{\"id\":1,\"method\":\"healthz\"}\n", |
| 3660 | "{\"method\":\"initialized\"}\n", |
| 3661 | "{\"id\":2,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"fixture\",\"version\":\"1\"}}}\n", |
| 3662 | "{\"id\":true,\"method\":\"shutdown\"}\n", |
| 3663 | "{\"id\":null,\"method\":\"shutdown\"}\n", |
| 3664 | "malformed json\n", |
| 3665 | "{\"id\":3,\"method\":\"healthz\"}\n", |
| 3666 | "{\"id\":3,\"result\":{}}\n", |
| 3667 | "{\"id\":3,\"error\":{\"code\":-32600,\"message\":\"unsolicited\"}}\n", |
| 3668 | "{\"method\":\"shutdown\"}\n", |
| 3669 | "{\"id\":4,\"method\":\"healthz\"}\n", |
| 3670 | ); |
| 3671 | let mut output = Vec::new(); |
| 3672 | let exit = run_stdio_loop( |
| 3673 | &state, |
| 3674 | BoundedLines::new(BufReader::new(input.as_bytes())), |
| 3675 | &mut output, |
| 3676 | StdioLoopPolicy::process_stdio(), |
| 3677 | None::<()>, |
| 3678 | ) |
| 3679 | .await |
| 3680 | .unwrap(); |
| 3681 | assert!(matches!(exit, StdioLoopExit::InputClosed)); |
| 3682 | let frames: Vec<Value> = String::from_utf8(output) |
| 3683 | .unwrap() |
| 3684 | .lines() |
| 3685 | .map(|line| serde_json::from_str(line).unwrap()) |
| 3686 | .collect(); |
| 3687 | assert_eq!(frames.len(), 6); |
| 3688 | assert_eq!(frames[0]["id"], 0); |
| 3689 | assert_eq!(frames[0]["error"]["code"], -32600); |
| 3690 | assert_eq!(frames[0]["error"]["message"], "Not initialized"); |
| 3691 | assert_eq!(frames[1]["id"], "init"); |
| 3692 | let initialized: codewhale_app_server_protocol::lifecycle::InitializeResponse = |
| 3693 | serde_json::from_value(frames[1]["result"].clone()).unwrap(); |
| 3694 | assert!(initialized.codex_home.is_absolute()); |
| 3695 | assert_eq!(frames[2]["id"], 1); |
| 3696 | assert_eq!(frames[2]["result"]["status"], "ok"); |
| 3697 | assert_eq!(frames[3]["id"], 2); |
| 3698 | assert_eq!(frames[3]["error"]["message"], "Already initialized"); |
| 3699 | assert_eq!(frames[4]["id"], 3); |
| 3700 | assert_eq!(frames[4]["result"]["status"], "ok"); |
| 3701 | assert_eq!(frames[5]["id"], 4); |
| 3702 | assert_eq!(frames[5]["result"]["status"], "ok"); |
| 3703 | assert!(frames.iter().all(|frame| frame.get("jsonrpc").is_none())); |
| 3704 | assert!( |
| 3705 | frames |
| 3706 | .iter() |
| 3707 | .all(|frame| frame.get("id").is_some_and(|id| !id.is_null())) |
| 3708 | ); |
| 3709 | assert!(state.in_flight_turns.lock().await.is_empty()); |
| 3710 | } |
| 3711 | |
| 3712 | #[tokio::test] |
| 3713 | async fn private_websocket_preserves_rpc_and_acp_objects_as_single_text_frames() { |
| 3714 | use futures_util::{SinkExt as _, StreamExt as _}; |
| 3715 | use tokio_tungstenite::tungstenite::Message; |
| 3716 | let (client, server) = tokio::io::duplex(65536); |
| 3717 | let server_task = tokio::spawn(async move { |
| 3718 | let (read, write) = tokio::io::split(server); |
| 3719 | let transport = crate::websocket::accept(read, write).await.unwrap(); |
| 3720 | let (read, mut write) = tokio::io::split(transport); |
| 3721 | let mut lines = BoundedLines::new(BufReader::new(read)); |
| 3722 | for _ in 0..5 { |
| 3723 | let line = lines.next_line().await.unwrap().unwrap(); |
| 3724 | write_control_line(&mut write, line.as_bytes()) |
| 3725 | .await |
| 3726 | .unwrap(); |
| 3727 | } |
| 3728 | write.shutdown().await.unwrap(); |
| 3729 | }); |
| 3730 | let (mut socket, _) = tokio_tungstenite::client_async("ws://localhost/", client) |
| 3731 | .await |
| 3732 | .unwrap(); |
| 3733 | for value in [ |
| 3734 | json!({"id":i64::MIN,"method":"initialize","params":{"clientInfo":{"name":"fixture","version":"1"}}}), |
| 3735 | json!({"method":"initialized"}), |
| 3736 | json!({"id":"request/string","result":null}), |
| 3737 | json!({"jsonrpc":"2.0","id":"permission","method":"session/request_permission","params":{"label":"line\nsecond"}}), |
| 3738 | ] { |
| 3739 | socket |
| 3740 | .send(Message::Text( |
| 3741 | serde_json::to_string_pretty(&value).unwrap().into(), |
| 3742 | )) |
| 3743 | .await |
| 3744 | .unwrap(); |
| 3745 | let frame = tokio::time::timeout(Duration::from_secs(5), socket.next()) |
| 3746 | .await |
| 3747 | .unwrap() |
| 3748 | .unwrap() |
| 3749 | .unwrap(); |
| 3750 | let Message::Text(text) = frame else { |
| 3751 | panic!("expected JSON text frame"); |
| 3752 | }; |
| 3753 | assert!(!text.ends_with('\n')); |
| 3754 | assert_eq!(serde_json::from_str::<Value>(&text).unwrap(), value); |
| 3755 | } |
| 3756 | socket.send(Message::Text("{broken}".into())).await.unwrap(); |
| 3757 | let malformed = tokio::time::timeout(Duration::from_secs(5), socket.next()) |
| 3758 | .await |
| 3759 | .unwrap() |
| 3760 | .unwrap() |
| 3761 | .unwrap(); |
| 3762 | assert!(matches!(malformed, Message::Text(text) if text == "{broken}")); |
| 3763 | assert!(matches!(socket.next().await, Some(Ok(Message::Close(_))))); |
| 3764 | server_task.await.unwrap(); |
| 3765 | for close_server in [false, true] { |
| 3766 | let (client, server) = tokio::io::duplex(65536); |
| 3767 | let server_task = tokio::spawn(async move { |
| 3768 | let (read, write) = tokio::io::split(server); |
| 3769 | crate::websocket::accept(read, write).await.unwrap() |
| 3770 | }); |
| 3771 | let (read, write) = tokio::io::split(client); |
| 3772 | let client = crate::websocket::connect(read, write).await.unwrap(); |
| 3773 | let server = server_task.await.unwrap(); |
| 3774 | let (mut remaining, dropped) = if close_server { |
| 3775 | (client, server) |
| 3776 | } else { |
| 3777 | (server, client) |
| 3778 | }; |
| 3779 | drop(dropped); |
| 3780 | let mut byte = [0u8; 1]; |
| 3781 | assert_eq!( |
| 3782 | tokio::time::timeout(Duration::from_secs(5), remaining.read(&mut byte)) |
| 3783 | .await |
| 3784 | .unwrap() |
| 3785 | .unwrap(), |
| 3786 | 0 |
| 3787 | ); |
| 3788 | assert_eq!( |
| 3789 | remaining.write(b"x").await.unwrap_err().kind(), |
| 3790 | std::io::ErrorKind::BrokenPipe |
| 3791 | ); |
| 3792 | } |
| 3793 | let (client, server) = tokio::io::duplex(65536); |
| 3794 | let server_task = tokio::spawn(async move { |
| 3795 | let (read, write) = tokio::io::split(server); |
| 3796 | crate::websocket::accept(read, write).await.unwrap() |
| 3797 | }); |
| 3798 | let (mut client, _) = tokio_tungstenite::client_async("ws://localhost/", client) |
| 3799 | .await |
| 3800 | .unwrap(); |
| 3801 | let mut server = server_task.await.unwrap(); |
| 3802 | client.get_mut().write_all(&[0x81, 1, b'{']).await.unwrap(); |
| 3803 | let mut byte = [0u8; 1]; |
| 3804 | let error = tokio::time::timeout(Duration::from_secs(5), server.read(&mut byte)) |
| 3805 | .await |
| 3806 | .unwrap() |
| 3807 | .unwrap_err(); |
| 3808 | assert!(matches!( |
| 3809 | error |
| 3810 | .get_ref() |
| 3811 | .and_then(|error| error.downcast_ref::<tokio_tungstenite::tungstenite::Error>()), |
| 3812 | Some(tokio_tungstenite::tungstenite::Error::Protocol( |
| 3813 | tokio_tungstenite::tungstenite::error::ProtocolError::UnmaskedFrameFromClient |
| 3814 | )) |
| 3815 | )); |
| 3816 | } |
| 3817 | |
| 3818 | #[tokio::test] |
| 3819 | async fn private_websocket_upgrade_refuses_origin_and_bounded_header_exhaustion() { |
| 3820 | use tokio_tungstenite::tungstenite::client::IntoClientRequest as _; |
| 3821 | for origin in [true, false] { |
| 3822 | let (mut client, server) = tokio::io::duplex(32768); |
| 3823 | let server_task = tokio::spawn(async move { |
| 3824 | let (read, write) = tokio::io::split(server); |
| 3825 | assert!(crate::websocket::accept(read, write).await.is_err()); |
| 3826 | }); |
| 3827 | if origin { |
| 3828 | let mut request = "ws://localhost/".into_client_request().unwrap(); |
| 3829 | request |
| 3830 | .headers_mut() |
| 3831 | .insert("origin", "http://localhost".parse().unwrap()); |
| 3832 | let refused = tokio_tungstenite::client_async(request, client) |
| 3833 | .await |
| 3834 | .unwrap_err(); |
| 3835 | assert!( |
| 3836 | matches!(refused, tokio_tungstenite::tungstenite::Error::Http(response) if response.status() == 403) |
| 3837 | ); |
| 3838 | } else { |
| 3839 | let bytes = format!( |
| 3840 | "GET / HTTP/1.1\r\nHost: localhost\r\nX-Oversized: {}", |
| 3841 | "x".repeat(16384) |
| 3842 | ); |
| 3843 | let _ = client.write_all(bytes.as_bytes()).await; |
| 3844 | client.shutdown().await.unwrap(); |
| 3845 | } |
| 3846 | tokio::time::timeout(Duration::from_secs(6), server_task) |
| 3847 | .await |
| 3848 | .unwrap() |
| 3849 | .unwrap(); |
| 3850 | } |
| 3851 | } |
| 3852 | |
| 3853 | struct MockRuntimeFrontend { |
| 3854 | bridge: SharedRuntimeBridge, |
| 3855 | stalled_subscription: Option<Arc<tokio::sync::Notify>>, |
| 3856 | } |
| 3857 | |
| 3858 | pub(super) async fn install_mock_native_services(state: &mut AppState) { |
| 3859 | state.owner_frontend = Some(Arc::new(MockRuntimeFrontend { |
| 3860 | stalled_subscription: None, |
| 3861 | bridge: state |
| 3862 | .runtime_bridge |
| 3863 | .lock() |
| 3864 | .await |
| 3865 | .clone() |
| 3866 | .expect("mock bridge"), |
| 3867 | })); |
| 3868 | } |
| 3869 | |
| 3870 | impl RuntimeOwnerFrontend for MockRuntimeFrontend { |
| 3871 | fn execute( |
| 3872 | &self, |
| 3873 | request: RuntimeOwnerRequest, |
| 3874 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value>> + Send + '_>> { |
| 3875 | Box::pin(async move { |
| 3876 | let (method, path, body, query) = match request { |
| 3877 | RuntimeOwnerRequest::Native { .. } => anyhow::bail!( |
| 3878 | "native Runtime requires the captured owner, not the HTTP fixture" |
| 3879 | ), |
| 3880 | RuntimeOwnerRequest::Capabilities => ( |
| 3881 | Method::GET, |
| 3882 | vec!["v1".to_owned(), "runtime".to_owned(), "info".to_owned()], |
| 3883 | None, |
| 3884 | Vec::new(), |
| 3885 | ), |
| 3886 | RuntimeOwnerRequest::Providers => ( |
| 3887 | Method::GET, |
| 3888 | vec!["v1".to_owned(), "providers".to_owned()], |
| 3889 | None, |
| 3890 | Vec::new(), |
| 3891 | ), |
| 3892 | RuntimeOwnerRequest::ProviderModels { |
| 3893 | provider, |
| 3894 | provider_id, |
| 3895 | cursor, |
| 3896 | } => { |
| 3897 | let mut query = vec![("limit", "250".to_owned())]; |
| 3898 | if let Some(id) = provider_id { |
| 3899 | query.push(("model_provider_id", id)); |
| 3900 | } |
| 3901 | if let Some(cursor) = cursor { |
| 3902 | query.push(("cursor", cursor)); |
| 3903 | } |
| 3904 | ( |
| 3905 | Method::GET, |
| 3906 | vec![ |
| 3907 | "v1".to_owned(), |
| 3908 | "providers".to_owned(), |
| 3909 | provider, |
| 3910 | "models".to_owned(), |
| 3911 | ], |
| 3912 | None, |
| 3913 | query, |
| 3914 | ) |
| 3915 | } |
| 3916 | RuntimeOwnerRequest::ReloadConfig => ( |
| 3917 | Method::POST, |
| 3918 | vec!["v1".to_owned(), "config".to_owned(), "reload".to_owned()], |
| 3919 | None, |
| 3920 | Vec::new(), |
| 3921 | ), |
| 3922 | RuntimeOwnerRequest::CreateThread(body) => ( |
| 3923 | Method::POST, |
| 3924 | vec!["v1".to_owned(), "threads".to_owned()], |
| 3925 | Some(body), |
| 3926 | Vec::new(), |
| 3927 | ), |
| 3928 | RuntimeOwnerRequest::ListThreads { |
| 3929 | include_archived, |
| 3930 | limit, |
| 3931 | } => ( |
| 3932 | Method::GET, |
| 3933 | vec!["v1".to_owned(), "threads".to_owned()], |
| 3934 | None, |
| 3935 | vec![ |
| 3936 | ("include_archived", include_archived.to_string()), |
| 3937 | ("limit", limit.to_string()), |
| 3938 | ], |
| 3939 | ), |
| 3940 | RuntimeOwnerRequest::LoadedThreads => { |
| 3941 | anyhow::bail!("this HTTP bridge fixture has no loaded-engine snapshot") |
| 3942 | } |
| 3943 | RuntimeOwnerRequest::RunningThreads => ( |
| 3944 | Method::GET, |
| 3945 | vec!["v1".to_owned(), "threads".to_owned(), "running".to_owned()], |
| 3946 | None, |
| 3947 | Vec::new(), |
| 3948 | ), |
| 3949 | RuntimeOwnerRequest::GetThread { thread_id } => ( |
| 3950 | Method::GET, |
| 3951 | vec!["v1".to_owned(), "threads".to_owned(), thread_id], |
| 3952 | None, |
| 3953 | Vec::new(), |
| 3954 | ), |
| 3955 | RuntimeOwnerRequest::UpdateThread { thread_id, body } => ( |
| 3956 | Method::PATCH, |
| 3957 | vec!["v1".to_owned(), "threads".to_owned(), thread_id], |
| 3958 | Some(body), |
| 3959 | Vec::new(), |
| 3960 | ), |
| 3961 | RuntimeOwnerRequest::GetGoal { thread_id } => ( |
| 3962 | Method::GET, |
| 3963 | vec![ |
| 3964 | "v1".to_owned(), |
| 3965 | "threads".to_owned(), |
| 3966 | thread_id, |
| 3967 | "goal".to_owned(), |
| 3968 | ], |
| 3969 | None, |
| 3970 | Vec::new(), |
| 3971 | ), |
| 3972 | RuntimeOwnerRequest::ClearGoal { thread_id } => ( |
| 3973 | Method::DELETE, |
| 3974 | vec![ |
| 3975 | "v1".to_owned(), |
| 3976 | "threads".to_owned(), |
| 3977 | thread_id, |
| 3978 | "goal".to_owned(), |
| 3979 | ], |
| 3980 | None, |
| 3981 | Vec::new(), |
| 3982 | ), |
| 3983 | RuntimeOwnerRequest::HistorySnapshot { thread_id } => ( |
| 3984 | Method::GET, |
| 3985 | vec![ |
| 3986 | "v1".to_owned(), |
| 3987 | "threads".to_owned(), |
| 3988 | thread_id, |
| 3989 | "history".to_owned(), |
| 3990 | ], |
| 3991 | None, |
| 3992 | Vec::new(), |
| 3993 | ), |
| 3994 | RuntimeOwnerRequest::HistoryImport(body) => ( |
| 3995 | Method::POST, |
| 3996 | vec![ |
| 3997 | "v1".to_owned(), |
| 3998 | "thread-history".to_owned(), |
| 3999 | "import".to_owned(), |
| 4000 | ], |
| 4001 | Some(serde_json::to_value(body)?), |
| 4002 | Vec::new(), |
| 4003 | ), |
| 4004 | RuntimeOwnerRequest::HistoryMutate(body) => ( |
| 4005 | Method::POST, |
| 4006 | vec![ |
| 4007 | "v1".to_owned(), |
| 4008 | "thread-history".to_owned(), |
| 4009 | "mutate".to_owned(), |
| 4010 | ], |
| 4011 | Some(serde_json::to_value(body)?), |
| 4012 | Vec::new(), |
| 4013 | ), |
| 4014 | RuntimeOwnerRequest::HistoryLookup(body) => ( |
| 4015 | Method::POST, |
| 4016 | vec![ |
| 4017 | "v1".to_owned(), |
| 4018 | "thread-history".to_owned(), |
| 4019 | "operations".to_owned(), |
| 4020 | "lookup".to_owned(), |
| 4021 | ], |
| 4022 | Some(serde_json::to_value(body)?), |
| 4023 | Vec::new(), |
| 4024 | ), |
| 4025 | RuntimeOwnerRequest::HistoryRecover(body) => ( |
| 4026 | Method::POST, |
| 4027 | vec![ |
| 4028 | "v1".to_owned(), |
| 4029 | "thread-history".to_owned(), |
| 4030 | "operations".to_owned(), |
| 4031 | "recover".to_owned(), |
| 4032 | ], |
| 4033 | Some(serde_json::to_value(body)?), |
| 4034 | Vec::new(), |
| 4035 | ), |
| 4036 | RuntimeOwnerRequest::LookupTurnOperation { |
| 4037 | thread_id, |
| 4038 | operation_key, |
| 4039 | } => ( |
| 4040 | Method::GET, |
| 4041 | vec![ |
| 4042 | "v1".into(), |
| 4043 | "threads".into(), |
| 4044 | thread_id, |
| 4045 | "turn-operations".into(), |
| 4046 | operation_key, |
| 4047 | ], |
| 4048 | None, |
| 4049 | Vec::new(), |
| 4050 | ), |
| 4051 | RuntimeOwnerRequest::StartTurn { thread_id, body } => ( |
| 4052 | Method::POST, |
| 4053 | vec![ |
| 4054 | "v1".to_owned(), |
| 4055 | "threads".to_owned(), |
| 4056 | thread_id, |
| 4057 | "turns".to_owned(), |
| 4058 | ], |
| 4059 | Some(body), |
| 4060 | Vec::new(), |
| 4061 | ), |
| 4062 | RuntimeOwnerRequest::DecideApproval { |
| 4063 | approval_id, |
| 4064 | binding: _, |
| 4065 | decision, |
| 4066 | } => { |
| 4067 | let (decision, remember) = match decision { |
| 4068 | codewhale_engine::runtime_threads::manager::ExternalApprovalDecision::Allow { remember } => ("allow", remember), |
| 4069 | codewhale_engine::runtime_threads::manager::ExternalApprovalDecision::Deny { remember } => ("deny", remember), |
| 4070 | }; |
| 4071 | ( |
| 4072 | Method::POST, |
| 4073 | vec!["v1".to_owned(), "approvals".to_owned(), approval_id], |
| 4074 | Some(json!({"decision": decision, "remember": remember})), |
| 4075 | Vec::new(), |
| 4076 | ) |
| 4077 | } |
| 4078 | RuntimeOwnerRequest::InterruptTurn { thread_id, turn_id } => ( |
| 4079 | Method::POST, |
| 4080 | vec![ |
| 4081 | "v1".to_owned(), |
| 4082 | "threads".to_owned(), |
| 4083 | thread_id, |
| 4084 | "turns".to_owned(), |
| 4085 | turn_id, |
| 4086 | "interrupt".to_owned(), |
| 4087 | ], |
| 4088 | None, |
| 4089 | Vec::new(), |
| 4090 | ), |
| 4091 | RuntimeOwnerRequest::SubmitUserInput { |
| 4092 | thread_id, |
| 4093 | input_id, |
| 4094 | turn_id: _, |
| 4095 | response, |
| 4096 | } => ( |
| 4097 | Method::POST, |
| 4098 | vec![ |
| 4099 | "v1".to_owned(), |
| 4100 | "user-input".to_owned(), |
| 4101 | thread_id, |
| 4102 | input_id, |
| 4103 | ], |
| 4104 | Some(json!({"answers": response.answers})), |
| 4105 | Vec::new(), |
| 4106 | ), |
| 4107 | RuntimeOwnerRequest::CancelUserInput { |
| 4108 | thread_id, |
| 4109 | input_id, |
| 4110 | turn_id: _, |
| 4111 | } => ( |
| 4112 | Method::DELETE, |
| 4113 | vec![ |
| 4114 | "v1".to_owned(), |
| 4115 | "user-input".to_owned(), |
| 4116 | thread_id, |
| 4117 | input_id, |
| 4118 | ], |
| 4119 | None, |
| 4120 | Vec::new(), |
| 4121 | ), |
| 4122 | RuntimeOwnerRequest::DeliverDynamicToolResult { |
| 4123 | thread_id, |
| 4124 | turn_id, |
| 4125 | call_id, |
| 4126 | result, |
| 4127 | } => ( |
| 4128 | Method::POST, |
| 4129 | vec![ |
| 4130 | "v1".to_owned(), |
| 4131 | "threads".to_owned(), |
| 4132 | thread_id, |
| 4133 | "turns".to_owned(), |
| 4134 | turn_id, |
| 4135 | "tool-calls".to_owned(), |
| 4136 | call_id, |
| 4137 | "result".to_owned(), |
| 4138 | ], |
| 4139 | Some(serde_json::to_value(result)?), |
| 4140 | Vec::new(), |
| 4141 | ), |
| 4142 | }; |
| 4143 | let (client, mut url, token) = { |
| 4144 | let bridge = self.bridge.lock().await; |
| 4145 | ( |
| 4146 | bridge.client.clone(), |
| 4147 | reqwest::Url::parse(&bridge.base_url)?, |
| 4148 | bridge.auth_token.clone(), |
| 4149 | ) |
| 4150 | }; |
| 4151 | url.path_segments_mut().unwrap().clear().extend(path.iter()); |
| 4152 | for (key, value) in query { |
| 4153 | url.query_pairs_mut().append_pair(key, &value); |
| 4154 | } |
| 4155 | let mut request = client.request(method, url); |
| 4156 | if let Some(body) = body { |
| 4157 | request = request.json(&body); |
| 4158 | } |
| 4159 | if let Some(token) = token { |
| 4160 | request = request.bearer_auth(token); |
| 4161 | } |
| 4162 | let response = request.send().await?; |
| 4163 | let status = response.status(); |
| 4164 | thread_control::read_json_response(response) |
| 4165 | .await |
| 4166 | .map_err(|error| { |
| 4167 | RuntimeOwnerFailure { |
| 4168 | status: status.as_u16(), |
| 4169 | message: error.to_string(), |
| 4170 | code: None, |
| 4171 | } |
| 4172 | .into() |
| 4173 | }) |
| 4174 | }) |
| 4175 | } |
| 4176 | |
| 4177 | fn events( |
| 4178 | &self, |
| 4179 | thread_id: String, |
| 4180 | since_seq: u64, |
| 4181 | ) -> std::pin::Pin< |
| 4182 | Box<dyn std::future::Future<Output = Result<RuntimeOwnerEventStream>> + Send + '_>, |
| 4183 | > { |
| 4184 | Box::pin(async move { |
| 4185 | if let Some(started) = &self.stalled_subscription { |
| 4186 | started.notify_one(); |
| 4187 | std::future::pending::<()>().await; |
| 4188 | } |
| 4189 | let (client, mut url, token) = { |
| 4190 | let bridge = self.bridge.lock().await; |
| 4191 | ( |
| 4192 | bridge.client.clone(), |
| 4193 | reqwest::Url::parse(&bridge.base_url)?, |
| 4194 | bridge.auth_token.clone(), |
| 4195 | ) |
| 4196 | }; |
| 4197 | url.path_segments_mut() |
| 4198 | .unwrap() |
| 4199 | .clear() |
| 4200 | .extend(["v1", "threads", &thread_id, "events"]); |
| 4201 | url.query_pairs_mut() |
| 4202 | .append_pair("since_seq", &since_seq.to_string()); |
| 4203 | let stream = async_stream::stream! { |
| 4204 | let opened = async { |
| 4205 | let mut request = client.get(url); |
| 4206 | if let Some(token) = token { request = request.bearer_auth(token); } |
| 4207 | request.send().await?.error_for_status() |
| 4208 | }.await; |
| 4209 | let mut response = match opened { |
| 4210 | Ok(response) => response, |
| 4211 | Err(error) => { |
| 4212 | yield RuntimeOwnerEventFrame { event: "stream.end".to_owned(), sequence: None, data: json!({"reason":error.to_string()}) }; |
| 4213 | return; |
| 4214 | } |
| 4215 | }; |
| 4216 | let mut pending = Vec::new(); |
| 4217 | loop { |
| 4218 | match response.chunk().await { |
| 4219 | Ok(Some(chunk)) => pending.extend_from_slice(&chunk), |
| 4220 | Ok(None) => return, |
| 4221 | Err(error) => { |
| 4222 | yield RuntimeOwnerEventFrame { event: "stream.end".to_owned(), sequence: None, data: json!({"reason":error.to_string()}) }; |
| 4223 | return; |
| 4224 | } |
| 4225 | } |
| 4226 | if pending.len() > MAX_SSE_FRAME_BYTES { |
| 4227 | yield RuntimeOwnerEventFrame { event: "stream.end".to_owned(), sequence: None, data: json!({"reason":"oversized mock stream"}) }; |
| 4228 | return; |
| 4229 | } |
| 4230 | while let Some(bytes) = take_sse_frame(&mut pending) { |
| 4231 | let Some((event, body)) = parse_sse_frame(&bytes) else { continue }; |
| 4232 | match serde_json::from_str::<Value>(&body) { |
| 4233 | Ok(data) => yield RuntimeOwnerEventFrame { event, sequence: data.get("seq").and_then(Value::as_u64), data }, |
| 4234 | Err(error) => { |
| 4235 | yield RuntimeOwnerEventFrame { event: "stream.end".to_owned(), sequence: None, data: json!({"reason":error.to_string()}) }; |
| 4236 | return; |
| 4237 | } |
| 4238 | } |
| 4239 | } |
| 4240 | } |
| 4241 | }; |
| 4242 | Ok(Box::pin(stream) as RuntimeOwnerEventStream) |
| 4243 | }) |
| 4244 | } |
| 4245 | |
| 4246 | fn validate_selection<'a>( |
| 4247 | &'a self, |
| 4248 | _selection: &'a RuntimeOwnerFrontendSelection, |
| 4249 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { |
| 4250 | Box::pin(async { anyhow::bail!("wire mock cannot admit a captured frontend selection") }) |
| 4251 | } |
| 4252 | |
| 4253 | fn serve<'a>( |
| 4254 | &'a self, |
| 4255 | _selection: RuntimeOwnerFrontendSelection, |
| 4256 | _compatibility: AppState, |
| 4257 | _input: Box<dyn tokio::io::AsyncBufRead + Send + Unpin>, |
| 4258 | _output: Box<dyn AsyncWrite + Send + Unpin + 'a>, |
| 4259 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> { |
| 4260 | Box::pin(async { anyhow::bail!("wire mock cannot serve a captured frontend") }) |
| 4261 | } |
| 4262 | } |
| 4263 |