返回 CodeWhale
test_cases_04.rs
根目录 / crates / engine / src / client / test_cases_04.rs
1
2 #[test]
3 fn default_headers_scenario() {
4 // Scenario consolidation of: default_headers_include_custom_headers_when_configured, default_headers_ignore_blank_custom_headers
5 // from default_headers_include_custom_headers_when_configured
6 {
7 let mut extra = HashMap::new();
8 extra.insert("X-Model-Provider-Id".to_string(), "tongyi".to_string());
9 let headers = CodewhaleClient::default_headers("sk-test", &extra).expect("headers");
10 assert_eq!(
11 headers
12 .get("x-model-provider-id")
13 .and_then(|value| value.to_str().ok()),
14 Some("tongyi")
15 );
16 }
17 // from default_headers_ignore_blank_custom_headers
18 {
19 let mut extra = HashMap::new();
20 extra.insert("X-Blank".to_string(), " ".to_string());
21 let headers = CodewhaleClient::default_headers("sk-test", &extra).expect("headers");
22 assert!(headers.get("x-blank").is_none());
23 }
24 }
25
26 #[test]
27 fn disabled_auth_strips_every_auth_header_dialect_at_client_sink() {
28 let mut extra = HashMap::new();
29 extra.insert(
30 "aUtHoRiZaTiOn".to_string(),
31 "Bearer configured-secret".to_string(),
32 );
33 extra.insert("X-API-Key".to_string(), "configured-x-key".to_string());
34 extra.insert("Api-Key".to_string(), "configured-key".to_string());
35 extra.insert(
36 "Proxy-Authorization".to_string(),
37 "Basic configured-proxy-secret".to_string(),
38 );
39 extra.insert(
40 "X-Auth-Token".to_string(),
41 "configured-auth-token".to_string(),
42 );
43 extra.insert(
44 "X-Access-Token".to_string(),
45 "configured-access-token".to_string(),
46 );
47 extra.insert(
48 "X-Goog-Api-Key".to_string(),
49 "configured-google-key".to_string(),
50 );
51 extra.insert("Cookie".to_string(), "session=secret".to_string());
52 extra.insert("X-Route-Metadata".to_string(), "safe".to_string());
53
54 let headers = CodewhaleClient::default_headers_for_provider_with_auth_disabled(
55 "generated-secret",
56 &extra,
57 ProviderKind::Deepseek,
58 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
59 )
60 .expect("headers");
61
62 for name in [
63 "authorization",
64 "x-api-key",
65 "api-key",
66 "proxy-authorization",
67 "x-auth-token",
68 "x-access-token",
69 "x-goog-api-key",
70 "cookie",
71 ] {
72 assert!(headers.get(name).is_none(), "disabled auth leaked {name}");
73 }
74 assert_eq!(
75 headers
76 .get("x-route-metadata")
77 .and_then(|value| value.to_str().ok()),
78 Some("safe")
79 );
80 }
81
82 #[test]
83 fn build_http_client_accepts_default_tls_verification() {
84 let client = CodewhaleClient::build_http_client(
85 "sk-test",
86 &HashMap::new(),
87 ProviderKind::Deepseek,
88 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_BASE_URL,
89 );
90
91 assert!(client.is_ok());
92 }
93
94 #[test]
95 fn client_new_rejects_provider_scoped_tls_skip_verify() {
96 let mut providers = codewhale_runtime::config::ProvidersConfig::default();
97 providers.openai.api_key = Some("sk-test".to_string());
98 providers.openai.base_url = Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL.to_string());
99 providers.openai.insecure_skip_tls_verify = Some(true);
100 let config = {
101 let __cw_config_init_0_0 = Some("openai".to_string());
102 let __cw_config_init_0_1 = Some(providers);
103 let mut __cw_config_init_0_value: Config = Config::default();
104 __cw_config_init_0_value.provider = __cw_config_init_0_0;
105 __cw_config_init_0_value.providers = __cw_config_init_0_1;
106 __cw_config_init_0_value
107 };
108 assert!(config.insecure_skip_tls_verify());
109
110 let err = match CodewhaleClient::new(&config) {
111 Ok(_) => panic!("tls skip verify should be rejected"),
112 Err(err) => err,
113 };
114 let message = err.to_string();
115 assert!(message.contains("cannot be disabled"));
116 assert!(message.contains("SSL_CERT_FILE"));
117 }
118
119 #[test]
120 fn client_stream_idle_timeout_uses_tui_config() {
121 let client = CodewhaleClient::new(
122 &{
123 let __cw_config_init_1_0 = Some(codewhale_runtime::config::TuiConfig {
124 stream_chunk_timeout_secs: Some(777),
125 max_model_steps: None,
126 turn_wall_clock_secs: None,
127 stream_max_content_mb: None,
128 stream_max_duration_secs: None,
129 ..codewhale_runtime::config::TuiConfig::default()
130 });
131 let mut __cw_config_init_1_value: Config = Config::default();
132 __cw_config_init_1_value.tui = __cw_config_init_1_0;
133 __cw_config_init_1_value
134 }
135 .with_legacy_root(Some("sk-test".to_string()), None),
136 )
137 .expect("client");
138
139 assert_eq!(client.stream_idle_timeout, Duration::from_secs(777));
140 }
141
142 #[test]
143 fn xiaomi_mimo_scenario() {
144 // Scenario consolidation of: xiaomi_mimo_token_plan_endpoint_uses_api_key_header, xiaomi_mimo_tp_key_uses_api_key_header_with_custom_base_url, xiaomi_mimo_pay_as_you_go_endpoint_keeps_bearer_header
145 // from xiaomi_mimo_token_plan_endpoint_uses_api_key_header
146 {
147 let headers = CodewhaleClient::default_headers_for_provider(
148 "tp-test",
149 &HashMap::new(),
150 ProviderKind::XiaomiMimo,
151 codewhale_config::descriptors::defaults::DEFAULT_XIAOMI_MIMO_BASE_URL,
152 )
153 .expect("headers");
154
155 assert_eq!(
156 headers.get("api-key").and_then(|value| value.to_str().ok()),
157 Some("tp-test")
158 );
159 assert!(
160 headers.get(AUTHORIZATION).is_none(),
161 "Token Plan requires api-key instead of Authorization Bearer"
162 );
163 }
164 // from xiaomi_mimo_tp_key_uses_api_key_header_with_custom_base_url
165 {
166 let mut extra = HashMap::new();
167 extra.insert("api-key".to_string(), "wrong".to_string());
168 extra.insert("Authorization".to_string(), "Bearer wrong".to_string());
169 let headers = CodewhaleClient::default_headers_for_provider(
170 "tp-custom",
171 &extra,
172 ProviderKind::XiaomiMimo,
173 "https://proxy.example.test/mimo/v1",
174 )
175 .expect("headers");
176
177 assert_eq!(
178 headers.get("api-key").and_then(|value| value.to_str().ok()),
179 Some("tp-custom")
180 );
181 assert!(
182 headers.get(AUTHORIZATION).is_none(),
183 "tp-* Token Plan keys should use api-key auth even through custom gateways"
184 );
185 }
186 // from xiaomi_mimo_pay_as_you_go_endpoint_keeps_bearer_header
187 {
188 let headers = CodewhaleClient::default_headers_for_provider(
189 "sk-test",
190 &HashMap::new(),
191 ProviderKind::XiaomiMimo,
192 codewhale_runtime::config::XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL,
193 )
194 .expect("headers");
195
196 assert_eq!(
197 headers
198 .get(AUTHORIZATION)
199 .and_then(|value| value.to_str().ok()),
200 Some("Bearer sk-test")
201 );
202 assert!(headers.get("api-key").is_none());
203 }
204 }
205
206 #[test]
207 fn openrouter_uses_bearer_header_after_mimo_token_plan_context() {
208 let mut extra = HashMap::new();
209 extra.insert("api-key".to_string(), "wrong".to_string());
210 let headers = CodewhaleClient::default_headers_for_provider(
211 "sk-or-test",
212 &extra,
213 ProviderKind::Openrouter,
214 codewhale_config::descriptors::defaults::DEFAULT_OPENROUTER_BASE_URL,
215 )
216 .expect("headers");
217
218 assert_eq!(
219 headers
220 .get(AUTHORIZATION)
221 .and_then(|value| value.to_str().ok()),
222 Some("Bearer sk-or-test")
223 );
224 assert!(
225 headers.get("api-key").is_none(),
226 "OpenRouter must not inherit Xiaomi MiMo's api-key header dialect"
227 );
228 }
229
230 #[test]
231 fn siliconflow_cn_uses_bearer_header_and_pins_content_type() {
232 let mut extra = HashMap::new();
233 extra.insert("Authorization".to_string(), "Bearer wrong".to_string());
234 extra.insert("Content-Type".to_string(), "text/plain".to_string());
235 let headers = CodewhaleClient::default_headers_for_provider(
236 "sf-cn-test",
237 &extra,
238 ProviderKind::SiliconflowCN,
239 codewhale_config::descriptors::defaults::DEFAULT_SILICONFLOW_CN_BASE_URL,
240 )
241 .expect("headers");
242
243 assert_eq!(
244 headers
245 .get(AUTHORIZATION)
246 .and_then(|value| value.to_str().ok()),
247 Some("Bearer sf-cn-test")
248 );
249 assert_eq!(
250 headers
251 .get(CONTENT_TYPE)
252 .and_then(|value| value.to_str().ok()),
253 Some("application/json")
254 );
255 assert!(headers.get("api-key").is_none());
256 }
257
258 #[tokio::test]
259 async fn opencode_sessions_follow_conversations_and_isolate_unscoped_clients() {
260 let server = MockServer::start().await;
261 Mock::given(method("POST"))
262 .respond_with(ResponseTemplate::new(200))
263 .mount(&server)
264 .await;
265 let client = opencode_go_client_for(&server);
266 async fn observed(client: &CodewhaleClient, server: &MockServer, path: &str) -> String {
267 let request = client.http_client.post(format!("{}{path}", server.uri()));
268 client
269 .dispatch_attempt(request, crate::llm_client::RetryOperation::Inference)
270 .await
271 .unwrap();
272 let calls = server.received_requests().await.unwrap();
273 calls.iter().find(|r| r.url.path() == path).unwrap().headers["x-opencode-session"]
274 .to_str()
275 .unwrap()
276 .to_owned()
277 }
278 let fallback = observed(&client, &server, "/first").await;
279 assert_eq!(observed(&client.clone(), &server, "/clone").await, fallback);
280 assert_ne!(
281 observed(&opencode_go_client_for(&server), &server, "/independent").await,
282 fallback
283 );
284 let parent = opencode_conversation_key("thread-one", None);
285 let child = opencode_conversation_key("thread-one", Some("alice"));
286 assert_ne!(child, parent);
287 assert_ne!(child, opencode_conversation_key("thread-one", Some("bob")));
288 assert_ne!(
289 child,
290 opencode_conversation_key("thread-two", Some("alice"))
291 );
292 let (first, second) = tokio::join!(
293 OPENCODE_CONVERSATION.scope(parent.clone(), observed(&client, &server, "/parent")),
294 OPENCODE_CONVERSATION.scope(child.clone(), observed(&client, &server, "/child"))
295 );
296 assert_eq!(first, parent);
297 assert_eq!(second, child);
298 let resumed = opencode_go_client_for(&server);
299 assert_eq!(
300 OPENCODE_CONVERSATION
301 .scope(
302 opencode_conversation_key("thread-one", None),
303 observed(&resumed, &server, "/resumed")
304 )
305 .await,
306 parent
307 );
308 }
309
310 #[test]
311 fn user_configured_opencode_session_header_wins() {
312 let mut extra = HashMap::new();
313 extra.insert(
314 "x-opencode-session".to_string(),
315 "user-configured-id".to_string(),
316 );
317 let headers = CodewhaleClient::default_headers_for_provider(
318 "configured-key",
319 &extra,
320 ProviderKind::OpencodeGo,
321 "https://opencode.ai/zen/go/v1",
322 )
323 .expect("headers");
324 assert_eq!(
325 headers
326 .get("x-opencode-session")
327 .and_then(|value| value.to_str().ok()),
328 Some("user-configured-id"),
329 "a user-configured x-opencode-session must override the default"
330 );
331 }
332
333 #[test]
334 fn non_opencode_providers_do_not_carry_session_header() {
335 for api_provider in [
336 ProviderKind::Deepseek,
337 ProviderKind::Anthropic,
338 ProviderKind::Openai,
339 ] {
340 let headers = CodewhaleClient::default_headers_for_provider(
341 "configured-key",
342 &HashMap::new(),
343 api_provider,
344 "https://example.invalid/v1",
345 )
346 .expect("headers");
347 assert!(
348 headers.get("x-opencode-session").is_none(),
349 "non-OpenCode provider {api_provider:?} must not send the session header"
350 );
351 }
352 }
353
354 #[test]
355 fn tokenhub_openai_compatible_route_uses_bearer_header() {
356 let mut extra = HashMap::new();
357 extra.insert("api-key".to_string(), "wrong".to_string());
358 extra.insert("x-api-key".to_string(), "wrong".to_string());
359 let headers = CodewhaleClient::default_headers_for_provider(
360 "tokenhub-test",
361 &extra,
362 ProviderKind::Openai,
363 "https://tokenhub.tencentmaas.com/v1",
364 )
365 .expect("headers");
366
367 assert_eq!(
368 headers
369 .get(AUTHORIZATION)
370 .and_then(|value| value.to_str().ok()),
371 Some("Bearer tokenhub-test")
372 );
373 assert!(headers.get("api-key").is_none());
374 assert!(headers.get("x-api-key").is_none());
375 }
376
377 #[test]
378 fn codewhale_authenticates_every_protocol_with_bearer_never_x_api_key() {
379 // The Codewhale API is a passthrough: it authenticates the account key
380 // with `Authorization: Bearer` on the Anthropic Messages route too, so
381 // the usual Messages `x-api-key` default must not apply here.
382 for wire in [
383 WireFormat::ChatCompletions,
384 WireFormat::AnthropicMessages,
385 WireFormat::Responses,
386 ] {
387 let headers = build_default_headers(
388 "cwc_key_test",
389 &HashMap::new(),
390 ProviderKind::Codewhale,
391 "https://api.codewhale.net/v1",
392 wire,
393 false,
394 AuthHeaderSurface::Inference,
395 )
396 .expect("headers");
397 assert_eq!(
398 headers
399 .get(AUTHORIZATION)
400 .and_then(|value| value.to_str().ok()),
401 Some("Bearer cwc_key_test"),
402 "{wire:?}"
403 );
404 assert!(headers.get("x-api-key").is_none(), "{wire:?}");
405 }
406 }
407
408 #[test]
409 fn deepseek_anthropic_uses_anthropic_header_dialect() {
410 let mut extra = HashMap::new();
411 extra.insert("Authorization".to_string(), "Bearer wrong".to_string());
412 extra.insert("api-key".to_string(), "wrong".to_string());
413 let headers = CodewhaleClient::default_headers_for_provider(
414 "ds-test",
415 &extra,
416 ProviderKind::DeepseekAnthropic,
417 codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL,
418 )
419 .expect("headers");
420
421 assert_eq!(
422 headers
423 .get("x-api-key")
424 .and_then(|value| value.to_str().ok()),
425 Some("ds-test")
426 );
427 assert_eq!(
428 headers
429 .get("anthropic-version")
430 .and_then(|value| value.to_str().ok()),
431 Some("2023-06-01")
432 );
433 assert!(
434 headers.get(AUTHORIZATION).is_none(),
435 "Anthropic-compatible DeepSeek route must not use Bearer auth"
436 );
437 assert!(
438 headers.get("api-key").is_none(),
439 "Anthropic-compatible DeepSeek route must not inherit MiMo auth headers"
440 );
441 }
442
443 #[test]
444 fn minimax_anthropic_uses_anthropic_header_dialect() {
445 let headers = CodewhaleClient::default_headers_for_provider(
446 "minimax-test",
447 &HashMap::new(),
448 ProviderKind::MinimaxAnthropic,
449 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL,
450 )
451 .expect("headers");
452
453 assert_eq!(
454 headers
455 .get("x-api-key")
456 .and_then(|value| value.to_str().ok()),
457 Some("minimax-test")
458 );
459 assert_eq!(
460 headers
461 .get("anthropic-version")
462 .and_then(|value| value.to_str().ok()),
463 Some("2023-06-01")
464 );
465 assert!(headers.get(AUTHORIZATION).is_none());
466 }
467
468 #[test]
469 fn openmodel_uses_bearer_auth_with_anthropic_version() {
470 let mut extra = HashMap::new();
471 extra.insert("Authorization".to_string(), "Bearer wrong".to_string());
472 extra.insert("api-key".to_string(), "wrong".to_string());
473 extra.insert("x-api-key".to_string(), "wrong".to_string());
474 let headers = CodewhaleClient::default_headers_for_provider(
475 "om-test",
476 &extra,
477 ProviderKind::Openmodel,
478 codewhale_config::descriptors::defaults::DEFAULT_OPENMODEL_BASE_URL,
479 )
480 .expect("headers");
481
482 assert_eq!(
483 headers
484 .get(AUTHORIZATION)
485 .and_then(|value| value.to_str().ok()),
486 Some("Bearer om-test")
487 );
488 assert_eq!(
489 headers
490 .get("anthropic-version")
491 .and_then(|value| value.to_str().ok()),
492 Some("2023-06-01")
493 );
494 assert!(
495 headers.get("x-api-key").is_none(),
496 "OpenModel uses Bearer auth so /v1/models and /v1/messages share one client"
497 );
498 assert!(
499 headers.get("api-key").is_none(),
500 "OpenModel Messages route must not inherit MiMo auth headers"
501 );
502 }
503
504 #[tokio::test]
505 async fn deepseek_anthropic_translate_uses_messages_endpoint() {
506 // `translate` resolves `max_tokens` when building the request and this
507 // test recomputes the same route allowance when asserting. That value
508 // reads `CODEWHALE_MAX_OUTPUT_TOKENS`/`DEEPSEEK_MAX_OUTPUT_TOKENS` from
509 // the process environment, so a concurrent test that redirects either
510 // variable between the two reads flips one side and fails the
511 // assertion (#5929). Hold the test env barrier for the whole request
512 // so both reads observe one stable environment.
513 let _env_lock = crate::test_support::lock_test_env();
514 let server = MockServer::start().await;
515 Mock::given(method("POST"))
516 .and(path("/v1/messages"))
517 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
518 "id": "msg_1",
519 "type": "message",
520 "role": "assistant",
521 "content": [{"type": "text", "text": "Hola"}],
522 "model": "deepseek-chat",
523 "stop_reason": "end_turn",
524 "stop_sequence": null,
525 "usage": {"input_tokens": 3, "output_tokens": 1}
526 })))
527 .expect(1)
528 .mount(&server)
529 .await;
530
531 let client = deepseek_anthropic_client(&server);
532 let translated = client
533 .translate("Hello", "deepseek-chat", "Spanish")
534 .await
535 .expect("translation succeeds");
536
537 assert_eq!(translated, "Hola");
538 let requests = server.received_requests().await.expect("recorded requests");
539 assert_eq!(requests.len(), 1);
540 let body: Value = serde_json::from_slice(&requests[0].body).expect("json body");
541 assert_eq!(
542 body.get("model").and_then(Value::as_str),
543 Some("deepseek-chat"),
544 "custom Messages endpoints own their model ids: {body}"
545 );
546 assert_eq!(
547 body.pointer("/messages/0/role").and_then(Value::as_str),
548 Some("user")
549 );
550 assert_eq!(
551 body.pointer("/messages/0/content/0/text")
552 .and_then(Value::as_str),
553 Some("Hello")
554 );
555 assert!(
556 body.get("thinking").is_none(),
557 "translation disables thinking: {body}"
558 );
559 assert!(
560 body.get("temperature").is_none() && body.get("top_p").is_none(),
561 "translation must not inject sampling controls: {body}"
562 );
563 assert_eq!(
564 body.get("max_tokens").and_then(Value::as_u64),
565 Some(u64::from(
566 crate::route_budget::effective_max_output_tokens_for_route(
567 ProviderKind::DeepseekAnthropic,
568 "deepseek-chat",
569 None,
570 )
571 )),
572 "translation must inherit its resolved route allowance: {body}"
573 );
574 assert!(
575 body.get("system")
576 .and_then(Value::as_str)
577 .is_some_and(|system| system.contains("Spanish")),
578 "target language should be in system prompt: {body}"
579 );
580 }
581
582 #[tokio::test]
583 async fn deepseek_anthropic_scenario() {
584 // Scenario consolidation of: deepseek_anthropic_health_check_skips_models_probe, deepseek_anthropic_fim_fails_without_http_request
585 // from deepseek_anthropic_health_check_skips_models_probe
586 {
587 let server = MockServer::start().await;
588 let client = deepseek_anthropic_client(&server);
589
590 assert!(client.health_check().await.expect("health check"));
591 assert!(!provider_api_key_verification_is_observed(
592 ProviderKind::DeepseekAnthropic
593 ));
594 let requests = server.received_requests().await.expect("recorded requests");
595 assert!(
596 requests.is_empty(),
597 "DeepSeek Anthropic-compatible route must not probe /models"
598 );
599 }
600 // from deepseek_anthropic_fim_fails_without_http_request
601 {
602 let server = MockServer::start().await;
603 let client = deepseek_anthropic_client(&server);
604
605 let err = client
606 .fim_completion("deepseek-chat", "fn main() {", "}", 16)
607 .await
608 .expect_err("FIM is unsupported");
609 let message = err.to_string();
610 assert!(
611 message.contains("FIM completion is not supported"),
612 "{message}"
613 );
614 assert!(message.contains("no proven FIM wire contract"), "{message}");
615 let requests = server.received_requests().await.expect("recorded requests");
616 assert!(
617 requests.is_empty(),
618 "unsupported FIM should fail locally before any HTTP call"
619 );
620 }
621 }
622
623 #[tokio::test]
624 async fn minimax_anthropic_health_check_uses_models_endpoint() {
625 let server = MockServer::start().await;
626 Mock::given(method("GET"))
627 .and(path("/anthropic/v1/models"))
628 .and(header("x-api-key", "minimax-test"))
629 .and(header("anthropic-version", "2023-06-01"))
630 .respond_with(ResponseTemplate::new(200).set_body_json(json!({"data": []})))
631 .expect(1)
632 .mount(&server)
633 .await;
634 let client = minimax_anthropic_client_with_base_url(format!("{}/anthropic", server.uri()));
635
636 assert!(client.health_check().await.expect("health check"));
637 }
638
639 #[tokio::test]
640 async fn minimax_anthropic_request_uses_messages_endpoint() {
641 let server = MockServer::start().await;
642 Mock::given(method("POST"))
643 .and(path("/anthropic/v1/messages"))
644 .and(header("x-api-key", "minimax-test"))
645 .and(header("anthropic-version", "2023-06-01"))
646 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
647 "id": "msg_1",
648 "type": "message",
649 "role": "assistant",
650 "content": [{"type": "text", "text": "ok"}],
651 "model": "MiniMax-M3",
652 "stop_reason": "end_turn",
653 "stop_sequence": null,
654 "usage": {"input_tokens": 3, "output_tokens": 1}
655 })))
656 .expect(1)
657 .mount(&server)
658 .await;
659
660 let mut client = minimax_anthropic_client_with_base_url(
661 codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL.to_string(),
662 );
663 client.test_messages_transport_base_url = Some(format!("{}/anthropic", server.uri()));
664 let response = client
665 .create_message(MessageRequest {
666 model: "MiniMax-M3".to_string(),
667 messages: vec![Message {
668 role: Role::User,
669 content: vec![ContentBlock::Text {
670 text: "hello".to_string(),
671 cache_control: None,
672 }],
673 }],
674 max_tokens: 32,
675 system: None,
676 tools: None,
677 tool_choice: None,
678 metadata: None,
679 thinking: None,
680 reasoning_effort: Some("off".to_string()),
681 stream: Some(false),
682 temperature: None,
683 top_p: None,
684 safety_check: None,
685 title: None,
686 })
687 .await
688 .expect("message succeeds");
689
690 assert_eq!(response.content.len(), 1);
691 let requests = server.received_requests().await.expect("recorded requests");
692 let body: Value = serde_json::from_slice(&requests[0].body).expect("request JSON");
693 assert_eq!(
694 body.pointer("/thinking/type").and_then(Value::as_str),
695 Some("disabled")
696 );
697 assert!(body.get("output_config").is_none(), "{body}");
698 }
699
700 #[test]
701 fn custom_api_key_header_is_allowed_without_primary_provider_key() {
702 let mut extra = HashMap::new();
703 extra.insert("api-key".to_string(), "gateway-key".to_string());
704 let headers = CodewhaleClient::default_headers_for_provider(
705 "",
706 &extra,
707 ProviderKind::Openai,
708 "https://gateway.example.test/v1",
709 )
710 .expect("headers");
711
712 assert_eq!(
713 headers.get("api-key").and_then(|value| value.to_str().ok()),
714 Some("gateway-key")
715 );
716 assert!(headers.get(AUTHORIZATION).is_none());
717 }
718
719 #[test]
720 fn chat_messages_keep_current_turn_reasoning_content() {
721 let message = Message {
722 role: Role::Assistant,
723 content: vec![
724 ContentBlock::Thinking {
725 signature: None,
726 state: None,
727 redacted_data: None,
728 thinking: "plan".to_string(),
729 },
730 ContentBlock::Text {
731 text: "done".to_string(),
732 cache_control: None,
733 },
734 ],
735 };
736 let out = build_chat_messages(None, &[message], "deepseek-v4-pro");
737 let assistant = out
738 .iter()
739 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
740 .expect("assistant message");
741 assert_eq!(
742 assistant.get("content").and_then(Value::as_str),
743 Some("done")
744 );
745 assert_eq!(
746 assistant.get("reasoning_content").and_then(Value::as_str),
747 Some("plan"),
748 "thinking-mode models keep reasoning_content while still in the current turn"
749 );
750 }
751
752 #[test]
753 fn generic_openai_provider_drops_reasoning_content_for_non_deepseek_models() {
754 // #1542 intent (narrowed by #1739/#1694): a *genuine non-DeepSeek*
755 // model on the generic openai provider must not carry DeepSeek-only
756 // `reasoning_content`. A DeepSeek reasoning model on the openai
757 // provider (DeepSeek-compatible endpoint) is now covered separately
758 // and DOES replay reasoning_content — see
759 // `deepseek_model_on_openai_provider_still_replays_reasoning_content`.
760 let request = MessageRequest {
761 model: "qwen3-coder".to_string(),
762 messages: vec![Message {
763 role: Role::Assistant,
764 content: vec![
765 ContentBlock::Thinking {
766 signature: None,
767 state: None,
768 redacted_data: None,
769 thinking: "plan".to_string(),
770 },
771 ContentBlock::Text {
772 text: "done".to_string(),
773 cache_control: None,
774 },
775 ],
776 }],
777 max_tokens: 16,
778 system: None,
779 tools: None,
780 tool_choice: None,
781 metadata: None,
782 thinking: None,
783 reasoning_effort: Some("max".to_string()),
784 stream: None,
785 temperature: None,
786 top_p: None,
787 safety_check: None,
788 title: None,
789 };
790
791 let openai = build_chat_messages_for_request_and_provider(&request, ProviderKind::Openai);
792 let generic_assistant = openai
793 .iter()
794 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
795 .expect("assistant message");
796 assert_eq!(
797 generic_assistant.get("content").and_then(Value::as_str),
798 Some("done")
799 );
800 assert!(
801 generic_assistant.get("reasoning_content").is_none(),
802 "generic OpenAI-compatible providers reject DeepSeek-only reasoning_content (#1542)"
803 );
804 }
805
806 #[test]
807 fn chat_messages_replay_tool_round_reasoning_before_new_user_turn() {
808 let messages = vec![
809 Message {
810 role: Role::User,
811 content: vec![ContentBlock::Text {
812 text: "Need the date".to_string(),
813 cache_control: None,
814 }],
815 },
816 Message {
817 role: Role::Assistant,
818 content: vec![
819 ContentBlock::Thinking {
820 signature: None,
821 state: None,
822 redacted_data: None,
823 thinking: "Need to call a tool".to_string(),
824 },
825 ContentBlock::ToolUse {
826 execution_id: None,
827 id: "tool-1".to_string(),
828 name: "get_date".to_string(),
829 input: json!({}),
830 caller: None,
831 thought_signature: None,
832 },
833 ],
834 },
835 Message {
836 role: Role::User,
837 content: vec![ContentBlock::ToolResult {
838 execution_id: None,
839 tool_use_id: "tool-1".to_string(),
840 content: "2026-04-23".to_string(),
841 is_error: None,
842 content_blocks: None,
843 }],
844 },
845 ];
846 let out = build_chat_messages(None, &messages, "deepseek-v4-pro");
847 let tool_assistant = out
848 .iter()
849 .find(|value| {
850 value.get("role").and_then(Value::as_str) == Some("assistant")
851 && value.get("tool_calls").is_some()
852 })
853 .expect("tool-call assistant message");
854 assert_eq!(
855 tool_assistant
856 .get("reasoning_content")
857 .and_then(Value::as_str),
858 Some("Need to call a tool"),
859 "thinking-mode tool sub-turns must replay reasoning_content until the tool chain finishes"
860 );
861 }
862
863 #[test]
864 fn chat_messages_replay_prior_tool_round_reasoning_after_new_user_turn() {
865 let messages = vec![
866 Message {
867 role: Role::User,
868 content: vec![ContentBlock::Text {
869 text: "Need the date".to_string(),
870 cache_control: None,
871 }],
872 },
873 Message {
874 role: Role::Assistant,
875 content: vec![
876 ContentBlock::Thinking {
877 signature: None,
878 state: None,
879 redacted_data: None,
880 thinking: "Need to call a tool".to_string(),
881 },
882 ContentBlock::ToolUse {
883 execution_id: None,
884 id: "tool-1".to_string(),
885 name: "get_date".to_string(),
886 input: json!({}),
887 caller: None,
888 thought_signature: None,
889 },
890 ],
891 },
892 Message {
893 role: Role::User,
894 content: vec![ContentBlock::ToolResult {
895 execution_id: None,
896 tool_use_id: "tool-1".to_string(),
897 content: "2026-04-23".to_string(),
898 is_error: None,
899 content_blocks: None,
900 }],
901 },
902 Message {
903 role: Role::Assistant,
904 content: vec![ContentBlock::Text {
905 text: "It is 2026-04-23.".to_string(),
906 cache_control: None,
907 }],
908 },
909 Message {
910 role: Role::User,
911 content: vec![ContentBlock::Text {
912 text: "Thanks. Next question.".to_string(),
913 cache_control: None,
914 }],
915 },
916 ];
917 let out = build_chat_messages(None, &messages, "deepseek-v4-pro");
918 let tool_assistant = out
919 .iter()
920 .find(|value| {
921 value.get("role").and_then(Value::as_str) == Some("assistant")
922 && value.get("tool_calls").is_some()
923 })
924 .expect("tool-call assistant message");
925 assert_eq!(
926 tool_assistant
927 .get("reasoning_content")
928 .and_then(Value::as_str),
929 Some("Need to call a tool"),
930 "tool-call reasoning_content must be replayed across later user turns"
931 );
932 }
933
934 #[test]
935 fn chat_messages_keep_prior_non_tool_reasoning_after_new_user_turn() {
936 // The serialized JSON for a stored assistant message MUST be a pure
937 // function of that message — never of what comes after it. DeepSeek's
938 // prompt cache hashes the leading bytes of every request; flipping
939 // `reasoning_content` on/off across turns rewrites historical bytes
940 // and busts the prefix cache from that message onwards. (#583)
941 let messages = vec![
942 Message {
943 role: Role::User,
944 content: vec![ContentBlock::Text {
945 text: "Explain it".to_string(),
946 cache_control: None,
947 }],
948 },
949 Message {
950 role: Role::Assistant,
951 content: vec![
952 ContentBlock::Thinking {
953 signature: None,
954 state: None,
955 redacted_data: None,
956 thinking: "Internal explanation plan".to_string(),
957 },
958 ContentBlock::Text {
959 text: "Final answer".to_string(),
960 cache_control: None,
961 },
962 ],
963 },
964 Message {
965 role: Role::User,
966 content: vec![ContentBlock::Text {
967 text: "Next question".to_string(),
968 cache_control: None,
969 }],
970 },
971 ];
972
973 let out = build_chat_messages(None, &messages, "deepseek-v4-pro");
974 let assistant = out
975 .iter()
976 .find(|value| value.get("role").and_then(Value::as_str) == Some("assistant"))
977 .expect("assistant message");
978
979 assert_eq!(
980 assistant.get("content").and_then(Value::as_str),
981 Some("Final answer")
982 );
983 assert_eq!(
984 assistant.get("reasoning_content").and_then(Value::as_str),
985 Some("Internal explanation plan"),
986 "reasoning_content must be preserved across follow-up user turns to keep DeepSeek's prefix cache warm"
987 );
988 }
989
990 #[test]
991 fn chat_messages_assistant_json_is_byte_stable_across_follow_up_user_turn() {
992 // Direct prefix-cache regression: the JSON for the assistant message
993 // built on turn N must equal the JSON for the same assistant message
994 // built on turn N+1, after a new user message has been appended.
995 let assistant = Message {
996 role: Role::Assistant,
997 content: vec![
998 ContentBlock::Thinking {
999 signature: None,
1000 state: None,
1001 redacted_data: None,
1002 thinking: "I should explain step by step.".to_string(),
1003 },
1004 ContentBlock::Text {
1005 text: "Here is the explanation.".to_string(),
1006 cache_control: None,
1007 },
1008 ],
1009 };
1010 let user_initial = Message {
1011 role: Role::User,
1012 content: vec![ContentBlock::Text {
1013 text: "Explain it".to_string(),
1014 cache_control: None,
1015 }],
1016 };
1017 let user_follow_up = Message {
1018 role: Role::User,
1019 content: vec![ContentBlock::Text {
1020 text: "Next question".to_string(),
1021 cache_control: None,
1022 }],
1023 };
1024
1025 let turn_n = build_chat_messages(
1026 None,
1027 &[user_initial.clone(), assistant.clone()],
1028 "deepseek-v4-pro",
1029 );
1030 let turn_n_plus_1 = build_chat_messages(
1031 None,
1032 &[user_initial, assistant, user_follow_up],
1033 "deepseek-v4-pro",
1034 );
1035
1036 let assistant_n = turn_n
1037 .iter()
1038 .find(|v| v.get("role").and_then(Value::as_str) == Some("assistant"))
1039 .expect("assistant present in turn N");
1040 let assistant_n1 = turn_n_plus_1
1041 .iter()
1042 .find(|v| v.get("role").and_then(Value::as_str) == Some("assistant"))
1043 .expect("assistant present in turn N+1");
1044
1045 assert_eq!(
1046 assistant_n, assistant_n1,
1047 "assistant message JSON must be byte-identical across turns or DeepSeek's prefix cache breaks"
1048 );
1049 }
1050
1051 #[test]
1052 fn chat_messages_allow_tool_round_without_reasoning_when_thinking_disabled() {
1053 let request = MessageRequest {
1054 model: "deepseek-v4-pro".to_string(),
1055 messages: vec![
1056 Message {
1057 role: Role::Assistant,
1058 content: vec![ContentBlock::ToolUse {
1059 execution_id: None,
1060 id: "call-no-thinking".to_string(),
1061 name: "read_file".to_string(),
1062 input: json!({"path": "Cargo.toml"}),
1063 caller: None,
1064 thought_signature: None,
1065 }],
1066 },
1067 Message {
1068 role: Role::User,
1069 content: vec![ContentBlock::ToolResult {
1070 execution_id: None,
1071 tool_use_id: "call-no-thinking".to_string(),
1072 content: "workspace manifest".to_string(),
1073 is_error: None,
1074 content_blocks: None,
1075 }],
1076 },
1077 ],
1078 max_tokens: 1024,
1079 system: None,
1080 tools: None,
1081 tool_choice: None,
1082 metadata: None,
1083 thinking: None,
1084 reasoning_effort: Some("off".to_string()),
1085 stream: None,
1086 temperature: None,
1087 top_p: None,
1088 safety_check: None,
1089 title: None,
1090 };
1091
1092 let out = build_chat_messages_for_request(&request);
1093 assert!(
1094 out.iter().any(
1095 |value| value.get("role").and_then(Value::as_str) == Some("assistant")
1096 && value.get("tool_calls").is_some()
1097 ),
1098 "tool calls remain valid when thinking mode is disabled"
1099 );
1100 assert!(
1101 out.iter()
1102 .any(|value| value.get("role").and_then(Value::as_str) == Some("tool")),
1103 "matching tool result should remain"
1104 );
1105 }
1106
1107 #[test]
1108 fn prompt_builder_keeps_system_first_and_current_user_input_last() {
1109 let request = MessageRequest {
1110 model: "deepseek-v4-pro".to_string(),
1111 messages: vec![
1112 Message {
1113 role: Role::Assistant,
1114 content: vec![ContentBlock::Text {
1115 text: "Previous answer".to_string(),
1116 cache_control: None,
1117 }],
1118 },
1119 Message {
1120 role: Role::User,
1121 content: vec![
1122 ContentBlock::Text {
1123 text: "<turn_meta>\nCurrent local date: 2026-05-08\n</turn_meta>"
1124 .to_string(),
1125 cache_control: None,
1126 },
1127 ContentBlock::Text {
1128 text: "Current user question".to_string(),
1129 cache_control: None,
1130 },
1131 ],
1132 },
1133 ],
1134 max_tokens: 1024,
1135 system: Some(SystemPrompt::Text(
1136 "Stable mode, project rules, and tool policy".to_string(),
1137 )),
1138 tools: None,
1139 tool_choice: None,
1140 metadata: None,
1141 thinking: None,
1142 reasoning_effort: Some("max".to_string()),
1143 stream: None,
1144 temperature: None,
1145 top_p: None,
1146 safety_check: None,
1147 title: None,
1148 };
1149
1150 let out = build_chat_messages_for_request(&request);
1151
1152 assert_eq!(out[0].get("role").and_then(Value::as_str), Some("system"));
1153 assert_eq!(
1154 out[0].get("content").and_then(Value::as_str),
1155 Some("Stable mode, project rules, and tool policy")
1156 );
1157 let last = out.last().expect("latest user message");
1158 assert_eq!(last.get("role").and_then(Value::as_str), Some("user"));
1159 assert!(
1160 last.get("content")
1161 .and_then(Value::as_str)
1162 .is_some_and(|content| content.ends_with("Current user question")),
1163 "current-turn user input must be at the tail of the wire prompt: {last:?}"
1164 );
1165 }
1166
1167 #[test]
1168 fn prompt_inspect_reports_stable_layers_and_dynamic_user_task() {
1169 let request = MessageRequest {
1170 model: "deepseek-v4-pro".to_string(),
1171 messages: vec![
1172 Message {
1173 role: Role::Assistant,
1174 content: vec![ContentBlock::Text {
1175 text: "Prior answer".to_string(),
1176 cache_control: None,
1177 }],
1178 },
1179 Message {
1180 role: Role::User,
1181 content: vec![ContentBlock::Text {
1182 text: "Current task".to_string(),
1183 cache_control: None,
1184 }],
1185 },
1186 ],
1187 max_tokens: 1024,
1188 system: Some(SystemPrompt::Text(
1189 "Base policy\n\n<project_instructions source=\"AGENTS.md\">\nRules\n</project_instructions>\n\n## Project Context Pack\n\n<project_context_pack>\n{}\n</project_context_pack>\n\n## Environment\n\n- lang: en"
1190 .to_string(),
1191 )),
1192 tools: None,
1193 tool_choice: None,
1194 metadata: None,
1195 thinking: None,
1196 reasoning_effort: Some("max".to_string()),
1197 stream: None,
1198 temperature: None,
1199 top_p: None,
1200 safety_check: None,
1201 title: None,
1202 };
1203
1204 let inspection = inspect_prompt_for_request(&request);
1205
1206 assert_eq!(inspection.base_static_prefix_hash.len(), 64);
1207 assert_eq!(inspection.full_request_prefix_hash.len(), 64);
1208 assert!(inspection.layers.iter().any(|layer| {
1209 layer.name == "Global system prefix"
1210 && layer.stability.label() == "static"
1211 && layer.char_len == "Base policy".chars().count()
1212 && layer.sha256.len() == 64
1213 }));
1214 assert!(
1215 inspection.layers.iter().any(|layer| {
1216 layer.name == "Project context" && layer.stability.label() == "static"
1217 })
1218 );
1219 assert!(inspection.layers.iter().any(|layer| {
1220 layer.name == "Project context pack" && layer.stability.label() == "static"
1221 }));
1222 assert!(inspection.layers.iter().any(|layer| {
1223 layer.name == "Message #1 assistant" && layer.stability.label() == "history"
1224 }));
1225 assert!(
1226 inspection
1227 .layers
1228 .last()
1229 .is_some_and(|layer| layer.name == "User task" && layer.stability.label() == "dynamic")
1230 );
1231 }
1232
1233 #[test]
1234 fn prompt_inspect_keeps_static_base_hash_across_different_user_tasks() {
1235 fn request_with_user_task(task: &str) -> MessageRequest {
1236 MessageRequest {
1237 model: "deepseek-v4-pro".to_string(),
1238 messages: vec![
1239 Message {
1240 role: Role::Assistant,
1241 content: vec![ContentBlock::Text {
1242 text: "Prior answer".to_string(),
1243 cache_control: None,
1244 }],
1245 },
1246 Message {
1247 role: Role::User,
1248 content: vec![ContentBlock::Text {
1249 text: task.to_string(),
1250 cache_control: None,
1251 }],
1252 },
1253 ],
1254 max_tokens: 1024,
1255 system: Some(SystemPrompt::Text(
1256 "Base policy\n\n## Environment\n\n- shell: powershell\n\n## Skills\n\n- rust\n\n## Context Management\n\nKeep concise\n\n## Compact\n\nTemplate"
1257 .to_string(),
1258 )),
1259 tools: None,
1260 tool_choice: None,
1261 metadata: None,
1262 thinking: None,
1263 reasoning_effort: Some("max".to_string()),
1264 stream: None,
1265 temperature: None,
1266 top_p: None,
1267 safety_check: None,
1268 title: None,
1269 }
1270 }
1271
1272 let first = inspect_prompt_for_request(&request_with_user_task("First task"));
1273 let second = inspect_prompt_for_request(&request_with_user_task("Second task"));
1274 let mut changed_history_request = request_with_user_task("Second task");
1275 changed_history_request.messages[0] = Message {
1276 role: Role::Assistant,
1277 content: vec![ContentBlock::Text {
1278 text: "Different prior answer".to_string(),
1279 cache_control: None,
1280 }],
1281 };
1282 let changed_history = inspect_prompt_for_request(&changed_history_request);
1283
1284 assert_eq!(
1285 first.base_static_prefix_hash,
1286 second.base_static_prefix_hash
1287 );
1288 assert_eq!(
1289 first.full_request_prefix_hash, second.full_request_prefix_hash,
1290 "full request prefix excludes the final dynamic user task"
1291 );
1292 assert_ne!(
1293 second.full_request_prefix_hash, changed_history.full_request_prefix_hash,
1294 "full request prefix can change when session history changes"
1295 );
1296 assert!(
1297 second
1298 .layers
1299 .last()
1300 .is_some_and(|layer| layer.name == "User task" && layer.stability.label() == "dynamic"),
1301 "current user task must remain the final layer"
1302 );
1303 assert!(second.layers.iter().any(|layer| {
1304 layer.name == "Message #1 assistant" && layer.stability.label() == "history"
1305 }));
1306 assert!(!second.layers.iter().any(
1307 |layer| layer.name.starts_with("Message #") && layer.stability.label() == "static"
1308 ));
1309 }
1310
1311 #[test]
1312 fn prompt_inspect_tracks_tool_catalog_in_static_prefix_hash() {
1313 let request = MessageRequest {
1314 model: "deepseek-v4-pro".to_string(),
1315 messages: vec![Message {
1316 role: Role::User,
1317 content: vec![ContentBlock::Text {
1318 text: "Current task".to_string(),
1319 cache_control: None,
1320 }],
1321 }],
1322 max_tokens: 1024,
1323 system: Some(SystemPrompt::Text("Base policy".to_string())),
1324 tools: Some(vec![test_tool("read_file")]),
1325 tool_choice: None,
1326 metadata: None,
1327 thinking: None,
1328 reasoning_effort: Some("max".to_string()),
1329 stream: None,
1330 temperature: None,
1331 top_p: None,
1332 safety_check: None,
1333 title: None,
1334 };
1335
1336 let first = inspect_prompt_for_request(&request);
1337 let mut changed_tools = request.clone();
1338 changed_tools.tools = Some(vec![test_tool("read_file"), test_tool("grep_files")]);
1339 let second = inspect_prompt_for_request(&changed_tools);
1340
1341 assert!(
1342 first
1343 .layers
1344 .iter()
1345 .any(|layer| { layer.name == "Tool catalog" && layer.stability.label() == "static" })
1346 );
1347 assert_ne!(
1348 first.base_static_prefix_hash, second.base_static_prefix_hash,
1349 "tool schema changes must be visible to cache-inspect base prefix diagnostics"
1350 );
1351 assert_ne!(
1352 first.full_request_prefix_hash, second.full_request_prefix_hash,
1353 "tool schema changes must be visible to full reusable-prefix diagnostics"
1354 );
1355 }
1356
1357 #[test]
1358 fn cache_warmup_request_reuses_stable_prefix_and_fixed_user_tail() {
1359 let request = MessageRequest {
1360 model: "deepseek-v4-pro".to_string(),
1361 messages: vec![
1362 Message {
1363 role: Role::Assistant,
1364 content: vec![ContentBlock::Text {
1365 text: "Stable prior answer".to_string(),
1366 cache_control: None,
1367 }],
1368 },
1369 Message {
1370 role: Role::User,
1371 content: vec![ContentBlock::Text {
1372 text: "Dynamic latest user task".to_string(),
1373 cache_control: None,
1374 }],
1375 },
1376 ],
1377 max_tokens: 1024,
1378 system: Some(SystemPrompt::Text(
1379 "Base policy\n\n<project_instructions source=\"AGENTS.md\">\nStable project rules\n</project_instructions>\n\n## Previous Session Relay\n\nDynamic relay"
1380 .to_string(),
1381 )),
1382 tools: Some(vec![test_tool("read_file")]),
1383 tool_choice: None,
1384 metadata: None,
1385 thinking: None,
1386 reasoning_effort: Some("max".to_string()),
1387 stream: Some(true),
1388 temperature: Some(0.7),
1389 top_p: None,
1390 safety_check: None,
1391 title: None,
1392 };
1393
1394 let warmup = build_cache_warmup_request(&request);
1395
1396 assert_eq!(warmup.max_tokens, 8);
1397 assert_eq!(warmup.temperature, None);
1398 assert_eq!(warmup.top_p, None);
1399 assert_eq!(warmup.reasoning_effort.as_deref(), Some("off"));
1400 assert_eq!(warmup.tools.as_ref().map(Vec::len), Some(1));
1401 assert_eq!(warmup.tool_choice, Some(json!("none")));
1402 assert_eq!(warmup.messages.len(), 2);
1403 assert_eq!(warmup.messages[0].role, "assistant");
1404 assert_eq!(warmup.messages[1].role, "user");
1405 assert_eq!(
1406 warmup.messages[1].content,
1407 vec![ContentBlock::Text {
1408 text: "请只回复 OK".to_string(),
1409 cache_control: None,
1410 }]
1411 );
1412
1413 let wire = build_chat_messages_for_request(&warmup);
1414 let system = wire
1415 .first()
1416 .and_then(|value| value.get("content"))
1417 .and_then(Value::as_str)
1418 .expect("warmup system prompt");
1419 assert!(system.contains("Stable project rules"));
1420 assert!(!system.contains("Dynamic relay"));
1421 assert!(
1422 !wire
1423 .iter()
1424 .any(|value| value.to_string().contains("Dynamic latest user task")),
1425 "warmup must not include the dynamic latest user task"
1426 );
1427 }
1428
1429 #[test]
1430 fn reasoning_effort_scenario() {
1431 // Scenario consolidation of: reasoning_effort_uses_deepseek_top_level_thinking_parameter, reasoning_effort_off_disables_top_level_thinking, reasoning_effort_off_is_omitted_for_strict_openai_like_providers, reasoning_effort_atlascloud_speaks_deepseek_dialect, reasoning_effort_modelstudio_writes_nothing_without_a_verified_route, reasoning_effort_moonshot_toggles_thinking, reasoning_effort_edenai_does_not_guess_a_model_dialect, reasoning_effort_ollama_toggles_think_flag
1432 // from reasoning_effort_uses_deepseek_top_level_thinking_parameter
1433 {
1434 let mut body = json!({});
1435 apply_reasoning_effort(&mut body, Some("max"), ProviderKind::Deepseek);
1436
1437 assert_eq!(
1438 body.get("reasoning_effort").and_then(Value::as_str),
1439 Some("max")
1440 );
1441 assert_eq!(
1442 body.pointer("/thinking/type").and_then(Value::as_str),
1443 Some("enabled")
1444 );
1445 assert!(body.get("extra_body").is_none());
1446 }
1447 // from reasoning_effort_off_disables_top_level_thinking
1448 {
1449 let mut body = json!({});
1450 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::Deepseek);
1451
1452 assert_eq!(
1453 body.pointer("/thinking/type").and_then(Value::as_str),
1454 Some("disabled")
1455 );
1456 assert!(body.get("reasoning_effort").is_none());
1457 assert!(body.get("extra_body").is_none());
1458 }
1459 // from reasoning_effort_off_is_omitted_for_strict_openai_like_providers
1460 {
1461 for provider in [
1462 ProviderKind::Openai,
1463 ProviderKind::WanjieArk,
1464 ProviderKind::Qianfan,
1465 ProviderKind::Arcee,
1466 ProviderKind::Huggingface,
1467 ProviderKind::Fireworks,
1468 ] {
1469 let mut body = json!({});
1470 apply_reasoning_effort(&mut body, Some("off"), provider);
1471
1472 assert_eq!(
1473 body,
1474 json!({}),
1475 "provider {provider:?} should not receive unsupported reasoning-off fields"
1476 );
1477 }
1478 }
1479 // from reasoning_effort_atlascloud_speaks_deepseek_dialect
1480 {
1481 let mut body = json!({});
1482 apply_reasoning_effort(&mut body, Some("high"), ProviderKind::Atlascloud);
1483 assert_eq!(
1484 body,
1485 json!({ "reasoning_effort": "high", "thinking": { "type": "enabled" } })
1486 );
1487
1488 let mut body = json!({});
1489 apply_reasoning_effort(&mut body, Some("max"), ProviderKind::Atlascloud);
1490 assert_eq!(
1491 body,
1492 json!({ "reasoning_effort": "max", "thinking": { "type": "enabled" } })
1493 );
1494
1495 let mut body = json!({});
1496 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::Atlascloud);
1497 assert_eq!(body, json!({ "thinking": { "type": "disabled" } }));
1498 }
1499 // from reasoning_effort_modelstudio_writes_nothing_without_a_verified_route
1500 {
1501 // The provider enum cannot decide DashScope's controls: `enable_thinking`
1502 // is wrong for the thinking-only models, `reasoning_effort` is only
1503 // valid for DeepSeek-V4/GLM, and a custom `base_url` on any of these
1504 // identities is an arbitrary gateway. All four variants must therefore
1505 // leave the body untouched here — the route shaper in client::chat is
1506 // the sole writer.
1507 for provider in [
1508 ProviderKind::ModelstudioTokenPlan,
1509 ProviderKind::ModelstudioTokenPlanAnthropic,
1510 ProviderKind::ModelstudioCodingPlan,
1511 ProviderKind::ModelstudioCodingPlanAnthropic,
1512 ] {
1513 for effort in [None, Some("off"), Some("low"), Some("high"), Some("max")] {
1514 let mut body = json!({});
1515 apply_reasoning_effort(&mut body, effort, provider);
1516 assert_eq!(body, json!({}), "{provider:?} {effort:?}");
1517 }
1518 }
1519 }
1520 // from reasoning_effort_moonshot_toggles_thinking
1521 {
1522 let mut body = json!({});
1523 apply_reasoning_effort(&mut body, Some("high"), ProviderKind::Moonshot);
1524 assert_eq!(body, json!({ "thinking": { "type": "enabled" } }));
1525
1526 let mut body = json!({});
1527 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::Moonshot);
1528 assert_eq!(body, json!({ "thinking": { "type": "disabled" } }));
1529 }
1530 // from reasoning_effort_edenai_does_not_guess_a_model_dialect
1531 {
1532 for effort in ["off", "low", "medium", "high", "max", "xhigh"] {
1533 let mut body = json!({});
1534 apply_reasoning_effort(&mut body, Some(effort), ProviderKind::Edenai);
1535 assert_eq!(body, json!({}), "unexpected Eden AI fields for {effort}");
1536 }
1537 }
1538 // from reasoning_effort_ollama_toggles_think_flag
1539 {
1540 let mut body = json!({});
1541 apply_reasoning_effort(&mut body, Some("high"), ProviderKind::Ollama);
1542 assert_eq!(body, json!({ "think": true }));
1543
1544 let mut body = json!({});
1545 apply_reasoning_effort(&mut body, Some("off"), ProviderKind::Ollama);
1546 assert_eq!(body, json!({ "think": false }));
1547 }
1548 }
1549
1550 /// First-party DeepSeek routes document `reasoning_effort` low/high/max on
1551 /// the wire (no medium): low is a real cheaper tier, medium rounds up to
1552 /// high (#52). Hosted DeepSeek-compatible routes keep the historic
1553 /// low/medium → high collapse because their own wire contracts are not
1554 /// verified here.
1555 #[test]
1556 fn stepfun_reasoning_effort_respects_each_model_wire_contract() {
1557 for (model, effort, expected) in [
1558 ("step-5", "low", Some("low")),
1559 ("step-5", "medium", Some("medium")),
1560 ("step-5", "max", Some("high")),
1561 ("step-5", "off", None),
1562 ("step-5-preview", "low", Some("low")),
1563 ("step-5-preview", "medium", Some("medium")),
1564 ("step-5-preview", "max", Some("high")),
1565 ("step-3.7-flash", "medium", Some("medium")),
1566 ("step-3.5-flash-2603", "medium", Some("high")),
1567 ("step-3.5-flash-2603", "low", Some("low")),
1568 ("step-3.5-flash", "high", None),
1569 ("step-5-preview", "off", None),
1570 ("step-5-preview", "auto", None),
1571 ("step-audio-2", "high", None),
1572 ] {
1573 let mut body = json!({"model": model});
1574 apply_reasoning_effort(&mut body, Some(effort), ProviderKind::Stepfun);
1575 assert_eq!(
1576 body.get("reasoning_effort").and_then(Value::as_str),
1577 expected,
1578 "{model}/{effort}"
1579 );
1580 assert!(body.get("thinking").is_none());
1581 }
1582 }
1583
1584 #[test]
1585 fn stepfun_discovery_excludes_non_coding_and_retired_models() {
1586 let models = parse_models_response(
1587 r#"{"data":[
1588 {"id":"step-5"},{"id":"step-5-preview"},{"id":"step-5.5"},
1589 {"id":"step-3.7-flash"},{"id":"step-3.5-flash"},{"id":"step-3.5-flash-2603"},
1590 {"id":"step-audio-2"},{"id":"stepaudio-chat"},{"id":"step-tts-2"},
1591 {"id":"step-1x-medium"},{"id":"step-image-edit-2"},{"id":"step-2x-large"},
1592 {"id":"custom-asr"},{"id":"custom-video"}
1593 ]}"#,
1594 )
1595 .unwrap();
1596 let filtered = apply_provider_model_cutline(ProviderKind::Stepfun, models);
1597 assert_eq!(
1598 filtered
1599 .iter()
1600 .map(|model| model.id.as_str())
1601 .collect::<Vec<_>>(),
1602 [
1603 "step-3.5-flash",
1604 "step-3.5-flash-2603",
1605 "step-3.7-flash",
1606 "step-5",
1607 "step-5-preview",
1608 "step-5.5"
1609 ]
1610 );
1611 }
1612
1613 #[test]
1614 fn reasoning_effort_deepseek_maps_the_documented_wire_ladder() {
1615 let mut body = json!({});
1616 apply_reasoning_effort(&mut body, Some("low"), ProviderKind::Deepseek);
1617 assert_eq!(
1618 body,
1619 json!({ "reasoning_effort": "low", "thinking": { "type": "enabled" } })
1620 );
1621
1622 let mut body = json!({});
1623 apply_reasoning_effort(&mut body, Some("medium"), ProviderKind::Deepseek);
1624 assert_eq!(
1625 body,
1626 json!({ "reasoning_effort": "high", "thinking": { "type": "enabled" } })
1627 );
1628
1629 for provider in [ProviderKind::Deepseek, ProviderKind::Deepseek] {
1630 let mut body = json!({});
1631 apply_reasoning_effort(&mut body, Some("high"), provider);
1632 assert_eq!(
1633 body,
1634 json!({ "reasoning_effort": "high", "thinking": { "type": "enabled" } }),
1635 "provider {provider:?}"
1636 );
1637 }
1638
1639 for provider in [ProviderKind::Siliconflow, ProviderKind::Deepinfra] {
1640 let mut body = json!({});
1641 apply_reasoning_effort(&mut body, Some("low"), provider);
1642 assert_eq!(
1643 body,
1644 json!({ "reasoning_effort": "high", "thinking": { "type": "enabled" } }),
1645 "hosted route {provider:?} keeps the collapse"
1646 );
1647 }
1648 }
1649
1650 #[tokio::test]
1651 async fn registry_admitted_custom_hosts_refuse_private_addresses_at_connect_time() {
1652 use codewhale_config::cloud_facts::{
1653 BuiltinNames, KeyRole, REGISTRY_SCHEMA, Registry, VerifiedRegistry, admit_registry,
1654 overlay,
1655 };
1656 use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
1657
1658 let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
1659 .await
1660 .expect("bind");
1661 let port = listener.local_addr().expect("addr").port();
1662 tokio::spawn(async move {
1663 while let Ok((mut socket, _)) = listener.accept().await {
1664 tokio::spawn(async move {
1665 let mut buf = [0u8; 2048];
1666 let _ = socket.read(&mut buf).await;
1667 let _ = socket
1668 .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok")
1669 .await;
1670 });
1671 }
1672 });
1673 let base_url = format!("http://localhost:{port}/v1");
1674 let probe = |provider: ProviderKind| {
1675 let client =
1676 CodewhaleClient::build_http_client("sk-test", &HashMap::new(), provider, &base_url)
1677 .expect("client");
1678 let url = format!("{base_url}/models");
1679 async move { client.get(url).send().await }
1680 };
1681
1682 overlay::clear();
1683 assert!(probe(ProviderKind::Custom).await.is_ok());
1684
1685 let registry: Registry = serde_json::from_value(json!({
1686 "schema": REGISTRY_SCHEMA,
1687 "revision": overlay::highest_seen(REGISTRY_SCHEMA).unwrap_or(0) + 1,
1688 "generated_at": "2026-11-17T00:00:00Z",
1689 "providers": [{
1690 "id": "acme-rebind",
1691 "label": "Acme Rebind",
1692 "wire_policy": "openai-compatible",
1693 "base_url": "https://api.acme-rebind.example/v1",
1694 "admission": {"founder_signature": "required"}
1695 }],
1696 "models": [],
1697 "offerings": [],
1698 "dialects": {}
1699 }))
1700 .expect("registry");
1701 let mut admitted = admit_registry(
1702 VerifiedRegistry {
1703 registry,
1704 key_id: "engine-guard-test".to_string(),
1705 key_role: KeyRole::Founder,
1706 sha256: String::new(),
1707 generated_at_unix: 0,
1708 not_after: None,
1709 },
1710 &BuiltinNames::bundled(),
1711 );
1712 assert_eq!(admitted.providers.len(), 1, "{:?}", admitted.refused);
1713 admitted.providers[0].base_url.clone_from(&base_url);
1714 let ticket = overlay::configure(true, "engine-pulled-guard-test").expect("ticket");
1715 assert!(overlay::publish_registry(
1716 &ticket,
1717 Some(std::sync::Arc::new(admitted)),
1718 |_| {}
1719 ));
1720
1721 let refused = probe(ProviderKind::Custom).await.expect_err("guarded");
1722 let chain = format!("{:?}", anyhow::Error::from(refused));
1723 assert!(chain.contains("restricted address"), "{chain}");
1724 assert!(probe(ProviderKind::Ollama).await.is_ok());
1725 assert!(probe(ProviderKind::Vllm).await.is_ok());
1726 assert!(
1727 CodewhaleClient::build_http_client(
1728 "sk-test",
1729 &HashMap::new(),
1730 ProviderKind::Custom,
1731 "http://127.0.0.1:1/v1",
1732 )
1733 .is_ok()
1734 );
1735
1736 overlay::clear();
1737 assert!(probe(ProviderKind::Custom).await.is_ok());
1738 }
1739
1739 lines RUST