| 1 | //! Drive `parse_sse_chunk` (the in-place SSE event extractor) over canned |
| 2 | //! chunk sequences. The full `handle_chat_completion_stream` path needs a |
| 3 | //! live `reqwest::Response` so it isn't unit-testable without a mock HTTP |
| 4 | //! harness (issue #69 tracks that). For #103 we exercise the chunk decoder |
| 5 | //! directly to verify each "class of stream failure" the engine relies on. |
| 6 | use super::*; |
| 7 | use crate::client::wire::{SseLineDecoder, SseLineError}; |
| 8 | const DEFAULT_GOOGLE_BASE_URL: &str = "https://generativelanguage.googleapis.com/v1beta/openai/"; |
| 9 | use codewhale_models::{ContentBlockStart, Delta, StreamEvent}; |
| 10 | |
| 11 | /// Decode a raw SSE-data JSON chunk into our internal events, mirroring |
| 12 | /// the per-event call shape used by `handle_chat_completion_stream`. |
| 13 | fn decode_chunk(json_text: &str) -> Vec<StreamEvent> { |
| 14 | decode_chunk_with_reasoning(json_text, true) |
| 15 | } |
| 16 | |
| 17 | fn decode_chunk_with_reasoning(json_text: &str, is_reasoning_model: bool) -> Vec<StreamEvent> { |
| 18 | let chunk: Value = serde_json::from_str(json_text).expect("valid SSE JSON"); |
| 19 | let mut content_index = 0u32; |
| 20 | let mut text_started = false; |
| 21 | let mut thinking_started = false; |
| 22 | let mut tool_indices = ChatToolStream::default(); |
| 23 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 24 | parse_sse_chunk( |
| 25 | &chunk, |
| 26 | &mut content_index, |
| 27 | &mut text_started, |
| 28 | &mut thinking_started, |
| 29 | &mut tool_indices, |
| 30 | &mut reasoning_detail_buffers, |
| 31 | is_reasoning_model, |
| 32 | ) |
| 33 | } |
| 34 | |
| 35 | fn decode_chunks_with_style( |
| 36 | chunks: &[&str], |
| 37 | reasoning_stream_style: ReasoningStreamStyle, |
| 38 | ) -> Vec<StreamEvent> { |
| 39 | decode_chunks_with_tool_stream(chunks, reasoning_stream_style, ChatToolStream::default()) |
| 40 | } |
| 41 | |
| 42 | fn decode_google_chunks(chunks: &[&str]) -> Vec<StreamEvent> { |
| 43 | decode_chunks_with_tool_stream( |
| 44 | chunks, |
| 45 | ReasoningStreamStyle::SeparateField, |
| 46 | ChatToolStream::for_base_url(DEFAULT_GOOGLE_BASE_URL), |
| 47 | ) |
| 48 | } |
| 49 | |
| 50 | fn decode_chunks_with_tool_stream( |
| 51 | chunks: &[&str], |
| 52 | reasoning_stream_style: ReasoningStreamStyle, |
| 53 | mut tool_indices: ChatToolStream, |
| 54 | ) -> Vec<StreamEvent> { |
| 55 | let mut content_index = 0u32; |
| 56 | let mut text_started = false; |
| 57 | let mut thinking_started = false; |
| 58 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 59 | let mut inline_reasoning_tags = InlineReasoningTagState::default(); |
| 60 | let mut events = Vec::new(); |
| 61 | |
| 62 | for chunk in chunks { |
| 63 | let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON"); |
| 64 | events.extend(parse_sse_chunk_with_reasoning_style( |
| 65 | &value, |
| 66 | &mut content_index, |
| 67 | &mut text_started, |
| 68 | &mut thinking_started, |
| 69 | &mut tool_indices, |
| 70 | &mut reasoning_detail_buffers, |
| 71 | &mut inline_reasoning_tags, |
| 72 | reasoning_stream_style, |
| 73 | )); |
| 74 | } |
| 75 | events |
| 76 | } |
| 77 | |
| 78 | /// Drive the Chat Completions SSE path with raw byte chunks so tests can |
| 79 | /// split a multi-byte UTF-8 character across HTTP/2-style DATA boundaries. |
| 80 | fn decode_sse_byte_chunks(chunks: &[&[u8]]) -> Result<Vec<StreamEvent>, SseLineError> { |
| 81 | struct FrameState { |
| 82 | line_buf: String, |
| 83 | content_index: u32, |
| 84 | text_started: bool, |
| 85 | thinking_started: bool, |
| 86 | tool_indices: ChatToolStream, |
| 87 | reasoning_detail_buffers: std::collections::HashMap<u32, String>, |
| 88 | inline_reasoning_tags: InlineReasoningTagState, |
| 89 | events: Vec<StreamEvent>, |
| 90 | } |
| 91 | |
| 92 | impl FrameState { |
| 93 | fn new() -> Self { |
| 94 | Self { |
| 95 | line_buf: String::new(), |
| 96 | content_index: 0, |
| 97 | text_started: false, |
| 98 | thinking_started: false, |
| 99 | tool_indices: ChatToolStream::default(), |
| 100 | reasoning_detail_buffers: std::collections::HashMap::new(), |
| 101 | inline_reasoning_tags: InlineReasoningTagState::default(), |
| 102 | events: Vec::new(), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | fn handle_line(&mut self, line: &str) -> bool { |
| 107 | if line.is_empty() { |
| 108 | return matches!(self.flush_frame(), SseDataFrame::Done); |
| 109 | } |
| 110 | if let Some(data) = extract_sse_data_value(line) { |
| 111 | if !self.line_buf.is_empty() { |
| 112 | self.line_buf.push('\n'); |
| 113 | } |
| 114 | self.line_buf.push_str(data); |
| 115 | } |
| 116 | false |
| 117 | } |
| 118 | |
| 119 | fn flush_frame(&mut self) -> SseDataFrame { |
| 120 | if self.line_buf.is_empty() { |
| 121 | return SseDataFrame::Events(Vec::new()); |
| 122 | } |
| 123 | let data = std::mem::take(&mut self.line_buf); |
| 124 | match parse_sse_data_frame( |
| 125 | &data, |
| 126 | &mut self.content_index, |
| 127 | &mut self.text_started, |
| 128 | &mut self.thinking_started, |
| 129 | &mut self.tool_indices, |
| 130 | &mut self.reasoning_detail_buffers, |
| 131 | &mut self.inline_reasoning_tags, |
| 132 | ReasoningStreamStyle::SeparateField, |
| 133 | ) { |
| 134 | SseDataFrame::Done => SseDataFrame::Done, |
| 135 | SseDataFrame::Events(frame_events) => { |
| 136 | self.events.extend(frame_events); |
| 137 | SseDataFrame::Events(Vec::new()) |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | let mut decoder = SseLineDecoder::new(); |
| 144 | let mut state = FrameState::new(); |
| 145 | for chunk in chunks { |
| 146 | for line in decoder.push(chunk)? { |
| 147 | if state.handle_line(&line) { |
| 148 | return Ok(state.events); |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | if let Some(line) = decoder.finish()? |
| 153 | && state.handle_line(&line) |
| 154 | { |
| 155 | return Ok(state.events); |
| 156 | } |
| 157 | state.flush_frame(); |
| 158 | Ok(state.events) |
| 159 | } |
| 160 | |
| 161 | fn cjk_content_sse(text: &str) -> Vec<u8> { |
| 162 | let payload = serde_json::json!({ |
| 163 | "choices": [{ "delta": { "content": text } }] |
| 164 | }); |
| 165 | format!("data: {payload}\n\n").into_bytes() |
| 166 | } |
| 167 | |
| 168 | fn mid_char_split(bytes: &[u8], ch: char) -> usize { |
| 169 | let needle = ch.to_string(); |
| 170 | let start = bytes |
| 171 | .windows(needle.len()) |
| 172 | .position(|window| window == needle.as_bytes()) |
| 173 | .unwrap_or_else(|| panic!("{ch:?} present in SSE frame")); |
| 174 | start + 1 |
| 175 | } |
| 176 | |
| 177 | fn text_delta_text(events: &[StreamEvent]) -> String { |
| 178 | events |
| 179 | .iter() |
| 180 | .filter_map(|event| match event { |
| 181 | StreamEvent::ContentBlockDelta { |
| 182 | delta: Delta::TextDelta { text }, |
| 183 | .. |
| 184 | } => Some(text.as_str()), |
| 185 | _ => None, |
| 186 | }) |
| 187 | .collect() |
| 188 | } |
| 189 | |
| 190 | fn thinking_delta_text(events: &[StreamEvent]) -> String { |
| 191 | events |
| 192 | .iter() |
| 193 | .filter_map(|event| match event { |
| 194 | StreamEvent::ContentBlockDelta { |
| 195 | delta: Delta::ThinkingDelta { thinking }, |
| 196 | .. |
| 197 | } => Some(thinking.as_str()), |
| 198 | _ => None, |
| 199 | }) |
| 200 | .collect() |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn decoder_reassembles_cjk_split_across_byte_chunks() { |
| 205 | let frame = cjk_content_sse("你好世界"); |
| 206 | let split = mid_char_split(&frame, '好'); |
| 207 | let events = decode_sse_byte_chunks(&[&frame[..split], &frame[split..]]).expect("valid utf-8"); |
| 208 | let text = text_delta_text(&events); |
| 209 | assert_eq!(text, "你好世界"); |
| 210 | assert!( |
| 211 | !text.contains('\u{FFFD}'), |
| 212 | "HTTP/2 mid-character split must not substitute U+FFFD; got {text:?}" |
| 213 | ); |
| 214 | } |
| 215 | |
| 216 | #[test] |
| 217 | fn decoder_reassembles_emoji_and_cjk_fed_one_byte_at_a_time() { |
| 218 | let frame = cjk_content_sse("你好🌊世界"); |
| 219 | let chunks: Vec<&[u8]> = frame.chunks(1).collect(); |
| 220 | let events = decode_sse_byte_chunks(&chunks).expect("valid utf-8"); |
| 221 | let text = text_delta_text(&events); |
| 222 | assert_eq!(text, "你好🌊世界"); |
| 223 | assert!( |
| 224 | !text.contains('\u{FFFD}'), |
| 225 | "byte-at-a-time feed garbled: {text:?}" |
| 226 | ); |
| 227 | } |
| 228 | |
| 229 | #[test] |
| 230 | fn decoder_rejects_invalid_sse_bytes_without_replacement() { |
| 231 | let mut frame = cjk_content_sse("ok"); |
| 232 | // Bare 0xFF is never valid UTF-8. Insert it inside the first SSE line. |
| 233 | let newline = frame.iter().position(|&b| b == b'\n').expect("SSE line"); |
| 234 | frame.insert(newline, 0xFF); |
| 235 | let result = decode_sse_byte_chunks(&[&frame]); |
| 236 | let err = result.expect_err("invalid SSE bytes must fail closed"); |
| 237 | assert!( |
| 238 | !err.to_string().contains('\u{FFFD}'), |
| 239 | "error path must not substitute U+FFFD: {err}" |
| 240 | ); |
| 241 | |
| 242 | // Unterminated tail of continuation bytes: fail on flush, no replacement. |
| 243 | let result = decode_sse_byte_chunks(&[&[0x80, 0xBF]]); |
| 244 | let err = result.expect_err("invalid unterminated flush must fail closed"); |
| 245 | assert!(!err.to_string().contains('\u{FFFD}')); |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn decoder_emits_text_delta_for_content_chunk() { |
| 250 | // The "happy" first chunk: a normal content delta. The engine treats |
| 251 | // this as `any_content_received = true` and would NOT transparently |
| 252 | // retry on a subsequent error. |
| 253 | let events = decode_chunk(r#"{"choices":[{"delta":{"content":"hello"}}]}"#); |
| 254 | assert!( |
| 255 | matches!( |
| 256 | events.first(), |
| 257 | Some(StreamEvent::ContentBlockStart { |
| 258 | content_block: ContentBlockStart::Text { .. }, |
| 259 | .. |
| 260 | }) |
| 261 | ), |
| 262 | "first event should open a text block; got {events:?}" |
| 263 | ); |
| 264 | assert!( |
| 265 | events |
| 266 | .iter() |
| 267 | .any(|e| matches!(e, StreamEvent::ContentBlockDelta { |
| 268 | delta: Delta::TextDelta { text }, |
| 269 | .. |
| 270 | } if text == "hello")), |
| 271 | "should yield a TextDelta carrying 'hello'; got {events:?}" |
| 272 | ); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn decoder_emits_thinking_delta_for_reasoning_chunk() { |
| 277 | // V4 thinking models surface reasoning_content first — the engine |
| 278 | // also counts these as content received (so a subsequent stream error |
| 279 | // surfaces rather than retrying transparently). |
| 280 | let events = decode_chunk(r#"{"choices":[{"delta":{"reasoning_content":"plan..."}}]}"#); |
| 281 | assert!( |
| 282 | matches!( |
| 283 | events.first(), |
| 284 | Some(StreamEvent::ContentBlockStart { |
| 285 | content_block: ContentBlockStart::Thinking { .. }, |
| 286 | .. |
| 287 | }) |
| 288 | ), |
| 289 | "first event should open a thinking block; got {events:?}" |
| 290 | ); |
| 291 | assert!( |
| 292 | events |
| 293 | .iter() |
| 294 | .any(|e| matches!(e, StreamEvent::ContentBlockDelta { |
| 295 | delta: Delta::ThinkingDelta { thinking }, |
| 296 | .. |
| 297 | } if thinking == "plan...")), |
| 298 | "should yield a ThinkingDelta carrying 'plan...'; got {events:?}" |
| 299 | ); |
| 300 | } |
| 301 | |
| 302 | #[test] |
| 303 | fn decoder_streams_moonshot_multi_chunk_reasoning_as_thinking() { |
| 304 | // #3016: recorded shape from Moonshot's native endpoint — kimi-k2.6 |
| 305 | // streams `reasoning_content` deltas before the answer text. The |
| 306 | // thinking deltas must accumulate into ONE thinking block and the |
| 307 | // answer must arrive as text, not be glued into the trace. |
| 308 | let chunks = [ |
| 309 | r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"Let me check"}}]}"#, |
| 310 | r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"reasoning_content":" the config."}}]}"#, |
| 311 | r#"{"id":"cmpl-kimi","model":"kimi-k2.6","choices":[{"index":0,"delta":{"content":"The answer is 42."}}]}"#, |
| 312 | ]; |
| 313 | |
| 314 | let is_reasoning = |
| 315 | is_reasoning_model_for_stream(codewhale_config::ProviderKind::Moonshot, "kimi-k2.6"); |
| 316 | let mut content_index = 0u32; |
| 317 | let mut text_started = false; |
| 318 | let mut thinking_started = false; |
| 319 | let mut tool_indices = ChatToolStream::default(); |
| 320 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 321 | let mut events = Vec::new(); |
| 322 | for chunk in chunks { |
| 323 | let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON"); |
| 324 | events.extend(parse_sse_chunk( |
| 325 | &value, |
| 326 | &mut content_index, |
| 327 | &mut text_started, |
| 328 | &mut thinking_started, |
| 329 | &mut tool_indices, |
| 330 | &mut reasoning_detail_buffers, |
| 331 | is_reasoning, |
| 332 | )); |
| 333 | } |
| 334 | |
| 335 | let thinking: String = events |
| 336 | .iter() |
| 337 | .filter_map(|event| match event { |
| 338 | StreamEvent::ContentBlockDelta { |
| 339 | delta: Delta::ThinkingDelta { thinking }, |
| 340 | .. |
| 341 | } => Some(thinking.as_str()), |
| 342 | _ => None, |
| 343 | }) |
| 344 | .collect(); |
| 345 | assert_eq!(thinking, "Let me check the config."); |
| 346 | |
| 347 | let thinking_starts = events |
| 348 | .iter() |
| 349 | .filter(|event| { |
| 350 | matches!( |
| 351 | event, |
| 352 | StreamEvent::ContentBlockStart { |
| 353 | content_block: ContentBlockStart::Thinking { .. }, |
| 354 | .. |
| 355 | } |
| 356 | ) |
| 357 | }) |
| 358 | .count(); |
| 359 | assert_eq!(thinking_starts, 1, "one thinking block: {events:?}"); |
| 360 | |
| 361 | let text: String = events |
| 362 | .iter() |
| 363 | .filter_map(|event| match event { |
| 364 | StreamEvent::ContentBlockDelta { |
| 365 | delta: Delta::TextDelta { text }, |
| 366 | .. |
| 367 | } => Some(text.as_str()), |
| 368 | _ => None, |
| 369 | }) |
| 370 | .collect(); |
| 371 | assert_eq!(text, "The answer is 42."); |
| 372 | } |
| 373 | |
| 374 | #[test] |
| 375 | fn decoder_accepts_openrouter_reasoning_delta_with_extra_fields() { |
| 376 | let events = decode_chunk( |
| 377 | r#"{"id":"or-1","choices":[{"delta":{"reasoning":"openrouter thought","reasoning_details":[{"type":"summary","text":"extra"}],"native_finish_reason":null}}],"usage":{"completion_tokens_details":{"reasoning_tokens":3}}}"#, |
| 378 | ); |
| 379 | |
| 380 | assert!( |
| 381 | events.iter().any(|e| matches!( |
| 382 | e, |
| 383 | StreamEvent::ContentBlockDelta { |
| 384 | delta: Delta::ThinkingDelta { thinking }, |
| 385 | .. |
| 386 | } if thinking == "openrouter thought" |
| 387 | )), |
| 388 | "OpenRouter-style reasoning deltas with extra fields should not crash decoding; got {events:?}" |
| 389 | ); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn decoder_streams_minimax_reasoning_details_as_incremental_thinking() { |
| 394 | // MiniMax's reasoning_split stream reports reasoning_details text as |
| 395 | // a cumulative buffer. Emit only the suffix so the Thinking cell does |
| 396 | // not duplicate earlier reasoning chunks. |
| 397 | let chunks = [ |
| 398 | r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"text","text":"Inspect"}]}}]}"#, |
| 399 | r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"reasoning_details":[{"type":"text","text":"Inspect config"}]}}]}"#, |
| 400 | r#"{"id":"minimax-1","choices":[{"index":0,"delta":{"content":"Done."}}]}"#, |
| 401 | ]; |
| 402 | |
| 403 | let is_reasoning = is_reasoning_model_for_stream(ProviderKind::Minimax, "MiniMax-M3"); |
| 404 | let mut content_index = 0u32; |
| 405 | let mut text_started = false; |
| 406 | let mut thinking_started = false; |
| 407 | let mut tool_indices = ChatToolStream::default(); |
| 408 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 409 | let mut events = Vec::new(); |
| 410 | for chunk in chunks { |
| 411 | let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON"); |
| 412 | events.extend(parse_sse_chunk( |
| 413 | &value, |
| 414 | &mut content_index, |
| 415 | &mut text_started, |
| 416 | &mut thinking_started, |
| 417 | &mut tool_indices, |
| 418 | &mut reasoning_detail_buffers, |
| 419 | is_reasoning, |
| 420 | )); |
| 421 | } |
| 422 | |
| 423 | let thinking: String = events |
| 424 | .iter() |
| 425 | .filter_map(|event| match event { |
| 426 | StreamEvent::ContentBlockDelta { |
| 427 | delta: Delta::ThinkingDelta { thinking }, |
| 428 | .. |
| 429 | } => Some(thinking.as_str()), |
| 430 | _ => None, |
| 431 | }) |
| 432 | .collect(); |
| 433 | assert_eq!(thinking, "Inspect config"); |
| 434 | |
| 435 | assert!(!events.iter().any(|event| matches!( |
| 436 | event, |
| 437 | StreamEvent::ContentBlockDelta { |
| 438 | delta: Delta::TextDelta { text }, |
| 439 | .. |
| 440 | } if text == "Inspect" || text == "Inspect config" |
| 441 | ))); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn modelstudio_streams_reasoning_content_as_thinking() { |
| 446 | // Recorded-style DashScope OpenAI-compatible frames (shape lifted from |
| 447 | // Model Studio's deep-thinking docs): reasoning streams in |
| 448 | // `delta.reasoning_content`, the answer in `delta.content`, and a |
| 449 | // trailing usage-only chunk closes the stream. |
| 450 | let chunks = [ |
| 451 | r#"{"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 452 | r#"{"choices":[{"delta":{"reasoning_content":"Let me think"},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 453 | r#"{"choices":[{"delta":{"reasoning_content":" about this."},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 454 | r#"{"choices":[{"delta":{"content":"The answer."},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 455 | r#"{"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0}],"object":"chat.completion.chunk","model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 456 | r#"{"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":30,"total_tokens":40,"completion_tokens_details":{"reasoning_tokens":20}},"model":"qwen3.8-max","id":"chatcmpl-ms-1"}"#, |
| 457 | ]; |
| 458 | |
| 459 | // Both OpenAI-dialect plans classify their reasoning catalog. |
| 460 | for (provider, base_url, model) in [ |
| 461 | ( |
| 462 | ProviderKind::ModelstudioTokenPlan, |
| 463 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 464 | "qwen3.8-max", |
| 465 | ), |
| 466 | ( |
| 467 | ProviderKind::ModelstudioCodingPlan, |
| 468 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL, |
| 469 | "qwen3.7-plus", |
| 470 | ), |
| 471 | ] { |
| 472 | let style = reasoning_stream_style_for_route(provider, base_url, model, None); |
| 473 | assert_eq!(style, ReasoningStreamStyle::SeparateField, "{provider:?}"); |
| 474 | |
| 475 | let mut content_index = 0u32; |
| 476 | let mut text_started = false; |
| 477 | let mut thinking_started = false; |
| 478 | let mut tool_indices = ChatToolStream::default(); |
| 479 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 480 | let mut inline_reasoning_tags = InlineReasoningTagState::default(); |
| 481 | let mut events = Vec::new(); |
| 482 | for chunk in chunks { |
| 483 | let value: Value = serde_json::from_str(chunk).expect("valid SSE JSON"); |
| 484 | events.extend(parse_sse_chunk_with_reasoning_style( |
| 485 | &value, |
| 486 | &mut content_index, |
| 487 | &mut text_started, |
| 488 | &mut thinking_started, |
| 489 | &mut tool_indices, |
| 490 | &mut reasoning_detail_buffers, |
| 491 | &mut inline_reasoning_tags, |
| 492 | style, |
| 493 | )); |
| 494 | } |
| 495 | |
| 496 | let thinking: String = events |
| 497 | .iter() |
| 498 | .filter_map(|event| match event { |
| 499 | StreamEvent::ContentBlockDelta { |
| 500 | delta: Delta::ThinkingDelta { thinking }, |
| 501 | .. |
| 502 | } => Some(thinking.as_str()), |
| 503 | _ => None, |
| 504 | }) |
| 505 | .collect(); |
| 506 | assert_eq!(thinking, "Let me think about this.", "{provider:?}"); |
| 507 | |
| 508 | let text: String = events |
| 509 | .iter() |
| 510 | .filter_map(|event| match event { |
| 511 | StreamEvent::ContentBlockDelta { |
| 512 | delta: Delta::TextDelta { text }, |
| 513 | .. |
| 514 | } => Some(text.as_str()), |
| 515 | _ => None, |
| 516 | }) |
| 517 | .collect(); |
| 518 | assert_eq!(text, "The answer.", "{provider:?}"); |
| 519 | |
| 520 | // The trailing usage chunk still surfaces token accounting. |
| 521 | assert!( |
| 522 | events.iter().any(|event| matches!( |
| 523 | event, |
| 524 | StreamEvent::MessageDelta { usage: Some(usage), .. } |
| 525 | if usage.output_tokens == 30 |
| 526 | )), |
| 527 | "{provider:?}: {events:?}" |
| 528 | ); |
| 529 | } |
| 530 | |
| 531 | // A model id the catalog does not know still routes the reasoning field |
| 532 | // to Thinking (#6501); a model that sends no reasoning field gets none. |
| 533 | let style = reasoning_stream_style_for_route( |
| 534 | ProviderKind::ModelstudioTokenPlan, |
| 535 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 536 | "qwen3.8-max-lite-unknown", |
| 537 | None, |
| 538 | ); |
| 539 | assert_eq!(style, ReasoningStreamStyle::SeparateField); |
| 540 | } |
| 541 | |
| 542 | #[test] |
| 543 | fn decoder_does_not_render_reasoning_as_text_for_known_provider_models() { |
| 544 | let mut content_index = 0u32; |
| 545 | let mut text_started = false; |
| 546 | let mut thinking_started = false; |
| 547 | let mut tool_indices = ChatToolStream::default(); |
| 548 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 549 | let is_reasoning_model = |
| 550 | is_reasoning_model_for_stream(ProviderKind::XiaomiMimo, "mimo-v2.5-pro"); |
| 551 | let events = parse_sse_chunk( |
| 552 | &serde_json::json!({ |
| 553 | "choices": [{ |
| 554 | "delta": { |
| 555 | "reasoning_content": "private plan" |
| 556 | } |
| 557 | }] |
| 558 | }), |
| 559 | &mut content_index, |
| 560 | &mut text_started, |
| 561 | &mut thinking_started, |
| 562 | &mut tool_indices, |
| 563 | &mut reasoning_detail_buffers, |
| 564 | is_reasoning_model, |
| 565 | ); |
| 566 | |
| 567 | assert!(events.iter().any(|event| matches!( |
| 568 | event, |
| 569 | StreamEvent::ContentBlockDelta { |
| 570 | delta: Delta::ThinkingDelta { thinking }, |
| 571 | .. |
| 572 | } if thinking == "private plan" |
| 573 | ))); |
| 574 | assert!(!events.iter().any(|event| matches!( |
| 575 | event, |
| 576 | StreamEvent::ContentBlockDelta { |
| 577 | delta: Delta::TextDelta { text }, |
| 578 | .. |
| 579 | } if text == "private plan" |
| 580 | ))); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn decoder_treats_reasoning_content_as_text_when_provider_does_not_support_reasoning() { |
| 585 | let events = decode_chunk_with_reasoning( |
| 586 | r#"{"choices":[{"delta":{"reasoning_content":"hello"}}]}"#, |
| 587 | false, |
| 588 | ); |
| 589 | |
| 590 | assert!( |
| 591 | matches!( |
| 592 | events.first(), |
| 593 | Some(StreamEvent::ContentBlockStart { |
| 594 | content_block: ContentBlockStart::Text { .. }, |
| 595 | .. |
| 596 | }) |
| 597 | ), |
| 598 | "first event should open a text block; got {events:?}" |
| 599 | ); |
| 600 | assert!( |
| 601 | events.iter().any(|e| matches!( |
| 602 | e, |
| 603 | StreamEvent::ContentBlockDelta { |
| 604 | delta: Delta::TextDelta { text }, |
| 605 | .. |
| 606 | } if text == "hello" |
| 607 | )), |
| 608 | "should yield a TextDelta carrying 'hello'; got {events:?}" |
| 609 | ); |
| 610 | assert!( |
| 611 | !events.iter().any(|e| matches!( |
| 612 | e, |
| 613 | StreamEvent::ContentBlockDelta { |
| 614 | delta: Delta::ThinkingDelta { .. }, |
| 615 | .. |
| 616 | } |
| 617 | )), |
| 618 | "should not emit thinking deltas for generic providers; got {events:?}" |
| 619 | ); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn reasoning_style_separate_field_routes_reasoning_to_thinking() { |
| 624 | let events = decode_chunks_with_style( |
| 625 | &[ |
| 626 | r#"{"choices":[{"delta":{"reasoning_content":"private plan"}}]}"#, |
| 627 | r#"{"choices":[{"delta":{"content":"Public answer."}}]}"#, |
| 628 | ], |
| 629 | ReasoningStreamStyle::SeparateField, |
| 630 | ); |
| 631 | |
| 632 | assert_eq!(thinking_delta_text(&events), "private plan"); |
| 633 | assert_eq!(text_delta_text(&events), "Public answer."); |
| 634 | } |
| 635 | |
| 636 | #[test] |
| 637 | fn exact_kimi_code_k3_streams_reasoning_content_as_thinking() { |
| 638 | let style = reasoning_stream_style_for_route( |
| 639 | ProviderKind::Moonshot, |
| 640 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 641 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 642 | None, |
| 643 | ); |
| 644 | assert_eq!(style, ReasoningStreamStyle::SeparateField); |
| 645 | |
| 646 | let events = decode_chunks_with_style( |
| 647 | &[r#"{"choices":[{"delta":{"reasoning_content":"private K3 plan"}}]}"#], |
| 648 | style, |
| 649 | ); |
| 650 | assert_eq!(thinking_delta_text(&events), "private K3 plan"); |
| 651 | assert_eq!(text_delta_text(&events), ""); |
| 652 | |
| 653 | let generic_style = reasoning_stream_style_for_route( |
| 654 | ProviderKind::Moonshot, |
| 655 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 656 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 657 | None, |
| 658 | ); |
| 659 | assert_eq!(generic_style, ReasoningStreamStyle::SeparateField); |
| 660 | } |
| 661 | |
| 662 | /// #6501 regression: the founder's grok-4.7 (xAI) and mimo-v2.6-pro |
| 663 | /// (Xiaomi MiMo) sessions persisted the reasoning summary glued to the answer |
| 664 | /// in one Text block ("...I should help them find large f...Sure, I'd be |
| 665 | /// happy to help"). Decode that stream shape through the real route style. |
| 666 | #[test] |
| 667 | fn issue_6501_reasoning_field_never_leaks_into_answer_text_on_unlisted_routes() { |
| 668 | for (provider, base_url, model) in [ |
| 669 | ( |
| 670 | ProviderKind::Xai, |
| 671 | codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL, |
| 672 | "grok-4.7", |
| 673 | ), |
| 674 | ( |
| 675 | ProviderKind::XiaomiMimo, |
| 676 | "https://token-plan-sgp.xiaomimimo.com/v1", |
| 677 | "mimo-v2.7-pro-unreleased", |
| 678 | ), |
| 679 | ( |
| 680 | ProviderKind::Openai, |
| 681 | "https://gateway.example.test/v1", |
| 682 | "some-new-reasoner", |
| 683 | ), |
| 684 | ] { |
| 685 | let style = reasoning_stream_style_for_route(provider, base_url, model, None); |
| 686 | assert_eq!(style, ReasoningStreamStyle::SeparateField, "{provider:?}"); |
| 687 | let events = decode_chunks_with_style( |
| 688 | &[ |
| 689 | r#"{"choices":[{"delta":{"role":"assistant","reasoning_content":"The user wants help finding large files"}}]}"#, |
| 690 | r#"{"choices":[{"delta":{"reasoning_content":"..."}}]}"#, |
| 691 | r#"{"choices":[{"delta":{"content":"Sure, I'd be happy to help."}}]}"#, |
| 692 | r#"{"choices":[{"delta":{"reasoning":"then a tool"}}]}"#, |
| 693 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"exec_shell","arguments":"{}"}}]}}]}"#, |
| 694 | r#"{"choices":[{"finish_reason":"tool_calls"}]}"#, |
| 695 | ], |
| 696 | style, |
| 697 | ); |
| 698 | assert_eq!( |
| 699 | thinking_delta_text(&events), |
| 700 | "The user wants help finding large files...then a tool", |
| 701 | "{provider:?}" |
| 702 | ); |
| 703 | assert_eq!( |
| 704 | text_delta_text(&events), |
| 705 | "Sure, I'd be happy to help.", |
| 706 | "{provider:?}: reasoning must not reach answer text" |
| 707 | ); |
| 708 | assert!( |
| 709 | events.iter().any(|event| matches!( |
| 710 | event, |
| 711 | StreamEvent::ContentBlockStart { |
| 712 | content_block: ContentBlockStart::ToolUse { .. }, |
| 713 | .. |
| 714 | } |
| 715 | )), |
| 716 | "{provider:?}: reasoning -> tool call transition must keep the tool call" |
| 717 | ); |
| 718 | } |
| 719 | |
| 720 | // The explicit opt-out keeps the legacy pass-through for gateways that |
| 721 | // really stream their answer in `reasoning_content`. |
| 722 | let passthrough = decode_chunks_with_style( |
| 723 | &[r#"{"choices":[{"delta":{"reasoning_content":"answer via reasoning field"}}]}"#], |
| 724 | reasoning_stream_style_for_route( |
| 725 | ProviderKind::Openai, |
| 726 | "https://gateway.example.test/v1", |
| 727 | "some-new-reasoner", |
| 728 | Some("none"), |
| 729 | ), |
| 730 | ); |
| 731 | assert_eq!(thinking_delta_text(&passthrough), ""); |
| 732 | assert_eq!(text_delta_text(&passthrough), "answer via reasoning field"); |
| 733 | } |
| 734 | |
| 735 | #[test] |
| 736 | fn reasoning_style_inline_tags_routes_think_blocks_to_thinking() { |
| 737 | let events = decode_chunks_with_style( |
| 738 | &[ |
| 739 | r#"{"choices":[{"delta":{"content":"Before <thi"}}]}"#, |
| 740 | r#"{"choices":[{"delta":{"content":"nk>private plan</thi"}}]}"#, |
| 741 | r#"{"choices":[{"delta":{"content":"nk> after."}}]}"#, |
| 742 | ], |
| 743 | ReasoningStreamStyle::InlineTags, |
| 744 | ); |
| 745 | |
| 746 | assert_eq!(thinking_delta_text(&events), "private plan"); |
| 747 | assert_eq!(text_delta_text(&events), "Before after."); |
| 748 | assert!( |
| 749 | !text_delta_text(&events).contains("<think>"), |
| 750 | "inline reasoning tags must not leak into visible text: {events:?}" |
| 751 | ); |
| 752 | } |
| 753 | |
| 754 | #[test] |
| 755 | fn reasoning_style_inline_tags_flushes_unclosed_think_at_stream_end() { |
| 756 | let events = decode_chunks_with_style( |
| 757 | &[ |
| 758 | r#"{"choices":[{"delta":{"content":"Before <think>partial reasoning"}}]}"#, |
| 759 | r#"{"choices":[{"finish_reason":"stop"}]}"#, |
| 760 | ], |
| 761 | ReasoningStreamStyle::InlineTags, |
| 762 | ); |
| 763 | |
| 764 | assert_eq!(thinking_delta_text(&events), "partial reasoning"); |
| 765 | assert_eq!(text_delta_text(&events), "Before "); |
| 766 | } |
| 767 | |
| 768 | #[test] |
| 769 | fn reasoning_style_inline_tags_ignores_separate_reasoning_field() { |
| 770 | let events = decode_chunks_with_style( |
| 771 | &[ |
| 772 | r#"{"choices":[{"delta":{"reasoning_content":"metadata","content":"<think>tagged</think> answer"}}]}"#, |
| 773 | ], |
| 774 | ReasoningStreamStyle::InlineTags, |
| 775 | ); |
| 776 | |
| 777 | assert_eq!(thinking_delta_text(&events), "tagged"); |
| 778 | assert_eq!(text_delta_text(&events), " answer"); |
| 779 | } |
| 780 | |
| 781 | #[test] |
| 782 | fn reasoning_style_none_keeps_inline_tags_visible_text() { |
| 783 | let events = decode_chunks_with_style( |
| 784 | &[r#"{"choices":[{"delta":{"content":"<think>visible</think> answer"}}]}"#], |
| 785 | ReasoningStreamStyle::None, |
| 786 | ); |
| 787 | |
| 788 | assert_eq!(thinking_delta_text(&events), ""); |
| 789 | assert_eq!(text_delta_text(&events), "<think>visible</think> answer"); |
| 790 | } |
| 791 | |
| 792 | #[test] |
| 793 | fn configured_reasoning_style_overrides_route_default() { |
| 794 | assert_eq!( |
| 795 | reasoning_stream_style_for_stream(ProviderKind::Openai, "custom-minimax", None), |
| 796 | ReasoningStreamStyle::SeparateField |
| 797 | ); |
| 798 | assert_eq!( |
| 799 | reasoning_stream_style_for_stream( |
| 800 | ProviderKind::Openai, |
| 801 | "custom-minimax", |
| 802 | Some("inline-tags") |
| 803 | ), |
| 804 | ReasoningStreamStyle::InlineTags |
| 805 | ); |
| 806 | assert_eq!( |
| 807 | reasoning_stream_style_for_stream(ProviderKind::XiaomiMimo, "mimo-v2.5-pro", None), |
| 808 | ReasoningStreamStyle::SeparateField |
| 809 | ); |
| 810 | assert_eq!( |
| 811 | reasoning_stream_style_for_stream(ProviderKind::XiaomiMimo, "mimo-v2.5-pro", Some("none")), |
| 812 | ReasoningStreamStyle::None |
| 813 | ); |
| 814 | } |
| 815 | |
| 816 | #[test] |
| 817 | fn decoder_yields_no_events_for_keepalive_chunk() { |
| 818 | // DeepSeek often sends `{"choices":[]}` keepalive chunks before |
| 819 | // emitting real content. The engine MUST treat a stream error after |
| 820 | // these as "no content received" and be eligible for transparent |
| 821 | // retry — assert here that the decoder yields no payload events. |
| 822 | let events = decode_chunk(r#"{"choices":[]}"#); |
| 823 | assert!( |
| 824 | events.is_empty(), |
| 825 | "empty-choices chunk must produce no events; got {events:?}" |
| 826 | ); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn decoder_treats_done_frame_as_terminal() { |
| 831 | let mut content_index = 0u32; |
| 832 | let mut text_started = false; |
| 833 | let mut thinking_started = false; |
| 834 | let mut tool_indices = ChatToolStream::default(); |
| 835 | let mut reasoning_detail_buffers = std::collections::HashMap::new(); |
| 836 | let mut inline_reasoning_tags = InlineReasoningTagState::default(); |
| 837 | |
| 838 | let outcome = parse_sse_data_frame( |
| 839 | " [DONE] ", |
| 840 | &mut content_index, |
| 841 | &mut text_started, |
| 842 | &mut thinking_started, |
| 843 | &mut tool_indices, |
| 844 | &mut reasoning_detail_buffers, |
| 845 | &mut inline_reasoning_tags, |
| 846 | ReasoningStreamStyle::SeparateField, |
| 847 | ); |
| 848 | |
| 849 | assert!( |
| 850 | matches!(outcome, SseDataFrame::Done), |
| 851 | "`data: [DONE]` must terminate the stream instead of waiting for the HTTP connection to close" |
| 852 | ); |
| 853 | assert_eq!(content_index, 0); |
| 854 | assert!(!text_started); |
| 855 | assert!(!thinking_started); |
| 856 | assert!(tool_indices.calls.is_empty()); |
| 857 | } |
| 858 | |
| 859 | #[test] |
| 860 | fn decoder_emits_tool_use_block_for_tool_call_delta() { |
| 861 | // Tool-call deltas are content too — once one arrives, transparent |
| 862 | // retry must be off (the model has committed to a tool invocation |
| 863 | // path that DeepSeek has billed for). |
| 864 | let events = decode_chunk( |
| 865 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"grep_files","arguments":"{\"pattern\":\"foo\"}"}}]}}]}"#, |
| 866 | ); |
| 867 | assert!( |
| 868 | events.iter().any(|e| matches!( |
| 869 | e, |
| 870 | StreamEvent::ContentBlockStart { |
| 871 | content_block: ContentBlockStart::ToolUse { name, ..}, |
| 872 | .. |
| 873 | } if name == "grep_files" |
| 874 | )), |
| 875 | "should open a ToolUse block for grep_files; got {events:?}" |
| 876 | ); |
| 877 | assert!( |
| 878 | events.iter().any(|e| matches!( |
| 879 | e, |
| 880 | StreamEvent::ContentBlockDelta { |
| 881 | delta: Delta::InputJsonDelta { partial_json }, |
| 882 | .. |
| 883 | } if partial_json.contains("\"pattern\"") |
| 884 | )), |
| 885 | "should yield InputJsonDelta carrying the tool args; got {events:?}" |
| 886 | ); |
| 887 | } |
| 888 | |
| 889 | #[test] |
| 890 | fn decoder_uses_fallback_name_for_empty_streaming_tool_name() { |
| 891 | let events = decode_chunk( |
| 892 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_empty","function":{"name":"","arguments":"{}"}}]}}]}"#, |
| 893 | ); |
| 894 | |
| 895 | assert!( |
| 896 | events.iter().any(|event| matches!( |
| 897 | event, |
| 898 | StreamEvent::ContentBlockStart { |
| 899 | content_block: ContentBlockStart::ToolUse { name, ..}, |
| 900 | .. |
| 901 | } if name == "unknown_tool" |
| 902 | )), |
| 903 | "empty upstream tool names should render as unknown_tool; got {events:?}" |
| 904 | ); |
| 905 | } |
| 906 | |
| 907 | #[test] |
| 908 | fn non_streaming_response_uses_fallback_name_for_missing_tool_name() { |
| 909 | let payload: Value = serde_json::from_str( |
| 910 | r#"{ |
| 911 | "id": "chatcmpl_1", |
| 912 | "model": "deepseek-v4-pro", |
| 913 | "choices": [{ |
| 914 | "message": { |
| 915 | "role": "assistant", |
| 916 | "tool_calls": [{ |
| 917 | "id": "call_missing", |
| 918 | "function": { "arguments": "{}" } |
| 919 | }] |
| 920 | }, |
| 921 | "finish_reason": "tool_calls" |
| 922 | }] |
| 923 | }"#, |
| 924 | ) |
| 925 | .expect("valid response"); |
| 926 | |
| 927 | let parsed = parse_chat_message(&payload).expect("message parses"); |
| 928 | let tool_name = parsed.content.iter().find_map(|block| match block { |
| 929 | ContentBlock::ToolUse { name, .. } => Some(name.as_str()), |
| 930 | _ => None, |
| 931 | }); |
| 932 | |
| 933 | assert_eq!(tool_name, Some("unknown_tool")); |
| 934 | } |
| 935 | |
| 936 | /// Regression for the parallel-tool-calls-without-id collision (audit |
| 937 | /// Finding 8): when the upstream chunk omits the `id` field, the |
| 938 | /// fallback used to be the literal string `"tool_call"` for every |
| 939 | /// parallel call, so two tool calls in one delta ended up sharing an |
| 940 | /// id. Downstream routing then matched the first call's tool_result |
| 941 | /// twice and the second call hung. |
| 942 | #[test] |
| 943 | fn decoder_assigns_unique_fallback_ids_to_parallel_tool_calls_missing_id() { |
| 944 | let events = decode_chunk( |
| 945 | r#"{"choices":[{"delta":{"tool_calls":[ |
| 946 | {"index":0,"function":{"name":"grep_files","arguments":"{\"pattern\":\"a\"}"}}, |
| 947 | {"index":1,"function":{"name":"read_file","arguments":"{\"path\":\"x\"}"}} |
| 948 | ]},"finish_reason":"tool_calls"}]}"#, |
| 949 | ); |
| 950 | |
| 951 | let ids = finalized_tool_call_ids(&events); |
| 952 | |
| 953 | assert_eq!( |
| 954 | ids.len(), |
| 955 | 2, |
| 956 | "expected two tool-use blocks for parallel tool calls; got {events:?}" |
| 957 | ); |
| 958 | assert_ne!( |
| 959 | ids[0], ids[1], |
| 960 | "parallel tool calls without upstream `id` must get distinct fallback ids; got {ids:?}" |
| 961 | ); |
| 962 | } |
| 963 | |
| 964 | /// Twin of `decoder_assigns_unique_fallback_ids_to_parallel_tool_calls_missing_id` |
| 965 | /// for the non-streaming `parse_chat_message` path (audit Finding V3): a |
| 966 | /// `chat/completions` response whose `tool_calls` entries omit `id` used to |
| 967 | /// give every call the literal fallback `"tool_call"`, so parallel calls |
| 968 | /// shared one id and the whole-response admission in |
| 969 | /// `validate_tool_call_ids_for_protocol` rejected the turn as a duplicate |
| 970 | /// pairing id. The fallback is now indexed by the tool-call position. |
| 971 | #[test] |
| 972 | fn non_streaming_assigns_unique_fallback_ids_to_parallel_tool_calls_missing_id() { |
| 973 | let payload: Value = serde_json::from_str( |
| 974 | r#"{ |
| 975 | "id": "chatcmpl_2", |
| 976 | "model": "deepseek-v4-pro", |
| 977 | "choices": [{ |
| 978 | "message": { |
| 979 | "role": "assistant", |
| 980 | "tool_calls": [ |
| 981 | { "function": { "name": "grep_files", "arguments": "{\"pattern\":\"a\"}" } }, |
| 982 | { "function": { "name": "read_file", "arguments": "{\"path\":\"x\"}" } } |
| 983 | ] |
| 984 | }, |
| 985 | "finish_reason": "tool_calls" |
| 986 | }] |
| 987 | }"#, |
| 988 | ) |
| 989 | .expect("valid response"); |
| 990 | |
| 991 | let parsed = parse_chat_message(&payload).expect("message parses"); |
| 992 | let ids: Vec<&str> = parsed |
| 993 | .content |
| 994 | .iter() |
| 995 | .filter_map(|block| match block { |
| 996 | ContentBlock::ToolUse { id, .. } => Some(id.as_str()), |
| 997 | _ => None, |
| 998 | }) |
| 999 | .collect(); |
| 1000 | |
| 1001 | assert_eq!( |
| 1002 | ids.len(), |
| 1003 | 2, |
| 1004 | "expected two tool-use blocks for parallel tool calls; got {ids:?}" |
| 1005 | ); |
| 1006 | assert_ne!( |
| 1007 | ids[0], ids[1], |
| 1008 | "parallel tool calls without upstream `id` must get distinct fallback ids; got {ids:?}" |
| 1009 | ); |
| 1010 | crate::client::validate_tool_call_ids_for_protocol( |
| 1011 | codewhale_config::provider::WireFormat::ChatCompletions, |
| 1012 | ids.iter().copied(), |
| 1013 | ) |
| 1014 | .expect("distinct fallback ids pass whole-response admission"); |
| 1015 | } |
| 1016 | |
| 1017 | #[test] |
| 1018 | fn decoder_fallback_id_does_not_collide_with_literal_call_index_id() { |
| 1019 | let events = decode_chunk( |
| 1020 | r#"{"choices":[{"delta":{"tool_calls":[ |
| 1021 | {"index":0,"id":"call_1","function":{"name":"grep_files","arguments":"{}"}}, |
| 1022 | {"index":1,"function":{"name":"read_file","arguments":"{}"}} |
| 1023 | ]},"finish_reason":"tool_calls"}]}"#, |
| 1024 | ); |
| 1025 | |
| 1026 | let ids = finalized_tool_call_ids(&events); |
| 1027 | |
| 1028 | assert_eq!(ids.len(), 2, "expected two tool-use blocks; got {events:?}"); |
| 1029 | assert_eq!(ids[0], "call_1"); |
| 1030 | assert_eq!( |
| 1031 | ids[1], "call_missing_1", |
| 1032 | "the id-less call gets its fallback id; got {ids:?}" |
| 1033 | ); |
| 1034 | assert_ne!(ids[0], ids[1]); |
| 1035 | crate::client::validate_tool_call_ids_for_protocol( |
| 1036 | codewhale_config::provider::WireFormat::ChatCompletions, |
| 1037 | ids.iter().copied(), |
| 1038 | ) |
| 1039 | .expect("a literal call_1 and a synthesized call_missing_1 are distinct"); |
| 1040 | } |
| 1041 | |
| 1042 | /// Twin of `decoder_fallback_id_does_not_collide_with_literal_call_index_id` |
| 1043 | /// for the non-streaming parser. |
| 1044 | #[test] |
| 1045 | fn non_streaming_fallback_id_does_not_collide_with_literal_call_index_id() { |
| 1046 | let payload: Value = serde_json::from_str( |
| 1047 | r#"{ |
| 1048 | "id": "chatcmpl_3", |
| 1049 | "model": "deepseek-v4-pro", |
| 1050 | "choices": [{ |
| 1051 | "message": { |
| 1052 | "role": "assistant", |
| 1053 | "tool_calls": [ |
| 1054 | { "id": "call_1", "function": { "name": "grep_files", "arguments": "{}" } }, |
| 1055 | { "function": { "name": "read_file", "arguments": "{}" } } |
| 1056 | ] |
| 1057 | }, |
| 1058 | "finish_reason": "tool_calls" |
| 1059 | }] |
| 1060 | }"#, |
| 1061 | ) |
| 1062 | .expect("valid response"); |
| 1063 | |
| 1064 | let parsed = parse_chat_message(&payload).expect("message parses"); |
| 1065 | let ids: Vec<&str> = parsed |
| 1066 | .content |
| 1067 | .iter() |
| 1068 | .filter_map(|block| match block { |
| 1069 | ContentBlock::ToolUse { id, .. } => Some(id.as_str()), |
| 1070 | _ => None, |
| 1071 | }) |
| 1072 | .collect(); |
| 1073 | |
| 1074 | assert_eq!(ids.len(), 2, "expected two tool-use blocks; got {ids:?}"); |
| 1075 | assert_eq!(ids[0], "call_1"); |
| 1076 | assert_eq!( |
| 1077 | ids[1], "call_missing_1", |
| 1078 | "the id-less call gets its fallback id; got {ids:?}" |
| 1079 | ); |
| 1080 | assert_ne!(ids[0], ids[1]); |
| 1081 | crate::client::validate_tool_call_ids_for_protocol( |
| 1082 | codewhale_config::provider::WireFormat::ChatCompletions, |
| 1083 | ids.iter().copied(), |
| 1084 | ) |
| 1085 | .expect("a literal call_1 and a synthesized call_missing_1 are distinct"); |
| 1086 | } |
| 1087 | |
| 1088 | fn finalized_tool_call_ids(events: &[StreamEvent]) -> Vec<&str> { |
| 1089 | let mut ids = std::collections::BTreeMap::new(); |
| 1090 | for event in events { |
| 1091 | match event { |
| 1092 | StreamEvent::ContentBlockStart { |
| 1093 | index, |
| 1094 | content_block: ContentBlockStart::ToolUse { id, .. }, |
| 1095 | } |
| 1096 | | StreamEvent::ContentBlockDelta { |
| 1097 | index, |
| 1098 | delta: Delta::ToolCallIdDelta { id }, |
| 1099 | } => { |
| 1100 | ids.insert(*index, id.as_str()); |
| 1101 | } |
| 1102 | _ => {} |
| 1103 | } |
| 1104 | } |
| 1105 | ids.into_values().collect() |
| 1106 | } |
| 1107 | |
| 1108 | #[test] |
| 1109 | fn fallback_identity_matches_non_streaming_with_late_literal_ids() { |
| 1110 | let events = decode_chunks_with_style( |
| 1111 | &[ |
| 1112 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"read_file","arguments":"{"}}]}}]}"#, |
| 1113 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"}"}},{"index":1,"function":{"name":"grep_files","arguments":"{}"}}]}}]}"#, |
| 1114 | r#"{"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_missing_0"}]},"finish_reason":"tool_calls"}]}"#, |
| 1115 | ], |
| 1116 | ReasoningStreamStyle::None, |
| 1117 | ); |
| 1118 | let ids = finalized_tool_call_ids(&events); |
| 1119 | let message = parse_chat_message(&json!({"choices":[{"message":{"tool_calls":[ |
| 1120 | {"function":{"name":"read_file","arguments":"{}"}}, |
| 1121 | {"id":"call_missing_0","function":{"name":"grep_files","arguments":"{}"}} |
| 1122 | ]}}]})) |
| 1123 | .expect("message parses"); |
| 1124 | let non_streaming: Vec<_> = message |
| 1125 | .content |
| 1126 | .iter() |
| 1127 | .filter_map(|block| match block { |
| 1128 | ContentBlock::ToolUse { id, .. } => Some(id.as_str()), |
| 1129 | _ => None, |
| 1130 | }) |
| 1131 | .collect(); |
| 1132 | assert_eq!(ids, non_streaming); |
| 1133 | assert_eq!(ids, ["call_missing_0_1", "call_missing_0"]); |
| 1134 | crate::client::validate_tool_call_ids_for_protocol( |
| 1135 | codewhale_config::provider::WireFormat::ChatCompletions, |
| 1136 | ids.iter().copied(), |
| 1137 | ) |
| 1138 | .expect("provider and generated ids pass admission"); |
| 1139 | } |
| 1140 | |
| 1141 | #[test] |
| 1142 | fn decoder_preserves_upstream_tool_call_id_when_present() { |
| 1143 | // Counter-test to the fallback regression: when the upstream chunk |
| 1144 | // does include `id`, we forward it verbatim — we shouldn't quietly |
| 1145 | // rewrite ids the API gave us just because we have a fallback path. |
| 1146 | let events = decode_chunk( |
| 1147 | r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_xyz","function":{"name":"grep_files","arguments":"{}"}}]}}]}"#, |
| 1148 | ); |
| 1149 | let id = events |
| 1150 | .iter() |
| 1151 | .find_map(|e| match e { |
| 1152 | StreamEvent::ContentBlockStart { |
| 1153 | content_block: ContentBlockStart::ToolUse { id, .. }, |
| 1154 | .. |
| 1155 | } => Some(id.as_str()), |
| 1156 | _ => None, |
| 1157 | }) |
| 1158 | .expect("tool-use block present"); |
| 1159 | assert_eq!(id, "call_xyz"); |
| 1160 | } |
| 1161 | |
| 1162 | #[test] |
| 1163 | fn request_builder_preserves_internal_system_messages() { |
| 1164 | let messages = vec![Message { |
| 1165 | role: Role::System, |
| 1166 | content: vec![ContentBlock::Text { |
| 1167 | text: "internal runtime event".to_string(), |
| 1168 | cache_control: None, |
| 1169 | }], |
| 1170 | }]; |
| 1171 | |
| 1172 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1173 | |
| 1174 | assert_eq!(built.len(), 1); |
| 1175 | assert_eq!(built[0]["role"], "system"); |
| 1176 | assert_eq!(built[0]["content"], "internal runtime event"); |
| 1177 | } |
| 1178 | |
| 1179 | fn tool_use_message(id: &str, name: &str, input: Value) -> Message { |
| 1180 | Message { |
| 1181 | role: Role::Assistant, |
| 1182 | content: vec![ContentBlock::ToolUse { |
| 1183 | execution_id: None, |
| 1184 | id: id.to_string(), |
| 1185 | name: name.to_string(), |
| 1186 | input, |
| 1187 | caller: None, |
| 1188 | thought_signature: None, |
| 1189 | }], |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | fn tool_result_message(id: &str, content: &str) -> Message { |
| 1194 | Message { |
| 1195 | role: Role::User, |
| 1196 | content: vec![ContentBlock::ToolResult { |
| 1197 | execution_id: None, |
| 1198 | tool_use_id: id.to_string(), |
| 1199 | content: content.to_string(), |
| 1200 | is_error: None, |
| 1201 | content_blocks: None, |
| 1202 | }], |
| 1203 | } |
| 1204 | } |
| 1205 | |
| 1206 | fn user_message_with_turn_meta(turn_meta: &str, task: &str) -> Message { |
| 1207 | Message { |
| 1208 | role: Role::User, |
| 1209 | content: vec![ |
| 1210 | ContentBlock::Text { |
| 1211 | text: turn_meta.to_string(), |
| 1212 | cache_control: None, |
| 1213 | }, |
| 1214 | ContentBlock::Text { |
| 1215 | text: task.to_string(), |
| 1216 | cache_control: None, |
| 1217 | }, |
| 1218 | ], |
| 1219 | } |
| 1220 | } |
| 1221 | |
| 1222 | fn user_message_with_tail_turn_meta(task: &str, turn_meta: &str) -> Message { |
| 1223 | Message { |
| 1224 | role: Role::User, |
| 1225 | content: vec![ |
| 1226 | ContentBlock::Text { |
| 1227 | text: task.to_string(), |
| 1228 | cache_control: None, |
| 1229 | }, |
| 1230 | ContentBlock::Text { |
| 1231 | text: turn_meta.to_string(), |
| 1232 | cache_control: None, |
| 1233 | }, |
| 1234 | ], |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | fn tool_message_content(messages: &[Value], index: usize) -> &str { |
| 1239 | messages |
| 1240 | .iter() |
| 1241 | .filter(|message| message.get("role").and_then(Value::as_str) == Some("tool")) |
| 1242 | .nth(index) |
| 1243 | .and_then(|message| message.get("content").and_then(Value::as_str)) |
| 1244 | .expect("tool message content") |
| 1245 | } |
| 1246 | |
| 1247 | fn user_message_content(messages: &[Value], index: usize) -> &str { |
| 1248 | messages |
| 1249 | .iter() |
| 1250 | .filter(|message| message.get("role").and_then(Value::as_str) == Some("user")) |
| 1251 | .nth(index) |
| 1252 | .and_then(|message| message.get("content").and_then(Value::as_str)) |
| 1253 | .expect("user message content") |
| 1254 | } |
| 1255 | |
| 1256 | fn with_tool_result_sha_spillover_root<T>(f: impl FnOnce() -> T) -> T { |
| 1257 | let _guard = crate::tools::truncate::TEST_SPILLOVER_GUARD |
| 1258 | .lock() |
| 1259 | .unwrap_or_else(|err| err.into_inner()); |
| 1260 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1261 | let prior = crate::tools::truncate::set_test_spillover_root(Some( |
| 1262 | tmp.path().join(".deepseek").join("tool_outputs"), |
| 1263 | )); |
| 1264 | struct Restore(Option<std::path::PathBuf>); |
| 1265 | impl Drop for Restore { |
| 1266 | fn drop(&mut self) { |
| 1267 | crate::tools::truncate::set_test_spillover_root(self.0.take()); |
| 1268 | } |
| 1269 | } |
| 1270 | let _restore = Restore(prior); |
| 1271 | f() |
| 1272 | } |
| 1273 | |
| 1274 | #[test] |
| 1275 | fn request_builder_deduplicates_consecutive_identical_turn_meta_for_wire() { |
| 1276 | let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>"; |
| 1277 | let messages = vec![ |
| 1278 | user_message_with_turn_meta(turn_meta, "first task"), |
| 1279 | Message { |
| 1280 | role: Role::Assistant, |
| 1281 | content: vec![ContentBlock::Text { |
| 1282 | text: "first answer".to_string(), |
| 1283 | cache_control: None, |
| 1284 | }], |
| 1285 | }, |
| 1286 | user_message_with_turn_meta(turn_meta, "second task"), |
| 1287 | ]; |
| 1288 | |
| 1289 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1290 | let first = user_message_content(&built, 0); |
| 1291 | let second = user_message_content(&built, 1); |
| 1292 | let expected_ref = "<turn_meta_unchanged />"; |
| 1293 | |
| 1294 | assert!(first.starts_with(turn_meta), "got: {first}"); |
| 1295 | assert!(second.starts_with(expected_ref), "got: {second}"); |
| 1296 | assert!(second.ends_with("second task"), "got: {second}"); |
| 1297 | assert_eq!( |
| 1298 | second, |
| 1299 | format!("{expected_ref}\nsecond task"), |
| 1300 | "ref text must stay stable" |
| 1301 | ); |
| 1302 | } |
| 1303 | |
| 1304 | #[test] |
| 1305 | fn request_builder_keeps_tail_turn_meta_after_user_text_for_wire() { |
| 1306 | let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>"; |
| 1307 | let messages = vec![ |
| 1308 | user_message_with_tail_turn_meta("first task", turn_meta), |
| 1309 | Message { |
| 1310 | role: Role::Assistant, |
| 1311 | content: vec![ContentBlock::Text { |
| 1312 | text: "first answer".to_string(), |
| 1313 | cache_control: None, |
| 1314 | }], |
| 1315 | }, |
| 1316 | user_message_with_tail_turn_meta("second task", turn_meta), |
| 1317 | ]; |
| 1318 | |
| 1319 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1320 | let first = user_message_content(&built, 0); |
| 1321 | let second = user_message_content(&built, 1); |
| 1322 | let expected_ref = "<turn_meta_unchanged />"; |
| 1323 | |
| 1324 | assert_eq!(first, format!("first task\n{turn_meta}")); |
| 1325 | assert_eq!(second, format!("second task\n{expected_ref}")); |
| 1326 | } |
| 1327 | |
| 1328 | #[test] |
| 1329 | fn request_builder_keeps_changed_turn_meta_full_and_updates_recent_hash() { |
| 1330 | let first_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>"; |
| 1331 | let second_meta = |
| 1332 | "<turn_meta>\nCurrent local date: 2026-05-09\nWorking set: src/lib.rs\n</turn_meta>"; |
| 1333 | let messages = vec![ |
| 1334 | user_message_with_turn_meta(first_meta, "first task"), |
| 1335 | user_message_with_turn_meta(second_meta, "second task"), |
| 1336 | ]; |
| 1337 | |
| 1338 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1339 | let first = user_message_content(&built, 0); |
| 1340 | let second = user_message_content(&built, 1); |
| 1341 | |
| 1342 | assert!(first.starts_with(first_meta), "got: {first}"); |
| 1343 | assert!(second.starts_with(second_meta), "got: {second}"); |
| 1344 | assert!(!second.contains("<TURN_META_REF"), "got: {second}"); |
| 1345 | } |
| 1346 | |
| 1347 | #[test] |
| 1348 | fn turn_meta_dedup_is_wire_only_and_does_not_mutate_session_message() { |
| 1349 | let turn_meta = "<turn_meta>\nCurrent local date: 2026-05-09\n</turn_meta>"; |
| 1350 | let messages = vec![ |
| 1351 | user_message_with_turn_meta(turn_meta, "first task"), |
| 1352 | user_message_with_turn_meta(turn_meta, "second task"), |
| 1353 | ]; |
| 1354 | |
| 1355 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1356 | assert!( |
| 1357 | user_message_content(&built, 1).starts_with("<turn_meta_unchanged />"), |
| 1358 | "got: {}", |
| 1359 | user_message_content(&built, 1) |
| 1360 | ); |
| 1361 | |
| 1362 | match &messages[1].content[0] { |
| 1363 | ContentBlock::Text { text, .. } => assert_eq!(text, turn_meta), |
| 1364 | other => panic!("expected text block, got {other:?}"), |
| 1365 | } |
| 1366 | } |
| 1367 | |
| 1368 | #[test] |
| 1369 | fn cache_inspect_reports_turn_meta_dedup_metadata() { |
| 1370 | let turn_meta = format!( |
| 1371 | "<turn_meta>\nCurrent local date: 2026-05-09\n{}\n</turn_meta>", |
| 1372 | "Working set: src/lib.rs\n".repeat(20) |
| 1373 | ); |
| 1374 | let request = MessageRequest { |
| 1375 | model: "deepseek-v4-flash".to_string(), |
| 1376 | messages: vec![ |
| 1377 | user_message_with_turn_meta(&turn_meta, "first task"), |
| 1378 | user_message_with_turn_meta(&turn_meta, "second task"), |
| 1379 | ], |
| 1380 | max_tokens: 0, |
| 1381 | system: None, |
| 1382 | tools: None, |
| 1383 | tool_choice: None, |
| 1384 | metadata: None, |
| 1385 | thinking: None, |
| 1386 | reasoning_effort: None, |
| 1387 | stream: None, |
| 1388 | temperature: None, |
| 1389 | top_p: None, |
| 1390 | safety_check: None, |
| 1391 | title: None, |
| 1392 | }; |
| 1393 | |
| 1394 | let inspection = inspect_prompt_for_request(&request); |
| 1395 | let turn_meta_layers: Vec<_> = inspection |
| 1396 | .layers |
| 1397 | .iter() |
| 1398 | .filter_map(|layer| layer.turn_meta.as_ref()) |
| 1399 | .collect(); |
| 1400 | |
| 1401 | assert_eq!(turn_meta_layers.len(), 2); |
| 1402 | assert_eq!( |
| 1403 | turn_meta_layers[0].original_chars, |
| 1404 | turn_meta.chars().count() |
| 1405 | ); |
| 1406 | assert_eq!(turn_meta_layers[0].sent_chars, turn_meta.chars().count()); |
| 1407 | assert!(!turn_meta_layers[0].deduplicated); |
| 1408 | assert_eq!(turn_meta_layers[0].sha256, sha256_hex(turn_meta.as_bytes())); |
| 1409 | assert_eq!( |
| 1410 | turn_meta_layers[1].original_chars, |
| 1411 | turn_meta.chars().count() |
| 1412 | ); |
| 1413 | assert!(turn_meta_layers[1].sent_chars < turn_meta_layers[1].original_chars); |
| 1414 | assert!(turn_meta_layers[1].deduplicated); |
| 1415 | assert_eq!(turn_meta_layers[1].sha256, turn_meta_layers[0].sha256); |
| 1416 | } |
| 1417 | |
| 1418 | #[test] |
| 1419 | fn request_builder_truncates_large_tool_result_for_wire() { |
| 1420 | let long_output = format!("{}{}", "A".repeat(70_000), "Z".repeat(70_000)); |
| 1421 | let messages = vec![ |
| 1422 | tool_use_message( |
| 1423 | "tool-long", |
| 1424 | "shell_command", |
| 1425 | json!({"command": "cargo test"}), |
| 1426 | ), |
| 1427 | tool_result_message("tool-long", &long_output), |
| 1428 | ]; |
| 1429 | |
| 1430 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1431 | let sent = tool_message_content(&built, 0); |
| 1432 | |
| 1433 | assert!(sent.contains("[TOOL_RESULT_TRUNCATED]"), "got: {sent}"); |
| 1434 | assert!(sent.contains("tool_name: shell_command"), "got: {sent}"); |
| 1435 | assert!(sent.contains("command_or_query: cargo test"), "got: {sent}"); |
| 1436 | assert!(sent.contains("original_chars: 140000"), "got: {sent}"); |
| 1437 | assert!(sent.contains("sha256:"), "got: {sent}"); |
| 1438 | assert!( |
| 1439 | sent.contains("exact_detail: unavailable; no session-owned artifact was recorded"), |
| 1440 | "got: {sent}" |
| 1441 | ); |
| 1442 | assert!(!sent.contains("retrieve_tool_result"), "got: {sent}"); |
| 1443 | // The model catalog supplies the window when no explicit route is available. |
| 1444 | let budget = tool_result_sent_char_budget("deepseek-v4-flash"); |
| 1445 | assert!(budget >= 100_000); |
| 1446 | let excerpt = budget - TOOL_RESULT_EXCERPT_FRAME_CHARS; |
| 1447 | let head = excerpt * 2 / 3; |
| 1448 | assert!(sent.contains(&"A".repeat(head)), "head kept"); |
| 1449 | assert!(sent.contains(&"Z".repeat(excerpt - head)), "tail kept"); |
| 1450 | assert!( |
| 1451 | sent.contains(&format!( |
| 1452 | "truncated {} chars from middle", |
| 1453 | 140_000 - excerpt |
| 1454 | )), |
| 1455 | "omitted count" |
| 1456 | ); |
| 1457 | assert_ne!(sent, long_output); |
| 1458 | } |
| 1459 | |
| 1460 | #[test] |
| 1461 | fn restored_tool_results_obey_the_active_route_budget() { |
| 1462 | let output = "x".repeat(20_000); |
| 1463 | let recovery = format!( |
| 1464 | "{output}\n{}", |
| 1465 | codewhale_tools::names::SPILLOVER_RECOVERY_HINT |
| 1466 | ); |
| 1467 | let request = MessageRequest { |
| 1468 | model: "trinity-mini".into(), |
| 1469 | messages: vec![ |
| 1470 | tool_use_message("raw", "read_file", json!({"path": "a.rs"})), |
| 1471 | tool_result_message("raw", &output), |
| 1472 | tool_use_message("repeat", "read_file", json!({"path": "a.rs"})), |
| 1473 | tool_result_message("repeat", &output), |
| 1474 | tool_use_message("saved", "read_file", json!({"path": "b.rs"})), |
| 1475 | tool_result_message("saved", &recovery), |
| 1476 | ], |
| 1477 | max_tokens: 1_024, |
| 1478 | system: None, |
| 1479 | tools: None, |
| 1480 | tool_choice: None, |
| 1481 | metadata: None, |
| 1482 | thinking: None, |
| 1483 | reasoning_effort: None, |
| 1484 | stream: None, |
| 1485 | temperature: None, |
| 1486 | top_p: None, |
| 1487 | safety_check: None, |
| 1488 | title: None, |
| 1489 | }; |
| 1490 | // The bundled 128K route and an explicit smaller offering both beat |
| 1491 | // the old unknown-route 100K ceiling. Streaming and blocking share it. |
| 1492 | for (limits, expected_budget) in [ |
| 1493 | (None, 15_360), |
| 1494 | ( |
| 1495 | Some(RouteLimits { |
| 1496 | context_tokens: Some(32_000), |
| 1497 | ..RouteLimits::default() |
| 1498 | }), |
| 1499 | 3_840, |
| 1500 | ), |
| 1501 | ] { |
| 1502 | for stream in [false, true] { |
| 1503 | let wire = build_chat_wire_body( |
| 1504 | &request, |
| 1505 | ProviderKind::Arcee, |
| 1506 | "https://api.arcee.ai/api/v1", |
| 1507 | stream, |
| 1508 | limits, |
| 1509 | ) |
| 1510 | .unwrap(); |
| 1511 | let messages = wire.body["messages"].as_array().unwrap(); |
| 1512 | for index in [0, 1] { |
| 1513 | let sent = tool_message_content(messages, index); |
| 1514 | assert!(sent.contains("[TOOL_RESULT_TRUNCATED]")); |
| 1515 | assert!(sent.chars().count() <= expected_budget); |
| 1516 | assert!(!sent.contains("<TOOL_RESULT_REF")); |
| 1517 | assert!(sent.contains("exact_detail: unavailable")); |
| 1518 | } |
| 1519 | assert_eq!(tool_message_content(messages, 2), recovery); |
| 1520 | } |
| 1521 | } |
| 1522 | assert!(matches!(&request.messages[1].content[0], |
| 1523 | ContentBlock::ToolResult { content, .. } if content == &output)); |
| 1524 | } |
| 1525 | |
| 1526 | #[test] |
| 1527 | fn request_builder_keeps_unowned_extreme_tool_output_bounded_without_false_hint() { |
| 1528 | with_tool_result_sha_spillover_root(|| { |
| 1529 | let huge_output = format!( |
| 1530 | "{}{}{}", |
| 1531 | "DIFF_HEAD\n".repeat(10_000), |
| 1532 | "MIDDLE_POISON\n".repeat(10_000), |
| 1533 | "DIFF_TAIL\n".repeat(10_000) |
| 1534 | ); |
| 1535 | let sha = sha256_hex(huge_output.as_bytes()); |
| 1536 | let messages = vec![ |
| 1537 | tool_use_message("tool-huge", "exec_shell", json!({"command": "git diff"})), |
| 1538 | tool_result_message("tool-huge", &huge_output), |
| 1539 | ]; |
| 1540 | |
| 1541 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1542 | let sent = tool_message_content(&built, 0); |
| 1543 | |
| 1544 | assert!(sent.contains("[TOOL_RESULT_TRUNCATED]"), "got: {sent}"); |
| 1545 | assert!(sent.contains("tool_name: exec_shell"), "got: {sent}"); |
| 1546 | assert!(sent.contains("command_or_query: git diff"), "got: {sent}"); |
| 1547 | assert!(sent.contains(&format!("sha256: {sha}")), "got: {sent}"); |
| 1548 | assert!(sent.contains("exact_detail: unavailable"), "got: {sent}"); |
| 1549 | assert!(!sent.contains("retrieve_tool_result"), "got: {sent}"); |
| 1550 | assert!( |
| 1551 | sent.chars().count() <= tool_result_sent_char_budget("deepseek-v4-flash"), |
| 1552 | "truncated result should stay bounded, sent {} chars", |
| 1553 | sent.chars().count() |
| 1554 | ); |
| 1555 | assert!( |
| 1556 | !sent.contains("MIDDLE_POISON"), |
| 1557 | "omitted middle should not be sent to the next model turn" |
| 1558 | ); |
| 1559 | assert_ne!(sent, huge_output); |
| 1560 | }); |
| 1561 | } |
| 1562 | |
| 1563 | #[test] |
| 1564 | fn request_builder_does_not_dedup_short_tool_results_for_wire() { |
| 1565 | let output = "same tool output"; |
| 1566 | let messages = vec![ |
| 1567 | tool_use_message("tool-1", "read_file", json!({"path": "README.md"})), |
| 1568 | tool_result_message("tool-1", output), |
| 1569 | tool_use_message("tool-2", "read_file", json!({"path": "README.md"})), |
| 1570 | tool_result_message("tool-2", output), |
| 1571 | ]; |
| 1572 | |
| 1573 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1574 | let first = tool_message_content(&built, 0); |
| 1575 | let second = tool_message_content(&built, 1); |
| 1576 | |
| 1577 | assert_eq!(first, output); |
| 1578 | assert_eq!(second, output); |
| 1579 | assert!(!second.contains("<TOOL_RESULT_REF"), "got: {second}"); |
| 1580 | } |
| 1581 | |
| 1582 | #[test] |
| 1583 | fn request_builder_deduplicates_medium_identical_tool_results_to_earlier_message() { |
| 1584 | with_tool_result_sha_spillover_root(|| { |
| 1585 | // 2,000 chars is intentionally above TOOL_RESULT_DEDUP_MIN_CHARS |
| 1586 | // (1,024) but below the wire backstop budget. This |
| 1587 | // verifies the cache-saving path for repeated medium outputs that |
| 1588 | // do not otherwise need truncation. |
| 1589 | let output = "A".repeat(2_000); |
| 1590 | let messages = vec![ |
| 1591 | tool_use_message("tool-1", "read_file", json!({"path": "README.md"})), |
| 1592 | tool_result_message("tool-1", &output), |
| 1593 | tool_use_message("tool-2", "read_file", json!({"path": "README.md"})), |
| 1594 | tool_result_message("tool-2", &output), |
| 1595 | ]; |
| 1596 | |
| 1597 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1598 | let first = tool_message_content(&built, 0); |
| 1599 | let second = tool_message_content(&built, 1); |
| 1600 | |
| 1601 | assert_eq!(first, output); |
| 1602 | assert!(!first.contains("[TOOL_RESULT_TRUNCATED]"), "got: {first}"); |
| 1603 | assert!( |
| 1604 | second.starts_with("<TOOL_RESULT_REF sha=\""), |
| 1605 | "got: {second}" |
| 1606 | ); |
| 1607 | assert!( |
| 1608 | second.contains("original_message=\"Message #1\""), |
| 1609 | "got: {second}" |
| 1610 | ); |
| 1611 | assert!(second.contains("chars=\"2000\""), "got: {second}"); |
| 1612 | assert!( |
| 1613 | second.contains("source: full content appears in Message #1 earlier in this request"), |
| 1614 | "got: {second}" |
| 1615 | ); |
| 1616 | assert!(!second.contains("retrieve_tool_result"), "got: {second}"); |
| 1617 | }); |
| 1618 | } |
| 1619 | |
| 1620 | #[test] |
| 1621 | fn request_builder_never_dedups_large_identical_write_file_confirmations() { |
| 1622 | with_tool_result_sha_spillover_root(|| { |
| 1623 | // A `write_file` result embeds the unified diff + summary; it is a |
| 1624 | // confirmation, not retrievable data. Two identical >1024-char |
| 1625 | // write_file results must BOTH stay inline — collapsing the second |
| 1626 | // to a SHA ref makes the model lose write-success context and |
| 1627 | // report the file as missing (#1695). |
| 1628 | let output = "A".repeat(2_000); |
| 1629 | let messages = vec![ |
| 1630 | tool_use_message("tool-1", "write_file", json!({"path": "big.txt"})), |
| 1631 | tool_result_message("tool-1", &output), |
| 1632 | tool_use_message("tool-2", "write_file", json!({"path": "big.txt"})), |
| 1633 | tool_result_message("tool-2", &output), |
| 1634 | ]; |
| 1635 | |
| 1636 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1637 | let first = tool_message_content(&built, 0); |
| 1638 | let second = tool_message_content(&built, 1); |
| 1639 | |
| 1640 | assert_eq!(first, output); |
| 1641 | assert_eq!(second, output); |
| 1642 | assert!(!second.contains("<TOOL_RESULT_REF"), "got: {second}"); |
| 1643 | |
| 1644 | // Non-mutation tools still dedup: an identical medium read_file |
| 1645 | // result points back to the first full message in this request. |
| 1646 | let read_messages = vec![ |
| 1647 | tool_use_message("read-1", "read_file", json!({"path": "README.md"})), |
| 1648 | tool_result_message("read-1", &output), |
| 1649 | tool_use_message("read-2", "read_file", json!({"path": "README.md"})), |
| 1650 | tool_result_message("read-2", &output), |
| 1651 | ]; |
| 1652 | let read_built = build_chat_messages(None, &read_messages, "deepseek-v4-flash"); |
| 1653 | let read_first = tool_message_content(&read_built, 0); |
| 1654 | let read_second = tool_message_content(&read_built, 1); |
| 1655 | assert_eq!(read_first, output); |
| 1656 | assert!( |
| 1657 | read_second.starts_with("<TOOL_RESULT_REF sha=\""), |
| 1658 | "got: {read_second}" |
| 1659 | ); |
| 1660 | assert!(read_second.contains("source: full content appears in Message #1")); |
| 1661 | assert!(!read_second.contains("retrieve_tool_result")); |
| 1662 | }); |
| 1663 | } |
| 1664 | |
| 1665 | #[test] |
| 1666 | fn large_unowned_results_stay_bounded_without_false_retrieval_handles() { |
| 1667 | // The adaptive router normally replaces a large result with a |
| 1668 | // session-owned artifact receipt before this provider-wire fallback. |
| 1669 | // If legacy/raw history reaches here, it may be excerpted but must not |
| 1670 | // advertise the process-wide SHA store as retrievable. |
| 1671 | let big_diff = "D".repeat(120_000); |
| 1672 | let sha = sha256_hex(big_diff.as_bytes()); |
| 1673 | |
| 1674 | let messages = vec![ |
| 1675 | tool_use_message("w-1", "write_file", json!({"path": "huge.rs"})), |
| 1676 | tool_result_message("w-1", &big_diff), |
| 1677 | tool_use_message("w-2", "write_file", json!({"path": "huge.rs"})), |
| 1678 | tool_result_message("w-2", &big_diff), |
| 1679 | ]; |
| 1680 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1681 | let first = tool_message_content(&built, 0); |
| 1682 | let second = tool_message_content(&built, 1); |
| 1683 | |
| 1684 | // Mutation confirmations are independently excerpted, never deduped. |
| 1685 | assert!( |
| 1686 | first.contains("[TOOL_RESULT_TRUNCATED]"), |
| 1687 | "first should be truncated, got: {first}" |
| 1688 | ); |
| 1689 | assert!( |
| 1690 | !first.contains("<TOOL_RESULT_REF"), |
| 1691 | "first must not be a dedup ref, got: {first}" |
| 1692 | ); |
| 1693 | assert!( |
| 1694 | !second.contains("<TOOL_RESULT_REF"), |
| 1695 | "second identical write_file must stay inline (#1695), got: {second}" |
| 1696 | ); |
| 1697 | assert!( |
| 1698 | second.contains("[TOOL_RESULT_TRUNCATED]"), |
| 1699 | "second should also be inline-truncated, got: {second}" |
| 1700 | ); |
| 1701 | assert!( |
| 1702 | first.contains(&format!("sha256: {sha}")), |
| 1703 | "truncation block should retain an integrity digest, got: {first}" |
| 1704 | ); |
| 1705 | assert!(first.contains("exact_detail: unavailable")); |
| 1706 | assert!(!first.contains("retrieve_tool_result")); |
| 1707 | |
| 1708 | // A huge non-mutation result cannot refer to an earlier *full* message, |
| 1709 | // because both wire messages are excerpts. It therefore stays a |
| 1710 | // truthful bounded excerpt too. |
| 1711 | let read_messages = vec![ |
| 1712 | tool_use_message("r-1", "read_file", json!({"path": "huge.rs"})), |
| 1713 | tool_result_message("r-1", &big_diff), |
| 1714 | tool_use_message("r-2", "read_file", json!({"path": "huge.rs"})), |
| 1715 | tool_result_message("r-2", &big_diff), |
| 1716 | ]; |
| 1717 | let read_built = build_chat_messages(None, &read_messages, "deepseek-v4-flash"); |
| 1718 | let read_second = tool_message_content(&read_built, 1); |
| 1719 | assert!(read_second.contains("[TOOL_RESULT_TRUNCATED]")); |
| 1720 | assert!(!read_second.contains("<TOOL_RESULT_REF")); |
| 1721 | assert!(!read_second.contains("retrieve_tool_result")); |
| 1722 | } |
| 1723 | |
| 1724 | #[test] |
| 1725 | fn tool_result_budget_is_wire_only_and_does_not_mutate_session_message() { |
| 1726 | let long_output = format!("{}{}", "A".repeat(70_000), "Z".repeat(70_000)); |
| 1727 | let messages = vec![ |
| 1728 | tool_use_message( |
| 1729 | "tool-long", |
| 1730 | "shell_command", |
| 1731 | json!({"command": "cargo test"}), |
| 1732 | ), |
| 1733 | tool_result_message("tool-long", &long_output), |
| 1734 | ]; |
| 1735 | |
| 1736 | let built = build_chat_messages(None, &messages, "deepseek-v4-flash"); |
| 1737 | let sent = tool_message_content(&built, 0); |
| 1738 | assert_ne!(sent, long_output); |
| 1739 | |
| 1740 | match &messages[1].content[0] { |
| 1741 | ContentBlock::ToolResult { content, .. } => assert_eq!(content, &long_output), |
| 1742 | other => panic!("expected tool result, got {other:?}"), |
| 1743 | } |
| 1744 | } |
| 1745 | |
| 1746 | #[test] |
| 1747 | fn cache_inspect_reports_bounded_unowned_tool_result_metadata() { |
| 1748 | let long_output = format!("{}{}", "A".repeat(70_000), "Z".repeat(70_000)); |
| 1749 | let request = MessageRequest { |
| 1750 | model: "deepseek-v4-flash".to_string(), |
| 1751 | messages: vec![ |
| 1752 | tool_use_message("tool-1", "shell_command", json!({"command": "cargo test"})), |
| 1753 | tool_result_message("tool-1", &long_output), |
| 1754 | tool_use_message("tool-2", "shell_command", json!({"command": "cargo test"})), |
| 1755 | tool_result_message("tool-2", &long_output), |
| 1756 | ], |
| 1757 | max_tokens: 0, |
| 1758 | system: None, |
| 1759 | tools: None, |
| 1760 | tool_choice: None, |
| 1761 | metadata: None, |
| 1762 | thinking: None, |
| 1763 | reasoning_effort: None, |
| 1764 | stream: None, |
| 1765 | temperature: None, |
| 1766 | top_p: None, |
| 1767 | safety_check: None, |
| 1768 | title: None, |
| 1769 | }; |
| 1770 | |
| 1771 | let inspection = inspect_prompt_for_request(&request); |
| 1772 | let tool_layers: Vec<_> = inspection |
| 1773 | .layers |
| 1774 | .iter() |
| 1775 | .filter_map(|layer| layer.tool_result.as_ref()) |
| 1776 | .collect(); |
| 1777 | |
| 1778 | assert_eq!(tool_layers.len(), 2); |
| 1779 | for layer in tool_layers { |
| 1780 | assert_eq!(layer.original_chars, 140_000); |
| 1781 | assert!(layer.sent_chars < layer.original_chars); |
| 1782 | assert!(layer.truncated); |
| 1783 | assert!(!layer.deduplicated); |
| 1784 | } |
| 1785 | } |
| 1786 | |
| 1787 | #[test] |
| 1788 | fn mistral_stream_blocks_are_decoded_only_by_the_mistral_style() { |
| 1789 | let chunk = r#"{ |
| 1790 | "choices": [{ |
| 1791 | "index": 0, |
| 1792 | "delta": {"content": [ |
| 1793 | {"type": "thinking", "thinking": [ |
| 1794 | {"type": "text", "text": "private trace"} |
| 1795 | ], "closed": true}, |
| 1796 | {"type": "text", "text": "public answer"} |
| 1797 | ]}, |
| 1798 | "finish_reason": null |
| 1799 | }] |
| 1800 | }"#; |
| 1801 | |
| 1802 | let mistral = decode_chunks_with_style(&[chunk], ReasoningStreamStyle::MistralBlocks); |
| 1803 | assert!(mistral.iter().any(|event| matches!( |
| 1804 | event, |
| 1805 | StreamEvent::ContentBlockDelta { |
| 1806 | delta: Delta::ThinkingDelta { thinking }, |
| 1807 | .. |
| 1808 | } if thinking == "private trace" |
| 1809 | ))); |
| 1810 | assert!(mistral.iter().any(|event| matches!( |
| 1811 | event, |
| 1812 | StreamEvent::ContentBlockDelta { |
| 1813 | delta: Delta::TextDelta { text }, |
| 1814 | .. |
| 1815 | } if text == "public answer" |
| 1816 | ))); |
| 1817 | |
| 1818 | let generic = decode_chunks_with_style(&[chunk], ReasoningStreamStyle::None); |
| 1819 | assert!(!generic.iter().any(|event| matches!( |
| 1820 | event, |
| 1821 | StreamEvent::ContentBlockDelta { |
| 1822 | delta: Delta::ThinkingDelta { .. }, |
| 1823 | .. |
| 1824 | } |
| 1825 | ))); |
| 1826 | assert!(!generic.iter().any(|event| matches!( |
| 1827 | event, |
| 1828 | StreamEvent::ContentBlockDelta { |
| 1829 | delta: Delta::TextDelta { .. }, |
| 1830 | .. |
| 1831 | } |
| 1832 | ))); |
| 1833 | } |
| 1834 | |
| 1835 | #[test] |
| 1836 | fn deepseek_flash_v41_classifies_reasoning_through_the_catalog() { |
| 1837 | // #6044: V4.1's official id dropped the version number, so the literal |
| 1838 | // `deepseek-v4` arms cannot see it. The catalog owns the capability and |
| 1839 | // every classifier — stream style, wire replay, prompt inspection — must |
| 1840 | // read it there instead of relying on another classifier's fallback. |
| 1841 | let base_url = "https://api.deepseek.com"; |
| 1842 | assert!( |
| 1843 | requires_reasoning_content("deepseek-flash"), |
| 1844 | "the name gate must recognize the official V4.1 id through the catalog" |
| 1845 | ); |
| 1846 | assert!( |
| 1847 | should_replay_reasoning_content("deepseek-flash", None), |
| 1848 | "prompt inspection must agree with the wire request" |
| 1849 | ); |
| 1850 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 1851 | ProviderKind::Deepseek, |
| 1852 | base_url, |
| 1853 | "deepseek-flash", |
| 1854 | None, |
| 1855 | )); |
| 1856 | |
| 1857 | let style = |
| 1858 | reasoning_stream_style_for_route(ProviderKind::Deepseek, base_url, "deepseek-flash", None); |
| 1859 | assert_eq!(style, ReasoningStreamStyle::SeparateField); |
| 1860 | let events = decode_chunks_with_style( |
| 1861 | &[r#"{"choices":[{"delta":{"reasoning_content":"private flash plan"}}]}"#], |
| 1862 | style, |
| 1863 | ); |
| 1864 | assert_eq!(thinking_delta_text(&events), "private flash plan"); |
| 1865 | assert_eq!( |
| 1866 | text_delta_text(&events), |
| 1867 | "", |
| 1868 | "reasoning must never leak into visible prose" |
| 1869 | ); |
| 1870 | |
| 1871 | // A non-reasoning DeepSeek name stays literal: the prefix alone is not |
| 1872 | // evidence, the catalog entry is. |
| 1873 | assert!(!requires_reasoning_content("deepseek-coder")); |
| 1874 | } |
| 1875 | |
| 1876 | #[test] |
| 1877 | fn deepseek_chat_web_tools_latest_reminder_replay_and_sse_parity() { |
| 1878 | let request = MessageRequest { |
| 1879 | model: "deepseek-v4".to_string(), |
| 1880 | messages: vec![ |
| 1881 | Message { |
| 1882 | role: Role::User, |
| 1883 | content: vec![ContentBlock::File { |
| 1884 | file_id: "file_chat_1".to_string(), |
| 1885 | }], |
| 1886 | }, |
| 1887 | Message { |
| 1888 | role: Role::Assistant, |
| 1889 | content: vec![ContentBlock::ServerToolCalls { |
| 1890 | steps: vec![json!({ "type": "search", "query": "rust 2024" })], |
| 1891 | }], |
| 1892 | }, |
| 1893 | Message { |
| 1894 | role: Role::LatestReminder, |
| 1895 | content: vec![ContentBlock::Text { |
| 1896 | text: "Stay factual".to_string(), |
| 1897 | cache_control: None, |
| 1898 | }], |
| 1899 | }, |
| 1900 | Message { |
| 1901 | role: Role::User, |
| 1902 | content: vec![ContentBlock::Text { |
| 1903 | text: "Go on".to_string(), |
| 1904 | cache_control: None, |
| 1905 | }], |
| 1906 | }, |
| 1907 | ], |
| 1908 | max_tokens: 512, |
| 1909 | system: None, |
| 1910 | tools: Some(vec![ |
| 1911 | Tool { |
| 1912 | tool_type: Some("deepseek_web_search".to_string()), |
| 1913 | name: "deepseek_web_search".to_string(), |
| 1914 | description: String::new(), |
| 1915 | input_schema: json!({}), |
| 1916 | allowed_callers: None, |
| 1917 | defer_loading: None, |
| 1918 | input_examples: None, |
| 1919 | strict: None, |
| 1920 | cache_control: None, |
| 1921 | }, |
| 1922 | Tool { |
| 1923 | tool_type: Some("deepseek_read_url".to_string()), |
| 1924 | name: "deepseek_read_url".to_string(), |
| 1925 | description: String::new(), |
| 1926 | input_schema: json!({}), |
| 1927 | allowed_callers: None, |
| 1928 | defer_loading: None, |
| 1929 | input_examples: None, |
| 1930 | strict: None, |
| 1931 | cache_control: None, |
| 1932 | }, |
| 1933 | ]), |
| 1934 | tool_choice: Some(json!("auto")), |
| 1935 | metadata: None, |
| 1936 | thinking: None, |
| 1937 | reasoning_effort: None, |
| 1938 | stream: Some(true), |
| 1939 | temperature: None, |
| 1940 | top_p: None, |
| 1941 | safety_check: Some(codewhale_models::SafetyCheckConfig { |
| 1942 | level: "high".to_string(), |
| 1943 | }), |
| 1944 | title: Some(codewhale_models::ConversationTitleConfig { enabled: true }), |
| 1945 | }; |
| 1946 | |
| 1947 | let wire = build_chat_wire_body( |
| 1948 | &request, |
| 1949 | ProviderKind::Deepseek, |
| 1950 | "https://api.deepseek.com/v1", |
| 1951 | true, |
| 1952 | None, |
| 1953 | ) |
| 1954 | .expect("chat wire body builds") |
| 1955 | .body; |
| 1956 | assert_eq!(wire["tool_choice"], json!("auto")); |
| 1957 | assert_eq!(wire["safety_check"], json!({ "level": "high" })); |
| 1958 | assert_eq!(wire["title"], json!({ "enabled": true })); |
| 1959 | assert_eq!( |
| 1960 | wire["tools"], |
| 1961 | json!([ |
| 1962 | { "type": "deepseek_web_search" }, |
| 1963 | { "type": "deepseek_read_url" } |
| 1964 | ]) |
| 1965 | ); |
| 1966 | assert_eq!( |
| 1967 | wire["messages"][0]["content"][0], |
| 1968 | json!({ "type": "file", "file_id": "file_chat_1" }) |
| 1969 | ); |
| 1970 | assert_eq!( |
| 1971 | wire["messages"][1]["server_tool_calls"], |
| 1972 | json!([{ "type": "search", "query": "rust 2024" }]) |
| 1973 | ); |
| 1974 | assert_eq!(wire["messages"][2]["role"], "latest_reminder"); |
| 1975 | |
| 1976 | for bad_choice in [ |
| 1977 | json!("required"), |
| 1978 | json!({ "type": "required" }), |
| 1979 | json!({ "type": "any" }), |
| 1980 | json!({ "type": "function", "function": { "name": "deepseek_web_search" } }), |
| 1981 | ] { |
| 1982 | let mut forced = request.clone(); |
| 1983 | forced.tool_choice = Some(bad_choice); |
| 1984 | assert!( |
| 1985 | build_chat_wire_body( |
| 1986 | &forced, |
| 1987 | ProviderKind::Deepseek, |
| 1988 | "https://api.deepseek.com/v1", |
| 1989 | true, |
| 1990 | None, |
| 1991 | ) |
| 1992 | .is_err() |
| 1993 | ); |
| 1994 | } |
| 1995 | |
| 1996 | assert!( |
| 1997 | build_chat_wire_body( |
| 1998 | &request, |
| 1999 | ProviderKind::Openai, |
| 2000 | "https://api.openai.com/v1", |
| 2001 | true, |
| 2002 | None, |
| 2003 | ) |
| 2004 | .is_err() |
| 2005 | ); |
| 2006 | |
| 2007 | let mut bad_opts = request; |
| 2008 | bad_opts.metadata = Some(json!({ "web_search_options": {} })); |
| 2009 | assert!( |
| 2010 | build_chat_wire_body( |
| 2011 | &bad_opts, |
| 2012 | ProviderKind::Deepseek, |
| 2013 | "https://api.deepseek.com/v1", |
| 2014 | true, |
| 2015 | None, |
| 2016 | ) |
| 2017 | .is_err() |
| 2018 | ); |
| 2019 | |
| 2020 | let sse_chunks = [json!({ |
| 2021 | "choices": [{ |
| 2022 | "index": 0, |
| 2023 | "delta": { |
| 2024 | "server_tool_event": { "type": "search_start", "query": "rust" }, |
| 2025 | "server_tool_calls": [{ "type": "search", "query": "rust" }], |
| 2026 | "annotations": [{ "type": "url_citation", "url": "https://example.com" }], |
| 2027 | "title": "Rust Chat", |
| 2028 | "refusal": "Policy block" |
| 2029 | }, |
| 2030 | "finish_reason": "content_filter" |
| 2031 | }], |
| 2032 | "usage": { |
| 2033 | "prompt_tokens": 10, |
| 2034 | "completion_tokens": 3, |
| 2035 | "safety_tokens": 5, |
| 2036 | "server_tool_use": { |
| 2037 | "tool_search": 1, |
| 2038 | "tool_fetch": 1, |
| 2039 | "tool_image_search": 0 |
| 2040 | } |
| 2041 | } |
| 2042 | }) |
| 2043 | .to_string()]; |
| 2044 | let refs: Vec<&str> = sse_chunks.iter().map(String::as_str).collect(); |
| 2045 | let events = decode_chunks_with_style(&refs, ReasoningStreamStyle::SeparateField); |
| 2046 | assert!(events.iter().any(|ev| matches!( |
| 2047 | ev, |
| 2048 | StreamEvent::ContentBlockStart { |
| 2049 | content_block: ContentBlockStart::ServerToolCalls { .. }, |
| 2050 | .. |
| 2051 | } |
| 2052 | ))); |
| 2053 | assert!(events.iter().any(|ev| matches!( |
| 2054 | ev, |
| 2055 | StreamEvent::ContentBlockDelta { |
| 2056 | delta: Delta::CitationsDelta { .. }, |
| 2057 | .. |
| 2058 | } |
| 2059 | ))); |
| 2060 | assert!(events.iter().any(|ev| matches!( |
| 2061 | ev, |
| 2062 | StreamEvent::ContentBlockDelta { |
| 2063 | delta: Delta::RefusalDelta { refusal }, .. |
| 2064 | } if refusal == "Policy block" |
| 2065 | ))); |
| 2066 | assert!(events.iter().any(|ev| matches!( |
| 2067 | ev, |
| 2068 | StreamEvent::MessageDelta { delta, usage } |
| 2069 | if delta.stop_reason.as_deref() == Some("content_filter") |
| 2070 | && delta.title.as_deref() == Some("Rust Chat") |
| 2071 | && usage.as_ref().and_then(|u| u.safety_tokens) == Some(5) |
| 2072 | ))); |
| 2073 | } |
| 2074 | |
| 2075 | #[test] |
| 2076 | fn google_parallel_tool_calls_without_index_keep_separate_blocks_and_replay_cleanly() { |
| 2077 | let sse_chunks = [ |
| 2078 | serde_json::json!({ |
| 2079 | "choices": [{ |
| 2080 | "index": 0, |
| 2081 | "delta": { |
| 2082 | "tool_calls": [ |
| 2083 | { |
| 2084 | "id": "call_g1", |
| 2085 | "type": "function", |
| 2086 | "function": { "name": "read_file", "arguments": "{\"path\":\"a.rs\"}" }, |
| 2087 | "extra_content": { "google": { "thought_signature": "sig_first" } } |
| 2088 | }, |
| 2089 | { |
| 2090 | "id": "call_g2", |
| 2091 | "type": "function", |
| 2092 | "function": { "name": "read_file", "arguments": "{\"path\":\"b.rs\"}" } |
| 2093 | } |
| 2094 | ] |
| 2095 | } |
| 2096 | }] |
| 2097 | }) |
| 2098 | .to_string(), |
| 2099 | serde_json::json!({ |
| 2100 | "choices": [{ |
| 2101 | "index": 0, |
| 2102 | "delta": { |
| 2103 | "tool_calls": [{ |
| 2104 | "id": "call_g3", |
| 2105 | "type": "function", |
| 2106 | "function": { "name": "grep_files", "arguments": "{\"pattern\":" } |
| 2107 | }] |
| 2108 | } |
| 2109 | }] |
| 2110 | }) |
| 2111 | .to_string(), |
| 2112 | serde_json::json!({ |
| 2113 | "choices": [{ |
| 2114 | "index": 0, |
| 2115 | "delta": { |
| 2116 | "tool_calls": [{ |
| 2117 | "function": { "arguments": "\"foo\"}" }, |
| 2118 | "extra_content": { "google": { "thought_signature": "sig_late" } } |
| 2119 | }] |
| 2120 | } |
| 2121 | }] |
| 2122 | }) |
| 2123 | .to_string(), |
| 2124 | serde_json::json!({ |
| 2125 | "choices": [{ |
| 2126 | "index": 0, |
| 2127 | "delta": {}, |
| 2128 | "finish_reason": "tool_calls" |
| 2129 | }] |
| 2130 | }) |
| 2131 | .to_string(), |
| 2132 | ]; |
| 2133 | let refs: Vec<&str> = sse_chunks.iter().map(String::as_str).collect(); |
| 2134 | let events = decode_google_chunks(&refs); |
| 2135 | |
| 2136 | let starts: Vec<(u32, String, Option<String>)> = events |
| 2137 | .into_iter() |
| 2138 | .filter_map(|ev| match ev { |
| 2139 | StreamEvent::ContentBlockStart { |
| 2140 | index, |
| 2141 | content_block: |
| 2142 | ContentBlockStart::ToolUse { |
| 2143 | id, |
| 2144 | thought_signature, |
| 2145 | .. |
| 2146 | }, |
| 2147 | } => Some((index, id, thought_signature)), |
| 2148 | _ => None, |
| 2149 | }) |
| 2150 | .collect(); |
| 2151 | assert_eq!( |
| 2152 | starts, |
| 2153 | vec![ |
| 2154 | (0, "call_g1".to_string(), Some("sig_first".to_string())), |
| 2155 | (1, "call_g2".to_string(), None), |
| 2156 | (2, "call_g3".to_string(), None), |
| 2157 | ] |
| 2158 | ); |
| 2159 | |
| 2160 | let events2 = decode_google_chunks(&refs); |
| 2161 | assert!(events2.iter().any(|ev| matches!( |
| 2162 | ev, |
| 2163 | StreamEvent::ContentBlockDelta { |
| 2164 | index: 2, |
| 2165 | delta: Delta::ThoughtSignatureDelta { thought_signature }, |
| 2166 | } if thought_signature == "sig_late" |
| 2167 | ))); |
| 2168 | |
| 2169 | let replay_messages = vec![serde_json::json!({ |
| 2170 | "role": "assistant", |
| 2171 | "tool_calls": [ |
| 2172 | { |
| 2173 | "id": "call_g1", |
| 2174 | "type": "function", |
| 2175 | "function": { "name": "read_file", "arguments": "{\"path\":\"a.rs\"}" }, |
| 2176 | "extra_content": { "google": { "thought_signature": "sig_first" } } |
| 2177 | }, |
| 2178 | { |
| 2179 | "id": "call_g2", |
| 2180 | "type": "function", |
| 2181 | "function": { "name": "read_file", "arguments": "{\"path\":\"b.rs\"}" } |
| 2182 | } |
| 2183 | ] |
| 2184 | })]; |
| 2185 | crate::client::chat::validate_google_thought_signature_replay( |
| 2186 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 2187 | "gemini-4-hydrogen", |
| 2188 | &replay_messages, |
| 2189 | ) |
| 2190 | .expect("parallel Gemini tool calls carry thought_signature only on tool_calls[0]"); |
| 2191 | |
| 2192 | let missing_first = vec![serde_json::json!({ |
| 2193 | "role": "assistant", |
| 2194 | "tool_calls": [ |
| 2195 | { |
| 2196 | "id": "call_unsigned", |
| 2197 | "type": "function", |
| 2198 | "function": { "name": "read_file", "arguments": "{}" } |
| 2199 | }, |
| 2200 | { |
| 2201 | "id": "call_second", |
| 2202 | "type": "function", |
| 2203 | "function": { "name": "read_file", "arguments": "{}" }, |
| 2204 | "extra_content": { "google": { "thought_signature": "sig_wrong_slot" } } |
| 2205 | } |
| 2206 | ] |
| 2207 | })]; |
| 2208 | assert!( |
| 2209 | crate::client::chat::validate_google_thought_signature_replay( |
| 2210 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 2211 | "gemini-4-hydrogen", |
| 2212 | &missing_first, |
| 2213 | ) |
| 2214 | .is_err() |
| 2215 | ); |
| 2216 | } |
| 2217 | |
| 2218 | #[test] |
| 2219 | fn google_parallel_tool_continuations_match_identity_then_batch_position() { |
| 2220 | let start = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2221 | {"id":"call_g1","function":{"name":"read_file","arguments":"{\"path\":"}}, |
| 2222 | {"id":"call_g2","function":{"name":"grep_files","arguments":"{\"pattern\":"}} |
| 2223 | ]}}]}"#; |
| 2224 | let continue_both = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2225 | {"id":"call_g1","function":{"arguments":"\"a.rs\"}"}}, |
| 2226 | {"function":{"arguments":"\"needle\"}"}} |
| 2227 | ]}}]}"#; |
| 2228 | let signature_for_first = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2229 | {"index":0,"id":"call_g1","extra_content":{"google":{"thought_signature":"sig_first"}}} |
| 2230 | ]}}]}"#; |
| 2231 | let events = decode_google_chunks(&[start, signature_for_first, continue_both]); |
| 2232 | let input: Vec<_> = events |
| 2233 | .iter() |
| 2234 | .filter_map(|event| match event { |
| 2235 | StreamEvent::ContentBlockDelta { |
| 2236 | index, |
| 2237 | delta: Delta::InputJsonDelta { partial_json }, |
| 2238 | } => Some((*index, partial_json.as_str())), |
| 2239 | _ => None, |
| 2240 | }) |
| 2241 | .collect(); |
| 2242 | assert_eq!( |
| 2243 | input, |
| 2244 | [ |
| 2245 | (0, "{\"path\":"), |
| 2246 | (1, "{\"pattern\":"), |
| 2247 | (0, "\"a.rs\"}"), |
| 2248 | (1, "\"needle\"}") |
| 2249 | ] |
| 2250 | ); |
| 2251 | assert!(events.iter().any(|event| matches!( |
| 2252 | event, |
| 2253 | StreamEvent::ContentBlockDelta { |
| 2254 | index: 0, |
| 2255 | delta: Delta::ThoughtSignatureDelta { thought_signature } |
| 2256 | } if thought_signature == "sig_first" |
| 2257 | ))); |
| 2258 | |
| 2259 | let ambiguous = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2260 | {"function":{"arguments":"\"unknown target\"}"}} |
| 2261 | ]}}]}"#; |
| 2262 | let events = decode_google_chunks(&[start, ambiguous]); |
| 2263 | assert!(matches!(events.last(), Some(StreamEvent::Error { .. }))); |
| 2264 | |
| 2265 | let anonymous_parallel = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2266 | {"function":{"arguments":"{}"}}, |
| 2267 | {"function":{"arguments":"{}"}} |
| 2268 | ]}}]}"#; |
| 2269 | let events = decode_google_chunks(&[start, anonymous_parallel]); |
| 2270 | assert!(matches!(events.last(), Some(StreamEvent::Error { .. }))); |
| 2271 | |
| 2272 | let partly_reordered = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2273 | {"id":"call_g2","function":{"arguments":"{}"}}, |
| 2274 | {"function":{"arguments":"{}"}} |
| 2275 | ]}}]}"#; |
| 2276 | let events = decode_google_chunks(&[start, partly_reordered]); |
| 2277 | assert!(matches!(events.last(), Some(StreamEvent::Error { .. }))); |
| 2278 | |
| 2279 | let unknown_continuation = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2280 | {"index":5,"function":{"arguments":"{}"}} |
| 2281 | ]}}]}"#; |
| 2282 | let events = decode_google_chunks(&[start, unknown_continuation]); |
| 2283 | assert!(matches!(events.last(), Some(StreamEvent::Error { .. }))); |
| 2284 | |
| 2285 | let indexed_batch = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2286 | {"index":0,"function":{"name":"read_file"}}, |
| 2287 | {"index":1,"id":"call_g2","function":{"name":"grep_files"}} |
| 2288 | ]}}]}"#; |
| 2289 | let conflicting_identity = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2290 | {"index":0,"id":"call_g2"} |
| 2291 | ]}}]}"#; |
| 2292 | let events = decode_google_chunks(&[indexed_batch, conflicting_identity]); |
| 2293 | assert!(matches!(events.last(), Some(StreamEvent::Error { .. }))); |
| 2294 | |
| 2295 | let pending_ids = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2296 | {"index":0,"function":{"name":"read_file","arguments":"{}"}}, |
| 2297 | {"index":1,"function":{"name":"grep_files","arguments":"{}"}} |
| 2298 | ]}}]}"#; |
| 2299 | let finish = r#"{"choices":[{"delta":{"tool_calls":[ |
| 2300 | {"index":0,"extra_content":{"google":{"thought_signature":"sig_first"}}}, |
| 2301 | {"index":1,"id":"call_missing_0"} |
| 2302 | ]},"finish_reason":"tool_calls"}]}"#; |
| 2303 | let events = decode_google_chunks(&[pending_ids, finish]); |
| 2304 | assert_eq!( |
| 2305 | finalized_tool_call_ids(&events), |
| 2306 | ["call_missing_0_1", "call_missing_0"] |
| 2307 | ); |
| 2308 | assert!(events.iter().any(|event| matches!( |
| 2309 | event, |
| 2310 | StreamEvent::ContentBlockDelta { |
| 2311 | index: 0, |
| 2312 | delta: Delta::ThoughtSignatureDelta { thought_signature }, |
| 2313 | } if thought_signature == "sig_first" |
| 2314 | ))); |
| 2315 | assert!( |
| 2316 | !events |
| 2317 | .iter() |
| 2318 | .any(|event| matches!(event, StreamEvent::Error { .. })) |
| 2319 | ); |
| 2320 | } |
| 2321 | |
| 2322 | #[test] |
| 2323 | fn google_reasoning_effort_honors_hydrogen_xhigh_and_gemini4_low_floor() { |
| 2324 | let url = "https://generativelanguage.googleapis.com/v1beta/openai"; |
| 2325 | |
| 2326 | let mut hydrogen_xhigh = serde_json::json!({}); |
| 2327 | crate::client::chat::apply_google_reasoning_effort( |
| 2328 | &mut hydrogen_xhigh, |
| 2329 | url, |
| 2330 | "gemini-4-hydrogen", |
| 2331 | Some("xhigh"), |
| 2332 | ); |
| 2333 | assert_eq!(hydrogen_xhigh["reasoning_effort"], "xhigh"); |
| 2334 | |
| 2335 | let mut carbon_xhigh = serde_json::json!({}); |
| 2336 | crate::client::chat::apply_google_reasoning_effort( |
| 2337 | &mut carbon_xhigh, |
| 2338 | url, |
| 2339 | "gemini-4-carbon", |
| 2340 | Some("xhigh"), |
| 2341 | ); |
| 2342 | assert_eq!(carbon_xhigh["reasoning_effort"], "high"); |
| 2343 | |
| 2344 | let mut hydrogen_off = serde_json::json!({}); |
| 2345 | crate::client::chat::apply_google_reasoning_effort( |
| 2346 | &mut hydrogen_off, |
| 2347 | url, |
| 2348 | "gemini-4-hydrogen", |
| 2349 | Some("off"), |
| 2350 | ); |
| 2351 | assert_eq!(hydrogen_off["reasoning_effort"], "low"); |
| 2352 | |
| 2353 | let mut flash_off = serde_json::json!({}); |
| 2354 | crate::client::chat::apply_google_reasoning_effort( |
| 2355 | &mut flash_off, |
| 2356 | url, |
| 2357 | "gemini-2.5-flash", |
| 2358 | Some("off"), |
| 2359 | ); |
| 2360 | assert_eq!(flash_off["reasoning_effort"], "none"); |
| 2361 | } |
| 2362 |