File size: 32,007 Bytes
1f2d50a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64ced8b
1f2d50a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
"""Tests for app handler functions.

This module tests the main handler functions used in the Gradio UI,
particularly focusing on input collection and execution handling.
"""

import json
from unittest.mock import patch

import pytest

# Import the function we're testing
from app import handle_execute_plan
from kg_services.ontology import MCPPrompt, MCPTool, PlannedStep


class TestHandleExecutePlan:
    """Test suite for handle_execute_plan function."""

    @pytest.fixture
    def sample_tool(self) -> MCPTool:
        """Create a sample MCPTool for testing."""
        return MCPTool(
            tool_id="test-tool-001",
            name="Test Sentiment Analyzer",
            description="A test tool for sentiment analysis",
            tags=["sentiment", "analysis", "test"],
            invocation_command_stub="sentiment_analyze --input {text}",
        )

    @pytest.fixture
    def sample_prompt(self) -> MCPPrompt:
        """Create a sample MCPPrompt for testing."""
        return MCPPrompt(
            prompt_id="test-prompt-001",
            name="Basic Sentiment Analysis",
            description="Analyze sentiment of provided text",
            target_tool_id="test-tool-001",
            template_string="Analyze the sentiment of this text: {{text_input}}",
            input_variables=["text_input"],
            difficulty_level="beginner",
            example_inputs={"text_input": "This is a great product!"},
        )

    @pytest.fixture
    def sample_planned_step(
        self, sample_tool: MCPTool, sample_prompt: MCPPrompt
    ) -> PlannedStep:
        """Create a sample PlannedStep for testing."""
        return PlannedStep(tool=sample_tool, prompt=sample_prompt, relevance_score=0.95)

    @pytest.fixture
    def multi_input_prompt(self) -> MCPPrompt:
        """Create a prompt with multiple input variables."""
        return MCPPrompt(
            prompt_id="test-prompt-multi",
            name="Multi-Input Analysis",
            description="Analysis with multiple inputs",
            target_tool_id="test-tool-001",
            template_string="Analyze {{input1}} with context {{input2}} and format {{input3}}",
            input_variables=["input1", "input2", "input3"],
            difficulty_level="intermediate",
        )

    @pytest.fixture
    def no_input_prompt(self) -> MCPPrompt:
        """Create a prompt with no input variables."""
        return MCPPrompt(
            prompt_id="test-prompt-no-input",
            name="No Input Required",
            description="A prompt that requires no inputs",
            target_tool_id="test-tool-001",
            template_string="Perform standard analysis",
            input_variables=[],
            difficulty_level="beginner",
        )

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_basic_success(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test successful input collection with single variable."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_123",
            "tool_information": {"tool_name": "Test Sentiment Analyzer"},
            "prompt_information": {"prompt_name": "Basic Sentiment Analysis"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }
        test_query = "analyze sentiment"
        test_input = "This is a great product!"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        assert "πŸŽ‰ **Execution Complete!**" in result
        assert "Test Sentiment Analyzer" in result
        assert "Basic Sentiment Analysis" in result
        assert test_input in result
        assert "βœ…" in result

        # Verify planner was called correctly
        mock_planner_agent.generate_plan.assert_called_once_with(test_query, top_k=1)
        # Verify executor was called
        mock_executor_agent.execute_plan_step.assert_called_once()

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_multiple_inputs(
        self, mock_planner_agent, mock_executor_agent, sample_tool, multi_input_prompt
    ):
        """Test input collection with multiple variables."""
        # Arrange
        planned_step = PlannedStep(
            tool=sample_tool, prompt=multi_input_prompt, relevance_score=0.88
        )
        mock_planner_agent.generate_plan.return_value = [planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_456",
            "tool_information": {"tool_name": "Test Tool"},
            "prompt_information": {"prompt_name": "Multi Input Prompt"},
            "execution_details": {"inputs_count": 3, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }

        test_query = "complex analysis"
        input1, input2, input3 = "data1", "context2", "format3"

        # Act
        result = handle_execute_plan(
            test_query, input1, input2, input3, "unused4", "unused5"
        )

        # Assert
        assert "πŸŽ‰ **Execution Complete!**" in result
        assert input1 in result
        assert input2 in result
        assert input3 in result

        # Parse the JSON section to verify correct mapping
        json_start = result.find("```json\n")
        if json_start != -1:
            json_start += 8
            json_end = result.find("\n```", json_start)
            if json_end != -1:
                json_content = result[json_start:json_end].strip()
                if json_content:
                    parsed_inputs = json.loads(json_content)
                    assert parsed_inputs == {"input1": input1, "input2": input2, "input3": input3}
                else:
                    # If JSON content is empty, just verify the inputs are present in the result
                    assert all(inp in result for inp in [input1, input2, input3])
            else:
                # If JSON section not properly closed, just verify inputs are present
                assert all(inp in result for inp in [input1, input2, input3])
        else:
            # If no JSON section found, just verify inputs are present in the result
            assert all(inp in result for inp in [input1, input2, input3])

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_no_inputs_required(
        self, mock_planner_agent, mock_executor_agent, sample_tool, no_input_prompt
    ):
        """Test handling of prompts that require no inputs."""
        # Arrange
        planned_step = PlannedStep(
            tool=sample_tool, prompt=no_input_prompt, relevance_score=0.90
        )
        mock_planner_agent.generate_plan.return_value = [planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_789",
            "tool_information": {"tool_name": "Test Tool"},
            "prompt_information": {"prompt_name": "No Input Prompt"},
            "execution_details": {"inputs_count": 0, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }

        test_query = "standard analysis"

        # Act
        result = handle_execute_plan(test_query, "unused1", "unused2")

        # Assert
        assert "πŸŽ‰ **Execution Complete!**" in result
        assert "No Input Required" in result

        # Verify empty inputs dict
        json_start = result.find("```json\n")
        if json_start != -1:
            json_start += 8
            json_end = result.find("\n```", json_start)
            if json_end != -1:
                json_content = result[json_start:json_end].strip()
                if json_content:
                    parsed_inputs = json.loads(json_content)
                    assert parsed_inputs == {}
                # If JSON content is empty, that's acceptable for no inputs required

    def test_handle_execute_plan_no_planner_agent(self):
        """Test error handling when planner agent is not available."""
        # Act
        with patch("app.planner_agent", None):
            result = handle_execute_plan("test query", "input1")

        # Assert
        assert "❌ **Error**: Planner service not available" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_empty_query(self, mock_planner_agent, mock_executor_agent):
        """Test error handling with empty query."""
        # Act
        result = handle_execute_plan("", "input1")

        # Assert
        assert "❌ **Error**: Original query is missing" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_no_planned_steps(self, mock_planner_agent, mock_executor_agent):
        """Test error handling when no planned steps are returned."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = []

        # Act
        result = handle_execute_plan("test query", "input1")

        # Assert
        assert "❌ **Error**: Could not retrieve the current action plan" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_planner_exception(self, mock_planner_agent, mock_executor_agent):
        """Test error handling when planner raises an exception."""
        # Arrange
        mock_planner_agent.generate_plan.side_effect = Exception("Planner error")

        # Act
        result = handle_execute_plan("test query", "input1")

        # Assert
        assert "❌ **Execution Error**" in result
        assert "Planner error" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_partial_inputs(
        self, mock_planner_agent, mock_executor_agent, sample_tool, multi_input_prompt
    ):
        """Test handling when fewer inputs are provided than required."""
        # Arrange
        planned_step = PlannedStep(
            tool=sample_tool, prompt=multi_input_prompt, relevance_score=0.75
        )
        mock_planner_agent.generate_plan.return_value = [planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_partial",
            "tool_information": {"tool_name": "Test Tool"},
            "prompt_information": {"prompt_name": "Multi Input Prompt"},
            "execution_details": {"inputs_count": 2, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }

        test_query = "partial input test"
        # Only provide 2 inputs for a 3-input prompt
        input1, input2 = "data1", "context2"

        # Act
        result = handle_execute_plan(test_query, input1, input2)

        # Assert
        assert "πŸŽ‰ **Execution Complete!**" in result

        # Parse JSON to verify partial input handling
        json_start = result.find("```json\n")
        if json_start != -1:
            json_start += 8
            json_end = result.find("\n```", json_start)
            if json_end != -1:
                json_content = result[json_start:json_end].strip()
                if json_content:
                    parsed_inputs = json.loads(json_content)
                    # Should have empty string for missing input
                    expected = {"input1": input1, "input2": input2, "input3": ""}
                    assert parsed_inputs == expected
                else:
                    # If JSON content is empty, just verify provided inputs are in the result
                    assert input1 in result and input2 in result
            else:
                # If JSON section not properly closed, just verify provided inputs are present
                assert input1 in result and input2 in result
        else:
            # If no JSON section found, just verify provided inputs are present in the result
            assert input1 in result and input2 in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    @patch("app.logger")
    def test_handle_execute_plan_logging(
        self, mock_logger, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test that appropriate logging occurs during execution."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_log",
            "tool_information": {"tool_name": "Test Sentiment Analyzer"},
            "prompt_information": {"prompt_name": "Basic Sentiment Analysis"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }
        test_query = "logging test"
        test_input = "test input"

        # Act
        handle_execute_plan(test_query, test_input)

        # Assert
        # Check that info logs were called
        assert mock_logger.info.call_count >= 2

        # Verify specific log messages
        log_calls = [call[0][0] for call in mock_logger.info.call_args_list]
        assert any("Executing plan with StubExecutorAgent" in log for log in log_calls)
        assert any(
            "Execution simulation completed successfully" in log for log in log_calls
        )

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_json_formatting(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test that JSON formatting in output is valid."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_json",
            "tool_information": {"tool_name": "Test Sentiment Analyzer"},
            "prompt_information": {"prompt_name": "Basic Sentiment Analysis"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }
        test_query = "json formatting test"
        test_input = "test input with special chars: @#$%^&*()"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        # Verify the input is properly displayed in the output
        assert "πŸŽ‰ **Execution Complete!**" in result
        assert test_input in result
        assert "Mock analysis results" in result

        # Verify special characters are handled properly
        assert "@#$%^&*()" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_markdown_formatting(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test that execution results are properly formatted in Markdown."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_test_md",
            "tool_information": {"tool_name": "Test Sentiment Analyzer"},
            "prompt_information": {"prompt_name": "Basic Sentiment Analysis"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 1250},
            "results": {
                "mock_output": "Mock analysis results",
                "confidence_score": 0.95,
            },
            "metadata": {"simulation_version": "MVP3_Sprint4"},
        }
        test_query = "markdown test"
        test_input = "test input"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        # Check for Markdown headers
        assert "# πŸŽ‰ **Execution Complete!**" in result
        assert "## πŸ“Š **Execution Summary**" in result
        assert "## πŸ”§ **Tool & Prompt Information**" in result
        assert "## πŸ“ **Input Summary**" in result
        assert "## 🎯 **Execution Results**" in result

        # Check for proper formatting elements
        assert "- **Status**: βœ…" in result
        assert "- **Tool**:" in result
        assert "Mock analysis results" in result


class TestErrorHandling:
    """Test suite for error handling in app handlers."""

    @pytest.fixture
    def sample_tool(self) -> MCPTool:
        """Create a sample MCPTool for testing."""
        return MCPTool(
            tool_id="test-tool-error",
            name="Test Error Tool",
            description="A tool for testing error scenarios",
            tags=["test", "error"],
            invocation_command_stub="test_error {input}",
        )

    @pytest.fixture
    def sample_prompt(self) -> MCPPrompt:
        """Create a sample MCPPrompt for testing."""
        return MCPPrompt(
            prompt_id="test-prompt-error",
            name="Test Error Prompt",
            description="A prompt for testing error scenarios",
            target_tool_id="test-tool-error",
            template_string="Process: {{text_input}}",
            input_variables=["text_input"],
            difficulty_level="beginner",
        )

    @pytest.fixture
    def sample_planned_step(
        self, sample_tool: MCPTool, sample_prompt: MCPPrompt
    ) -> PlannedStep:
        """Create a sample PlannedStep for testing."""
        return PlannedStep(tool=sample_tool, prompt=sample_prompt, relevance_score=0.95)

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_error_response(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test handling of error responses from executor."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_error",
            "execution_id": "exec_err_test_123",
            "tool_information": {"tool_name": "Test Error Tool"},
            "prompt_information": {"prompt_name": "Test Error Prompt"},
            "execution_details": {
                "inputs_count": 1,
                "execution_time_ms": 500,
                "error_occurred_at": 45,
            },
            "error_information": {
                "error_type": "user_requested",
                "error_code": "USR_REQ_001",
                "error_severity": "medium",
                "error_message": "User explicitly requested error simulation",
                "error_details": "Error simulation was triggered by user input containing error keywords",
                "suggested_fixes": [
                    "Remove error keywords from input",
                    "Use different test data",
                ],
                "retry_recommended": True,
            },
            "results": {
                "message": "Tool execution failed: User explicitly requested error simulation",
                "mock_output": "**Error Simulation Activated**\n\n❌ **User-Requested Error**\nThis error was triggered because your input contained error simulation keywords.",
                "confidence_score": 0.0,
            },
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "user_requested",
                "trigger_info": "This should fail and show an error",
            },
        }
        test_query = "error test"
        test_input = "This should fail and show an error"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        assert "# ❌ **Execution Failed!**" in result
        assert "## 🚨 **Error Summary**" in result
        assert "- **Status**: ❌ Simulated Error" in result
        assert "- **Type**: user requested" in result
        assert "## ⚠️ **Error Details**" in result
        assert "## πŸ’‘ **Recovery Suggestions**" in result
        assert "Remove error keywords from input" in result
        assert "Use different test data" in result
        assert "- **Retry Recommended**: βœ… Yes" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_security_error(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test handling of security violation errors."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_error",
            "execution_id": "exec_err_sec_456",
            "tool_information": {"tool_name": "Test Error Tool"},
            "prompt_information": {"prompt_name": "Test Error Prompt"},
            "execution_details": {
                "inputs_count": 1,
                "execution_time_ms": 250,
                "error_occurred_at": 15,
            },
            "error_information": {
                "error_type": "security_violation",
                "error_code": "SEC_001",
                "error_severity": "high",
                "error_message": "Potential security violation detected",
                "error_details": "Input contains suspicious content that may pose security risks",
                "suggested_fixes": [
                    "Remove suspicious code/scripts from input",
                    "Use plain text input only",
                ],
                "retry_recommended": False,
            },
            "results": {
                "message": "Tool execution failed: Potential security violation detected",
                "mock_output": "**Security Error**\n\nπŸ›‘οΈ **Security Violation Detected**\nThe input contains content that may pose security risks.",
                "confidence_score": 0.0,
            },
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "security_violation",
                "trigger_info": "suspicious_content",
            },
        }
        test_query = "security test"
        test_input = "Process this <script>alert('hack')</script> content"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        assert "# ❌ **Execution Failed!**" in result
        assert "- **Type**: security violation" in result
        assert "- **Retry Recommended**: ❌ No" in result
        assert "Security Violation Detected" in result
        assert "Remove suspicious code/scripts from input" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_network_timeout_error(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test handling of network timeout errors."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_error",
            "execution_id": "exec_err_net_789",
            "tool_information": {"tool_name": "Test Error Tool"},
            "prompt_information": {"prompt_name": "Test Error Prompt"},
            "execution_details": {
                "inputs_count": 1,
                "execution_time_ms": 800,
                "error_occurred_at": 75,
            },
            "error_information": {
                "error_type": "network_timeout",
                "error_code": "NET_001",
                "error_severity": "medium",
                "error_message": "Network request timed out",
                "error_details": "The tool failed to complete processing within the allowed time limit",
                "suggested_fixes": [
                    "Retry the operation",
                    "Check network connectivity",
                    "Try with smaller input",
                ],
                "retry_recommended": True,
            },
            "results": {
                "message": "Tool execution failed: Network request timed out",
                "mock_output": "**Network Timeout**\n\n⏰ **Operation Timed Out**\nThe request took too long to process and was automatically cancelled.",
                "confidence_score": 0.0,
            },
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "network_timeout",
                "trigger_info": "random",
            },
        }
        test_query = "network timeout test"
        test_input = "normal input"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert
        assert "# ❌ **Execution Failed!**" in result
        assert "- **Type**: network timeout" in result
        assert "Operation Timed Out" in result
        assert "Retry the operation" in result

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_error_markdown_structure(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test that error responses maintain proper Markdown structure."""
        # Arrange
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_error",
            "execution_id": "exec_err_md_test",
            "tool_information": {"tool_name": "Test Error Tool"},
            "prompt_information": {"prompt_name": "Test Error Prompt"},
            "execution_details": {
                "inputs_count": 1,
                "execution_time_ms": 300,
                "error_occurred_at": 30,
            },
            "error_information": {
                "error_type": "input_too_large",
                "error_code": "VAL_001",
                "error_severity": "medium",
                "error_message": "Input exceeds maximum allowed size",
                "error_details": "Input size limit exceeded",
                "suggested_fixes": [
                    "Reduce input size",
                    "Split large inputs into smaller chunks",
                ],
                "retry_recommended": True,
            },
            "results": {
                "message": "Tool execution failed: Input exceeds maximum allowed size",
                "mock_output": "**Input Size Error**\n\nπŸ“ **Input Too Large**\nThe provided input exceeds the maximum allowed size for this tool.",
                "confidence_score": 0.0,
            },
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "input_too_large",
                "trigger_info": "large_input",
            },
        }
        test_query = "markdown structure test"
        test_input = "test input"

        # Act
        result = handle_execute_plan(test_query, test_input)

        # Assert - Check for proper Markdown headers in error response
        assert result.startswith("# ❌ **Execution Failed!**")
        assert "## 🚨 **Error Summary**" in result
        assert "## πŸ”§ **Tool & Prompt Information**" in result
        assert "## ⚠️ **Error Details**" in result
        assert "## πŸ’‘ **Recovery Suggestions**" in result
        assert "## πŸ“ **Input Summary**" in result
        assert "## πŸ“„ **Error Output**" in result

        # Check for proper list formatting
        assert "1. Reduce input size" in result
        assert "2. Split large inputs into smaller chunks" in result

        # Check for proper formatting
        assert "---" in result  # Separator line

    @patch("app.executor_agent")
    @patch("app.planner_agent")
    def test_handle_execute_plan_error_vs_success_distinction(
        self, mock_planner_agent, mock_executor_agent, sample_planned_step
    ):
        """Test that error and success responses are clearly distinguished."""
        # Test error response first
        mock_planner_agent.generate_plan.return_value = [sample_planned_step]
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_error",
            "execution_id": "exec_err_test",
            "tool_information": {"tool_name": "Test Tool"},
            "prompt_information": {"prompt_name": "Test Prompt"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 300},
            "error_information": {
                "error_type": "test_scenario",
                "error_code": "TST_ERR_001",
                "error_severity": "high",
                "error_message": "Test error scenario activated",
                "error_details": "Test error details",
                "suggested_fixes": ["This is for testing"],
                "retry_recommended": True,
            },
            "results": {"mock_output": "Error output", "confidence_score": 0.0},
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "test_scenario",
            },
        }

        # Act
        error_result = handle_execute_plan("error test", "test error")

        # Assert error response characteristics
        assert "❌ **Execution Failed!**" in error_result
        assert "🚨 **Error Summary**" in error_result
        assert "⚠️ **Error Details**" in error_result
        assert "πŸ“„ **Error Output**" in error_result
        assert "πŸŽ‰ **Execution Complete!**" not in error_result
        assert (
            "- **Status**: βœ…" not in error_result
        )  # Status should not show success checkmark

        # Now test success response
        mock_executor_agent.execute_plan_step.return_value = {
            "status": "simulated_success",
            "execution_id": "exec_success_test",
            "tool_information": {"tool_name": "Test Tool"},
            "prompt_information": {"prompt_name": "Test Prompt"},
            "execution_details": {"inputs_count": 1, "execution_time_ms": 1500},
            "results": {"mock_output": "Success output", "confidence_score": 0.95},
            "metadata": {
                "simulation_version": "MVP3_Sprint4",
                "error_simulation": "none",
            },
        }

        # Act
        success_result = handle_execute_plan("success test", "normal input")

        # Assert success response characteristics
        assert "πŸŽ‰ **Execution Complete!**" in success_result
        assert "πŸ“Š **Execution Summary**" in success_result
        assert "🎯 **Execution Results**" in success_result
        assert "❌ **Execution Failed!**" not in success_result
        assert "🚨 **Error Summary**" not in success_result