返回 CodeWhale
mock.rs
根目录 / crates / engine / src / llm_client / mock.rs
1 //! `MockLlmClient` — a queue-driven `LlmClient` implementation for tests.
2 //!
3 //! This client implements the [`LlmClient`](super::LlmClient) trait by replaying a
4 //! pre-loaded queue of canned responses (one per turn). It captures every
5 //! request the runtime sends so tests can assert on the outgoing payload —
6 //! e.g. confirming that prior `reasoning_content` is replayed in DeepSeek V4
7 //! thinking-mode tool-calling turns (V4 §5.1.1; the bug that broke
8 //! v0.4.9-v0.5.1).
9 //!
10 //! # Mocking strategy
11 //!
12 //! Tests mock at the **trait boundary** (`LlmClient`), never at the `reqwest`
13 //! HTTP layer. The trait is the durable abstraction — internal HTTP plumbing
14 //! changes frequently and is not part of the public engine contract.
15 //!
16 //! # Example
17 //!
18 //! ```ignore
19 //! use crate::llm_client::mock::{MockLlmClient, canned};
20 //! use crate::llm_client::LlmClient;
21 //!
22 //! // One canned turn that emits "hello world" as two text deltas, then
23 //! // finishes with stop_reason = "end_turn".
24 //! let turn = vec![
25 //! canned::message_start("msg_1"),
26 //! canned::text_delta(0, "hello "),
27 //! canned::text_delta(0, "world"),
28 //! canned::message_stop(),
29 //! ];
30 //!
31 //! let mock = MockLlmClient::new(vec![turn]);
32 //! let stream = mock.create_message_stream(/* ... */).await.unwrap();
33 //! // ... drain the stream, assert deltas ...
34 //! assert_eq!(mock.call_count(), 1);
35 //! assert_eq!(mock.captured_requests().len(), 1);
36 //! ```
37
38 use std::collections::VecDeque;
39 use std::pin::Pin;
40 use std::sync::Mutex;
41 use std::sync::atomic::{AtomicUsize, Ordering};
42
43 use anyhow::{Result, anyhow};
44 use async_stream::try_stream;
45 use futures_util::Stream;
46
47 use codewhale_models::{
48 ContentBlock, MessageDelta, MessageRequest, MessageResponse, StreamEvent, Usage,
49 };
50
51 use super::{LlmClient, RequestTransmission, StreamEventBox};
52 #[cfg(test)]
53 use codewhale_models::Role;
54
55 /// A pre-recorded "turn" the mock will replay on the next streaming call.
56 ///
57 /// `MessageStop` does *not* need to be the final element — the mock will
58 /// auto-emit one if missing, mirroring the real client's behaviour. Likewise
59 /// the mock does not require `MessageStart` to be present.
60 pub type CannedTurn = Vec<StreamEvent>;
61
62 /// A queued mock response step.
63 pub enum FauxStep {
64 Canned(CannedTurn),
65 /// Build a canned turn from the live outgoing request.
66 ///
67 /// Tests can assert DeepSeek V4's thinking-mode tool-call invariant here:
68 /// on the assistant turn that produced the previous tool call, the next
69 /// outgoing request must still carry `reasoning_content` (represented in
70 /// this model as a [`ContentBlock::Thinking`] block). If it is missing,
71 /// DeepSeek V4 returns HTTP 400 on the follow-up turn. This guards the
72 /// [v0.4.9-v0.5.1 regression range](https://github.com/codewhale-hq/CodeWhale/compare/v0.4.9...v0.5.1)
73 /// where that content was dropped.
74 Factory(Box<dyn Fn(&MessageRequest) -> CannedTurn + Send + Sync>),
75 /// Fail the request itself with this message, as a provider that refuses
76 /// it (a 401 for a bad key, say) does before any stream starts.
77 Error(String),
78 }
79
80 /// A queue-driven mock LLM client.
81 ///
82 /// The mock holds a FIFO queue of canned response turns. Each call to
83 /// [`LlmClient::create_message_stream`] dequeues the next turn and replays its
84 /// events as a stream. If the queue is exhausted, the call returns an error
85 /// — tests should ensure they push exactly as many turns as the runtime will
86 /// consume.
87 ///
88 /// The mock also captures the [`MessageRequest`] passed to every call so tests
89 /// can assert on the outgoing payload (e.g. that prior `reasoning_content` is
90 /// preserved across turns).
91 pub struct MockLlmClient {
92 canned: Mutex<VecDeque<FauxStep>>,
93 captured_requests: Mutex<Vec<MessageRequest>>,
94 calls: AtomicUsize,
95 provider_name: &'static str,
96 model: String,
97 /// If set, [`LlmClient::create_message`] returns this verbatim. Otherwise
98 /// it falls back to streaming + collection. Useful for non-streaming
99 /// compaction-style calls.
100 canned_messages: Mutex<VecDeque<MessageResponse>>,
101 }
102
103 impl MockLlmClient {
104 /// Construct a mock that will replay the given canned turns in order.
105 #[must_use]
106 pub fn new(canned: Vec<CannedTurn>) -> Self {
107 Self {
108 canned: Mutex::new(canned.into_iter().map(FauxStep::Canned).collect()),
109 captured_requests: Mutex::new(Vec::new()),
110 calls: AtomicUsize::new(0),
111 provider_name: "mock",
112 model: "mock-model".to_string(),
113 canned_messages: Mutex::new(VecDeque::new()),
114 }
115 }
116
117 /// Set the provider-name string returned by [`LlmClient::provider_name`].
118 #[must_use]
119 pub fn with_provider(mut self, name: &'static str) -> Self {
120 self.provider_name = name;
121 self
122 }
123
124 /// Set the model identifier returned by [`LlmClient::model`].
125 #[must_use]
126 pub fn with_model(mut self, model: impl Into<String>) -> Self {
127 self.model = model.into();
128 self
129 }
130
131 /// Push a canned turn onto the back of the queue.
132 pub fn push_turn(&self, turn: CannedTurn) {
133 self.canned
134 .lock()
135 .expect("MockLlmClient.canned mutex poisoned")
136 .push_back(FauxStep::Canned(turn));
137 }
138
139 /// Push a factory step onto the back of the queue.
140 ///
141 /// The closure receives the live outgoing [`MessageRequest`] before the
142 /// response stream is built, so assertions panic directly from the client
143 /// call rather than later while polling the returned stream.
144 pub fn push_factory<F>(&self, factory: F)
145 where
146 F: Fn(&MessageRequest) -> CannedTurn + Send + Sync + 'static,
147 {
148 self.canned
149 .lock()
150 .expect("MockLlmClient.canned mutex poisoned")
151 .push_back(FauxStep::Factory(Box::new(factory)));
152 }
153
154 /// Push a request failure onto the back of the queue.
155 pub fn push_error(&self, message: impl Into<String>) {
156 self.canned
157 .lock()
158 .expect("MockLlmClient.canned mutex poisoned")
159 .push_back(FauxStep::Error(message.into()));
160 }
161
162 /// Push a canned non-streaming `MessageResponse`. Consumed by
163 /// [`LlmClient::create_message`] (FIFO).
164 pub fn push_message_response(&self, response: MessageResponse) {
165 self.canned_messages
166 .lock()
167 .expect("MockLlmClient.canned_messages mutex poisoned")
168 .push_back(response);
169 }
170
171 /// Number of completed calls to either `create_message` or
172 /// `create_message_stream`.
173 #[must_use]
174 pub fn call_count(&self) -> usize {
175 self.calls.load(Ordering::SeqCst)
176 }
177
178 /// Number of canned turns still queued.
179 #[must_use]
180 pub fn remaining_turns(&self) -> usize {
181 self.canned
182 .lock()
183 .expect("MockLlmClient.canned mutex poisoned")
184 .len()
185 }
186
187 /// Snapshot of every request the mock has been asked to handle, in order.
188 #[must_use]
189 pub fn captured_requests(&self) -> Vec<MessageRequest> {
190 self.captured_requests
191 .lock()
192 .expect("MockLlmClient.captured_requests mutex poisoned")
193 .clone()
194 }
195
196 /// Convenience: return the most recently captured request, or `None` if
197 /// the mock has not been called yet.
198 #[must_use]
199 pub fn last_request(&self) -> Option<MessageRequest> {
200 self.captured_requests
201 .lock()
202 .expect("MockLlmClient.captured_requests mutex poisoned")
203 .last()
204 .cloned()
205 }
206
207 fn record_request(&self, request: &MessageRequest) {
208 self.captured_requests
209 .lock()
210 .expect("MockLlmClient.captured_requests mutex poisoned")
211 .push(request.clone());
212 self.calls.fetch_add(1, Ordering::SeqCst);
213 }
214
215 fn pop_step(&self) -> Option<FauxStep> {
216 self.canned
217 .lock()
218 .expect("MockLlmClient.canned mutex poisoned")
219 .pop_front()
220 }
221
222 fn turn_from_step(&self, step: FauxStep, request: &MessageRequest) -> Result<CannedTurn> {
223 match step {
224 FauxStep::Canned(turn) => Ok(turn),
225 FauxStep::Factory(factory) => Ok(factory(request)),
226 FauxStep::Error(message) => Err(anyhow!(message)),
227 }
228 }
229
230 fn pop_message(&self) -> Option<MessageResponse> {
231 self.canned_messages
232 .lock()
233 .expect("MockLlmClient.canned_messages mutex poisoned")
234 .pop_front()
235 }
236 }
237
238 impl LlmClient for MockLlmClient {
239 fn provider_name(&self) -> &'static str {
240 self.provider_name
241 }
242
243 fn model(&self) -> &str {
244 &self.model
245 }
246
247 async fn create_message(&self, request: MessageRequest) -> Result<MessageResponse> {
248 self.record_request(&request);
249 record_transmission();
250
251 if let Some(canned) = self.pop_message() {
252 return Ok(canned);
253 }
254
255 // Fallback: synthesize a MessageResponse from the next streaming turn.
256 let Some(step) = self.pop_step() else {
257 return Err(anyhow!(
258 "MockLlmClient: create_message called but no canned response queued (request #{})",
259 self.calls.load(Ordering::SeqCst)
260 ));
261 };
262
263 let turn = self.turn_from_step(step, &request)?;
264 Ok(synthesize_message_response(turn, &self.model))
265 }
266
267 async fn create_message_stream(&self, request: MessageRequest) -> Result<StreamEventBox> {
268 self.record_request(&request);
269 record_transmission();
270
271 let Some(step) = self.pop_step() else {
272 return Err(anyhow!(
273 "MockLlmClient: create_message_stream called but no canned turn queued (call #{})",
274 self.calls.load(Ordering::SeqCst)
275 ));
276 };
277
278 let turn = self.turn_from_step(step, &request)?;
279 Ok(stream_from_canned(turn))
280 }
281
282 async fn health_check(&self) -> Result<bool> {
283 Ok(true)
284 }
285 }
286
287 fn record_transmission() {
288 if let Some((wire, source)) = super::begin_outbound_transmission(&reqwest::Method::POST) {
289 wire.settle_transmission(&source, RequestTransmission::OutcomeUnknown, Some(200));
290 }
291 }
292
293 /// Wrap a canned event vector as a stream that yields each event in order and
294 /// auto-appends `MessageStop` if the trailing event is not already one.
295 fn stream_from_canned(turn: CannedTurn) -> StreamEventBox {
296 let s = try_stream! {
297 let has_stop = matches!(turn.last(), Some(StreamEvent::MessageStop));
298 for ev in turn {
299 yield ev;
300 }
301 if !has_stop {
302 yield StreamEvent::MessageStop;
303 }
304 };
305 Box::pin(s) as Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send + 'static>>
306 }
307
308 /// Best-effort: collapse a streaming turn into a non-streaming
309 /// `MessageResponse` by concatenating text deltas. Used only as a fallback
310 /// when callers `create_message` without a queued `MessageResponse`.
311 fn synthesize_message_response(turn: CannedTurn, model: &str) -> MessageResponse {
312 use codewhale_models::Delta;
313
314 let mut text = String::new();
315 let mut stop_reason: Option<String> = None;
316
317 for ev in turn {
318 match ev {
319 StreamEvent::ContentBlockDelta {
320 delta: Delta::TextDelta { text: t },
321 ..
322 } => text.push_str(&t),
323 StreamEvent::MessageDelta {
324 delta: MessageDelta {
325 stop_reason: sr, ..
326 },
327 ..
328 } => stop_reason = sr,
329 _ => {}
330 }
331 }
332
333 MessageResponse {
334 tool_projection_warning: None,
335 id: "mock_msg".to_string(),
336 r#type: "message".to_string(),
337 role: "assistant".to_string(),
338 content: vec![ContentBlock::Text {
339 text,
340 cache_control: None,
341 }],
342 model: model.to_string(),
343 stop_reason: stop_reason.or_else(|| Some("end_turn".to_string())),
344 stop_sequence: None,
345 container: None,
346 usage: Usage::default(),
347 title: None,
348 stop_details: None,
349 refusal: None,
350 }
351 }
352
353 /// Builders for common canned-event patterns. Re-exported so tests can build
354 /// realistic streams without wiring `StreamEvent` shapes by hand.
355 pub mod canned {
356 use serde_json::Value;
357
358 use codewhale_models::{
359 ContentBlockStart, Delta, MessageDelta, MessageResponse, StreamEvent, Usage,
360 };
361
362 /// `MessageStart` event with a synthetic message envelope.
363 #[must_use]
364 pub fn message_start(id: &str) -> StreamEvent {
365 StreamEvent::MessageStart {
366 message: MessageResponse {
367 tool_projection_warning: None,
368 id: id.to_string(),
369 r#type: "message".to_string(),
370 role: "assistant".to_string(),
371 content: vec![],
372 model: "mock-model".to_string(),
373 stop_reason: None,
374 stop_sequence: None,
375 container: None,
376 usage: Usage::default(),
377 title: None,
378 stop_details: None,
379 refusal: None,
380 },
381 }
382 }
383
384 /// Open a text content block at `index`.
385 #[must_use]
386 pub fn text_block_start(index: u32) -> StreamEvent {
387 StreamEvent::ContentBlockStart {
388 index,
389 content_block: ContentBlockStart::Text {
390 text: String::new(),
391 },
392 }
393 }
394
395 /// Append `text` to the content block at `index`.
396 #[must_use]
397 pub fn text_delta(index: u32, text: &str) -> StreamEvent {
398 StreamEvent::ContentBlockDelta {
399 index,
400 delta: Delta::TextDelta {
401 text: text.to_string(),
402 },
403 }
404 }
405
406 /// Append a thinking-content delta at `index`.
407 #[must_use]
408 pub fn thinking_delta(index: u32, thinking: &str) -> StreamEvent {
409 StreamEvent::ContentBlockDelta {
410 index,
411 delta: Delta::ThinkingDelta {
412 thinking: thinking.to_string(),
413 },
414 }
415 }
416
417 /// Open a tool_use content block at `index`.
418 #[must_use]
419 pub fn tool_use_block_start(index: u32, id: &str, name: &str) -> StreamEvent {
420 StreamEvent::ContentBlockStart {
421 index,
422 content_block: ContentBlockStart::ToolUse {
423 id: id.to_string(),
424 name: name.to_string(),
425 input: Value::Null,
426 caller: None,
427 thought_signature: None,
428 },
429 }
430 }
431
432 /// Stream partial JSON for a tool's input arguments.
433 #[must_use]
434 pub fn tool_input_delta(index: u32, partial_json: &str) -> StreamEvent {
435 StreamEvent::ContentBlockDelta {
436 index,
437 delta: Delta::InputJsonDelta {
438 partial_json: partial_json.to_string(),
439 },
440 }
441 }
442
443 /// Close the content block at `index`.
444 #[must_use]
445 pub fn block_stop(index: u32) -> StreamEvent {
446 StreamEvent::ContentBlockStop { index }
447 }
448
449 /// Emit a `message_delta` carrying `stop_reason` and optional `usage`.
450 #[must_use]
451 pub fn message_delta(stop_reason: &str, usage: Option<Usage>) -> StreamEvent {
452 StreamEvent::MessageDelta {
453 delta: MessageDelta {
454 stop_reason: Some(stop_reason.to_string()),
455 stop_sequence: None,
456 title: None,
457 stop_details: None,
458 refusal: None,
459 },
460 usage,
461 }
462 }
463
464 /// Final `message_stop` sentinel.
465 #[must_use]
466 pub fn message_stop() -> StreamEvent {
467 StreamEvent::MessageStop
468 }
469
470 /// Convenience: a complete "assistant emits this text" turn ending with
471 /// `stop_reason = "end_turn"`.
472 #[must_use]
473 pub fn simple_text_turn(text: &str) -> Vec<StreamEvent> {
474 vec![
475 message_start("mock_msg_1"),
476 text_block_start(0),
477 text_delta(0, text),
478 block_stop(0),
479 message_delta("end_turn", None),
480 message_stop(),
481 ]
482 }
483
484 /// Convenience: a turn that emits one assistant tool_call and stops.
485 #[must_use]
486 pub fn tool_call_turn(call_id: &str, tool_name: &str, args_json: &str) -> Vec<StreamEvent> {
487 vec![
488 message_start("mock_msg_tool"),
489 tool_use_block_start(0, call_id, tool_name),
490 tool_input_delta(0, args_json),
491 block_stop(0),
492 message_delta("tool_use", None),
493 message_stop(),
494 ]
495 }
496 }
497
498 // === Tests ===
499
500 #[cfg(test)]
501 mod tests {
502 use futures_util::StreamExt;
503
504 use super::*;
505 use crate::llm_client::LlmClient;
506 use codewhale_models::{Delta, Message, MessageRequest, StreamEvent};
507
508 fn empty_request() -> MessageRequest {
509 MessageRequest {
510 model: "mock-model".to_string(),
511 messages: vec![Message {
512 role: Role::User,
513 content: vec![],
514 }],
515 max_tokens: 1024,
516 system: None,
517 tools: None,
518 tool_choice: None,
519 metadata: None,
520 thinking: None,
521 reasoning_effort: None,
522 stream: Some(true),
523 temperature: None,
524 top_p: None,
525 safety_check: None,
526 title: None,
527 }
528 }
529
530 #[tokio::test]
531 async fn replays_canned_turn_via_stream() {
532 let mock = MockLlmClient::new(vec![canned::simple_text_turn("hello world")]);
533
534 let mut stream = mock
535 .create_message_stream(empty_request())
536 .await
537 .expect("stream should open");
538
539 let mut text = String::new();
540 let mut saw_stop = false;
541 while let Some(ev) = stream.next().await {
542 match ev.expect("event") {
543 StreamEvent::ContentBlockDelta {
544 delta: Delta::TextDelta { text: t },
545 ..
546 } => text.push_str(&t),
547 StreamEvent::MessageStop => {
548 saw_stop = true;
549 break;
550 }
551 _ => {}
552 }
553 }
554
555 assert_eq!(text, "hello world");
556 assert!(saw_stop);
557 assert_eq!(mock.call_count(), 1);
558 assert_eq!(mock.captured_requests().len(), 1);
559 assert_eq!(mock.remaining_turns(), 0);
560 }
561
562 #[tokio::test]
563 async fn errors_when_queue_exhausted() {
564 let mock = MockLlmClient::new(Vec::new());
565 let result = mock.create_message_stream(empty_request()).await;
566 match result {
567 Ok(_) => panic!("should error on empty queue"),
568 Err(err) => assert!(format!("{err}").contains("no canned")),
569 }
570 }
571
572 #[tokio::test]
573 async fn captures_request_payload_for_assertions() {
574 let mock = MockLlmClient::new(vec![canned::simple_text_turn("ok")]);
575 let mut req = empty_request();
576 req.temperature = Some(0.42);
577 let _ = mock.create_message_stream(req).await.unwrap();
578
579 let captured = mock.last_request().expect("should have captured");
580 assert_eq!(captured.temperature, Some(0.42));
581 }
582
583 #[tokio::test]
584 async fn stream_auto_appends_message_stop() {
585 // Queue a turn missing MessageStop — mock should append one.
586 let turn = vec![canned::text_block_start(0), canned::text_delta(0, "x")];
587 let mock = MockLlmClient::new(vec![turn]);
588
589 let mut stream = mock.create_message_stream(empty_request()).await.unwrap();
590 let mut saw_stop = false;
591 while let Some(ev) = stream.next().await {
592 if matches!(ev.expect("event"), StreamEvent::MessageStop) {
593 saw_stop = true;
594 }
595 }
596 assert!(saw_stop, "auto MessageStop missing");
597 }
598
599 #[tokio::test]
600 async fn create_message_uses_canned_message_response_first() {
601 let mock = MockLlmClient::new(vec![canned::simple_text_turn("from stream")]);
602 mock.push_message_response(MessageResponse {
603 tool_projection_warning: None,
604 id: "preset".to_string(),
605 r#type: "message".to_string(),
606 role: "assistant".to_string(),
607 content: vec![ContentBlock::Text {
608 text: "from preset".to_string(),
609 cache_control: None,
610 }],
611 model: "mock-model".to_string(),
612 stop_reason: Some("end_turn".to_string()),
613 stop_sequence: None,
614 container: None,
615 usage: Usage::default(),
616 title: None,
617 stop_details: None,
618 refusal: None,
619 });
620
621 let resp = mock.create_message(empty_request()).await.unwrap();
622 assert_eq!(resp.id, "preset");
623 }
624
625 #[tokio::test]
626 async fn create_message_synthesizes_from_streaming_turn_when_no_message_queued() {
627 let mock = MockLlmClient::new(vec![canned::simple_text_turn("synthesized")]);
628 let resp = mock.create_message(empty_request()).await.unwrap();
629 let text = match &resp.content[0] {
630 ContentBlock::Text { text, .. } => text.clone(),
631 _ => panic!("expected text"),
632 };
633 assert_eq!(text, "synthesized");
634 assert_eq!(resp.stop_reason.as_deref(), Some("end_turn"));
635 }
636
637 #[tokio::test]
638 async fn create_message_synthesizes_from_factory_turn() {
639 let mock = MockLlmClient::new(Vec::new());
640 mock.push_factory(|request| {
641 assert_eq!(request.model, "mock-model");
642 canned::simple_text_turn("from factory")
643 });
644
645 let resp = mock.create_message(empty_request()).await.unwrap();
646 let text = match &resp.content[0] {
647 ContentBlock::Text { text, .. } => text.clone(),
648 _ => panic!("expected text"),
649 };
650 assert_eq!(text, "from factory");
651 }
652
653 #[tokio::test]
654 async fn provider_and_model_are_overridable() {
655 let mock = MockLlmClient::new(vec![canned::simple_text_turn("x")])
656 .with_provider("test-provider")
657 .with_model("test-model");
658 assert_eq!(mock.provider_name(), "test-provider");
659 assert_eq!(mock.model(), "test-model");
660 }
661
662 #[tokio::test]
663 async fn tool_call_turn_serializes_correctly() {
664 let mock = MockLlmClient::new(vec![canned::tool_call_turn(
665 "call_1",
666 "list_dir",
667 r#"{"path":"/tmp"}"#,
668 )]);
669 let mut stream = mock.create_message_stream(empty_request()).await.unwrap();
670
671 let mut saw_tool_use = false;
672 let mut json_seen = String::new();
673 while let Some(ev) = stream.next().await {
674 match ev.unwrap() {
675 StreamEvent::ContentBlockStart { content_block, .. } => {
676 use codewhale_models::ContentBlockStart;
677 if let ContentBlockStart::ToolUse { name, .. } = content_block {
678 assert_eq!(name, "list_dir");
679 saw_tool_use = true;
680 }
681 }
682 StreamEvent::ContentBlockDelta {
683 delta: Delta::InputJsonDelta { partial_json },
684 ..
685 } => json_seen.push_str(&partial_json),
686 _ => {}
687 }
688 }
689 assert!(saw_tool_use, "expected tool_use start event");
690 assert!(json_seen.contains("/tmp"));
691 }
692
693 #[tokio::test]
694 async fn multiple_turns_consumed_in_order() {
695 let mock = MockLlmClient::new(vec![
696 canned::simple_text_turn("turn-one"),
697 canned::simple_text_turn("turn-two"),
698 ]);
699 for expected in ["turn-one", "turn-two"] {
700 let mut stream = mock.create_message_stream(empty_request()).await.unwrap();
701 let mut text = String::new();
702 while let Some(ev) = stream.next().await {
703 if let StreamEvent::ContentBlockDelta {
704 delta: Delta::TextDelta { text: t },
705 ..
706 } = ev.unwrap()
707 {
708 text.push_str(&t);
709 }
710 }
711 assert_eq!(text, expected);
712 }
713 assert_eq!(mock.call_count(), 2);
714 assert_eq!(mock.remaining_turns(), 0);
715 }
716 }
717
717 lines RUST