Files
AstrBot/tests/unit/test_plugin_handler_trace.py
Soulter 8774e53ff4 feat: improve message tracing and add bounded SQLite history (#10515) (#10614)
* feat: expand message tracing and redesign trace explorer

* feat: add trace metadata chips and preserve response ownership

* feat: show full-width tracing list with optional details

* style: remove gray trace tab card

* feat: unify trace toolbar controls and use Vuetify datatable

* style: use native Vuetify trace table rows

* fix: prevent trace platform header wrapping

* feat: persist message traces in bounded SQLite storage

* fix: expose trace settings and preserve long prompt attributes

* docs: simplify trace storage setting hints

* feat: add trace history cleanup and disk usage accounting

* fix: finish event traces and fold Agent execution chains

* feat: fold long trace messages and consolidate persona metadata

* fix: hide redundant adapter event labels in traces

* refactor: remove redundant persisted span metadata

* feat: paginate trace history with Vuetify table controls

* style: reduce trace table text size

* style: increase trace table text to 13px

* style: flatten trace status chips and narrow platform column

* feat: show independent Agent and command trace types

* feat: show cumulative Agent token usage in trace details

* style: abbreviate trace token counts with k and M

* style: reduce trace table header height

* feat: show group and private chat trace types

* fix: include month and day in trace timestamps

* style: use system trace fonts and blue running status

* style: separate trace origin and sender metadata rows

* fix: trace successful proactive message tool deliveries

* feat: show model persona and tool counts on Agent headings

* style: prefix trace plugin chips with puzzle icons

* style: add icons and spacing to Agent metadata chips

* style: remove execution mode prefix from trace chips

* refactor: centralize response tracing without source attribution

* style: hide module metadata in trace details

* refactor: omit redundant module metadata from plugin traces

* refactor: remove obsolete module filtering from trace UI

* feat: expose trace recording toggle in system settings

* docs: simplify trace recording setting description

* feat: retain traces only for command responses and Agent calls

* fix: revert trace admission filtering and expand writer queue

* refactor: adopt OpenTelemetry SDK and simplify trace tests

* refactor: separate event and trace execution contexts

* fix: include OpenTelemetry SDK in runtime requirements

* refactor: dispatch session waiters in the core pipeline

Preserve access and safety checks before waiter dispatch and limit built-in group context handlers to group messages.

* test: remove trace dashboard tests

* fix: recover orphaned traces and enforce minimum storage budget

* fix: increase trace queue byte budgets and remove frame count limit
2026-10-18 17:09:08 +08:00

139 lines
5.4 KiB
Python

from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from astrbot.core.pipeline import context_utils
from astrbot.core.pipeline.process_stage.method import star_request
from astrbot.core.star.filter.command import CommandFilter
from astrbot.core.star.filter.command_group import CommandGroupFilter
from astrbot.core.star.filter.regex import RegexFilter
from astrbot.core.star.star_handler import EventType
from astrbot.dashboard.services.plugin_service import PluginService
@pytest.mark.asyncio
@pytest.mark.parametrize(
("event_filter", "category"),
[
(CommandFilter("test"), "command"),
(CommandGroupFilter("test"), "command"),
(RegexFilter("test"), "command"),
(None, "listener"),
],
)
async def test_message_handler_trace_category(monkeypatch, event_filter, category):
handler = SimpleNamespace(
handler=AsyncMock(return_value=None),
handler_name="test_handler",
handler_full_name="test_plugin.test_handler",
handler_module_path="test_plugin",
event_type=EventType.AdapterMessageEvent,
event_filters=[event_filter] if event_filter else [],
extras_configs={},
)
monkeypatch.setitem(
star_request.star_map,
"test_plugin",
SimpleNamespace(name="test_plugin", display_name="Test Plugin"),
)
extras = {"activated_handlers": [handler], "handlers_parsed_params": {}}
event = MagicMock()
event._extras = extras
event.get_extra.side_effect = extras.get
event.set_extra.side_effect = extras.__setitem__
event.is_stopped.return_value = False
async for _ in star_request.StarRequestSubStage().process(event):
pass
records = event.trace.record.call_args_list
assert [record.args[0] for record in records] == ["handler_start", "handler_end"]
for record in records:
assert record.kwargs["handler_category"] == category
assert record.kwargs["handler_type"] == "AdapterMessageEvent"
assert record.kwargs["plugin_display_name"] == "Test Plugin"
assert "module" not in record.kwargs
assert extras == {"activated_handlers": [handler], "handlers_parsed_params": {}}
@pytest.mark.asyncio
@pytest.mark.parametrize(
("hook_type", "category"),
[
(EventType.OnLLMRequestEvent, "hook"),
(EventType.OnCallingFuncToolEvent, "llm_tool"),
],
)
@pytest.mark.parametrize("fails", [False, True])
async def test_event_hook_trace_category(monkeypatch, hook_type, category, fails):
handler = SimpleNamespace(
handler=AsyncMock(side_effect=ValueError("test failure") if fails else None),
handler_name="test_hook",
handler_full_name="test_plugin.test_hook",
handler_module_path="test_plugin",
event_type=hook_type,
)
monkeypatch.setattr(
context_utils.star_handlers_registry,
"get_handlers_by_event_type",
MagicMock(return_value=[handler]),
)
monkeypatch.setitem(
context_utils.star_map,
"test_plugin",
SimpleNamespace(name="test_plugin", display_name="Test Plugin"),
)
extras = {}
event = MagicMock()
event._extras = extras
event.get_extra.side_effect = extras.get
event.set_extra.side_effect = extras.__setitem__
event.is_stopped.return_value = False
assert await context_utils.call_event_hook(event, hook_type) is False
records = event.trace.record.call_args_list
assert [record.args[0] for record in records] == ["handler_start", "handler_end"]
for record in records:
assert record.kwargs["handler_category"] == category
assert record.kwargs["handler_type"] == hook_type.name
assert "module" not in record.kwargs
assert records[-1].kwargs["status"] == ("error" if fails else "success")
assert extras == {}
@pytest.mark.asyncio
async def test_nested_command_details_preserve_handler_identity(monkeypatch):
handlers = {}
group = CommandGroupFilter("admin")
for command in ("first", "second"):
event_filter = CommandFilter(command, parent_command_names=["admin"])
handler = SimpleNamespace(
handler_name=f"handle_{command}",
handler_full_name=f"test_plugin.handle_{command}",
event_type=EventType.AdapterMessageEvent,
event_filters=[event_filter],
desc=f"Description for {command}",
)
event_filter.handler_md = handler
handlers[handler.handler_full_name] = handler
group.add_sub_command_filter(event_filter)
monkeypatch.setattr(
context_utils.star_handlers_registry, "star_handlers_map", handlers
)
service = PluginService(MagicMock(), MagicMock())
components = await service.get_plugin_handler_components(list(handlers))
assert len(components) == 1
assert components[0]["name"] == "admin"
for command, child in zip(("first", "second"), components[0]["subcommands"]):
assert child["handler_full_name"] == f"test_plugin.handle_{command}"
assert child["handler_name"] == f"handle_{command}"
assert child["description"] == f"Description for {command}"
group_component = service._build_command_group_component(group)
for command, child in zip(("first", "second"), group_component["subcommands"]):
assert child["handler_full_name"] == f"test_plugin.handle_{command}"
assert child["description"] == f"Description for {command}"