-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathtest_astr_main_agent.py
More file actions
2595 lines (2156 loc) · 95.6 KB
/
Copy pathtest_astr_main_agent.py
File metadata and controls
2595 lines (2156 loc) · 95.6 KB
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for astr_main_agent module."""
import datetime
import os
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from astrbot.core import astr_main_agent as ama
from astrbot.core.agent.mcp_client import MCPTool
from astrbot.core.agent.message import Message, dump_messages_with_checkpoints
from astrbot.core.agent.tool import FunctionTool, ToolSet
from astrbot.core.conversation_mgr import Conversation
from astrbot.core.message.components import File, Image, Plain, Reply, Video
from astrbot.core.platform.astr_message_event import AstrMessageEvent
from astrbot.core.platform.platform_metadata import PlatformMetadata
from astrbot.core.provider import Provider
from astrbot.core.provider.entities import ProviderRequest
from astrbot.core.skills.skill_manager import SkillInfo
from astrbot.core.star.star import StarMetadata
@pytest.fixture
def mock_provider():
"""Create a mock provider."""
provider = MagicMock(spec=Provider)
provider.provider_config = {
"id": "test-provider",
"modalities": ["image", "tool_use"],
}
provider.get_model.return_value = "gpt-4"
return provider
@pytest.fixture
def mock_context():
"""Create a mock Context."""
ctx = MagicMock()
ctx.get_config.return_value = {}
ctx.conversation_manager = MagicMock()
ctx.persona_manager = MagicMock()
ctx.persona_manager.personas_v3 = []
ctx.persona_manager.resolve_selected_persona = AsyncMock(
return_value=(None, None, None, False)
)
ctx.persona_manager.get_persona_v3_by_id = MagicMock(return_value=None)
tool_mgr = MagicMock()
tool_mgr.get_builtin_tool.side_effect = lambda cls, **kwargs: cls(**kwargs)
ctx.get_llm_tool_manager.return_value = tool_mgr
ctx.subagent_orchestrator = None
return ctx
@pytest.fixture
def mock_event():
"""Create a mock AstrMessageEvent."""
platform_meta = PlatformMetadata(
id="test_platform",
name="test_platform",
description="Test platform",
)
message_obj = MagicMock()
message_obj.message = [Plain(text="Hello")]
message_obj.sender = MagicMock(user_id="user123", nickname="TestUser")
message_obj.group_id = None
message_obj.group = None
event = MagicMock(spec=AstrMessageEvent)
event.message_str = "Hello"
event.message_obj = message_obj
event.platform_meta = platform_meta
event.session_id = "session123"
event.unified_msg_origin = "test_platform:private:session123"
event.get_extra.return_value = None
event.get_platform_name.return_value = "test_platform"
event.get_platform_id.return_value = "test_platform"
event.get_group_id.return_value = None
event.get_sender_name.return_value = "TestUser"
event.trace = MagicMock()
event.plugins_name = None
return event
@pytest.fixture
def mock_conversation():
"""Create a mock conversation."""
conv = MagicMock(spec=Conversation)
conv.cid = "conv-id"
conv.persona_id = None
conv.history = "[]"
return conv
def test_provider_supports_modality_requires_explicit_list():
provider = MagicMock(spec=Provider)
provider.provider_config = {"modalities": ["text", "image"]}
assert ama._provider_supports_modality(provider, "image")
provider.provider_config = {"modalities": ["text"]}
assert not ama._provider_supports_modality(provider, "image")
provider.provider_config = {}
assert not ama._provider_supports_modality(provider, "image")
provider.provider_config = {"modalities": "image"}
assert not ama._provider_supports_modality(provider, "image")
@pytest.fixture
def sample_config():
"""Create a sample MainAgentBuildConfig."""
module = ama
return module.MainAgentBuildConfig(
tool_call_timeout=60,
streaming_response=True,
file_extract_enabled=True,
file_extract_prov="moonshotai",
file_extract_msh_api_key="test-api-key",
)
def _new_mock_conversation(cid: str = "conv-id") -> MagicMock:
conv = MagicMock(spec=Conversation)
conv.cid = cid
conv.persona_id = None
conv.history = "[]"
return conv
def _setup_conversation_for_build(conv_mgr, cid: str = "conv-id") -> MagicMock:
conv_mgr.get_curr_conversation_id = AsyncMock(return_value=None)
conv_mgr.new_conversation = AsyncMock(return_value=cid)
conversation = _new_mock_conversation(cid=cid)
conv_mgr.get_conversation = AsyncMock(return_value=conversation)
return conversation
def test_append_system_reminders_includes_weekday(mock_event):
"""Test datetime reminder includes weekday information."""
req = ProviderRequest(prompt="Hello")
fixed_now = datetime.datetime(
2026,
6,
8,
12,
34,
tzinfo=datetime.timezone.utc,
)
class FixedDateTime(datetime.datetime):
@classmethod
def now(cls, tz=None):
if tz:
return fixed_now.astimezone(tz)
return fixed_now
with patch("astrbot.core.astr_main_agent.datetime.datetime", FixedDateTime):
ama._append_system_reminders(
mock_event,
req,
{"datetime_system_prompt": True},
"UTC",
)
assert [part.text for part in req.extra_user_content_parts] == [
"<system_reminder>Current datetime: "
"2026-06-08 12:34 (UTC), Weekday: Monday</system_reminder>"
]
class TestMainAgentBuildConfig:
"""Tests for MainAgentBuildConfig dataclass."""
def test_config_initialization(self):
"""Test MainAgentBuildConfig initialization with defaults."""
module = ama
config = module.MainAgentBuildConfig(tool_call_timeout=60)
assert config.tool_call_timeout == 60
assert config.tool_schema_mode == "full"
assert config.provider_wake_prefix == ""
assert config.streaming_response is True
assert config.sanitize_context_by_modalities is False
assert config.kb_agentic_mode is False
assert config.file_extract_enabled is False
assert config.llm_safety_mode is True
def test_config_with_custom_values(self):
"""Test MainAgentBuildConfig with custom values."""
module = ama
config = module.MainAgentBuildConfig(
tool_call_timeout=120,
tool_schema_mode="skills-like",
provider_wake_prefix="/",
streaming_response=False,
kb_agentic_mode=True,
file_extract_enabled=True,
computer_use_runtime="sandbox",
add_cron_tools=False,
)
assert config.tool_call_timeout == 120
assert config.tool_schema_mode == "skills-like"
assert config.provider_wake_prefix == "/"
assert config.streaming_response is False
assert config.kb_agentic_mode is True
assert config.file_extract_enabled is True
assert config.computer_use_runtime == "sandbox"
assert config.add_cron_tools is False
class TestSelectProvider:
"""Tests for _select_provider function."""
def test_select_provider_by_id(self, mock_event, mock_context, mock_provider):
"""Test selecting provider by ID from event extra."""
module = ama
mock_event.get_extra.side_effect = lambda k: (
"test-provider" if k == "selected_provider" else None
)
mock_context.get_provider_by_id.return_value = mock_provider
result = module._select_provider(mock_event, mock_context)
assert result == mock_provider
mock_context.get_provider_by_id.assert_called_once_with("test-provider")
def test_select_provider_not_found(self, mock_event, mock_context):
"""Test selecting provider when ID is not found."""
module = ama
mock_event.get_extra.side_effect = lambda k: (
"non-existent" if k == "selected_provider" else None
)
mock_context.get_provider_by_id.return_value = None
result = module._select_provider(mock_event, mock_context)
assert result is None
mock_event.set_extra.assert_called_with(
module.LLM_ERROR_MESSAGE_EXTRA_KEY,
"LLM 请求失败:未找到指定的提供商 `non-existent`。请检查提供商配置或重新选择可用模型。",
)
def test_select_provider_invalid_type(self, mock_event, mock_context):
"""Test selecting provider when result is not a Provider instance."""
module = ama
mock_event.get_extra.side_effect = lambda k: (
"invalid" if k == "selected_provider" else None
)
mock_context.get_provider_by_id.return_value = "not a provider"
result = module._select_provider(mock_event, mock_context)
assert result is None
mock_event.set_extra.assert_called_with(
module.LLM_ERROR_MESSAGE_EXTRA_KEY,
"LLM 请求失败:选择的提供商类型无效(str),已跳过本次请求。",
)
def test_select_provider_fallback(self, mock_event, mock_context, mock_provider):
"""Test provider selection fallback to using provider."""
module = ama
mock_event.get_extra.return_value = None
mock_context.get_using_provider.return_value = mock_provider
result = module._select_provider(mock_event, mock_context)
assert result == mock_provider
mock_context.get_using_provider.assert_called_once_with(
umo=mock_event.unified_msg_origin
)
def test_select_provider_fallback_error(self, mock_event, mock_context):
"""Test provider selection when fallback raises ValueError."""
module = ama
mock_event.get_extra.return_value = None
mock_context.get_using_provider.side_effect = ValueError("Test error")
result = module._select_provider(mock_event, mock_context)
assert result is None
mock_event.set_extra.assert_called_with(
module.LLM_ERROR_MESSAGE_EXTRA_KEY,
"LLM 请求失败:Test error",
)
class TestGetSessionConv:
"""Tests for _get_session_conv function."""
@pytest.mark.asyncio
async def test_get_session_conv_existing(
self, mock_event, mock_context, mock_conversation
):
"""Test getting existing conversation."""
module = ama
conv_mgr = mock_context.conversation_manager
conv_mgr.get_curr_conversation_id = AsyncMock(return_value="existing-conv-id")
conv_mgr.get_conversation = AsyncMock(return_value=mock_conversation)
result = await module._get_session_conv(mock_event, mock_context)
assert result == mock_conversation
conv_mgr.get_curr_conversation_id.assert_called_once_with(
mock_event.unified_msg_origin
)
conv_mgr.get_conversation.assert_called_once_with(
mock_event.unified_msg_origin, "existing-conv-id"
)
@pytest.mark.asyncio
async def test_get_session_conv_create_new(self, mock_event, mock_context):
"""Test creating new conversation when none exists."""
module = ama
conv_mgr = mock_context.conversation_manager
conv_mgr.get_curr_conversation_id = AsyncMock(return_value=None)
conv_mgr.new_conversation = AsyncMock(return_value="new-conv-id")
mock_conversation = MagicMock(spec=Conversation)
mock_conversation.cid = "new-conv-id"
mock_conversation.persona_id = None
mock_conversation.history = "[]"
conv_mgr.get_conversation = AsyncMock(return_value=mock_conversation)
result = await module._get_session_conv(mock_event, mock_context)
assert result == mock_conversation
conv_mgr.new_conversation.assert_called_once_with(
mock_event.unified_msg_origin, mock_event.get_platform_id()
)
@pytest.mark.asyncio
async def test_get_session_conv_retry(self, mock_event, mock_context):
"""Test retrying conversation creation after failure."""
module = ama
conv_mgr = mock_context.conversation_manager
conv_mgr.get_curr_conversation_id = AsyncMock(return_value="conv-id")
conv_mgr.get_conversation = AsyncMock(return_value=None)
conv_mgr.new_conversation = AsyncMock(return_value="retry-conv-id")
mock_conversation = MagicMock(spec=Conversation)
mock_conversation.cid = "retry-conv-id"
mock_conversation.persona_id = None
mock_conversation.history = "[]"
conv_mgr.get_conversation.side_effect = [None, mock_conversation]
result = await module._get_session_conv(mock_event, mock_context)
assert result == mock_conversation
assert conv_mgr.new_conversation.call_count == 1
assert conv_mgr.get_conversation.call_count == 2
@pytest.mark.asyncio
async def test_get_session_conv_failure(self, mock_event, mock_context):
"""Test RuntimeError when conversation creation fails."""
module = ama
conv_mgr = mock_context.conversation_manager
conv_mgr.get_curr_conversation_id = AsyncMock(return_value=None)
conv_mgr.new_conversation = AsyncMock(return_value="new-conv-id")
conv_mgr.get_conversation = AsyncMock(return_value=None)
with pytest.raises(RuntimeError, match="无法创建新的对话。"):
await module._get_session_conv(mock_event, mock_context)
class TestApplyKb:
"""Tests for _apply_kb function."""
@pytest.mark.asyncio
async def test_apply_kb_without_agentic_mode(self, mock_event, mock_context):
"""Test applying knowledge base in non-agentic mode."""
module = ama
req = ProviderRequest(prompt="test question", system_prompt="System prompt")
config = module.MainAgentBuildConfig(
tool_call_timeout=60, kb_agentic_mode=False
)
with patch(
"astrbot.core.astr_main_agent.retrieve_knowledge_base",
AsyncMock(return_value="KB result"),
):
await module._apply_kb(mock_event, req, mock_context, config)
assert req.system_prompt == "System prompt"
assert len(req.extra_user_content_parts) == 1
kb_part = req.extra_user_content_parts[0]
assert kb_part.text == "[Related Knowledge Base Results]:\nKB result"
message = Message.model_validate(await req.assemble_context())
assert isinstance(message.content, list)
assert message.content[0].text == "test question"
assert message.content[1].text == "[Related Knowledge Base Results]:\nKB result"
assert dump_messages_with_checkpoints([message]) == [
{"role": "user", "content": [{"type": "text", "text": "test question"}]}
]
@pytest.mark.asyncio
async def test_apply_kb_with_agentic_mode(self, mock_event, mock_context):
"""Test applying knowledge base in agentic mode."""
module = ama
req = ProviderRequest(prompt="test question")
config = module.MainAgentBuildConfig(tool_call_timeout=60, kb_agentic_mode=True)
await module._apply_kb(mock_event, req, mock_context, config)
assert req.func_tool is not None
@pytest.mark.asyncio
async def test_apply_kb_no_prompt(self, mock_event, mock_context):
"""Test applying knowledge base when prompt is None."""
module = ama
req = ProviderRequest(prompt=None, system_prompt="System")
config = module.MainAgentBuildConfig(
tool_call_timeout=60, kb_agentic_mode=False
)
await module._apply_kb(mock_event, req, mock_context, config)
assert req.system_prompt == "System"
@pytest.mark.asyncio
@pytest.mark.parametrize("prompt", ["", " \n\t"])
async def test_apply_kb_blank_prompt(self, prompt, mock_event, mock_context):
"""Test applying knowledge base when prompt is blank."""
module = ama
req = ProviderRequest(prompt=prompt, system_prompt="System")
config = module.MainAgentBuildConfig(
tool_call_timeout=60, kb_agentic_mode=False
)
retrieve = AsyncMock(return_value="KB result")
with patch("astrbot.core.astr_main_agent.retrieve_knowledge_base", retrieve):
await module._apply_kb(mock_event, req, mock_context, config)
retrieve.assert_not_awaited()
assert req.system_prompt == "System"
@pytest.mark.asyncio
async def test_apply_kb_no_result(self, mock_event, mock_context):
"""Test applying knowledge base when no result is returned."""
module = ama
req = ProviderRequest(prompt="test", system_prompt="System")
config = module.MainAgentBuildConfig(
tool_call_timeout=60, kb_agentic_mode=False
)
with patch(
"astrbot.core.astr_main_agent.retrieve_knowledge_base",
AsyncMock(return_value=None),
):
await module._apply_kb(mock_event, req, mock_context, config)
assert req.system_prompt == "System"
@pytest.mark.asyncio
async def test_apply_kb_with_existing_tools(self, mock_event, mock_context):
"""Test applying knowledge base with existing toolset."""
module = ama
existing_tools = ToolSet()
req = ProviderRequest(prompt="test", func_tool=existing_tools)
config = module.MainAgentBuildConfig(tool_call_timeout=60, kb_agentic_mode=True)
await module._apply_kb(mock_event, req, mock_context, config)
assert req.func_tool is not None
class TestBuiltinToolInjection:
"""Tests for builtin tool injection paths."""
@pytest.mark.asyncio
async def test_apply_web_search_tools_uses_builtin_tool_manager(
self, mock_event, mock_context
):
"""Test web search tool injection through the builtin tool manager."""
module = ama
req = ProviderRequest()
mock_context.get_config.return_value = {
"provider_settings": {
"web_search": True,
"websearch_provider": "baidu_ai_search",
}
}
builtin_tool = MagicMock(spec=FunctionTool)
builtin_tool.name = "web_search_baidu"
tool_mgr = MagicMock()
tool_mgr.get_builtin_tool.return_value = builtin_tool
mock_context.get_llm_tool_manager.return_value = tool_mgr
await module._apply_web_search_tools(mock_event, req, mock_context)
tool_mgr.get_builtin_tool.assert_called_once_with(module.BaiduWebSearchTool)
assert req.func_tool is not None
assert req.func_tool.get_tool("web_search_baidu") is builtin_tool
@pytest.mark.asyncio
async def test_apply_web_search_tools_adds_firecrawl_search_and_extract_tools(
self, mock_event, mock_context
):
"""Test Firecrawl web search injects search and extract tools."""
module = ama
req = ProviderRequest()
mock_context.get_config.return_value = {
"provider_settings": {
"web_search": True,
"websearch_provider": "firecrawl",
}
}
search_tool = MagicMock(spec=FunctionTool)
search_tool.name = "web_search_firecrawl"
extract_tool = MagicMock(spec=FunctionTool)
extract_tool.name = "firecrawl_extract_web_page"
tool_mgr = MagicMock()
tool_mgr.get_builtin_tool.side_effect = [search_tool, extract_tool]
mock_context.get_llm_tool_manager.return_value = tool_mgr
await module._apply_web_search_tools(mock_event, req, mock_context)
assert tool_mgr.get_builtin_tool.call_args_list == [
((module.FirecrawlWebSearchTool,),),
((module.FirecrawlExtractWebPageTool,),),
]
assert req.func_tool is not None
assert req.func_tool.get_tool("web_search_firecrawl") is search_tool
assert req.func_tool.get_tool("firecrawl_extract_web_page") is extract_tool
def test_apply_web_search_citation_prompt_for_webchat(self, mock_event):
module = ama
req = ProviderRequest(system_prompt="base")
search_tool = MagicMock(spec=FunctionTool)
search_tool.name = "web_search_tavily"
req.func_tool = ToolSet()
req.func_tool.add_tool(search_tool)
mock_event.get_platform_name.return_value = "webchat"
module._apply_web_search_citation_prompt(mock_event, req)
assert module.WEB_SEARCH_CITATION_PROMPT in req.system_prompt
def test_apply_web_search_citation_prompt_is_idempotent(self, mock_event):
module = ama
req = ProviderRequest(system_prompt="")
search_tool = MagicMock(spec=FunctionTool)
search_tool.name = "web_search_tavily"
req.func_tool = ToolSet()
req.func_tool.add_tool(search_tool)
mock_event.get_platform_name.return_value = "webchat"
module._apply_web_search_citation_prompt(mock_event, req)
module._apply_web_search_citation_prompt(mock_event, req)
assert req.system_prompt.count(module.WEB_SEARCH_CITATION_PROMPT) == 1
def test_apply_web_search_citation_prompt_requires_webchat(self, mock_event):
module = ama
req = ProviderRequest(system_prompt="")
search_tool = MagicMock(spec=FunctionTool)
search_tool.name = "web_search_tavily"
req.func_tool = ToolSet()
req.func_tool.add_tool(search_tool)
mock_event.get_platform_name.return_value = "test_platform"
module._apply_web_search_citation_prompt(mock_event, req)
assert module.WEB_SEARCH_CITATION_PROMPT not in req.system_prompt
def test_proactive_cron_job_tools_uses_builtin_tool_manager(self, mock_context):
"""Test cron tool injection through the builtin tool manager."""
module = ama
req = ProviderRequest()
tool_mgr = MagicMock()
future_task_tool = MagicMock(spec=FunctionTool)
future_task_tool.name = "future_task"
tool_mgr.get_builtin_tool.return_value = future_task_tool
mock_context.get_llm_tool_manager.return_value = tool_mgr
module._proactive_cron_job_tools(req, mock_context)
tool_mgr.get_builtin_tool.assert_called_once_with(module.FutureTaskTool)
assert req.func_tool is not None
assert req.func_tool.get_tool("future_task") is future_task_tool
class TestApplyFileExtract:
"""Tests for _apply_file_extract function."""
@pytest.mark.asyncio
async def test_file_extract_basic(self, mock_event, sample_config):
"""Test basic file extraction."""
module = ama
mock_file = MagicMock(spec=File)
mock_file.name = "test.pdf"
mock_file.get_file = AsyncMock(return_value="/path/to/test.pdf")
mock_event.message_obj.message = [mock_file]
req = ProviderRequest(prompt="Summarize")
with patch(
"astrbot.core.astr_main_agent.extract_file_moonshotai"
) as mock_extract:
mock_extract.return_value = "File content"
await module._apply_file_extract(mock_event, req, sample_config)
assert len(req.contexts) == 1
assert "File Extract Results" in req.contexts[0]["content"]
@pytest.mark.asyncio
async def test_file_extract_no_files(self, mock_event, sample_config):
"""Test file extraction when no files present."""
module = ama
mock_event.message_obj.message = [Plain(text="Hello")]
req = ProviderRequest(prompt="Hello")
await module._apply_file_extract(mock_event, req, sample_config)
assert len(req.contexts) == 0
@pytest.mark.asyncio
async def test_file_extract_in_reply(self, mock_event, sample_config):
"""Test file extraction from reply chain."""
module = ama
mock_file = MagicMock(spec=File)
mock_file.name = "reply.pdf"
mock_file.get_file = AsyncMock(return_value="/path/to/reply.pdf")
mock_reply = MagicMock(spec=Reply)
mock_reply.chain = [mock_file]
mock_event.message_obj.message = [mock_reply]
req = ProviderRequest(prompt="Summarize")
with patch(
"astrbot.core.astr_main_agent.extract_file_moonshotai"
) as mock_extract:
mock_extract.return_value = "Reply content"
await module._apply_file_extract(mock_event, req, sample_config)
assert len(req.contexts) == 1
@pytest.mark.asyncio
async def test_file_extract_no_prompt(self, mock_event, sample_config):
"""Test file extraction when prompt is empty."""
module = ama
mock_file = MagicMock(spec=File)
mock_file.name = "test.pdf"
mock_file.get_file = AsyncMock(return_value="/path/to/test.pdf")
mock_event.message_obj.message = [mock_file]
req = ProviderRequest(prompt=None)
with patch(
"astrbot.core.astr_main_agent.extract_file_moonshotai"
) as mock_extract:
mock_extract.return_value = "Content"
await module._apply_file_extract(mock_event, req, sample_config)
assert req.prompt == "总结一下文件里面讲了什么?"
@pytest.mark.asyncio
async def test_file_extract_no_api_key(self, mock_event):
"""Test file extraction when no API key is configured."""
module = ama
config = module.MainAgentBuildConfig(
tool_call_timeout=60,
file_extract_enabled=True,
file_extract_msh_api_key="",
)
mock_file = MagicMock(spec=File)
mock_file.name = "test.pdf"
mock_file.get_file = AsyncMock(return_value="/path/to/test.pdf")
mock_event.message_obj.message = [mock_file]
req = ProviderRequest(prompt="Summarize")
await module._apply_file_extract(mock_event, req, config)
assert len(req.contexts) == 0
class TestEnsurePersonaAndSkills:
"""Tests for _ensure_persona_and_skills function."""
def test_filter_plugin_skills_uses_current_config_plugin_set(self, monkeypatch):
module = ama
monkeypatch.setattr(
module,
"star_registry",
[
StarMetadata(
name="allowed_plugin",
root_dir_name="astrbot_plugin_allowed",
activated=True,
),
StarMetadata(
name="blocked_plugin",
root_dir_name="astrbot_plugin_blocked",
activated=True,
),
],
)
skills = [
SkillInfo(name="local", description="", path="local/SKILL.md", active=True),
SkillInfo(
name="allowed-skill",
description="",
path="allowed/SKILL.md",
active=True,
source_type="plugin",
plugin_name="astrbot_plugin_allowed",
),
SkillInfo(
name="blocked-skill",
description="",
path="blocked/SKILL.md",
active=True,
source_type="plugin",
plugin_name="astrbot_plugin_blocked",
),
]
filtered = module._filter_skills_for_current_config(
skills,
{"plugin_set": ["allowed_plugin"]},
)
assert [skill.name for skill in filtered] == ["local", "allowed-skill"]
def test_filter_plugin_skills_skips_inactive_plugins_even_when_all_allowed(
self, monkeypatch
):
module = ama
monkeypatch.setattr(
module,
"star_registry",
[
StarMetadata(
name="inactive_plugin",
root_dir_name="astrbot_plugin_inactive",
activated=False,
)
],
)
skills = [
SkillInfo(
name="inactive-skill",
description="",
path="inactive/SKILL.md",
active=True,
source_type="plugin",
plugin_name="astrbot_plugin_inactive",
)
]
filtered = module._filter_skills_for_current_config(
skills,
{"plugin_set": ["*"]},
)
assert filtered == []
@pytest.mark.asyncio
async def test_ensure_persona_from_session(self, mock_event, mock_context):
"""Test applying persona from session service config."""
module = ama
persona = {"name": "test-persona", "prompt": "You are helpful."}
mock_context.persona_manager.personas_v3 = [persona]
mock_context.persona_manager.resolve_selected_persona = AsyncMock(
return_value=("test-persona", persona, "test-persona", False)
)
mock_event.trace = MagicMock(record=MagicMock())
req = ProviderRequest()
req.conversation = MagicMock(persona_id=None)
await module._ensure_persona_and_skills(req, {}, mock_context, mock_event)
assert "You are helpful." in req.system_prompt
@pytest.mark.asyncio
async def test_ensure_persona_from_conversation(self, mock_event, mock_context):
"""Test applying persona from conversation setting."""
module = ama
persona = {"name": "conv-persona", "prompt": "Custom persona."}
mock_context.persona_manager.personas_v3 = [persona]
mock_context.persona_manager.resolve_selected_persona = AsyncMock(
return_value=("conv-persona", persona, None, False)
)
req = ProviderRequest()
req.conversation = MagicMock(persona_id="conv-persona")
await module._ensure_persona_and_skills(req, {}, mock_context, mock_event)
assert "Custom persona." in req.system_prompt
@pytest.mark.asyncio
async def test_ensure_persona_none_explicit(self, mock_event, mock_context):
"""Test that [%None] persona is explicitly set to no persona."""
module = ama
mock_context.persona_manager.personas_v3 = []
mock_context.persona_manager.resolve_selected_persona = AsyncMock(
return_value=("[%None]", None, None, False)
)
req = ProviderRequest()
req.conversation = MagicMock(persona_id="[%None]")
await module._ensure_persona_and_skills(req, {}, mock_context, mock_event)
assert "Persona Instructions" not in req.system_prompt
@pytest.mark.asyncio
async def test_ensure_skills_includes_workspace_skills(
self,
monkeypatch,
tmp_path,
mock_event,
mock_context,
):
module = ama
data_dir = tmp_path / "data"
global_skills_dir = tmp_path / "global_skills"
plugins_dir = tmp_path / "plugins"
workspaces_dir = tmp_path / "workspaces"
for path in (data_dir, global_skills_dir, plugins_dir):
path.mkdir(parents=True, exist_ok=True)
global_skill_dir = global_skills_dir / "workspace-skill"
global_skill_dir.mkdir(parents=True)
global_skill_dir.joinpath("SKILL.md").write_text(
"---\ndescription: Global scoped skill.\n---\n",
encoding="utf-8",
)
workspace_root = workspaces_dir / module.normalize_umo_for_workspace(
mock_event.unified_msg_origin
)
workspace_skill_dir = workspace_root / "skills" / "workspace-skill"
workspace_skill_dir.mkdir(parents=True)
workspace_skill_dir.joinpath("SKILL.md").write_text(
"---\ndescription: Workspace scoped skill.\n---\n",
encoding="utf-8",
)
monkeypatch.setattr(
module,
"get_astrbot_workspaces_path",
lambda: str(workspaces_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_data_path",
lambda: str(data_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_skills_path",
lambda: str(global_skills_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_plugin_path",
lambda: str(plugins_dir),
)
req = ProviderRequest()
req.conversation = MagicMock(persona_id=None)
runtime_config = {"computer_use_runtime": "local"}
await module._ensure_persona_and_skills(
req, runtime_config, mock_context, mock_event
)
assert "**workspace-skill**" in req.system_prompt
assert "Workspace scoped skill." in req.system_prompt
assert "Global scoped skill." not in req.system_prompt
assert (
str(workspace_skill_dir / "SKILL.md").replace("\\", "/")
in req.system_prompt
)
@pytest.mark.asyncio
async def test_ensure_skills_skips_workspace_skills_for_group_sessions(
self,
monkeypatch,
tmp_path,
mock_event,
mock_context,
):
module = ama
data_dir = tmp_path / "data"
global_skills_dir = tmp_path / "global_skills"
plugins_dir = tmp_path / "plugins"
workspaces_dir = tmp_path / "workspaces"
for path in (data_dir, global_skills_dir, plugins_dir):
path.mkdir(parents=True, exist_ok=True)
mock_event.get_group_id.return_value = "group123"
mock_event.message_obj.group_id = "group123"
mock_event.unified_msg_origin = "test_platform:GroupMessage:group123"
workspace_root = workspaces_dir / module.normalize_umo_for_workspace(
mock_event.unified_msg_origin
)
workspace_skill_dir = workspace_root / "skills" / "workspace-skill"
workspace_skill_dir.mkdir(parents=True)
workspace_skill_dir.joinpath("SKILL.md").write_text(
"---\ndescription: Workspace scoped skill.\n---\n",
encoding="utf-8",
)
monkeypatch.setattr(
module,
"get_astrbot_workspaces_path",
lambda: str(workspaces_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_data_path",
lambda: str(data_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_skills_path",
lambda: str(global_skills_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_plugin_path",
lambda: str(plugins_dir),
)
req = ProviderRequest()
req.conversation = MagicMock(persona_id=None)
await module._ensure_persona_and_skills(
req, {"computer_use_runtime": "local"}, mock_context, mock_event
)
assert "Workspace scoped skill." not in req.system_prompt
assert "## Skills" not in req.system_prompt
@pytest.mark.asyncio
async def test_ensure_skills_respects_empty_persona_skills_for_workspace(
self,
monkeypatch,
tmp_path,
mock_event,
mock_context,
):
module = ama
data_dir = tmp_path / "data"
global_skills_dir = tmp_path / "global_skills"
plugins_dir = tmp_path / "plugins"
workspaces_dir = tmp_path / "workspaces"
for path in (data_dir, global_skills_dir, plugins_dir):
path.mkdir(parents=True, exist_ok=True)
workspace_root = workspaces_dir / module.normalize_umo_for_workspace(
mock_event.unified_msg_origin
)
workspace_skill_dir = workspace_root / "skills" / "workspace-skill"
workspace_skill_dir.mkdir(parents=True)
workspace_skill_dir.joinpath("SKILL.md").write_text(
"---\ndescription: Workspace scoped skill.\n---\n",
encoding="utf-8",
)
monkeypatch.setattr(
module,
"get_astrbot_workspaces_path",
lambda: str(workspaces_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_data_path",
lambda: str(data_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_skills_path",
lambda: str(global_skills_dir),
)
monkeypatch.setattr(
"astrbot.core.skills.skill_manager.get_astrbot_plugin_path",
lambda: str(plugins_dir),
)
persona = {"name": "no-skills", "prompt": "", "skills": []}
mock_context.persona_manager.resolve_selected_persona = AsyncMock(
return_value=("no-skills", persona, None, False)
)
req = ProviderRequest()
req.conversation = MagicMock(persona_id="no-skills")
await module._ensure_persona_and_skills(req, {}, mock_context, mock_event)
assert "Workspace scoped skill." not in req.system_prompt
assert "## Skills" not in req.system_prompt
@pytest.mark.asyncio
async def test_ensure_skills_skips_workspace_skills_in_sandbox_runtime(
self,
monkeypatch,
tmp_path,
mock_event,
mock_context,
):
module = ama
data_dir = tmp_path / "data"
global_skills_dir = tmp_path / "global_skills"
plugins_dir = tmp_path / "plugins"