| 1 | use super::CodewhaleClient; |
| 2 | use super::chat::{ChatToolStream, parse_chat_message, parse_sse_chunk}; |
| 3 | use anyhow::Result; |
| 4 | use codewhale_models::Role; |
| 5 | use codewhale_models::{ContentBlock, Delta, Message, MessageRequest, StreamEvent, Tool}; |
| 6 | use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig}; |
| 7 | use serde_json::{Value, json}; |
| 8 | use wiremock::matchers::method; |
| 9 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 10 | |
| 11 | fn ds4_client() -> CodewhaleClient { |
| 12 | let mut providers = ProvidersConfig::default(); |
| 13 | providers.custom.insert( |
| 14 | "ds4".to_string(), |
| 15 | ProviderConfig { |
| 16 | kind: Some("openai-compatible".to_string()), |
| 17 | base_url: Some("http://127.0.0.1:8000/v1".to_string()), |
| 18 | model: Some("deepseek-v4-flash".to_string()), |
| 19 | context_window: Some(100_000), |
| 20 | auth_mode: Some("none".to_string()), |
| 21 | ..Default::default() |
| 22 | }, |
| 23 | ); |
| 24 | CodewhaleClient::new(&{ |
| 25 | let __cw_config_init_0_0 = Some("ds4".to_string()); |
| 26 | let __cw_config_init_0_1 = Some(providers); |
| 27 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 28 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 29 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 30 | __cw_config_init_0_value |
| 31 | }) |
| 32 | .expect("DS4 client") |
| 33 | } |
| 34 | |
| 35 | /// The same named `ds4` identity, bound to a mock endpoint. DS4 is identified by |
| 36 | /// the identity key plus a local host, so a loopback mock server is a real DS4 |
| 37 | /// route as far as the client is concerned. |
| 38 | fn ds4_client_at(server: &MockServer) -> CodewhaleClient { |
| 39 | let mut providers = ProvidersConfig::default(); |
| 40 | providers.custom.insert( |
| 41 | "ds4".to_string(), |
| 42 | ProviderConfig { |
| 43 | kind: Some("openai-compatible".to_string()), |
| 44 | base_url: Some(format!("{}/v1", server.uri())), |
| 45 | model: Some("deepseek-v4-flash".to_string()), |
| 46 | context_window: Some(100_000), |
| 47 | auth_mode: Some("none".to_string()), |
| 48 | ..Default::default() |
| 49 | }, |
| 50 | ); |
| 51 | CodewhaleClient::new(&{ |
| 52 | let __cw_config_init_1_0 = Some("ds4".to_string()); |
| 53 | let __cw_config_init_1_1 = Some(providers); |
| 54 | let mut __cw_config_init_1_value: Config = Default::default(); |
| 55 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 56 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 57 | __cw_config_init_1_value |
| 58 | }) |
| 59 | .expect("DS4 client") |
| 60 | } |
| 61 | |
| 62 | /// DS4 is a named `openai-compatible` route, so its `api_provider` is `Custom`. |
| 63 | /// It implements the first-party DeepSeek dialect, which means the helper paths |
| 64 | /// that bypass `chat_shape_provider` must still send the thinking toggle. |
| 65 | /// Translation is one of those paths and always requests `off`. |
| 66 | #[tokio::test] |
| 67 | async fn named_ds4_translation_keeps_the_disabled_thinking_toggle() -> Result<()> { |
| 68 | let server = MockServer::start().await; |
| 69 | Mock::given(method("POST")) |
| 70 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 71 | "id": "chatcmpl-ds4-translate", |
| 72 | "object": "chat.completion", |
| 73 | "model": "deepseek-v4-flash", |
| 74 | "choices": [{ |
| 75 | "index": 0, |
| 76 | "message": {"role": "assistant", "content": "Hola"}, |
| 77 | "finish_reason": "stop" |
| 78 | }], |
| 79 | "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4} |
| 80 | }))) |
| 81 | .expect(1) |
| 82 | .mount(&server) |
| 83 | .await; |
| 84 | |
| 85 | let client = ds4_client_at(&server); |
| 86 | client |
| 87 | .translate_with_usage( |
| 88 | "hello", |
| 89 | "deepseek-v4-flash", |
| 90 | "Spanish", |
| 91 | &crate::cost_status::NativeUsageSource::capture( |
| 92 | format!("ds4-translate-test:{}", uuid::Uuid::new_v4()), |
| 93 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 94 | ), |
| 95 | ) |
| 96 | .await?; |
| 97 | |
| 98 | let requests = server.received_requests().await.expect("recorded request"); |
| 99 | assert_eq!(requests.len(), 1); |
| 100 | let body: Value = serde_json::from_slice(&requests[0].body)?; |
| 101 | assert_eq!( |
| 102 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 103 | Some("disabled"), |
| 104 | "DS4 speaks the first-party DeepSeek dialect: {body}" |
| 105 | ); |
| 106 | Ok(()) |
| 107 | } |
| 108 | |
| 109 | /// The mirror of the test above on an ordinary compatible gateway. Translation |
| 110 | /// always asks for `off`; on a gateway that must arrive as `none` with no |
| 111 | /// `thinking` object, because the object is what such an endpoint rejects. |
| 112 | /// Without this case a future shaper could re-add the toggle on the translation |
| 113 | /// path and only the gateway would notice. |
| 114 | #[tokio::test] |
| 115 | async fn a_gateway_translation_asks_for_none_instead_of_the_thinking_toggle() -> Result<()> { |
| 116 | let server = MockServer::start().await; |
| 117 | Mock::given(method("POST")) |
| 118 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 119 | "id": "chatcmpl-gateway-translate", |
| 120 | "object": "chat.completion", |
| 121 | "model": "DeepSeek-V4.1-Flash", |
| 122 | "choices": [{ |
| 123 | "index": 0, |
| 124 | "message": {"role": "assistant", "content": "Hola"}, |
| 125 | "finish_reason": "stop" |
| 126 | }], |
| 127 | "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4} |
| 128 | }))) |
| 129 | .expect(1) |
| 130 | .mount(&server) |
| 131 | .await; |
| 132 | |
| 133 | let client = super::tests::custom_mock_client_for_identity(&server, "aicraft"); |
| 134 | client |
| 135 | .translate_with_usage( |
| 136 | "hello", |
| 137 | "DeepSeek-V4.1-Flash", |
| 138 | "Spanish", |
| 139 | &crate::cost_status::NativeUsageSource::capture( |
| 140 | format!("gateway-translate-test:{}", uuid::Uuid::new_v4()), |
| 141 | crate::cost_status::UsageSpendOwner::Auxiliary, |
| 142 | ), |
| 143 | ) |
| 144 | .await?; |
| 145 | |
| 146 | let requests = server.received_requests().await.expect("recorded request"); |
| 147 | assert_eq!(requests.len(), 1); |
| 148 | let body: Value = serde_json::from_slice(&requests[0].body)?; |
| 149 | assert!( |
| 150 | body.get("thinking").is_none(), |
| 151 | "a gateway rejects DeepSeek's toggle object: {body}" |
| 152 | ); |
| 153 | assert_eq!( |
| 154 | body.get("reasoning_effort").and_then(Value::as_str), |
| 155 | Some("none"), |
| 156 | "translation asks for off, which a gateway expresses as none: {body}" |
| 157 | ); |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | fn request(effort: &str) -> MessageRequest { |
| 162 | MessageRequest { |
| 163 | model: "deepseek-v4-flash".to_string(), |
| 164 | messages: vec![Message { |
| 165 | role: Role::User, |
| 166 | content: vec![ContentBlock::Text { |
| 167 | text: "hello".to_string(), |
| 168 | cache_control: None, |
| 169 | }], |
| 170 | }], |
| 171 | max_tokens: 128, |
| 172 | system: None, |
| 173 | tools: None, |
| 174 | tool_choice: None, |
| 175 | metadata: None, |
| 176 | thinking: None, |
| 177 | reasoning_effort: Some(effort.to_string()), |
| 178 | stream: None, |
| 179 | temperature: None, |
| 180 | top_p: None, |
| 181 | safety_check: None, |
| 182 | title: None, |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn named_ds4_route_uses_deepseek_reasoning_controls() -> Result<()> { |
| 188 | let client = ds4_client(); |
| 189 | |
| 190 | let off = client.prepare_outbound_request(request("off"), true)?; |
| 191 | assert_eq!(off.body["thinking"]["type"], "disabled"); |
| 192 | assert!(off.body.get("reasoning_effort").is_none()); |
| 193 | |
| 194 | let max = client.prepare_outbound_request(request("max"), true)?; |
| 195 | assert_eq!(max.body["thinking"]["type"], "enabled"); |
| 196 | assert_eq!(max.body["reasoning_effort"], "max"); |
| 197 | Ok(()) |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn named_ds4_route_removes_unsupported_strict_tool_flag() -> Result<()> { |
| 202 | let client = ds4_client(); |
| 203 | let mut request = request("high"); |
| 204 | request.tools = Some(vec![Tool { |
| 205 | tool_type: Some("function".to_string()), |
| 206 | name: "read_file".to_string(), |
| 207 | description: "Read one file".to_string(), |
| 208 | input_schema: json!({"type": "object", "properties": {"path": {"type": "string"}}}), |
| 209 | allowed_callers: None, |
| 210 | defer_loading: None, |
| 211 | input_examples: None, |
| 212 | strict: Some(true), |
| 213 | cache_control: None, |
| 214 | }]); |
| 215 | |
| 216 | let outbound = client.prepare_outbound_request(request, true)?; |
| 217 | assert!( |
| 218 | outbound.body["tools"][0]["function"] |
| 219 | .get("strict") |
| 220 | .is_none() |
| 221 | ); |
| 222 | Ok(()) |
| 223 | } |
| 224 | |
| 225 | #[test] |
| 226 | fn non_streaming_fixture_preserves_tool_call_and_usage() -> Result<()> { |
| 227 | // Recorded DS4/OpenAI-compatible response shape. Keep this fixture |
| 228 | // provider-free: DS4 should stay on the shared parser contract. |
| 229 | let response = parse_chat_message(&json!({ |
| 230 | "id": "chatcmpl-ds4-tool", |
| 231 | "model": "deepseek-v4-flash", |
| 232 | "choices": [{ |
| 233 | "index": 0, |
| 234 | "message": { |
| 235 | "role": "assistant", |
| 236 | "content": null, |
| 237 | "tool_calls": [{ |
| 238 | "index": 0, |
| 239 | "id": "call_ds4_0", |
| 240 | "type": "function", |
| 241 | "function": { |
| 242 | "name": "read_file", |
| 243 | "arguments": "{\"path\":\"src/main.rs\"}" |
| 244 | } |
| 245 | }] |
| 246 | }, |
| 247 | "finish_reason": "tool_calls" |
| 248 | }], |
| 249 | "usage": { |
| 250 | "prompt_tokens": 23, |
| 251 | "completion_tokens": 7, |
| 252 | "total_tokens": 30 |
| 253 | } |
| 254 | }))?; |
| 255 | |
| 256 | assert!(matches!( |
| 257 | response.content.as_slice(), |
| 258 | [ContentBlock::ToolUse { id, name, input, ..}] |
| 259 | if id == "call_ds4_0" |
| 260 | && name == "read_file" |
| 261 | && input == &json!({"path": "src/main.rs"}) |
| 262 | )); |
| 263 | assert_eq!(response.usage.input_tokens, 23); |
| 264 | assert_eq!(response.usage.output_tokens, 7); |
| 265 | Ok(()) |
| 266 | } |
| 267 | |
| 268 | #[test] |
| 269 | fn malformed_tool_arguments_remain_visible_for_feedback() -> Result<()> { |
| 270 | let response = parse_chat_message(&json!({ |
| 271 | "id": "chatcmpl-ds4-malformed", |
| 272 | "model": "deepseek-v4-flash", |
| 273 | "choices": [{ |
| 274 | "message": { |
| 275 | "role": "assistant", |
| 276 | "content": null, |
| 277 | "tool_calls": [{ |
| 278 | "id": "call_bad", |
| 279 | "type": "function", |
| 280 | "function": {"name": "read_file", "arguments": "{bad json"} |
| 281 | }] |
| 282 | }, |
| 283 | "finish_reason": "tool_calls" |
| 284 | }] |
| 285 | }))?; |
| 286 | |
| 287 | assert!(matches!( |
| 288 | response.content.as_slice(), |
| 289 | [ContentBlock::ToolUse { input: Value::String(raw), ..}] if raw == "{bad json" |
| 290 | )); |
| 291 | Ok(()) |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn replay_placeholder_echo_is_dropped_from_ingest() { |
| 296 | // GLM-5.x mirrors the serializer's outgoing `(reasoning omitted)` |
| 297 | // placeholder back as a live reasoning delta. Ingesting it persisted a |
| 298 | // fake thinking block into the transcript and rendered it live. Only the |
| 299 | // exact transport echo is dropped; genuine reasoning passes through. |
| 300 | let mut content_index = 0; |
| 301 | let mut text_started = false; |
| 302 | let mut thinking_started = false; |
| 303 | let mut tool_indices = ChatToolStream::default(); |
| 304 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 305 | let chunks = [ |
| 306 | json!({ |
| 307 | "choices": [{ |
| 308 | "index": 0, |
| 309 | "delta": {"reasoning_content": "(reasoning omitted)"}, |
| 310 | "finish_reason": null |
| 311 | }] |
| 312 | }), |
| 313 | json!({ |
| 314 | "choices": [{ |
| 315 | "index": 0, |
| 316 | "delta": {"reasoning_content": " (reasoning omitted) \n"}, |
| 317 | "finish_reason": null |
| 318 | }] |
| 319 | }), |
| 320 | json!({ |
| 321 | "choices": [{ |
| 322 | "index": 0, |
| 323 | "delta": {"reasoning_content": "the user wants a table"}, |
| 324 | "finish_reason": null |
| 325 | }] |
| 326 | }), |
| 327 | ]; |
| 328 | let events = chunks |
| 329 | .iter() |
| 330 | .flat_map(|chunk| { |
| 331 | parse_sse_chunk( |
| 332 | chunk, |
| 333 | &mut content_index, |
| 334 | &mut text_started, |
| 335 | &mut thinking_started, |
| 336 | &mut tool_indices, |
| 337 | &mut reasoning_detail_buffers, |
| 338 | true, |
| 339 | ) |
| 340 | }) |
| 341 | .collect::<Vec<_>>(); |
| 342 | let thinking_deltas = events |
| 343 | .iter() |
| 344 | .filter_map(|event| match event { |
| 345 | StreamEvent::ContentBlockDelta { |
| 346 | delta: Delta::ThinkingDelta { thinking }, |
| 347 | .. |
| 348 | } => Some(thinking.as_str()), |
| 349 | _ => None, |
| 350 | }) |
| 351 | .collect::<Vec<_>>(); |
| 352 | assert_eq!( |
| 353 | thinking_deltas, |
| 354 | vec!["the user wants a table"], |
| 355 | "placeholder echoes must be dropped, real reasoning kept" |
| 356 | ); |
| 357 | } |
| 358 | |
| 359 | #[test] |
| 360 | fn streaming_fixture_accepts_delayed_tool_arguments_and_usage_tail() { |
| 361 | let mut content_index = 0; |
| 362 | let mut text_started = false; |
| 363 | let mut thinking_started = false; |
| 364 | let mut tool_indices = ChatToolStream::default(); |
| 365 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 366 | let chunks = [ |
| 367 | json!({ |
| 368 | "choices": [{ |
| 369 | "index": 0, |
| 370 | "delta": { |
| 371 | "tool_calls": [{ |
| 372 | "index": 0, |
| 373 | "id": "call_ds4_0", |
| 374 | "type": "function", |
| 375 | "function": {"name": "read_file", "arguments": "{\"path\":"} |
| 376 | }] |
| 377 | }, |
| 378 | "finish_reason": null |
| 379 | }] |
| 380 | }), |
| 381 | json!({ |
| 382 | "choices": [{ |
| 383 | "index": 0, |
| 384 | "delta": { |
| 385 | "tool_calls": [{ |
| 386 | "index": 0, |
| 387 | "function": {"arguments": "\"src/main.rs\"}"} |
| 388 | }] |
| 389 | }, |
| 390 | "finish_reason": "tool_calls" |
| 391 | }] |
| 392 | }), |
| 393 | json!({ |
| 394 | "choices": [], |
| 395 | "usage": {"prompt_tokens": 23, "completion_tokens": 7, "total_tokens": 30} |
| 396 | }), |
| 397 | ]; |
| 398 | |
| 399 | let events = chunks |
| 400 | .iter() |
| 401 | .flat_map(|chunk| { |
| 402 | parse_sse_chunk( |
| 403 | chunk, |
| 404 | &mut content_index, |
| 405 | &mut text_started, |
| 406 | &mut thinking_started, |
| 407 | &mut tool_indices, |
| 408 | &mut reasoning_detail_buffers, |
| 409 | false, |
| 410 | ) |
| 411 | }) |
| 412 | .collect::<Vec<_>>(); |
| 413 | |
| 414 | let argument_deltas = events |
| 415 | .iter() |
| 416 | .filter_map(|event| match event { |
| 417 | StreamEvent::ContentBlockDelta { |
| 418 | delta: Delta::InputJsonDelta { partial_json }, |
| 419 | .. |
| 420 | } => Some(partial_json.as_str()), |
| 421 | _ => None, |
| 422 | }) |
| 423 | .collect::<String>(); |
| 424 | assert_eq!(argument_deltas, "{\"path\":\"src/main.rs\"}"); |
| 425 | assert!(events.iter().any(|event| matches!( |
| 426 | event, |
| 427 | StreamEvent::MessageDelta { usage: Some(usage), .. } |
| 428 | if usage.input_tokens == 23 && usage.output_tokens == 7 |
| 429 | ))); |
| 430 | } |
| 431 |