| 1 | /// A catalog row stating `codewhale.protocol = "responses"` must dispatch |
| 2 | /// to the account API's Responses surface — `{base}/responses` — not the |
| 3 | /// Chat Completions default its `openai/` namespace alone would imply. |
| 4 | #[tokio::test] |
| 5 | async fn codewhale_responses_catalog_row_dispatches_to_responses_endpoint() { |
| 6 | let _env = crate::test_support::lock_test_env(); |
| 7 | let _live = crate::provider_lake::lock_live_snapshot(); |
| 8 | let home = tempfile::tempdir().expect("home"); |
| 9 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 10 | crate::provider_catalog_live::reset_cache_for_test(); |
| 11 | crate::provider_lake::clear_live_snapshot(); |
| 12 | |
| 13 | let server = MockServer::start().await; |
| 14 | Mock::given(method("POST")) |
| 15 | .and(path("/v1/responses")) |
| 16 | .respond_with( |
| 17 | ResponseTemplate::new(200) |
| 18 | .insert_header("Content-Type", "text/event-stream") |
| 19 | .set_body_string(concat!( |
| 20 | "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\"", |
| 21 | ",\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n\n", |
| 22 | "data: [DONE]\n\n" |
| 23 | )), |
| 24 | ) |
| 25 | .expect(1) |
| 26 | .mount(&server) |
| 27 | .await; |
| 28 | |
| 29 | // Seed the account catalog through the same refresh seam the runtime |
| 30 | // uses, so the wire choice comes from the row's stated protocol. |
| 31 | let fingerprint = base_url_fingerprint(&server.uri()); |
| 32 | let offerings = codewhale_catalog_offerings_from_body( |
| 33 | r#"{"object":"list","data":[ |
| 34 | {"id":"openai/gpt-5.6","object":"model","owned_by":"openai", |
| 35 | "codewhale":{"provider":"openai","model":"gpt-5.6", |
| 36 | "protocol":"responses","endpoint":"/v1/responses", |
| 37 | "default":true,"usable":true}} |
| 38 | ]}"#, |
| 39 | "codewhale", |
| 40 | &fingerprint, |
| 41 | now_unix(), |
| 42 | ) |
| 43 | .expect("fixture catalog parses"); |
| 44 | crate::provider_catalog_live::record_success(ProviderCatalogDelta { |
| 45 | provider: "codewhale".to_string(), |
| 46 | base_url_fingerprint: fingerprint, |
| 47 | fetched_at: now_unix(), |
| 48 | offerings, |
| 49 | }); |
| 50 | |
| 51 | let mut client = codewhale_client(&server, "openai/gpt-5.6"); |
| 52 | assert_eq!(client.wire_format, WireFormat::Responses); |
| 53 | client.retry.enabled = false; |
| 54 | let response = client |
| 55 | .create_message(minimal_zen_request("openai/gpt-5.6")) |
| 56 | .await |
| 57 | .expect("Codewhale responses request should succeed"); |
| 58 | |
| 59 | // Responses usage arrives on the terminal `response.completed` event — |
| 60 | // the dialect's equivalent of chat's `stream_options.include_usage`. |
| 61 | assert_eq!(response.usage.input_tokens, 3); |
| 62 | assert_eq!(response.usage.output_tokens, 1); |
| 63 | let requests = server.received_requests().await.expect("recorded request"); |
| 64 | assert_eq!(requests.len(), 1); |
| 65 | assert_codewhale_bearer(&requests[0]); |
| 66 | let body: Value = serde_json::from_slice(&requests[0].body).expect("responses JSON body"); |
| 67 | assert_eq!( |
| 68 | body.get("model").and_then(Value::as_str), |
| 69 | Some("openai/gpt-5.6") |
| 70 | ); |
| 71 | assert!(body.get("input").is_some(), "Responses body: {body}"); |
| 72 | assert!(body.get("messages").is_none(), "Responses body: {body}"); |
| 73 | |
| 74 | crate::provider_catalog_live::reset_cache_for_test(); |
| 75 | crate::provider_lake::clear_live_snapshot(); |
| 76 | } |
| 77 | |
| 78 | fn opencode_zen_client(server: &MockServer, model: &str) -> CodewhaleClient { |
| 79 | let config = { |
| 80 | let __cw_config_init_0_0 = Some("opencode-zen".to_string()); |
| 81 | let __cw_config_init_0_1 = Some(ProvidersConfig { |
| 82 | opencode_zen: ProviderConfig { |
| 83 | api_key: Some("zen-test-key".to_string()), |
| 84 | base_url: Some(server.uri()), |
| 85 | model: Some(model.to_string()), |
| 86 | ..ProviderConfig::default() |
| 87 | }, |
| 88 | ..ProvidersConfig::default() |
| 89 | }); |
| 90 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 91 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 92 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 93 | __cw_config_init_0_value |
| 94 | }; |
| 95 | CodewhaleClient::new(&config).expect("OpenCode Zen client should resolve its model route") |
| 96 | } |
| 97 | |
| 98 | fn minimal_zen_request(model: &str) -> MessageRequest { |
| 99 | translation_message_request("hello", model.to_string(), "English", 4096) |
| 100 | } |
| 101 | |
| 102 | fn assert_zen_bearer_without_codex_headers(request: &wiremock::Request) { |
| 103 | assert_eq!( |
| 104 | request |
| 105 | .headers |
| 106 | .get(AUTHORIZATION) |
| 107 | .and_then(|value| value.to_str().ok()), |
| 108 | Some("Bearer zen-test-key") |
| 109 | ); |
| 110 | for forbidden in [ |
| 111 | "openai-beta", |
| 112 | "originator", |
| 113 | "chatgpt-account-id", |
| 114 | "x-api-key", |
| 115 | ] { |
| 116 | assert!( |
| 117 | request.headers.get(forbidden).is_none(), |
| 118 | "Zen request must not include {forbidden}" |
| 119 | ); |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn assert_zen_messages_api_key_without_bearer(request: &wiremock::Request) { |
| 124 | assert_eq!( |
| 125 | request |
| 126 | .headers |
| 127 | .get("x-api-key") |
| 128 | .and_then(|value| value.to_str().ok()), |
| 129 | Some("zen-test-key") |
| 130 | ); |
| 131 | assert!( |
| 132 | request.headers.get(AUTHORIZATION).is_none(), |
| 133 | "Zen Messages request must not include Authorization" |
| 134 | ); |
| 135 | for forbidden in ["openai-beta", "originator", "chatgpt-account-id"] { |
| 136 | assert!( |
| 137 | request.headers.get(forbidden).is_none(), |
| 138 | "Zen request must not include {forbidden}" |
| 139 | ); |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | #[tokio::test] |
| 144 | async fn opencode_go_dispatches_all_three_wires_with_gateway_auth_and_stable_session() { |
| 145 | let session = opencode_conversation_key("same-thread", None); |
| 146 | for (model, wire, endpoint) in [ |
| 147 | ( |
| 148 | "deepseek-v4-pro", |
| 149 | WireFormat::ChatCompletions, |
| 150 | "/zen/go/v1/chat/completions", |
| 151 | ), |
| 152 | ("grok-4.6", WireFormat::Responses, "/zen/go/v1/responses"), |
| 153 | ( |
| 154 | "minimax-m3", |
| 155 | WireFormat::AnthropicMessages, |
| 156 | "/zen/go/v1/messages", |
| 157 | ), |
| 158 | ] { |
| 159 | let server = MockServer::start().await; |
| 160 | let response = match wire { |
| 161 | WireFormat::Responses => ResponseTemplate::new(200) |
| 162 | .insert_header("Content-Type", "text/event-stream") |
| 163 | .set_body_string("data: [DONE]\n\n"), |
| 164 | WireFormat::AnthropicMessages => ResponseTemplate::new(200).set_body_json(json!({ |
| 165 | "id":"msg_go", "type":"message", "role":"assistant", |
| 166 | "content":[{"type":"text", "text":"ok"}], "model":model, |
| 167 | "stop_reason":"end_turn", "stop_sequence":null, |
| 168 | "usage":{"input_tokens":3,"output_tokens":1} |
| 169 | })), |
| 170 | WireFormat::ChatCompletions => ResponseTemplate::new(200).set_body_json(json!({ |
| 171 | "id":"chat_go", "object":"chat.completion", "created":1, "model":model, |
| 172 | "choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}], |
| 173 | "usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4} |
| 174 | })), |
| 175 | WireFormat::GenerateContent => ResponseTemplate::new(200) |
| 176 | .insert_header("Content-Type", "text/event-stream") |
| 177 | .set_body_string("data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}\n\n"), |
| 178 | }; |
| 179 | Mock::given(method("POST")) |
| 180 | .and(path(endpoint)) |
| 181 | .respond_with(response) |
| 182 | .expect(1) |
| 183 | .mount(&server) |
| 184 | .await; |
| 185 | let mut client = CodewhaleClient::new(&{ |
| 186 | let __cw_config_init_1_0 = Some("opencode-go".into()); |
| 187 | let __cw_config_init_1_1 = Some(ProvidersConfig { |
| 188 | opencode_go: ProviderConfig { |
| 189 | api_key: Some("go-test-key".into()), |
| 190 | base_url: Some(format!("{}/zen/go/v1", server.uri())), |
| 191 | model: Some(format!("opencode-go/{model}")), |
| 192 | ..ProviderConfig::default() |
| 193 | }, |
| 194 | ..ProvidersConfig::default() |
| 195 | }); |
| 196 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 197 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 198 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 199 | __cw_config_init_1_value |
| 200 | }) |
| 201 | .expect("Go client resolves the model protocol"); |
| 202 | client.retry.enabled = false; |
| 203 | assert_eq!(client.wire_format, wire); |
| 204 | OPENCODE_CONVERSATION |
| 205 | .scope(session.clone(), async { |
| 206 | if wire == WireFormat::Responses { |
| 207 | let mut stream = client |
| 208 | .create_message_stream(minimal_zen_request(model)) |
| 209 | .await |
| 210 | .unwrap(); |
| 211 | while let Some(event) = stream.next().await { |
| 212 | event.unwrap(); |
| 213 | } |
| 214 | assert!( |
| 215 | client |
| 216 | .prepare_outbound_request(minimal_zen_request("minimax-m3"), false) |
| 217 | .is_err(), |
| 218 | "a request cannot silently change an existing client's protocol" |
| 219 | ); |
| 220 | } else { |
| 221 | client |
| 222 | .create_message(minimal_zen_request(model)) |
| 223 | .await |
| 224 | .unwrap(); |
| 225 | } |
| 226 | }) |
| 227 | .await; |
| 228 | let requests = server.received_requests().await.unwrap(); |
| 229 | assert_eq!(requests.len(), 1); |
| 230 | let request = &requests[0]; |
| 231 | let header = |name: &str| { |
| 232 | request |
| 233 | .headers |
| 234 | .get(name) |
| 235 | .and_then(|value| value.to_str().ok()) |
| 236 | }; |
| 237 | let observed_session = header("x-opencode-session").expect("stable session header"); |
| 238 | assert_eq!(observed_session, session); |
| 239 | assert!( |
| 240 | header("user-agent") |
| 241 | .is_some_and(|value| value.contains("Codewhale") || value.contains("codewhale")) |
| 242 | ); |
| 243 | for forbidden in ["openai-beta", "originator", "chatgpt-account-id"] { |
| 244 | assert!( |
| 245 | header(forbidden).is_none(), |
| 246 | "gateway requests cannot carry {forbidden}" |
| 247 | ); |
| 248 | } |
| 249 | let body: Value = serde_json::from_slice(&request.body).unwrap(); |
| 250 | assert_eq!(body["model"], model); |
| 251 | if wire == WireFormat::AnthropicMessages { |
| 252 | assert_eq!(header("x-api-key"), Some("go-test-key")); |
| 253 | assert_eq!(header("anthropic-version"), Some("2023-06-01")); |
| 254 | assert!(header("authorization").is_none()); |
| 255 | assert!(body.get("messages").is_some()); |
| 256 | } else { |
| 257 | assert_eq!(header("authorization"), Some("Bearer go-test-key")); |
| 258 | assert!(header("x-api-key").is_none()); |
| 259 | assert!( |
| 260 | body.get(if wire == WireFormat::Responses { |
| 261 | "input" |
| 262 | } else { |
| 263 | "messages" |
| 264 | }) |
| 265 | .is_some() |
| 266 | ); |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | #[tokio::test] |
| 272 | async fn opencode_zen_responses_request_uses_responses_route_without_oauth_headers() { |
| 273 | let server = MockServer::start().await; |
| 274 | Mock::given(method("POST")) |
| 275 | .and(path("/v1/responses")) |
| 276 | .respond_with( |
| 277 | ResponseTemplate::new(200) |
| 278 | .insert_header("Content-Type", "text/event-stream") |
| 279 | .set_body_string("data: [DONE]\n\n"), |
| 280 | ) |
| 281 | .expect(1) |
| 282 | .mount(&server) |
| 283 | .await; |
| 284 | |
| 285 | let client = opencode_zen_client(&server, "gpt-5.5"); |
| 286 | assert_eq!(client.wire_format, WireFormat::Responses); |
| 287 | let mut stream = client |
| 288 | .create_message_stream(minimal_zen_request("gpt-5.5")) |
| 289 | .await |
| 290 | .expect("Zen Responses request should start"); |
| 291 | while let Some(event) = stream.next().await { |
| 292 | event.expect("Zen Responses stream event"); |
| 293 | } |
| 294 | |
| 295 | let requests = server.received_requests().await.expect("recorded request"); |
| 296 | assert_eq!(requests.len(), 1); |
| 297 | assert_zen_bearer_without_codex_headers(&requests[0]); |
| 298 | let body: Value = serde_json::from_slice(&requests[0].body).expect("Responses JSON body"); |
| 299 | assert_eq!(body.get("model").and_then(Value::as_str), Some("gpt-5.5")); |
| 300 | assert!(body.get("input").is_some(), "Responses body: {body}"); |
| 301 | assert!(body.get("messages").is_none(), "Responses body: {body}"); |
| 302 | } |
| 303 | |
| 304 | #[tokio::test] |
| 305 | async fn opencode_zen_messages_request_shape_uses_api_key_anthropic_route() { |
| 306 | let server = MockServer::start().await; |
| 307 | Mock::given(method("POST")) |
| 308 | .and(path("/v1/messages")) |
| 309 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 310 | "id": "msg_zen", |
| 311 | "type": "message", |
| 312 | "role": "assistant", |
| 313 | "content": [{"type": "text", "text": "ok"}], |
| 314 | "model": "claude-sonnet-4-6", |
| 315 | "stop_reason": "end_turn", |
| 316 | "stop_sequence": null, |
| 317 | "usage": {"input_tokens": 1, "output_tokens": 1} |
| 318 | }))) |
| 319 | .expect(1) |
| 320 | .mount(&server) |
| 321 | .await; |
| 322 | |
| 323 | let client = opencode_zen_client(&server, "claude-sonnet-4-6"); |
| 324 | assert_eq!(client.wire_format, WireFormat::AnthropicMessages); |
| 325 | client |
| 326 | .create_message(minimal_zen_request("claude-sonnet-4-6")) |
| 327 | .await |
| 328 | .expect("Zen Messages request should succeed"); |
| 329 | |
| 330 | let requests = server.received_requests().await.expect("recorded request"); |
| 331 | assert_eq!(requests.len(), 1); |
| 332 | assert_zen_messages_api_key_without_bearer(&requests[0]); |
| 333 | assert_eq!( |
| 334 | requests[0] |
| 335 | .headers |
| 336 | .get("anthropic-version") |
| 337 | .and_then(|value| value.to_str().ok()), |
| 338 | Some("2023-06-01") |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | #[tokio::test] |
| 343 | async fn opencode_zen_chat_request_uses_chat_completions_route() { |
| 344 | let server = MockServer::start().await; |
| 345 | Mock::given(method("POST")) |
| 346 | .and(path("/v1/chat/completions")) |
| 347 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 348 | "id": "chatcmpl_zen", |
| 349 | "object": "chat.completion", |
| 350 | "model": "deepseek-v4-pro", |
| 351 | "choices": [{ |
| 352 | "index": 0, |
| 353 | "message": {"role": "assistant", "content": "ok"}, |
| 354 | "finish_reason": "stop" |
| 355 | }], |
| 356 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} |
| 357 | }))) |
| 358 | .expect(1) |
| 359 | .mount(&server) |
| 360 | .await; |
| 361 | |
| 362 | let client = opencode_zen_client(&server, "deepseek-v4-pro"); |
| 363 | assert_eq!(client.wire_format, WireFormat::ChatCompletions); |
| 364 | client |
| 365 | .create_message(minimal_zen_request("deepseek-v4-pro")) |
| 366 | .await |
| 367 | .expect("Zen Chat Completions request should succeed"); |
| 368 | |
| 369 | let requests = server.received_requests().await.expect("recorded request"); |
| 370 | assert_eq!(requests.len(), 1); |
| 371 | assert_zen_bearer_without_codex_headers(&requests[0]); |
| 372 | assert!(requests[0].headers.get("anthropic-version").is_none()); |
| 373 | } |
| 374 | |
| 375 | #[tokio::test] |
| 376 | async fn opencode_zen_client_fails_closed_when_request_model_changes_protocol() { |
| 377 | let server = MockServer::start().await; |
| 378 | let client = opencode_zen_client(&server, "gpt-5.5"); |
| 379 | |
| 380 | let error = client |
| 381 | .create_message(minimal_zen_request("claude-sonnet-4-6")) |
| 382 | .await |
| 383 | .expect_err("a Responses-bound client must not send a Messages model"); |
| 384 | assert!(format!("{error:#}").contains("resolve a new model route")); |
| 385 | assert!( |
| 386 | server |
| 387 | .received_requests() |
| 388 | .await |
| 389 | .expect("recorded requests") |
| 390 | .is_empty() |
| 391 | ); |
| 392 | } |
| 393 | |
| 394 | const CONFIG_SECRET_SENTINELS: [&str; 8] = [ |
| 395 | "deepseek-config-secret-001", |
| 396 | "arcee-config-secret-002", |
| 397 | "moonshot-config-secret-003", |
| 398 | "openrouter-config-secret-004", |
| 399 | "together-config-secret-005", |
| 400 | "xiaomi-config-secret-006", |
| 401 | "zai-active-config-secret-007", |
| 402 | "sakana-config-secret-008", |
| 403 | ]; |
| 404 | |
| 405 | #[test] |
| 406 | fn chatgpt_client_rejects_external_tokens_and_uses_its_owned_grant() { |
| 407 | let _env = crate::test_support::lock_test_env(); |
| 408 | let temp = tempfile::tempdir().expect("credential fixture"); |
| 409 | let root = temp |
| 410 | .path() |
| 411 | .canonicalize() |
| 412 | .expect("canonical credential home"); |
| 413 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root); |
| 414 | let _ambient = |
| 415 | crate::test_support::EnvVarGuard::set("OPENAI_CODEX_ACCESS_TOKEN", "external-token"); |
| 416 | let mut config = { |
| 417 | let __cw_config_init_2_0 = Some("openai-codex".to_string()); |
| 418 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 419 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 420 | __cw_config_init_2_value |
| 421 | }; |
| 422 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 423 | assert!(CodewhaleClient::new(&config).is_err()); |
| 424 | assert_eq!( |
| 425 | codewhale_runtime::external_credentials::complete_side_effect_trap_counts(), |
| 426 | (0, 0, 0, 0, 0) |
| 427 | ); |
| 428 | let token = codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config) |
| 429 | .expect("owned registration"); |
| 430 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 431 | let client = CodewhaleClient::new(&config).expect("official ChatGPT client"); |
| 432 | assert_eq!(client.api_key, token); |
| 433 | assert_eq!(client.base_url, "https://api.openai.com/v1"); |
| 434 | assert_eq!( |
| 435 | codewhale_runtime::external_credentials::complete_side_effect_trap_counts(), |
| 436 | (0, 0, 0, 0, 0) |
| 437 | ); |
| 438 | } |
| 439 | |
| 440 | #[test] |
| 441 | fn chatgpt_reasoning_scope_separates_account_workspace_and_custom_routes() { |
| 442 | let _env = crate::test_support::lock_test_env(); |
| 443 | let temp = tempfile::tempdir().unwrap(); |
| 444 | let root = temp |
| 445 | .path() |
| 446 | .canonicalize() |
| 447 | .expect("canonical credential home"); |
| 448 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root); |
| 449 | let mut config = { |
| 450 | let __cw_config_init_3_0 = Some("openai-codex".into()); |
| 451 | let mut __cw_config_init_3_value: Config = Default::default(); |
| 452 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 453 | __cw_config_init_3_value |
| 454 | }; |
| 455 | let mut scopes = Vec::new(); |
| 456 | for (subject, client_id) in [ |
| 457 | ("account-a", "oaiapp_workspace_a"), |
| 458 | ("account-b", "oaiapp_workspace_a"), |
| 459 | ("account-a", "oaiapp_workspace_b"), |
| 460 | ] { |
| 461 | codewhale_runtime::oauth::install_test_chatgpt_registration_for( |
| 462 | &mut config, |
| 463 | subject, |
| 464 | client_id, |
| 465 | ) |
| 466 | .unwrap(); |
| 467 | let client = CodewhaleClient::new(&config).unwrap(); |
| 468 | assert_eq!( |
| 469 | client.chatgpt_reasoning_api, |
| 470 | client.clone().chatgpt_reasoning_api |
| 471 | ); |
| 472 | scopes.push(client.chatgpt_reasoning_api.unwrap()); |
| 473 | } |
| 474 | assert_ne!(scopes[0], scopes[1]); |
| 475 | assert_ne!(scopes[0], scopes[2]); |
| 476 | assert!( |
| 477 | scopes |
| 478 | .iter() |
| 479 | .all(|scope| scope.starts_with("openai-responses-siwc-v1:") |
| 480 | && !scope.contains("account-")) |
| 481 | ); |
| 482 | let provider = config |
| 483 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 484 | .unwrap(); |
| 485 | provider.base_url = Some("http://127.0.0.1:9/v1".into()); |
| 486 | provider.api_key = Some("configured-fixture-key".into()); |
| 487 | provider.auth_mode = None; |
| 488 | provider.oauth_credential_generation = None; |
| 489 | assert!( |
| 490 | CodewhaleClient::new(&config) |
| 491 | .unwrap() |
| 492 | .chatgpt_reasoning_api |
| 493 | .is_none() |
| 494 | ); |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn chatgpt_roster_preserves_visible_account_order_and_labels() { |
| 499 | let roster = parse_models_response_for_provider( |
| 500 | r#"{"models":[ |
| 501 | {"slug":"gpt-z","display_name":"GPT Z","visibility":"list"}, |
| 502 | {"slug":"gpt-hidden","display_name":"Hidden","visibility":"hidden"}, |
| 503 | {"slug":"gpt-a","display_name":"GPT A","visibility":"list"}, |
| 504 | {"slug":"gpt-z","display_name":"Duplicate","visibility":"list"} |
| 505 | ]}"#, |
| 506 | ProviderKind::OpenaiCodex, |
| 507 | ) |
| 508 | .expect("roster"); |
| 509 | assert_eq!( |
| 510 | roster.iter().map(|row| row.id.as_str()).collect::<Vec<_>>(), |
| 511 | ["gpt-z", "gpt-a"] |
| 512 | ); |
| 513 | assert_eq!(roster[0].display_name.as_deref(), Some("GPT Z")); |
| 514 | assert!( |
| 515 | parse_models_response_for_provider( |
| 516 | r#"{"data":[{"id":"gpt-z"}]}"#, |
| 517 | ProviderKind::OpenaiCodex |
| 518 | ) |
| 519 | .is_err() |
| 520 | ); |
| 521 | assert!( |
| 522 | parse_models_response_for_provider( |
| 523 | r#"{"models":[{"slug":"gpt-bad\n","display_name":"Bad","visibility":"list"}]}"#, |
| 524 | ProviderKind::OpenaiCodex |
| 525 | ) |
| 526 | .is_err() |
| 527 | ); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn chatgpt_roster_parses_context_windows_efforts_and_rejects_invalid_bounds() { |
| 532 | let roster = parse_models_response_for_provider( |
| 533 | r#"{"models":[ |
| 534 | { |
| 535 | "slug":"gpt-6.2-sol", |
| 536 | "display_name":"GPT-6.2-Sol", |
| 537 | "visibility":"list", |
| 538 | "context_window":500000, |
| 539 | "max_context_window":872000, |
| 540 | "effective_context_window_percent":95, |
| 541 | "supported_reasoning_levels":[ |
| 542 | {"effort":"low","description":"Fast"}, |
| 543 | {"effort":"medium","description":"Balanced"}, |
| 544 | {"effort":"high","description":"Deep"}, |
| 545 | {"effort":"xhigh","description":"Extra"}, |
| 546 | {"effort":"max","description":"Max"}, |
| 547 | {"effort":"ultra","description":"Ultra"} |
| 548 | ] |
| 549 | }, |
| 550 | { |
| 551 | "slug":"gpt-alias-max", |
| 552 | "display_name":"GPT Alias Max", |
| 553 | "visibility":"list", |
| 554 | "max_context_tokens":272000, |
| 555 | "reasoning_levels":["low","high","unknown_tier"] |
| 556 | }, |
| 557 | { |
| 558 | "slug":"gpt-alias-len", |
| 559 | "display_name":"GPT Alias Len", |
| 560 | "visibility":"list", |
| 561 | "context_window":null, |
| 562 | "context_length":"400000", |
| 563 | "supported_reasoning_levels":[] |
| 564 | }, |
| 565 | { |
| 566 | "slug":"gpt-zero", |
| 567 | "display_name":"GPT Zero", |
| 568 | "visibility":"list", |
| 569 | "context_window":0, |
| 570 | "context_length":272000 |
| 571 | }, |
| 572 | { |
| 573 | "slug":"gpt-huge", |
| 574 | "display_name":"GPT Huge", |
| 575 | "visibility":"list", |
| 576 | "context_window":16000001, |
| 577 | "effective_context_window_percent":105 |
| 578 | }, |
| 579 | { |
| 580 | "slug":"gpt-negative", |
| 581 | "display_name":"GPT Negative", |
| 582 | "visibility":"list", |
| 583 | "context_window":-100 |
| 584 | } |
| 585 | ]}"#, |
| 586 | ProviderKind::OpenaiCodex, |
| 587 | ) |
| 588 | .expect("roster"); |
| 589 | |
| 590 | assert_eq!(roster[0].id, "gpt-6.2-sol"); |
| 591 | assert_eq!(roster[0].context_window, Some(500_000)); |
| 592 | assert_eq!(roster[0].effective_context_window_percent, Some(95)); |
| 593 | assert_eq!(roster[0].reasoning, Some(true)); |
| 594 | assert_eq!( |
| 595 | roster[0].efforts, |
| 596 | vec!["low", "medium", "high", "xhigh", "max", "ultra"] |
| 597 | ); |
| 598 | |
| 599 | assert_eq!(roster[1].id, "gpt-alias-max"); |
| 600 | assert_eq!(roster[1].context_window, Some(272_000)); |
| 601 | assert_eq!(roster[1].reasoning, Some(true)); |
| 602 | assert_eq!(roster[1].efforts, vec!["low", "high"]); |
| 603 | |
| 604 | assert_eq!(roster[2].id, "gpt-alias-len"); |
| 605 | assert_eq!(roster[2].context_window, Some(400_000)); |
| 606 | assert_eq!(roster[2].reasoning, Some(false)); |
| 607 | assert!(roster[2].efforts.is_empty()); |
| 608 | |
| 609 | assert_eq!(roster[3].id, "gpt-zero"); |
| 610 | assert_eq!(roster[3].context_window, None); |
| 611 | |
| 612 | assert_eq!(roster[4].id, "gpt-huge"); |
| 613 | assert_eq!(roster[4].context_window, None); |
| 614 | assert_eq!(roster[4].effective_context_window_percent, None); |
| 615 | |
| 616 | assert_eq!(roster[5].id, "gpt-negative"); |
| 617 | assert_eq!(roster[5].context_window, None); |
| 618 | } |
| 619 | |
| 620 | fn client_with_config_secret_sentinels() -> CodewhaleClient { |
| 621 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 622 | CodewhaleClient::new( |
| 623 | &{ |
| 624 | let __cw_config_init_4_0 = Some("zai".to_string()); |
| 625 | let __cw_config_init_4_1 = Some(ProvidersConfig { |
| 626 | arcee: ProviderConfig { |
| 627 | api_key: Some(CONFIG_SECRET_SENTINELS[1].to_string()), |
| 628 | ..ProviderConfig::default() |
| 629 | }, |
| 630 | moonshot: ProviderConfig { |
| 631 | api_key: Some(CONFIG_SECRET_SENTINELS[2].to_string()), |
| 632 | ..ProviderConfig::default() |
| 633 | }, |
| 634 | openrouter: ProviderConfig { |
| 635 | api_key: Some(CONFIG_SECRET_SENTINELS[3].to_string()), |
| 636 | ..ProviderConfig::default() |
| 637 | }, |
| 638 | together: ProviderConfig { |
| 639 | api_key: Some(CONFIG_SECRET_SENTINELS[4].to_string()), |
| 640 | ..ProviderConfig::default() |
| 641 | }, |
| 642 | xiaomi_mimo: ProviderConfig { |
| 643 | api_key: Some(CONFIG_SECRET_SENTINELS[5].to_string()), |
| 644 | ..ProviderConfig::default() |
| 645 | }, |
| 646 | zai: ProviderConfig { |
| 647 | api_key: Some(CONFIG_SECRET_SENTINELS[6].to_string()), |
| 648 | ..ProviderConfig::default() |
| 649 | }, |
| 650 | sakana: ProviderConfig { |
| 651 | api_key: Some(CONFIG_SECRET_SENTINELS[7].to_string()), |
| 652 | ..ProviderConfig::default() |
| 653 | }, |
| 654 | ..ProvidersConfig::default() |
| 655 | }); |
| 656 | let mut __cw_config_init_4_value: Config = Config::default(); |
| 657 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 658 | __cw_config_init_4_value.providers = __cw_config_init_4_1; |
| 659 | __cw_config_init_4_value |
| 660 | } |
| 661 | .with_legacy_root(Some(CONFIG_SECRET_SENTINELS[0].to_string()), None), |
| 662 | ) |
| 663 | .expect("client with secret sentinels") |
| 664 | } |
| 665 | |
| 666 | fn request_with_tool_result(content: impl Into<String>) -> MessageRequest { |
| 667 | MessageRequest { |
| 668 | model: "glm-5.2".to_string(), |
| 669 | messages: vec![ |
| 670 | Message { |
| 671 | role: Role::Assistant, |
| 672 | content: vec![ContentBlock::ToolUse { |
| 673 | execution_id: None, |
| 674 | id: "call-secret-test".to_string(), |
| 675 | name: "read_file".to_string(), |
| 676 | input: json!({"path": "config.toml"}), |
| 677 | caller: None, |
| 678 | thought_signature: None, |
| 679 | }], |
| 680 | }, |
| 681 | Message { |
| 682 | role: Role::User, |
| 683 | content: vec![ContentBlock::ToolResult { |
| 684 | execution_id: None, |
| 685 | tool_use_id: "call-secret-test".to_string(), |
| 686 | content: content.into(), |
| 687 | is_error: None, |
| 688 | content_blocks: None, |
| 689 | }], |
| 690 | }, |
| 691 | ], |
| 692 | max_tokens: 128, |
| 693 | system: None, |
| 694 | tools: None, |
| 695 | tool_choice: None, |
| 696 | metadata: None, |
| 697 | thinking: None, |
| 698 | reasoning_effort: None, |
| 699 | stream: None, |
| 700 | temperature: None, |
| 701 | top_p: None, |
| 702 | safety_check: None, |
| 703 | title: None, |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | fn tool_result_content(request: &MessageRequest) -> &str { |
| 708 | request |
| 709 | .messages |
| 710 | .iter() |
| 711 | .flat_map(|message| &message.content) |
| 712 | .find_map(|block| match block { |
| 713 | ContentBlock::ToolResult { content, .. } => Some(content.as_str()), |
| 714 | _ => None, |
| 715 | }) |
| 716 | .expect("tool result content") |
| 717 | } |
| 718 | |
| 719 | #[test] |
| 720 | fn model_bound_request_repairs_dangling_tool_call_before_adapter_projection() { |
| 721 | let client = client_with_config_secret_sentinels(); |
| 722 | let mut request = request_with_tool_result("unused"); |
| 723 | request.messages.pop(); |
| 724 | |
| 725 | let prepared = client.prepare_model_bound_request(request); |
| 726 | |
| 727 | assert!(prepared.messages.iter().any(|message| { |
| 728 | message.content.iter().any(|block| { |
| 729 | matches!( |
| 730 | block, |
| 731 | ContentBlock::ToolResult { |
| 732 | tool_use_id, |
| 733 | content, |
| 734 | is_error: Some(true), |
| 735 | .. |
| 736 | } if tool_use_id == "call-secret-test" |
| 737 | && content.contains("crashed_and_repaired") |
| 738 | ) |
| 739 | }) |
| 740 | })); |
| 741 | assert_eq!( |
| 742 | prepared.messages.last().expect("repaired result").role, |
| 743 | "user" |
| 744 | ); |
| 745 | assert!(!prepared.messages.iter().any(|message| { |
| 746 | message.content.iter().any(|block| { |
| 747 | matches!( |
| 748 | block, |
| 749 | ContentBlock::Text { text, .. } |
| 750 | if text.contains("[tool_history_repair]") |
| 751 | ) |
| 752 | }) |
| 753 | })); |
| 754 | } |
| 755 | |
| 756 | #[test] |
| 757 | fn model_bound_tool_results_keep_ordinary_code_byte_exact() { |
| 758 | // #5546: key-only hits in source files must reach the model unchanged |
| 759 | // so exact-match edits and read-back verification keep working. |
| 760 | let client = client_with_config_secret_sentinels(); |
| 761 | let source = "\ |
| 762 | \"jsonwebtoken\": \"^9.0.2\", |
| 763 | password: credentials?.password, |
| 764 | token = generate_verification_token() |
| 765 | secret: process.env.NEXTAUTH_SECRET!, |
| 766 | {\"id\":1, \"password\": \"x\", \"language\": \"en\"} |
| 767 | "; |
| 768 | let prepared = client.prepare_model_bound_request(request_with_tool_result(source.to_string())); |
| 769 | assert_eq!(tool_result_content(&prepared), source); |
| 770 | |
| 771 | // A configured credential and a credential-shaped value are still hidden. |
| 772 | let leaking = format!( |
| 773 | "api_key = \"{}\"\nsession = \"{}\"\n", |
| 774 | CONFIG_SECRET_SENTINELS[0], |
| 775 | ["sk-", "abcdef1234567890abcdef"].concat() |
| 776 | ); |
| 777 | let prepared = client.prepare_model_bound_request(request_with_tool_result(leaking)); |
| 778 | let content = tool_result_content(&prepared); |
| 779 | assert!(!content.contains(CONFIG_SECRET_SENTINELS[0])); |
| 780 | assert!(!content.contains("abcdef1234567890abcdef")); |
| 781 | assert_eq!( |
| 782 | content |
| 783 | .matches(codewhale_config::persistence::REDACTED) |
| 784 | .count(), |
| 785 | 2 |
| 786 | ); |
| 787 | } |
| 788 | |
| 789 | #[test] |
| 790 | fn model_bound_scenario() { |
| 791 | // Scenario consolidation of: model_bound_request_redacts_configured_secrets_and_bare_active_key, model_bound_request_leaves_ordinary_tool_output_unchanged |
| 792 | // from model_bound_request_redacts_configured_secrets_and_bare_active_key |
| 793 | { |
| 794 | let client = client_with_config_secret_sentinels(); |
| 795 | let config_dump = format!( |
| 796 | "api_key = \"{}\"\n[providers.arcee]\napi_key = \"{}\"\n\ |
| 797 | ordinary_setting = \"keep-me\"\nall bare values: {}", |
| 798 | CONFIG_SECRET_SENTINELS[0], |
| 799 | CONFIG_SECRET_SENTINELS[1], |
| 800 | CONFIG_SECRET_SENTINELS.join(" ") |
| 801 | ); |
| 802 | |
| 803 | let prepared = client.prepare_model_bound_request(request_with_tool_result(config_dump)); |
| 804 | let content = tool_result_content(&prepared); |
| 805 | |
| 806 | for secret in CONFIG_SECRET_SENTINELS { |
| 807 | assert!(!content.contains(secret), "secret survived redaction"); |
| 808 | } |
| 809 | assert!(content.contains(codewhale_config::persistence::REDACTED)); |
| 810 | assert!(content.contains("ordinary_setting")); |
| 811 | assert!(content.contains("keep-me")); |
| 812 | } |
| 813 | // from model_bound_request_leaves_ordinary_tool_output_unchanged |
| 814 | { |
| 815 | let client = client_with_config_secret_sentinels(); |
| 816 | let ordinary = "tests passed: 42\nREADME.md updated\n"; |
| 817 | let prepared = |
| 818 | client.prepare_model_bound_request(request_with_tool_result(ordinary.to_string())); |
| 819 | assert_eq!(tool_result_content(&prepared), ordinary); |
| 820 | } |
| 821 | } |
| 822 | |
| 823 | /// The `[redaction] model_bound = "disabled"` opt-out, once confirmed on |
| 824 | /// the startup gate, must let the model see tool output byte-for-byte — |
| 825 | /// including configured secrets and credential-shaped values that the |
| 826 | /// default masking would have removed (#5546 keeps code quotable; this |
| 827 | /// opt-out goes further and keeps credentials quotable too). |
| 828 | #[test] |
| 829 | fn confirmed_opt_out_keeps_configured_secrets_visible_to_the_model() { |
| 830 | let _env_lock = crate::test_support::lock_test_env(); |
| 831 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 832 | let home = tmp.path().join("home"); |
| 833 | std::fs::create_dir_all(&home).expect("create isolated home"); |
| 834 | let _home = crate::test_support::EnvVarGuard::set("HOME", &home); |
| 835 | let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 836 | let codewhale_home = tmp.path().join("codewhale-home"); |
| 837 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 838 | std::fs::create_dir_all(&codewhale_home).expect("create config home"); |
| 839 | std::fs::write( |
| 840 | codewhale_home.join("config.toml"), |
| 841 | "[redaction]\nmodel_bound = \"disabled\"\n", |
| 842 | ) |
| 843 | .expect("write opt-out request"); |
| 844 | codewhale_config::redaction::record_model_bound_disabled_confirmation( |
| 845 | &codewhale_home.join("config.toml"), |
| 846 | ) |
| 847 | .expect("record opt-out confirmation"); |
| 848 | |
| 849 | let client = CodewhaleClient::new( |
| 850 | &{ |
| 851 | let __cw_config_init_5_0 = Some(codewhale_home.join("config.toml")); |
| 852 | let __cw_config_init_5_1 = Some("zai".to_string()); |
| 853 | let __cw_config_init_5_2 = Some(ProvidersConfig { |
| 854 | zai: ProviderConfig { |
| 855 | api_key: Some(CONFIG_SECRET_SENTINELS[6].to_string()), |
| 856 | ..ProviderConfig::default() |
| 857 | }, |
| 858 | ..ProvidersConfig::default() |
| 859 | }); |
| 860 | let __cw_config_init_5_3 = Some(codewhale_config::redaction::RedactionToml { |
| 861 | model_bound: Some(codewhale_config::redaction::ModelBoundMasking::Disabled), |
| 862 | }); |
| 863 | let mut __cw_config_init_5_value: Config = Config::default(); |
| 864 | __cw_config_init_5_value.loaded_config_path = __cw_config_init_5_0; |
| 865 | __cw_config_init_5_value.provider = __cw_config_init_5_1; |
| 866 | __cw_config_init_5_value.providers = __cw_config_init_5_2; |
| 867 | __cw_config_init_5_value.redaction = __cw_config_init_5_3; |
| 868 | __cw_config_init_5_value |
| 869 | } |
| 870 | .with_legacy_root(Some(CONFIG_SECRET_SENTINELS[0].to_string()), None), |
| 871 | ) |
| 872 | .expect("client with confirmed opt-out"); |
| 873 | |
| 874 | let tool_output = format!( |
| 875 | "api_key = \"{}\"\n[providers.arcee]\napi_key = \"{}\"\nbearer {}", |
| 876 | CONFIG_SECRET_SENTINELS[0], CONFIG_SECRET_SENTINELS[1], CONFIG_SECRET_SENTINELS[3] |
| 877 | ); |
| 878 | let prepared = |
| 879 | client.prepare_model_bound_request(request_with_tool_result(tool_output.clone())); |
| 880 | assert_eq!( |
| 881 | tool_result_content(&prepared), |
| 882 | tool_output, |
| 883 | "a confirmed opt-out must keep tool output byte-exact" |
| 884 | ); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn redaction_confirmation_follows_explicit_and_environment_config_loading() { |
| 889 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 890 | let _lock = lock_test_env(); |
| 891 | let temp = tempfile::tempdir().unwrap(); |
| 892 | let _home = EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 893 | let default = temp.path().join("config.toml"); |
| 894 | let custom = temp.path().join("selected.toml"); |
| 895 | let body = format!( |
| 896 | "provider = \"zai\"\n[providers.zai]\napi_key = \"{}\"\n[redaction]\nmodel_bound = \"disabled\"\n", |
| 897 | CONFIG_SECRET_SENTINELS[6] |
| 898 | ); |
| 899 | std::fs::write(&default, &body).unwrap(); |
| 900 | std::fs::write(&custom, &body).unwrap(); |
| 901 | codewhale_config::redaction::record_model_bound_disabled_confirmation(&default).unwrap(); |
| 902 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &custom); |
| 903 | let _legacy_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 904 | let tool_output = format!("api_key = \"{}\"", CONFIG_SECRET_SENTINELS[6]); |
| 905 | for explicit in [Some(custom.clone()), None] { |
| 906 | let config = codewhale_plugins::providers::load_config(explicit, None).unwrap(); |
| 907 | assert_eq!( |
| 908 | config |
| 909 | .loaded_config_path |
| 910 | .as_ref() |
| 911 | .unwrap() |
| 912 | .canonicalize() |
| 913 | .unwrap(), |
| 914 | custom.canonicalize().unwrap() |
| 915 | ); |
| 916 | assert!(config.redaction_confirmation_required()); |
| 917 | let client = CodewhaleClient::new(&config).unwrap(); |
| 918 | let prepared = |
| 919 | client.prepare_model_bound_request(request_with_tool_result(tool_output.clone())); |
| 920 | assert!(!tool_result_content(&prepared).contains(CONFIG_SECRET_SENTINELS[6])); |
| 921 | } |
| 922 | let config = codewhale_plugins::providers::load_config(None, None).unwrap(); |
| 923 | config.record_redaction_confirmation().unwrap(); |
| 924 | for explicit in [Some(custom.clone()), None] { |
| 925 | let config = codewhale_plugins::providers::load_config(explicit, None).unwrap(); |
| 926 | assert!(!config.redaction_confirmation_required()); |
| 927 | let client = CodewhaleClient::new(&config).unwrap(); |
| 928 | let prepared = |
| 929 | client.prepare_model_bound_request(request_with_tool_result(tool_output.clone())); |
| 930 | assert_eq!(tool_result_content(&prepared), tool_output); |
| 931 | } |
| 932 | // Local provenance is never accepted from serialized configuration. |
| 933 | let decoded: Config = |
| 934 | toml::from_str("loaded_config_path = \"/untrusted/config.toml\"\n").unwrap(); |
| 935 | assert!(decoded.loaded_config_path.is_none()); |
| 936 | } |
| 937 | |
| 938 | /// Without a confirmation receipt the same config request stays masked: |
| 939 | /// the gate is what separates a wish from an effective opt-out. |
| 940 | #[test] |
| 941 | fn unconfirmed_opt_out_request_stays_masked() { |
| 942 | let _env_lock = crate::test_support::lock_test_env(); |
| 943 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 944 | let home = tmp.path().join("home"); |
| 945 | std::fs::create_dir_all(&home).expect("create isolated home"); |
| 946 | let _home = crate::test_support::EnvVarGuard::set("HOME", &home); |
| 947 | let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 948 | let codewhale_home = tmp.path().join("codewhale-home"); |
| 949 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 950 | |
| 951 | let client = CodewhaleClient::new( |
| 952 | &{ |
| 953 | let __cw_config_init_6_0 = Some("zai".to_string()); |
| 954 | let __cw_config_init_6_1 = Some(ProvidersConfig { |
| 955 | zai: ProviderConfig { |
| 956 | api_key: Some(CONFIG_SECRET_SENTINELS[6].to_string()), |
| 957 | ..ProviderConfig::default() |
| 958 | }, |
| 959 | ..ProvidersConfig::default() |
| 960 | }); |
| 961 | let __cw_config_init_6_2 = Some(codewhale_config::redaction::RedactionToml { |
| 962 | model_bound: Some(codewhale_config::redaction::ModelBoundMasking::Disabled), |
| 963 | }); |
| 964 | let mut __cw_config_init_6_value: Config = Config::default(); |
| 965 | __cw_config_init_6_value.provider = __cw_config_init_6_0; |
| 966 | __cw_config_init_6_value.providers = __cw_config_init_6_1; |
| 967 | __cw_config_init_6_value.redaction = __cw_config_init_6_2; |
| 968 | __cw_config_init_6_value |
| 969 | } |
| 970 | .with_legacy_root(Some(CONFIG_SECRET_SENTINELS[0].to_string()), None), |
| 971 | ) |
| 972 | .expect("client with unconfirmed opt-out request"); |
| 973 | |
| 974 | let secret = CONFIG_SECRET_SENTINELS[0]; |
| 975 | let prepared = client |
| 976 | .prepare_model_bound_request(request_with_tool_result(format!("api_key = \"{secret}\""))); |
| 977 | let content = tool_result_content(&prepared); |
| 978 | assert!( |
| 979 | !content.contains(secret), |
| 980 | "an unconfirmed request must stay on the safe default" |
| 981 | ); |
| 982 | } |
| 983 | |
| 984 | #[test] |
| 985 | fn model_bound_request_redacts_inactive_file_store_and_environment_secrets() { |
| 986 | const FILE_STORED_INACTIVE: &str = "inactive-arcee-file-secret-901"; |
| 987 | const BUILTIN_ENV_SECRET: &str = "inactive-arcee-env-secret-902"; |
| 988 | const CUSTOM_ENV_NAME: &str = "CW_TEST_CUSTOM_PROVIDER_API_KEY"; |
| 989 | const CUSTOM_ENV_SECRET: &str = "inactive-custom-env-secret-903"; |
| 990 | |
| 991 | let _env_lock = crate::test_support::lock_test_env(); |
| 992 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 993 | let codewhale_home = tmp.path().join("codewhale-home"); |
| 994 | let home = tmp.path().join("home"); |
| 995 | std::fs::create_dir_all(&home).expect("create isolated home"); |
| 996 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 997 | let _secret_backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 998 | let _home = crate::test_support::EnvVarGuard::set("HOME", &home); |
| 999 | let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home); |
| 1000 | let builtin_env_name = ProviderKind::Arcee |
| 1001 | .provider() |
| 1002 | .env_vars() |
| 1003 | .first() |
| 1004 | .copied() |
| 1005 | .expect("Arcee API-key environment variable"); |
| 1006 | let _builtin_env = crate::test_support::EnvVarGuard::set(builtin_env_name, BUILTIN_ENV_SECRET); |
| 1007 | let _custom_env = crate::test_support::EnvVarGuard::set(CUSTOM_ENV_NAME, CUSTOM_ENV_SECRET); |
| 1008 | |
| 1009 | codewhale_secrets::Secrets::file_backed() |
| 1010 | .set("arcee", FILE_STORED_INACTIVE) |
| 1011 | .expect("write isolated inactive provider credential"); |
| 1012 | |
| 1013 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1014 | let client = CodewhaleClient::new(&{ |
| 1015 | let __cw_config_init_7_0 = Some("zai".to_string()); |
| 1016 | let __cw_config_init_7_1 = Some(ProvidersConfig { |
| 1017 | zai: ProviderConfig { |
| 1018 | api_key: Some("active-zai-secret-900".to_string()), |
| 1019 | ..ProviderConfig::default() |
| 1020 | }, |
| 1021 | custom: HashMap::from([( |
| 1022 | "example-custom".to_string(), |
| 1023 | ProviderConfig { |
| 1024 | kind: Some("openai-compatible".to_string()), |
| 1025 | api_key_env: Some(CUSTOM_ENV_NAME.to_string()), |
| 1026 | ..ProviderConfig::default() |
| 1027 | }, |
| 1028 | )]), |
| 1029 | ..ProvidersConfig::default() |
| 1030 | }); |
| 1031 | let mut __cw_config_init_7_value: Config = Config::default(); |
| 1032 | __cw_config_init_7_value.provider = __cw_config_init_7_0; |
| 1033 | __cw_config_init_7_value.providers = __cw_config_init_7_1; |
| 1034 | __cw_config_init_7_value |
| 1035 | }) |
| 1036 | .expect("client with inactive file-store credential"); |
| 1037 | let prepared = client.prepare_model_bound_request(request_with_tool_result(format!( |
| 1038 | "retrieved values: {FILE_STORED_INACTIVE} {BUILTIN_ENV_SECRET} {CUSTOM_ENV_SECRET}\nordinary output survives" |
| 1039 | ))); |
| 1040 | let content = tool_result_content(&prepared); |
| 1041 | |
| 1042 | for secret in [FILE_STORED_INACTIVE, BUILTIN_ENV_SECRET, CUSTOM_ENV_SECRET] { |
| 1043 | assert!( |
| 1044 | !content.contains(secret), |
| 1045 | "inactive secret survived redaction" |
| 1046 | ); |
| 1047 | } |
| 1048 | assert!(content.contains(codewhale_config::persistence::REDACTED)); |
| 1049 | assert!(content.contains("ordinary output survives")); |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn whitespace_codewhale_home_does_not_load_ambient_redaction_secrets() { |
| 1054 | let _env_lock = crate::test_support::lock_test_env(); |
| 1055 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1056 | let ambient_home = tmp.path().join("ambient-home"); |
| 1057 | std::fs::create_dir_all(&ambient_home).expect("create ambient home"); |
| 1058 | let _home = crate::test_support::EnvVarGuard::set("HOME", &ambient_home); |
| 1059 | let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &ambient_home); |
| 1060 | let _codewhale_home_unset = crate::test_support::EnvVarGuard::remove("CODEWHALE_HOME"); |
| 1061 | let _secret_backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1062 | codewhale_secrets::Secrets::file_backed() |
| 1063 | .set("arcee", "ambient-redaction-secret-sentinel") |
| 1064 | .expect("seed ambient file secret store"); |
| 1065 | let _whitespace_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", " \t "); |
| 1066 | let mut values = Vec::new(); |
| 1067 | |
| 1068 | push_file_backed_model_bound_secrets(&mut values); |
| 1069 | |
| 1070 | assert!( |
| 1071 | !values |
| 1072 | .iter() |
| 1073 | .any(|value| value == "ambient-redaction-secret-sentinel"), |
| 1074 | "whitespace must not opt tests into reading the ambient secret store" |
| 1075 | ); |
| 1076 | } |
| 1077 | |
| 1078 | #[test] |
| 1079 | fn short_chat_tool_payload_is_redacted_before_wire_serialization() { |
| 1080 | let client = client_with_config_secret_sentinels(); |
| 1081 | let prepared = client.prepare_model_bound_request(request_with_tool_result(format!( |
| 1082 | "active token: {}", |
| 1083 | CONFIG_SECRET_SENTINELS[6] |
| 1084 | ))); |
| 1085 | let wire = build_chat_messages_for_request(&prepared); |
| 1086 | let serialized = serde_json::to_string(&wire).expect("serialize chat wire messages"); |
| 1087 | |
| 1088 | assert!(!serialized.contains(CONFIG_SECRET_SENTINELS[6])); |
| 1089 | assert!(serialized.contains(codewhale_config::persistence::REDACTED)); |
| 1090 | } |
| 1091 | |
| 1092 | #[test] |
| 1093 | fn configured_secret_redaction_reaches_all_protocol_bodies() { |
| 1094 | let client = client_with_config_secret_sentinels(); |
| 1095 | let prepared = client.prepare_model_bound_request(request_with_tool_result(format!( |
| 1096 | "safe output then {}", |
| 1097 | CONFIG_SECRET_SENTINELS[6] |
| 1098 | ))); |
| 1099 | |
| 1100 | let chat = serde_json::to_string(&build_chat_messages_for_request(&prepared)) |
| 1101 | .expect("serialize Chat Completions body"); |
| 1102 | let anthropic = client.build_anthropic_body(&prepared, false).to_string(); |
| 1103 | let responses = |
| 1104 | build_responses_body_for_provider(&prepared, ProviderKind::OpenaiCodex, None).to_string(); |
| 1105 | |
| 1106 | for (route, body) in [ |
| 1107 | ("chat", chat.as_str()), |
| 1108 | ("anthropic", anthropic.as_str()), |
| 1109 | ("responses", responses.as_str()), |
| 1110 | ] { |
| 1111 | assert!( |
| 1112 | !body.contains(CONFIG_SECRET_SENTINELS[6]), |
| 1113 | "{route} body retained the configured credential" |
| 1114 | ); |
| 1115 | assert!( |
| 1116 | body.contains(codewhale_config::persistence::REDACTED), |
| 1117 | "{route} body lost the redaction marker" |
| 1118 | ); |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | // This test deliberately serializes access to process-global spillover |
| 1123 | // state while awaiting the retrieval path. |
| 1124 | #[allow(clippy::await_holding_lock)] |
| 1125 | #[tokio::test] |
| 1126 | async fn retrieved_turn_loop_spillover_is_sanitized_before_model_wire() { |
| 1127 | let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD |
| 1128 | .lock() |
| 1129 | .unwrap_or_else(|err| err.into_inner()); |
| 1130 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1131 | let spillover_root = tmp.path().join(".codewhale").join("tool_outputs"); |
| 1132 | let prior = crate::tools::truncate::set_test_spillover_root(Some(spillover_root.clone())); |
| 1133 | struct Restore(Option<std::path::PathBuf>); |
| 1134 | impl Drop for Restore { |
| 1135 | fn drop(&mut self) { |
| 1136 | crate::tools::truncate::set_test_spillover_root(self.0.take()); |
| 1137 | } |
| 1138 | } |
| 1139 | let _restore = Restore(prior); |
| 1140 | |
| 1141 | let head = (0..40) |
| 1142 | .map(|_| format!("{}\n", "safe-head".repeat(100))) |
| 1143 | .collect::<String>(); |
| 1144 | let tail = (0..80) |
| 1145 | .map(|_| format!("{}\n", "safe-tail".repeat(100))) |
| 1146 | .collect::<String>(); |
| 1147 | let raw = format!("{head}\n{}\n{tail}", CONFIG_SECRET_SENTINELS[6]); |
| 1148 | assert!( |
| 1149 | raw.len() > crate::tools::truncate::SPILLOVER_THRESHOLD_BYTES, |
| 1150 | "fixture must enter turn-loop spillover" |
| 1151 | ); |
| 1152 | |
| 1153 | let mut spilled = crate::tools::spec::ToolResult::success(raw.clone()); |
| 1154 | let path = crate::tools::truncate::apply_spillover(&mut spilled, "call-local-secret") |
| 1155 | .expect("turn-loop spillover"); |
| 1156 | crate::tools::truncate::publish_legacy_spillover_ownership(&path, "workspace", raw.as_bytes()) |
| 1157 | .expect("publish compatibility ownership proof"); |
| 1158 | assert_eq!(path.parent(), Some(spillover_root.as_path())); |
| 1159 | assert!( |
| 1160 | std::fs::read_to_string(&path) |
| 1161 | .expect("read local spillover") |
| 1162 | .contains(CONFIG_SECRET_SENTINELS[6]), |
| 1163 | "the full raw result remains available only in the local spillover store" |
| 1164 | ); |
| 1165 | assert!( |
| 1166 | !spilled.content.contains(CONFIG_SECRET_SENTINELS[6]), |
| 1167 | "middle-only secret should not be present in retained head/tail" |
| 1168 | ); |
| 1169 | |
| 1170 | let context = crate::tools::spec::ToolContext::new(tmp.path().to_path_buf()); |
| 1171 | let retrieved = crate::tools::spec::ToolSpec::execute( |
| 1172 | &crate::tools::tool_result_retrieval::RetrieveToolResultTool, |
| 1173 | json!({ |
| 1174 | "ref": "call-local-secret", |
| 1175 | "mode": "query", |
| 1176 | "query": CONFIG_SECRET_SENTINELS[6], |
| 1177 | }), |
| 1178 | &context, |
| 1179 | ) |
| 1180 | .await |
| 1181 | .expect("retrieve secret-bearing local spillover slice"); |
| 1182 | assert!(retrieved.content.contains(CONFIG_SECRET_SENTINELS[6])); |
| 1183 | |
| 1184 | let client = client_with_config_secret_sentinels(); |
| 1185 | let prepared = client.prepare_model_bound_request(request_with_tool_result(retrieved.content)); |
| 1186 | let wire = serde_json::to_string(&build_chat_messages_for_request(&prepared)) |
| 1187 | .expect("serialize sanitized retrieval result"); |
| 1188 | assert!(!wire.contains(CONFIG_SECRET_SENTINELS[6])); |
| 1189 | assert!(wire.contains(codewhale_config::persistence::REDACTED)); |
| 1190 | } |
| 1191 | |
| 1192 | #[test] |
| 1193 | fn wire_adapter_does_not_persist_sessionless_sha_spillover() { |
| 1194 | let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD |
| 1195 | .lock() |
| 1196 | .unwrap_or_else(|err| err.into_inner()); |
| 1197 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1198 | let prior = crate::tools::truncate::set_test_spillover_root(Some( |
| 1199 | tmp.path().join(".codewhale").join("tool_outputs"), |
| 1200 | )); |
| 1201 | struct Restore(Option<std::path::PathBuf>); |
| 1202 | impl Drop for Restore { |
| 1203 | fn drop(&mut self) { |
| 1204 | crate::tools::truncate::set_test_spillover_root(self.0.take()); |
| 1205 | } |
| 1206 | } |
| 1207 | let _restore = Restore(prior); |
| 1208 | |
| 1209 | let client = client_with_config_secret_sentinels(); |
| 1210 | let raw = format!( |
| 1211 | "{}\ncredential={}\n{}", |
| 1212 | "ordinary output ".repeat(80), |
| 1213 | CONFIG_SECRET_SENTINELS[6], |
| 1214 | "tail ".repeat(80) |
| 1215 | ); |
| 1216 | assert!(raw.len() > 1024, "fixture must enter wire dedup size class"); |
| 1217 | let raw_sha = codewhale_runtime::hashing::sha256_hex(raw.as_bytes()); |
| 1218 | let prepared = client.prepare_model_bound_request(request_with_tool_result(raw)); |
| 1219 | let sanitized = tool_result_content(&prepared).to_string(); |
| 1220 | let sanitized_sha = codewhale_runtime::hashing::sha256_hex(sanitized.as_bytes()); |
| 1221 | |
| 1222 | let wire = build_chat_messages_for_request(&prepared); |
| 1223 | let serialized = serde_json::to_string(&wire).expect("serialize chat wire messages"); |
| 1224 | assert!(!serialized.contains(CONFIG_SECRET_SENTINELS[6])); |
| 1225 | |
| 1226 | let sanitized_path = crate::tools::truncate::sha_spillover_path(&sanitized_sha) |
| 1227 | .expect("sanitized spillover path"); |
| 1228 | assert!( |
| 1229 | !sanitized_path.exists(), |
| 1230 | "sessionless wire fallback must not create an ownerless SHA artifact" |
| 1231 | ); |
| 1232 | |
| 1233 | let raw_path = |
| 1234 | crate::tools::truncate::sha_spillover_path(&raw_sha).expect("raw spillover path"); |
| 1235 | assert!( |
| 1236 | !raw_path.exists(), |
| 1237 | "unsanitized tool output must never be persisted by the wire adapter" |
| 1238 | ); |
| 1239 | assert!(!serialized.contains("retrieve_tool_result ref=sha:")); |
| 1240 | } |
| 1241 | |
| 1242 | fn deepseek_anthropic_client(server: &MockServer) -> CodewhaleClient { |
| 1243 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1244 | let providers = ProvidersConfig { |
| 1245 | deepseek_anthropic: ProviderConfig { |
| 1246 | api_key: Some("ds-test".to_string()), |
| 1247 | base_url: Some(server.uri()), |
| 1248 | ..ProviderConfig::default() |
| 1249 | }, |
| 1250 | ..ProvidersConfig::default() |
| 1251 | }; |
| 1252 | CodewhaleClient::new(&{ |
| 1253 | let __cw_config_init_8_0 = Some("deepseek-anthropic".to_string()); |
| 1254 | let __cw_config_init_8_1 = Some(providers); |
| 1255 | let mut __cw_config_init_8_value: Config = Config::default(); |
| 1256 | __cw_config_init_8_value.provider = __cw_config_init_8_0; |
| 1257 | __cw_config_init_8_value.providers = __cw_config_init_8_1; |
| 1258 | __cw_config_init_8_value |
| 1259 | }) |
| 1260 | .expect("deepseek anthropic client") |
| 1261 | } |
| 1262 | |
| 1263 | fn minimax_anthropic_client_with_base_url(base_url: String) -> CodewhaleClient { |
| 1264 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1265 | let providers = ProvidersConfig { |
| 1266 | minimax_anthropic: ProviderConfig { |
| 1267 | api_key: Some("minimax-test".to_string()), |
| 1268 | base_url: Some(base_url), |
| 1269 | ..ProviderConfig::default() |
| 1270 | }, |
| 1271 | ..ProvidersConfig::default() |
| 1272 | }; |
| 1273 | CodewhaleClient::new(&{ |
| 1274 | let __cw_config_init_9_0 = Some("minimax-anthropic".to_string()); |
| 1275 | let __cw_config_init_9_1 = Some(providers); |
| 1276 | let mut __cw_config_init_9_value: Config = Config::default(); |
| 1277 | __cw_config_init_9_value.provider = __cw_config_init_9_0; |
| 1278 | __cw_config_init_9_value.providers = __cw_config_init_9_1; |
| 1279 | __cw_config_init_9_value |
| 1280 | }) |
| 1281 | .expect("minimax anthropic client") |
| 1282 | } |
| 1283 | |
| 1284 | fn zai_client_for_test() -> CodewhaleClient { |
| 1285 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1286 | let providers = ProvidersConfig { |
| 1287 | zai: ProviderConfig { |
| 1288 | api_key: Some("zai-test".to_string()), |
| 1289 | base_url: Some("https://api.z.ai/api/coding/paas/v4".to_string()), |
| 1290 | ..ProviderConfig::default() |
| 1291 | }, |
| 1292 | ..ProvidersConfig::default() |
| 1293 | }; |
| 1294 | CodewhaleClient::new(&{ |
| 1295 | let __cw_config_init_10_0 = Some("zai".to_string()); |
| 1296 | let __cw_config_init_10_1 = Some(providers); |
| 1297 | let mut __cw_config_init_10_value: Config = Config::default(); |
| 1298 | __cw_config_init_10_value.provider = __cw_config_init_10_0; |
| 1299 | __cw_config_init_10_value.providers = __cw_config_init_10_1; |
| 1300 | __cw_config_init_10_value |
| 1301 | }) |
| 1302 | .expect("zai client") |
| 1303 | } |
| 1304 | |
| 1305 | fn runtime_chat_gate_client(isolated: bool, unrelated: bool) -> CodewhaleClient { |
| 1306 | CodewhaleClient::new(&{ |
| 1307 | let __cw_config_init_11_0 = Some("ollama".to_string()); |
| 1308 | let __cw_config_init_11_1 = Some("fixture-local:tag".to_string()); |
| 1309 | let __cw_config_init_11_2 = isolated; |
| 1310 | let __cw_config_init_11_3 = unrelated; |
| 1311 | let mut __cw_config_init_11_value: Config = Config::default(); |
| 1312 | __cw_config_init_11_value.provider = __cw_config_init_11_0; |
| 1313 | __cw_config_init_11_value.default_text_model = __cw_config_init_11_1; |
| 1314 | __cw_config_init_11_value.runtime_chat_isolated = __cw_config_init_11_2; |
| 1315 | __cw_config_init_11_value.runtime_thread_inference_unrelated = __cw_config_init_11_3; |
| 1316 | __cw_config_init_11_value |
| 1317 | }) |
| 1318 | .expect("runtime chat gate test client") |
| 1319 | } |
| 1320 | |
| 1321 | #[tokio::test] |
| 1322 | async fn runtime_chat_provider_gate_blocks_only_attached_run_participants() { |
| 1323 | let participant = runtime_chat_gate_client(false, false); |
| 1324 | let participant_clone = participant.clone(); |
| 1325 | assert!(participant.remote_control_inference_participant); |
| 1326 | assert!(participant_clone.remote_control_inference_participant); |
| 1327 | assert!( |
| 1328 | !runtime_chat_gate_client(true, false).remote_control_inference_participant, |
| 1329 | "the isolated relay client must not deadlock on its own exclusive lease" |
| 1330 | ); |
| 1331 | assert!( |
| 1332 | !runtime_chat_gate_client(false, true).remote_control_inference_participant, |
| 1333 | "an unrelated RuntimeThreadManager must remain concurrent" |
| 1334 | ); |
| 1335 | |
| 1336 | let ownership = acquire_runtime_chat_inference_ownership().await; |
| 1337 | let waiting = tokio::spawn(async move { |
| 1338 | participant_clone |
| 1339 | .acquire_remote_control_inference_permit() |
| 1340 | .await |
| 1341 | }); |
| 1342 | let mut waiting = waiting; |
| 1343 | assert!( |
| 1344 | tokio::time::timeout(Duration::from_millis(40), &mut waiting) |
| 1345 | .await |
| 1346 | .is_err(), |
| 1347 | "an attached-run provider call must wait behind Runtime Chat ownership" |
| 1348 | ); |
| 1349 | assert!( |
| 1350 | runtime_chat_gate_client(true, false) |
| 1351 | .acquire_remote_control_inference_permit() |
| 1352 | .await |
| 1353 | .is_none() |
| 1354 | ); |
| 1355 | assert!( |
| 1356 | runtime_chat_gate_client(false, true) |
| 1357 | .acquire_remote_control_inference_permit() |
| 1358 | .await |
| 1359 | .is_none() |
| 1360 | ); |
| 1361 | drop(ownership); |
| 1362 | assert!( |
| 1363 | tokio::time::timeout(Duration::from_secs(1), waiting) |
| 1364 | .await |
| 1365 | .expect("participant should resume") |
| 1366 | .expect("permit task") |
| 1367 | .is_some() |
| 1368 | ); |
| 1369 | } |
| 1370 | |
| 1371 | #[tokio::test] |
| 1372 | async fn provider_request_scenario() { |
| 1373 | // Scenario consolidation of: provider_request_concurrency_limiter_is_shared_across_client_clones, provider_request_permit_lives_until_stream_is_consumed |
| 1374 | // from provider_request_concurrency_limiter_is_shared_across_client_clones |
| 1375 | { |
| 1376 | let client = zai_client_for_test(); |
| 1377 | assert_eq!( |
| 1378 | client.provider_request_concurrency_limit(), |
| 1379 | Some(codewhale_runtime::config::DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY) |
| 1380 | ); |
| 1381 | |
| 1382 | let clone = client.clone(); |
| 1383 | let permit = client |
| 1384 | .acquire_provider_request_permit() |
| 1385 | .await |
| 1386 | .expect("zai default should install provider request limiter"); |
| 1387 | |
| 1388 | assert_eq!(client.active_provider_requests(), 1); |
| 1389 | assert_eq!(clone.active_provider_requests(), 1); |
| 1390 | |
| 1391 | drop(permit); |
| 1392 | |
| 1393 | assert_eq!(client.active_provider_requests(), 0); |
| 1394 | assert_eq!(clone.active_provider_requests(), 0); |
| 1395 | } |
| 1396 | // from provider_request_permit_lives_until_stream_is_consumed |
| 1397 | { |
| 1398 | let client = zai_client_for_test(); |
| 1399 | let permit = client |
| 1400 | .acquire_provider_request_permit() |
| 1401 | .await |
| 1402 | .expect("zai default should install provider request limiter"); |
| 1403 | let stream: crate::llm_client::StreamEventBox = |
| 1404 | Box::pin(futures_util::stream::iter(vec![Ok( |
| 1405 | StreamEvent::MessageStop, |
| 1406 | )])); |
| 1407 | let mut wrapped = |
| 1408 | CodewhaleClient::hold_provider_request_permit_for_stream(stream, Some(permit)); |
| 1409 | |
| 1410 | assert_eq!(client.active_provider_requests(), 1); |
| 1411 | assert!(wrapped.next().await.is_some()); |
| 1412 | assert!(wrapped.next().await.is_none()); |
| 1413 | assert_eq!(client.active_provider_requests(), 0); |
| 1414 | } |
| 1415 | } |
| 1416 | |
| 1417 | #[tokio::test] |
| 1418 | async fn runtime_chat_read_permit_lives_until_stream_is_dropped() { |
| 1419 | let client = runtime_chat_gate_client(false, false); |
| 1420 | let permit = client |
| 1421 | .acquire_remote_control_inference_permit() |
| 1422 | .await |
| 1423 | .expect("interactive participant read permit"); |
| 1424 | let stream: crate::llm_client::StreamEventBox = Box::pin(futures_util::stream::pending()); |
| 1425 | let wrapped = |
| 1426 | CodewhaleClient::hold_remote_control_inference_permit_for_stream(stream, Some(permit)); |
| 1427 | |
| 1428 | let mut writer = tokio::spawn(acquire_runtime_chat_inference_ownership()); |
| 1429 | assert!( |
| 1430 | tokio::time::timeout(Duration::from_millis(40), &mut writer) |
| 1431 | .await |
| 1432 | .is_err(), |
| 1433 | "a live participant stream must retain attached-run ownership through EOF/drop" |
| 1434 | ); |
| 1435 | drop(wrapped); |
| 1436 | let ownership = tokio::time::timeout(Duration::from_secs(1), writer) |
| 1437 | .await |
| 1438 | .expect("writer resumes after stream drop") |
| 1439 | .expect("writer task"); |
| 1440 | drop(ownership); |
| 1441 | } |
| 1442 | |
| 1443 | #[test] |
| 1444 | fn parse_speech_scenario() { |
| 1445 | // Scenario consolidation of: parse_speech_audio_response_accepts_message_audio, parse_speech_audio_response_accepts_data_uri |
| 1446 | // from parse_speech_audio_response_accepts_message_audio |
| 1447 | { |
| 1448 | let encoded = general_purpose::STANDARD.encode(b"hi"); |
| 1449 | let payload = json!({ |
| 1450 | "choices": [{ |
| 1451 | "message": { |
| 1452 | "audio": { |
| 1453 | "data": encoded, |
| 1454 | "transcript": "hi" |
| 1455 | } |
| 1456 | } |
| 1457 | }] |
| 1458 | }); |
| 1459 | |
| 1460 | let (audio, transcript) = parse_speech_audio_response(&payload).unwrap(); |
| 1461 | assert_eq!(audio, b"hi"); |
| 1462 | assert_eq!(transcript.as_deref(), Some("hi")); |
| 1463 | } |
| 1464 | // from parse_speech_audio_response_accepts_data_uri |
| 1465 | { |
| 1466 | let encoded = general_purpose::STANDARD.encode(b"wav"); |
| 1467 | let payload = json!({ |
| 1468 | "audio": { |
| 1469 | "data": format!("data:audio/wav;base64,{encoded}") |
| 1470 | } |
| 1471 | }); |
| 1472 | |
| 1473 | let (audio, transcript) = parse_speech_audio_response(&payload).unwrap(); |
| 1474 | assert_eq!(audio, b"wav"); |
| 1475 | assert_eq!(transcript, None); |
| 1476 | } |
| 1477 | } |
| 1478 | |
| 1479 | #[test] |
| 1480 | fn speech_synthesis_scenario() { |
| 1481 | // Scenario consolidation of: speech_synthesis_body_omits_user_message_without_instruction, speech_synthesis_body_ignores_blank_instruction, speech_synthesis_body_includes_non_empty_instruction_first |
| 1482 | // from speech_synthesis_body_omits_user_message_without_instruction |
| 1483 | { |
| 1484 | let body = |
| 1485 | build_speech_synthesis_body("mimo-v2.5-tts", "hello", None, json!({"format": "wav"})); |
| 1486 | let messages = body["messages"].as_array().expect("messages array"); |
| 1487 | |
| 1488 | assert_eq!(messages.len(), 1); |
| 1489 | assert_eq!(messages[0]["role"], "assistant"); |
| 1490 | assert_eq!(messages[0]["content"], "hello"); |
| 1491 | assert!( |
| 1492 | messages |
| 1493 | .iter() |
| 1494 | .all(|message| message["content"].as_str() != Some("")) |
| 1495 | ); |
| 1496 | } |
| 1497 | // from speech_synthesis_body_ignores_blank_instruction |
| 1498 | { |
| 1499 | let body = build_speech_synthesis_body( |
| 1500 | "mimo-v2.5-tts", |
| 1501 | "hello", |
| 1502 | Some(" \t\n "), |
| 1503 | json!({"format": "wav"}), |
| 1504 | ); |
| 1505 | let messages = body["messages"].as_array().expect("messages array"); |
| 1506 | |
| 1507 | assert_eq!(messages.len(), 1); |
| 1508 | assert_eq!(messages[0]["role"], "assistant"); |
| 1509 | } |
| 1510 | // from speech_synthesis_body_includes_non_empty_instruction_first |
| 1511 | { |
| 1512 | let body = build_speech_synthesis_body( |
| 1513 | "mimo-v2.5-tts-voicedesign", |
| 1514 | "hello", |
| 1515 | Some("warm and calm"), |
| 1516 | json!({"format": "wav"}), |
| 1517 | ); |
| 1518 | let messages = body["messages"].as_array().expect("messages array"); |
| 1519 | |
| 1520 | assert_eq!(messages.len(), 2); |
| 1521 | assert_eq!(messages[0]["role"], "user"); |
| 1522 | assert_eq!(messages[0]["content"], "warm and calm"); |
| 1523 | assert_eq!(messages[1]["role"], "assistant"); |
| 1524 | assert_eq!(messages[1]["content"], "hello"); |
| 1525 | } |
| 1526 | } |
| 1527 | |
| 1528 | #[test] |
| 1529 | fn tool_name_scenario() { |
| 1530 | // Scenario consolidation of: tool_name_roundtrip_dot, tool_name_decode_mangled_dot_prefix, tool_name_decode_bare_hex_no_trailing_dash, tool_name_bare_hex_preserves_alnum, tool_name_bare_hex_preserves_underscore, tool_name_roundtrip_colon |
| 1531 | // from tool_name_roundtrip_dot |
| 1532 | { |
| 1533 | let original = "multi_tool_use.parallel"; |
| 1534 | let encoded = to_api_tool_name(original); |
| 1535 | assert_eq!(encoded, "multi_tool_use-x00002E-parallel"); |
| 1536 | let decoded = from_api_tool_name(&encoded); |
| 1537 | assert_eq!(decoded, original); |
| 1538 | } |
| 1539 | // from tool_name_decode_mangled_dot_prefix |
| 1540 | { |
| 1541 | let mangled = "multi_tool_use.x00002E-parallel"; |
| 1542 | let decoded = from_api_tool_name(mangled); |
| 1543 | assert_eq!(decoded, "multi_tool_use..parallel"); |
| 1544 | } |
| 1545 | // from tool_name_decode_bare_hex_no_trailing_dash |
| 1546 | { |
| 1547 | let exact = "foo_x00002Ebar"; |
| 1548 | assert_eq!(from_api_tool_name(exact), exact); |
| 1549 | let mangled = "foo_.x00002Ebar"; |
| 1550 | assert_eq!(from_api_tool_name(mangled), "foo_..bar"); |
| 1551 | } |
| 1552 | // from tool_name_bare_hex_preserves_alnum |
| 1553 | { |
| 1554 | let input = "foox000041bar"; |
| 1555 | let decoded = from_api_tool_name(input); |
| 1556 | assert_eq!(decoded, input); |
| 1557 | } |
| 1558 | // from tool_name_bare_hex_preserves_underscore |
| 1559 | { |
| 1560 | let input = "foox00005Fbar"; |
| 1561 | let decoded = from_api_tool_name(input); |
| 1562 | assert_eq!(decoded, input); |
| 1563 | } |
| 1564 | // from tool_name_roundtrip_colon |
| 1565 | { |
| 1566 | let original = "mcp__server:tool_name"; |
| 1567 | let encoded = to_api_tool_name(original); |
| 1568 | let decoded = from_api_tool_name(&encoded); |
| 1569 | assert_eq!(decoded, original); |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | #[test] |
| 1574 | fn api_url_scenario() { |
| 1575 | // Scenario consolidation of: api_url_handles_default_v1_and_beta_base_urls, api_url_routes_beta_paths_from_any_deepseek_base, api_url_with_suffix_strips_version_before_chat_suffix, api_url_with_suffix_handles_leading_slash, api_url_with_suffix_ignores_suffix_for_models, api_url_with_suffix_ignores_suffix_for_beta_paths, api_url_with_suffix_default_behavior_without_suffix |
| 1576 | // from api_url_handles_default_v1_and_beta_base_urls |
| 1577 | { |
| 1578 | assert_eq!( |
| 1579 | api_url("https://api.deepseek.com", "chat/completions"), |
| 1580 | "https://api.deepseek.com/v1/chat/completions" |
| 1581 | ); |
| 1582 | assert_eq!( |
| 1583 | api_url("https://api.deepseek.com/v1", "chat/completions"), |
| 1584 | "https://api.deepseek.com/v1/chat/completions" |
| 1585 | ); |
| 1586 | // Non-beta paths from a /beta base URL route to /v1. |
| 1587 | // Only paths with an explicit beta/ prefix use the beta surface. |
| 1588 | assert_eq!( |
| 1589 | api_url("https://api.deepseek.com/beta", "chat/completions"), |
| 1590 | "https://api.deepseek.com/v1/chat/completions" |
| 1591 | ); |
| 1592 | assert_eq!( |
| 1593 | api_url( |
| 1594 | "https://openai-compatible.example/api/coding/paas/v4", |
| 1595 | "chat/completions" |
| 1596 | ), |
| 1597 | "https://openai-compatible.example/api/coding/paas/v4/chat/completions" |
| 1598 | ); |
| 1599 | } |
| 1600 | // from api_url_routes_beta_paths_from_any_deepseek_base |
| 1601 | { |
| 1602 | assert_eq!( |
| 1603 | api_url("https://api.deepseek.com", "beta/completions"), |
| 1604 | "https://api.deepseek.com/beta/completions" |
| 1605 | ); |
| 1606 | assert_eq!( |
| 1607 | api_url("https://api.deepseek.com/v1", "beta/completions"), |
| 1608 | "https://api.deepseek.com/beta/completions" |
| 1609 | ); |
| 1610 | assert_eq!( |
| 1611 | api_url("https://api.deepseek.com/beta", "beta/completions"), |
| 1612 | "https://api.deepseek.com/beta/completions" |
| 1613 | ); |
| 1614 | } |
| 1615 | // from api_url_with_suffix_strips_version_before_chat_suffix |
| 1616 | { |
| 1617 | assert_eq!( |
| 1618 | api_url_with_suffix( |
| 1619 | "https://api.example.com/v1", |
| 1620 | "chat/completions", |
| 1621 | Some("/chat/completions") |
| 1622 | ), |
| 1623 | "https://api.example.com/chat/completions" |
| 1624 | ); |
| 1625 | assert_eq!( |
| 1626 | api_url_with_suffix( |
| 1627 | "https://api.example.com/beta", |
| 1628 | "chat/completions", |
| 1629 | Some("/chat/completions") |
| 1630 | ), |
| 1631 | "https://api.example.com/chat/completions" |
| 1632 | ); |
| 1633 | } |
| 1634 | // from api_url_with_suffix_handles_leading_slash |
| 1635 | { |
| 1636 | assert_eq!( |
| 1637 | api_url_with_suffix( |
| 1638 | "https://api.example.com/v1", |
| 1639 | "chat/completions", |
| 1640 | Some("chat/completions") |
| 1641 | ), |
| 1642 | "https://api.example.com/chat/completions" |
| 1643 | ); |
| 1644 | } |
| 1645 | // from api_url_with_suffix_ignores_suffix_for_models |
| 1646 | { |
| 1647 | assert_eq!( |
| 1648 | api_url_with_suffix( |
| 1649 | "https://api.example.com/v1", |
| 1650 | "models", |
| 1651 | Some("/chat/completions") |
| 1652 | ), |
| 1653 | "https://api.example.com/v1/models" |
| 1654 | ); |
| 1655 | } |
| 1656 | // from api_url_with_suffix_ignores_suffix_for_beta_paths |
| 1657 | { |
| 1658 | assert_eq!( |
| 1659 | api_url_with_suffix( |
| 1660 | "https://api.example.com/v1", |
| 1661 | "beta/completions", |
| 1662 | Some("/chat/completions") |
| 1663 | ), |
| 1664 | "https://api.example.com/beta/completions" |
| 1665 | ); |
| 1666 | } |
| 1667 | // from api_url_with_suffix_default_behavior_without_suffix |
| 1668 | { |
| 1669 | assert_eq!( |
| 1670 | api_url_with_suffix("https://api.deepseek.com", "chat/completions", None), |
| 1671 | "https://api.deepseek.com/v1/chat/completions" |
| 1672 | ); |
| 1673 | } |
| 1674 | } |
| 1675 | |
| 1676 | #[test] |
| 1677 | fn api_url_routes_models_and_non_beta_paths_to_v1() { |
| 1678 | // The /models endpoint only exists at /v1/models, never at |
| 1679 | // /beta/models. Non-beta paths from a /beta base URL must |
| 1680 | // still route to /v1. |
| 1681 | assert_eq!( |
| 1682 | api_url("https://api.deepseek.com", "models"), |
| 1683 | "https://api.deepseek.com/v1/models" |
| 1684 | ); |
| 1685 | assert_eq!( |
| 1686 | api_url("https://api.deepseek.com/v1", "models"), |
| 1687 | "https://api.deepseek.com/v1/models" |
| 1688 | ); |
| 1689 | assert_eq!( |
| 1690 | api_url("https://api.deepseek.com/beta", "models"), |
| 1691 | "https://api.deepseek.com/v1/models" |
| 1692 | ); |
| 1693 | assert_eq!( |
| 1694 | api_url("https://api.minimax.io/anthropic", "models"), |
| 1695 | "https://api.minimax.io/anthropic/v1/models" |
| 1696 | ); |
| 1697 | assert_eq!( |
| 1698 | api_url("https://api.minimaxi.com/anthropic", "models"), |
| 1699 | "https://api.minimaxi.com/anthropic/v1/models" |
| 1700 | ); |
| 1701 | // explicit v<N> versions other than /v1 should be preserved |
| 1702 | assert_eq!( |
| 1703 | api_url( |
| 1704 | "https://openai-compatible.example/api/coding/paas/v4", |
| 1705 | "models" |
| 1706 | ), |
| 1707 | "https://openai-compatible.example/api/coding/paas/v4/models" |
| 1708 | ); |
| 1709 | assert_eq!( |
| 1710 | api_url( |
| 1711 | "https://generativelanguage.googleapis.com/v1beta/openai/", |
| 1712 | "models" |
| 1713 | ), |
| 1714 | "https://generativelanguage.googleapis.com/v1beta/openai/models" |
| 1715 | ); |
| 1716 | assert_eq!( |
| 1717 | api_url("https://api.deepinfra.com/v1/openai", "models"), |
| 1718 | "https://api.deepinfra.com/v1/openai/models" |
| 1719 | ); |
| 1720 | assert_eq!( |
| 1721 | api_url("https://api.opper.ai/v3/compat", "models"), |
| 1722 | "https://api.opper.ai/v3/compat/models" |
| 1723 | ); |
| 1724 | } |
| 1725 |