1use crate::error::{MojenticError, Result};
66use crate::llm::chat_session::ChatSession;
67use crate::llm::tools::LlmTool;
68use crate::llm::LlmBroker;
69use std::future::Future;
70use std::pin::Pin;
71use std::sync::Arc;
72use tokio::sync::{mpsc, Mutex};
73use tokio::time::{timeout, Duration};
74use tracing::warn;
75
76#[derive(Debug, Clone)]
78pub struct GoalState {
79 pub goal: String,
81 pub iteration: usize,
83 pub max_iterations: usize,
85 pub solution: Option<String>,
87 pub is_complete: bool,
89}
90
91impl GoalState {
92 pub fn new(goal: impl Into<String>, max_iterations: usize) -> Self {
94 Self {
95 goal: goal.into(),
96 iteration: 0,
97 max_iterations,
98 solution: None,
99 is_complete: false,
100 }
101 }
102}
103
104pub trait SolverEvent: Send + Sync + std::fmt::Debug {
106 fn state(&self) -> &GoalState;
108}
109
110#[derive(Debug, Clone)]
112pub struct GoalSubmittedEvent {
113 pub state: GoalState,
114}
115
116impl SolverEvent for GoalSubmittedEvent {
117 fn state(&self) -> &GoalState {
118 &self.state
119 }
120}
121
122#[derive(Debug, Clone)]
124pub struct IterationCompletedEvent {
125 pub state: GoalState,
126 pub response: String,
128}
129
130impl SolverEvent for IterationCompletedEvent {
131 fn state(&self) -> &GoalState {
132 &self.state
133 }
134}
135
136#[derive(Debug, Clone)]
138pub struct GoalAchievedEvent {
139 pub state: GoalState,
140}
141
142impl SolverEvent for GoalAchievedEvent {
143 fn state(&self) -> &GoalState {
144 &self.state
145 }
146}
147
148#[derive(Debug, Clone)]
150pub struct GoalFailedEvent {
151 pub state: GoalState,
152}
153
154impl SolverEvent for GoalFailedEvent {
155 fn state(&self) -> &GoalState {
156 &self.state
157 }
158}
159
160#[derive(Debug, Clone)]
162pub struct TimeoutEvent {
163 pub state: GoalState,
164}
165
166impl SolverEvent for TimeoutEvent {
167 fn state(&self) -> &GoalState {
168 &self.state
169 }
170}
171
172#[derive(Debug, Clone)]
174pub enum AnySolverEvent {
175 GoalSubmitted(GoalSubmittedEvent),
176 IterationCompleted(IterationCompletedEvent),
177 GoalAchieved(GoalAchievedEvent),
178 GoalFailed(GoalFailedEvent),
179 Timeout(TimeoutEvent),
180}
181
182impl AnySolverEvent {
183 pub fn state(&self) -> &GoalState {
185 match self {
186 AnySolverEvent::GoalSubmitted(e) => &e.state,
187 AnySolverEvent::IterationCompleted(e) => &e.state,
188 AnySolverEvent::GoalAchieved(e) => &e.state,
189 AnySolverEvent::GoalFailed(e) => &e.state,
190 AnySolverEvent::Timeout(e) => &e.state,
191 }
192 }
193}
194
195type EventCallback = Arc<dyn Fn(AnySolverEvent) + Send + Sync>;
197
198pub struct EventEmitter {
204 subscribers: Arc<Mutex<Vec<EventCallback>>>,
205 error_tx: Arc<Mutex<Option<mpsc::Sender<MojenticError>>>>,
207}
208
209impl EventEmitter {
210 pub fn new() -> Self {
212 Self {
213 subscribers: Arc::new(Mutex::new(Vec::new())),
214 error_tx: Arc::new(Mutex::new(None)),
215 }
216 }
217
218 pub async fn set_error_sink(&self, tx: mpsc::Sender<MojenticError>) {
223 let mut guard = self.error_tx.lock().await;
224 *guard = Some(tx);
225 }
226
227 pub async fn subscribe<F>(&self, callback: F)
237 where
238 F: Fn(AnySolverEvent) + Send + Sync + 'static,
239 {
240 let mut subscribers = self.subscribers.lock().await;
241 subscribers.push(Arc::new(callback));
242 }
243
244 pub async fn emit(&self, event: AnySolverEvent) {
250 let subscribers = self.subscribers.lock().await.clone();
251 let error_tx = self.error_tx.lock().await.clone();
252
253 for callback in subscribers {
254 let event = event.clone();
255 let callback = callback.clone();
256 let error_tx = error_tx.clone();
257
258 let handle = tokio::spawn(async move {
260 callback(event);
261 });
262
263 if let Some(tx) = error_tx.clone() {
265 tokio::spawn(async move {
266 if let Err(join_err) = handle.await {
267 if join_err.is_panic() {
268 let msg = join_err
269 .into_panic()
270 .downcast::<&str>()
271 .map(|s| s.to_string())
272 .unwrap_or_else(|_| "handler panicked".to_string());
273 let _ = tx.send(MojenticError::HandlerError(msg)).await;
274 }
275 }
276 });
277 }
278 }
279 }
280}
281
282impl Default for EventEmitter {
283 fn default() -> Self {
284 Self::new()
285 }
286}
287
288pub struct SimpleRecursiveAgent {
294 broker: Arc<LlmBroker>,
295 tools: Vec<Box<dyn LlmTool>>,
296 max_iterations: usize,
297 system_prompt: String,
298 pub emitter: Arc<EventEmitter>,
300}
301
302impl SimpleRecursiveAgent {
303 pub fn new(broker: Arc<LlmBroker>) -> Self {
320 Self::builder(broker).build()
321 }
322
323 pub fn builder(broker: Arc<LlmBroker>) -> SimpleRecursiveAgentBuilder {
341 SimpleRecursiveAgentBuilder::new(broker)
342 }
343
344 pub async fn solve(&self, problem: impl Into<String>) -> Result<String> {
368 let problem = problem.into();
369
370 let (solution_tx, mut solution_rx) = mpsc::channel::<String>(1);
372
373 let (error_tx, mut error_rx) = mpsc::channel::<MojenticError>(8);
375 self.emitter.set_error_sink(error_tx).await;
376
377 let state = GoalState::new(problem.clone(), self.max_iterations);
379
380 let solution_tx_clone = solution_tx.clone();
382
383 let emitter = self.emitter.clone();
385 emitter
386 .subscribe(move |event: AnySolverEvent| match &event {
387 AnySolverEvent::GoalAchieved(_)
388 | AnySolverEvent::GoalFailed(_)
389 | AnySolverEvent::Timeout(_) => {
390 if let Some(solution) = &event.state().solution {
391 let _ = solution_tx_clone.try_send(solution.clone());
392 }
393 }
394 _ => {}
395 })
396 .await;
397
398 self.emitter
400 .emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent {
401 state: state.clone(),
402 }))
403 .await;
404
405 let agent = self.clone_for_handler();
407 tokio::spawn(async move {
408 agent.handle_goal_submitted(state).await;
409 });
410
411 match timeout(Duration::from_secs(300), async {
413 tokio::select! {
414 solution = solution_rx.recv() => {
415 Ok(solution)
416 }
417 Some(err) = error_rx.recv() => {
418 Err(err)
419 }
420 }
421 })
422 .await
423 {
424 Ok(Ok(Some(solution))) => Ok(solution),
425 Ok(Err(handler_err)) => Err(handler_err),
426 Ok(Ok(None)) | Err(_) => {
427 let timeout_message =
428 "Timeout: Could not solve the problem within 300 seconds.".to_string();
429 let mut timeout_state = GoalState::new(problem, self.max_iterations);
430 timeout_state.solution = Some(timeout_message.clone());
431 timeout_state.is_complete = true;
432
433 self.emitter
434 .emit(AnySolverEvent::Timeout(TimeoutEvent {
435 state: timeout_state,
436 }))
437 .await;
438
439 Ok(timeout_message)
440 }
441 }
442 }
443
444 fn handle_goal_submitted(
446 &self,
447 state: GoalState,
448 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
449 Box::pin(async move {
450 self.process_iteration(state).await;
451 })
452 }
453
454 fn handle_iteration_completed(
456 &self,
457 mut state: GoalState,
458 response: String,
459 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
460 Box::pin(async move {
461 let normalized = response.trim().to_uppercase();
462
463 if normalized == "FAIL" {
465 state.solution = Some(format!(
466 "Failed to solve after {} iterations:\n{}",
467 state.iteration, response
468 ));
469 state.is_complete = true;
470
471 self.emitter.emit(AnySolverEvent::GoalFailed(GoalFailedEvent { state })).await;
472 return;
473 }
474
475 if normalized == "DONE" {
477 state.solution = Some(response);
478 state.is_complete = true;
479
480 self.emitter
481 .emit(AnySolverEvent::GoalAchieved(GoalAchievedEvent { state }))
482 .await;
483 return;
484 }
485
486 if state.iteration >= state.max_iterations {
488 state.solution = Some(format!(
489 "Best solution after {} iterations:\n{}",
490 state.max_iterations, response
491 ));
492 state.is_complete = true;
493
494 self.emitter
495 .emit(AnySolverEvent::GoalAchieved(GoalAchievedEvent { state }))
496 .await;
497 return;
498 }
499
500 self.process_iteration(state).await;
502 })
503 }
504
505 fn process_iteration(
507 &self,
508 mut state: GoalState,
509 ) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
510 Box::pin(async move {
511 state.iteration += 1;
513
514 let prompt = format!(
516 "Given the user request:\n\
517 {}\n\
518 \n\
519 Use the tools at your disposal to act on their request.\n\
520 You may wish to create a step-by-step plan for more complicated requests.\n\
521 \n\
522 If you cannot provide an answer, say only \"FAIL\".\n\
523 If you have the answer, say only \"DONE\".",
524 state.goal
525 );
526
527 match self.generate_response(&prompt).await {
529 Ok(response) => {
530 self.emitter
531 .emit(AnySolverEvent::IterationCompleted(IterationCompletedEvent {
532 state: state.clone(),
533 response: response.clone(),
534 }))
535 .await;
536
537 self.handle_iteration_completed(state, response).await;
539 }
540 Err(e) => {
541 warn!("Error generating response: {}", e);
542 let mut error_state = state;
543 error_state.solution = Some(format!("Error: {}", e));
544 error_state.is_complete = true;
545
546 self.emitter
547 .emit(AnySolverEvent::GoalFailed(GoalFailedEvent { state: error_state }))
548 .await;
549 }
550 }
551 })
552 }
553
554 async fn generate_response(&self, prompt: &str) -> Result<String> {
556 let broker = Arc::clone(&self.broker);
558 let mut chat = ChatSession::builder((*broker).clone())
559 .system_prompt(&self.system_prompt)
560 .tools(self.tools.iter().map(|t| t.clone_box()).collect())
561 .build();
562
563 chat.send(prompt).await
564 }
565
566 fn clone_for_handler(&self) -> Self {
570 Self {
571 broker: self.broker.clone(),
572 tools: self.tools.iter().map(|t| t.clone_box()).collect(),
573 max_iterations: self.max_iterations,
574 system_prompt: self.system_prompt.clone(),
575 emitter: self.emitter.clone(),
576 }
577 }
578}
579
580pub struct SimpleRecursiveAgentBuilder {
582 broker: Arc<LlmBroker>,
583 tools: Vec<Box<dyn LlmTool>>,
584 max_iterations: usize,
585 system_prompt: Option<String>,
586}
587
588impl SimpleRecursiveAgentBuilder {
589 fn new(broker: Arc<LlmBroker>) -> Self {
591 Self {
592 broker,
593 tools: Vec::new(),
594 max_iterations: 5,
595 system_prompt: None,
596 }
597 }
598
599 pub fn tools(mut self, tools: Vec<Box<dyn LlmTool>>) -> Self {
601 self.tools = tools;
602 self
603 }
604
605 pub fn max_iterations(mut self, max_iterations: usize) -> Self {
607 self.max_iterations = max_iterations;
608 self
609 }
610
611 pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
613 self.system_prompt = Some(prompt.into());
614 self
615 }
616
617 pub fn build(self) -> SimpleRecursiveAgent {
619 let system_prompt = self.system_prompt.unwrap_or_else(|| {
620 "You are a problem-solving assistant that can solve complex problems step by step. \
621 You analyze problems, break them down into smaller parts, and solve them systematically. \
622 If you cannot solve a problem completely in one step, you make progress and identify what to do next."
623 .to_string()
624 });
625
626 SimpleRecursiveAgent {
627 broker: self.broker,
628 tools: self.tools,
629 max_iterations: self.max_iterations,
630 system_prompt,
631 emitter: Arc::new(EventEmitter::new()),
632 }
633 }
634}
635
636#[cfg(test)]
637mod tests {
638 use super::*;
639 use crate::llm::gateway::{CompletionConfig, LlmGateway, StreamChunk};
640 use crate::llm::models::{LlmGatewayResponse, LlmMessage};
641 use crate::llm::tools::{FunctionDescriptor, ToolDescriptor};
642 use async_trait::async_trait;
643 use futures::stream::{self, Stream};
644 use serde_json::{json, Value};
645 use std::collections::HashMap;
646 use std::pin::Pin;
647 use std::sync::atomic::{AtomicUsize, Ordering};
648
649 struct MockGateway {
651 responses: Vec<String>,
652 call_count: Arc<AtomicUsize>,
653 }
654
655 impl MockGateway {
656 fn new(responses: Vec<String>) -> Self {
657 Self {
658 responses,
659 call_count: Arc::new(AtomicUsize::new(0)),
660 }
661 }
662 }
663
664 #[async_trait::async_trait]
665 impl LlmGateway for MockGateway {
666 async fn complete(
667 &self,
668 _model: &str,
669 _messages: &[LlmMessage],
670 _tools: Option<&[Box<dyn LlmTool>]>,
671 _config: &CompletionConfig,
672 ) -> Result<LlmGatewayResponse> {
673 let idx = self.call_count.fetch_add(1, Ordering::SeqCst);
674
675 let content = if idx < self.responses.len() {
676 self.responses[idx].clone()
677 } else {
678 "default response".to_string()
679 };
680
681 Ok(LlmGatewayResponse {
682 content: Some(content),
683 object: None,
684 tool_calls: vec![],
685 thinking: None,
686 ..Default::default()
687 })
688 }
689
690 async fn complete_json(
691 &self,
692 _model: &str,
693 _messages: &[LlmMessage],
694 _schema: Value,
695 _config: &CompletionConfig,
696 ) -> Result<Value> {
697 Ok(json!({}))
698 }
699
700 async fn get_available_models(&self) -> Result<Vec<String>> {
701 Ok(vec!["test-model".to_string()])
702 }
703
704 async fn calculate_embeddings(
705 &self,
706 _text: &str,
707 _model: Option<&str>,
708 ) -> Result<Vec<f32>> {
709 Ok(vec![0.1, 0.2, 0.3])
710 }
711
712 fn complete_stream<'a>(
713 &'a self,
714 _model: &'a str,
715 _messages: &'a [LlmMessage],
716 _tools: Option<&'a [Box<dyn LlmTool>]>,
717 _config: &'a CompletionConfig,
718 ) -> Pin<Box<dyn Stream<Item = Result<StreamChunk>> + Send + 'a>> {
719 Box::pin(stream::iter(vec![Ok(StreamChunk::Content("test".to_string()))]))
720 }
721 }
722
723 #[derive(Clone)]
725 struct MockTool {
726 name: String,
727 }
728
729 #[async_trait]
730
731 impl LlmTool for MockTool {
732 async fn run(
733 &self,
734 _args: &HashMap<String, Value>,
735 _ctx: &crate::llm::tools::ToolRunCtx,
736 ) -> Result<Value> {
737 Ok(json!({"result": "success"}))
738 }
739
740 fn descriptor(&self) -> ToolDescriptor {
741 ToolDescriptor {
742 r#type: "function".to_string(),
743 function: FunctionDescriptor {
744 name: self.name.clone(),
745 description: "A mock tool".to_string(),
746 parameters: json!({}),
747 },
748 }
749 }
750
751 fn clone_box(&self) -> Box<dyn LlmTool> {
752 Box::new(self.clone())
753 }
754 }
755
756 #[tokio::test]
757 async fn test_goal_state_creation() {
758 let state = GoalState::new("Test problem", 5);
759
760 assert_eq!(state.goal, "Test problem");
761 assert_eq!(state.iteration, 0);
762 assert_eq!(state.max_iterations, 5);
763 assert_eq!(state.solution, None);
764 assert!(!state.is_complete);
765 }
766
767 #[tokio::test]
768 async fn test_event_emitter_subscribe_and_emit() {
769 let emitter = EventEmitter::new();
770 let received = Arc::new(Mutex::new(false));
771 let received_clone = received.clone();
772
773 emitter
774 .subscribe(move |_event: AnySolverEvent| {
775 let received = received_clone.clone();
776 tokio::spawn(async move {
777 *received.lock().await = true;
778 });
779 })
780 .await;
781
782 let state = GoalState::new("Test", 5);
783 emitter.emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent { state })).await;
784
785 tokio::time::sleep(Duration::from_millis(50)).await;
787
788 assert!(*received.lock().await);
789 }
790
791 #[tokio::test]
792 async fn test_builder_default_settings() {
793 let gateway = Arc::new(MockGateway::new(vec![]));
794 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
795 let agent = SimpleRecursiveAgent::new(broker);
796
797 assert_eq!(agent.max_iterations, 5);
798 assert_eq!(agent.tools.len(), 0);
799 }
800
801 #[tokio::test]
802 async fn test_builder_custom_max_iterations() {
803 let gateway = Arc::new(MockGateway::new(vec![]));
804 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
805 let agent = SimpleRecursiveAgent::builder(broker).max_iterations(10).build();
806
807 assert_eq!(agent.max_iterations, 10);
808 }
809
810 #[tokio::test]
811 async fn test_builder_with_tools() {
812 let gateway = Arc::new(MockGateway::new(vec![]));
813 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
814
815 let tools: Vec<Box<dyn LlmTool>> = vec![Box::new(MockTool {
816 name: "test_tool".to_string(),
817 })];
818
819 let agent = SimpleRecursiveAgent::builder(broker).tools(tools).build();
820
821 assert_eq!(agent.tools.len(), 1);
822 }
823
824 #[tokio::test]
825 async fn test_builder_custom_system_prompt() {
826 let gateway = Arc::new(MockGateway::new(vec![]));
827 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
828 let agent = SimpleRecursiveAgent::builder(broker).system_prompt("Custom prompt").build();
829
830 assert_eq!(agent.system_prompt, "Custom prompt");
831 }
832
833 #[tokio::test]
834 async fn test_solve_completes_with_done() {
835 let gateway = Arc::new(MockGateway::new(vec!["DONE".to_string()]));
836 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
837 let agent = SimpleRecursiveAgent::new(broker);
838
839 let result = agent.solve("Test problem").await.unwrap();
840
841 assert_eq!(result, "DONE");
842 }
843
844 #[tokio::test]
845 async fn test_solve_fails_with_fail() {
846 let gateway = Arc::new(MockGateway::new(vec!["FAIL".to_string()]));
847 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
848 let agent = SimpleRecursiveAgent::new(broker);
849
850 let result = agent.solve("Impossible problem").await.unwrap();
851
852 assert!(result.contains("Failed to solve after 1 iterations"));
853 assert!(result.contains("FAIL"));
854 }
855
856 #[tokio::test]
857 async fn test_solve_case_insensitive_done() {
858 let gateway = Arc::new(MockGateway::new(vec!["done".to_string()]));
859 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
860 let agent = SimpleRecursiveAgent::new(broker);
861
862 let result = agent.solve("Test problem").await.unwrap();
863
864 assert_eq!(result, "done");
865 }
866
867 #[tokio::test]
868 async fn test_solve_case_insensitive_fail() {
869 let gateway = Arc::new(MockGateway::new(vec!["fail".to_string()]));
870 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
871 let agent = SimpleRecursiveAgent::new(broker);
872
873 let result = agent.solve("Test problem").await.unwrap();
874
875 assert!(result.contains("Failed to solve"));
876 assert!(result.contains("fail"));
877 }
878
879 #[tokio::test]
880 async fn test_solve_word_boundary_done() {
881 let gateway = Arc::new(MockGateway::new(vec!["I'm DONE with this task".to_string()]));
884 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
885 let agent = SimpleRecursiveAgent::builder(broker).max_iterations(1).build();
886
887 let result = agent.solve("Test problem").await.unwrap();
888
889 assert!(result.contains("Best solution after 1 iterations"));
891 assert!(result.contains("I'm DONE with this task"));
892 }
893
894 #[tokio::test]
895 async fn test_solve_word_boundary_fail() {
896 let gateway = Arc::new(MockGateway::new(vec!["This will FAIL".to_string()]));
899 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
900 let agent = SimpleRecursiveAgent::builder(broker).max_iterations(1).build();
901
902 let result = agent.solve("Test problem").await.unwrap();
903
904 assert!(result.contains("Best solution after 1 iterations"));
906 assert!(result.contains("This will FAIL"));
907 }
908
909 #[tokio::test]
910 async fn test_solve_stops_at_max_iterations() {
911 let gateway = Arc::new(MockGateway::new(vec![
912 "Step 1".to_string(),
913 "Step 2".to_string(),
914 "Step 3".to_string(),
915 ]));
916 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
917 let agent = SimpleRecursiveAgent::builder(broker).max_iterations(3).build();
918
919 let result = agent.solve("Long problem").await.unwrap();
920
921 assert!(result.contains("Best solution after 3 iterations"));
922 assert!(result.contains("Step 3"));
923 }
924
925 #[tokio::test]
926 async fn test_solve_multiple_iterations_before_done() {
927 let gateway = Arc::new(MockGateway::new(vec![
928 "Working...".to_string(),
929 "Still working...".to_string(),
930 "DONE".to_string(),
931 ]));
932 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
933 let agent = SimpleRecursiveAgent::builder(broker).max_iterations(5).build();
934
935 let result = agent.solve("Complex problem").await.unwrap();
936
937 assert_eq!(result, "DONE");
938 }
939
940 #[tokio::test]
941 async fn test_event_emission_during_solve() {
942 let gateway = Arc::new(MockGateway::new(vec!["DONE".to_string()]));
943 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
944 let agent = SimpleRecursiveAgent::new(broker);
945
946 let goal_submitted = Arc::new(Mutex::new(false));
947 let iteration_completed = Arc::new(Mutex::new(false));
948 let goal_achieved = Arc::new(Mutex::new(false));
949
950 let goal_submitted_clone = goal_submitted.clone();
951 let iteration_completed_clone = iteration_completed.clone();
952 let goal_achieved_clone = goal_achieved.clone();
953
954 agent
955 .emitter
956 .subscribe(move |event: AnySolverEvent| {
957 let gs = goal_submitted_clone.clone();
958 let ic = iteration_completed_clone.clone();
959 let ga = goal_achieved_clone.clone();
960
961 tokio::spawn(async move {
962 match event {
963 AnySolverEvent::GoalSubmitted(_) => *gs.lock().await = true,
964 AnySolverEvent::IterationCompleted(_) => *ic.lock().await = true,
965 AnySolverEvent::GoalAchieved(_) => *ga.lock().await = true,
966 _ => {}
967 }
968 });
969 })
970 .await;
971
972 let _result = agent.solve("Test problem").await.unwrap();
973
974 tokio::time::sleep(Duration::from_millis(100)).await;
976
977 assert!(*goal_submitted.lock().await, "GoalSubmitted event not fired");
978 assert!(*iteration_completed.lock().await, "IterationCompleted event not fired");
979 assert!(*goal_achieved.lock().await, "GoalAchieved event not fired");
980 }
981
982 #[tokio::test]
983 async fn test_event_emission_on_failure() {
984 let gateway = Arc::new(MockGateway::new(vec!["FAIL".to_string()]));
985 let broker = Arc::new(LlmBroker::new("test-model", gateway, None));
986 let agent = SimpleRecursiveAgent::new(broker);
987
988 let goal_failed = Arc::new(Mutex::new(false));
989 let goal_failed_clone = goal_failed.clone();
990
991 agent
992 .emitter
993 .subscribe(move |event: AnySolverEvent| {
994 let gf = goal_failed_clone.clone();
995 tokio::spawn(async move {
996 if matches!(event, AnySolverEvent::GoalFailed(_)) {
997 *gf.lock().await = true;
998 }
999 });
1000 })
1001 .await;
1002
1003 let _result = agent.solve("Test problem").await.unwrap();
1004
1005 tokio::time::sleep(Duration::from_millis(100)).await;
1007
1008 assert!(*goal_failed.lock().await, "GoalFailed event not fired");
1009 }
1010
1011 #[tokio::test]
1012 async fn test_handler_panic_surfaces_as_error() {
1013 let emitter = EventEmitter::new();
1014
1015 emitter
1017 .subscribe(|_event: AnySolverEvent| {
1018 panic!("intentional test panic");
1019 })
1020 .await;
1021
1022 let (error_tx, mut error_rx) = mpsc::channel::<MojenticError>(8);
1023 emitter.set_error_sink(error_tx).await;
1024
1025 let state = GoalState::new("Test", 5);
1026 emitter.emit(AnySolverEvent::GoalSubmitted(GoalSubmittedEvent { state })).await;
1027
1028 let err = tokio::time::timeout(Duration::from_secs(2), error_rx.recv())
1030 .await
1031 .expect("timed out waiting for handler error")
1032 .expect("channel closed without error");
1033
1034 match err {
1035 MojenticError::HandlerError(msg) => {
1036 assert!(msg.contains("intentional test panic"), "unexpected error message: {msg}");
1037 }
1038 other => panic!("Expected HandlerError, got: {:?}", other),
1039 }
1040 }
1041}