mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-07-16 17:36:07 +00:00
feat(agent-platform): add bot route dry-run
This commit is contained in:
@@ -38,6 +38,33 @@ class BotsRouterGroup(group.RouterGroup):
|
||||
logs, total_count = await self.ap.bot_service.list_event_logs(bot_uuid, from_index, max_count)
|
||||
return self.success(data={'logs': logs, 'total_count': total_count})
|
||||
|
||||
async def _dry_run_event_route(bot_uuid: str) -> str:
|
||||
json_data = await quart.request.json
|
||||
if not isinstance(json_data, dict):
|
||||
return self.http_status(400, -1, 'invalid request body')
|
||||
|
||||
result = await self.ap.bot_service.dry_run_event_route(
|
||||
bot_uuid=bot_uuid,
|
||||
event_type=json_data.get('event_type'),
|
||||
event_data=json_data.get('event_data', json_data.get('payload')),
|
||||
context=json_data.get('context'),
|
||||
event_bindings=json_data.get('event_bindings'),
|
||||
)
|
||||
return self.success(data=result)
|
||||
|
||||
self.route(
|
||||
'/<bot_uuid>/event-routes/dry-run',
|
||||
methods=['POST'],
|
||||
auth_type=group.AuthType.USER_TOKEN_OR_API_KEY,
|
||||
)(_dry_run_event_route)
|
||||
# Backward-compatible alias for early local clients/tests created before
|
||||
# the product route naming was settled.
|
||||
self.route(
|
||||
'/<bot_uuid>/event_route/dry_run',
|
||||
methods=['POST'],
|
||||
auth_type=group.AuthType.USER_TOKEN_OR_API_KEY,
|
||||
)(_dry_run_event_route)
|
||||
|
||||
@self.route('/<bot_uuid>/send_message', methods=['POST'], auth_type=group.AuthType.API_KEY)
|
||||
async def _(bot_uuid: str) -> str:
|
||||
json_data = await quart.request.json
|
||||
|
||||
@@ -15,6 +15,12 @@ class BotService:
|
||||
"""Bot service"""
|
||||
|
||||
ap: app.Application
|
||||
FAILURE_ROUTE_NOT_FOUND = 'route_not_found'
|
||||
FAILURE_PROCESSOR_DISABLED = 'processor_disabled'
|
||||
FAILURE_PROCESSOR_NOT_FOUND = 'processor_not_found'
|
||||
FAILURE_PROCESSOR_INCOMPATIBLE = 'processor_incompatible'
|
||||
FAILURE_INVALID_EVENT = 'invalid_event'
|
||||
|
||||
BOT_FIELDS = {
|
||||
'uuid',
|
||||
'name',
|
||||
@@ -68,6 +74,384 @@ class BotService:
|
||||
patterns = supported_patterns or ['*']
|
||||
return any(cls._event_pattern_covers(pattern, event_pattern) for pattern in patterns)
|
||||
|
||||
@staticmethod
|
||||
def _format_diagnostic_step(step: dict[str, typing.Any]) -> str:
|
||||
step_name = step.get('step') or 'diagnostic'
|
||||
reason = step.get('reason') or step.get('failure_code') or 'No reason provided'
|
||||
|
||||
if step_name == 'evaluate_binding':
|
||||
route_number = step.get('binding_index')
|
||||
if not isinstance(route_number, int):
|
||||
route_number = step.get('order')
|
||||
route_label = f'Route {int(route_number) + 1}' if isinstance(route_number, int) else 'Route'
|
||||
event_pattern = step.get('event_pattern') or '*'
|
||||
if step.get('selected'):
|
||||
return f'{route_label} ({event_pattern}) selected: {reason}'
|
||||
if step.get('matched'):
|
||||
return f'{route_label} ({event_pattern}) matched: {reason}'
|
||||
return f'{route_label} ({event_pattern}) skipped: {reason}'
|
||||
|
||||
if step_name == 'validate_processor':
|
||||
target_type = step.get('target_type') or 'processor'
|
||||
target_uuid = step.get('target_uuid') or ''
|
||||
suffix = f' {target_uuid}' if target_uuid else ''
|
||||
return f'Validate {target_type}{suffix}: {reason}'
|
||||
|
||||
return str(reason)
|
||||
|
||||
@classmethod
|
||||
def _format_diagnostic_steps(cls, diagnostic_details: list[dict[str, typing.Any]] | None) -> list[str]:
|
||||
return [cls._format_diagnostic_step(step) for step in diagnostic_details or []]
|
||||
|
||||
@staticmethod
|
||||
def _target_kind(target_type: typing.Any, target_kind: str | None = None) -> str | None:
|
||||
if target_kind:
|
||||
return target_kind
|
||||
if target_type == 'discard':
|
||||
return 'discard'
|
||||
if target_type in {'agent', 'pipeline'}:
|
||||
return str(target_type)
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _diagnostic_result(
|
||||
cls,
|
||||
*,
|
||||
matched: bool,
|
||||
failure_code: str | None = None,
|
||||
reason: str = '',
|
||||
binding: dict[str, typing.Any] | None = None,
|
||||
diagnostic_steps: list[dict[str, typing.Any]] | None = None,
|
||||
target_name: str | None = None,
|
||||
target_kind: str | None = None,
|
||||
) -> dict[str, typing.Any]:
|
||||
binding = binding or {}
|
||||
target_type = binding.get('target_type')
|
||||
target_uuid = binding.get('target_uuid') or ''
|
||||
matched_binding_index = binding.get('_dry_run_index')
|
||||
if not isinstance(matched_binding_index, int):
|
||||
matched_binding_index = binding.get('order')
|
||||
if not isinstance(matched_binding_index, int):
|
||||
matched_binding_index = None
|
||||
target = None
|
||||
if target_type:
|
||||
target = {
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid or None,
|
||||
'target_name': target_name,
|
||||
'kind': cls._target_kind(target_type, target_kind),
|
||||
}
|
||||
return {
|
||||
'matched': matched,
|
||||
'binding_id': binding.get('id'),
|
||||
'matched_binding_id': binding.get('id'),
|
||||
'matched_binding_index': matched_binding_index,
|
||||
'event_pattern': binding.get('event_pattern'),
|
||||
'target_type': binding.get('target_type'),
|
||||
'target_uuid': target_uuid,
|
||||
'target': target,
|
||||
'reason': reason,
|
||||
'failure_code': failure_code,
|
||||
'diagnostic_steps': cls._format_diagnostic_steps(diagnostic_steps),
|
||||
'diagnostic_details': diagnostic_steps or [],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _build_dry_run_event(event_type: str, event_data: typing.Any, context: typing.Any) -> dict[str, typing.Any]:
|
||||
event: dict[str, typing.Any] = {}
|
||||
if isinstance(event_data, dict):
|
||||
event.update(event_data)
|
||||
elif event_data is not None:
|
||||
raise ValueError('event_data must be an object')
|
||||
event['type'] = event_type
|
||||
|
||||
if context is None:
|
||||
return event
|
||||
if not isinstance(context, dict):
|
||||
raise ValueError('context must be an object')
|
||||
event['context'] = context
|
||||
return event
|
||||
|
||||
@staticmethod
|
||||
def _normalize_dry_run_bindings(bindings: typing.Any) -> list[dict[str, typing.Any]]:
|
||||
if bindings is None:
|
||||
return []
|
||||
if not isinstance(bindings, list):
|
||||
raise ValueError('event_bindings must be an array')
|
||||
|
||||
normalized: list[dict[str, typing.Any]] = []
|
||||
for index, raw_binding in enumerate(bindings):
|
||||
if not isinstance(raw_binding, dict):
|
||||
continue
|
||||
event_pattern = str(raw_binding.get('event_pattern') or '').strip()
|
||||
target_type = str(raw_binding.get('target_type') or '').strip()
|
||||
if not event_pattern or not target_type:
|
||||
continue
|
||||
|
||||
try:
|
||||
priority = int(raw_binding.get('priority') or 0)
|
||||
except (TypeError, ValueError):
|
||||
priority = 0
|
||||
|
||||
target_uuid = str(raw_binding.get('target_uuid') or '').strip()
|
||||
if target_type == 'discard':
|
||||
target_uuid = ''
|
||||
|
||||
filters = raw_binding.get('filters') if isinstance(raw_binding.get('filters'), list) else []
|
||||
normalized.append(
|
||||
{
|
||||
'id': raw_binding.get('id'),
|
||||
'event_pattern': event_pattern,
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'filters': filters,
|
||||
'priority': priority,
|
||||
'enabled': bool(raw_binding.get('enabled', True)),
|
||||
# For draft bindings, current array order is the effective order
|
||||
# that would be persisted on save.
|
||||
'order': index,
|
||||
'_dry_run_index': index,
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def _index_event_bindings(bindings: list[dict[str, typing.Any]]) -> list[dict[str, typing.Any]]:
|
||||
indexed: list[dict[str, typing.Any]] = []
|
||||
for index, binding in enumerate(bindings):
|
||||
copied = binding.copy()
|
||||
copied.setdefault('_dry_run_index', index)
|
||||
indexed.append(copied)
|
||||
return indexed
|
||||
|
||||
async def _get_pipeline_entity(self, pipeline_uuid: str) -> persistence_pipeline.LegacyPipeline | None:
|
||||
result = await self.ap.persistence_mgr.execute_async(
|
||||
sqlalchemy.select(persistence_pipeline.LegacyPipeline).where(
|
||||
persistence_pipeline.LegacyPipeline.uuid == pipeline_uuid
|
||||
)
|
||||
)
|
||||
return result.first()
|
||||
|
||||
async def _get_agent_entity(self, agent_uuid: str) -> persistence_agent.Agent | None:
|
||||
result = await self.ap.persistence_mgr.execute_async(
|
||||
sqlalchemy.select(persistence_agent.Agent).where(persistence_agent.Agent.uuid == agent_uuid)
|
||||
)
|
||||
return result.first()
|
||||
|
||||
async def dry_run_event_route(
|
||||
self,
|
||||
bot_uuid: str,
|
||||
event_type: str,
|
||||
event_data: dict[str, typing.Any] | None = None,
|
||||
context: dict[str, typing.Any] | None = None,
|
||||
event_bindings: list[dict[str, typing.Any]] | None = None,
|
||||
) -> dict[str, typing.Any]:
|
||||
"""Diagnose Bot event routing without dispatching to Agent, Pipeline, or platform actions."""
|
||||
from ....platform.botmgr import RuntimeBot
|
||||
|
||||
event_type = str(event_type or '').strip()
|
||||
if not event_type:
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
failure_code=self.FAILURE_INVALID_EVENT,
|
||||
reason='event_type is required',
|
||||
diagnostic_steps=[
|
||||
{
|
||||
'step': 'validate_event',
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_INVALID_EVENT,
|
||||
'reason': 'event_type is required',
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
bot = await self.get_bot(bot_uuid, include_secret=False)
|
||||
if bot is None:
|
||||
raise Exception('Bot not found')
|
||||
|
||||
try:
|
||||
event = self._build_dry_run_event(event_type, event_data, context)
|
||||
bindings = (
|
||||
self._normalize_dry_run_bindings(event_bindings)
|
||||
if event_bindings is not None
|
||||
else self._index_event_bindings(
|
||||
RuntimeBot._get_event_bindings_from_value(bot.get('event_bindings') or [])
|
||||
)
|
||||
)
|
||||
except ValueError as exc:
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
failure_code=self.FAILURE_INVALID_EVENT,
|
||||
reason=str(exc),
|
||||
diagnostic_steps=[
|
||||
{
|
||||
'step': 'validate_event',
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_INVALID_EVENT,
|
||||
'reason': str(exc),
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
selected_binding, diagnostic_steps = RuntimeBot._evaluate_eba_event_bindings(
|
||||
bindings,
|
||||
event,
|
||||
event_type,
|
||||
)
|
||||
if selected_binding is None:
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
failure_code=self.FAILURE_ROUTE_NOT_FOUND,
|
||||
reason='No enabled event binding matched event_type and filters',
|
||||
diagnostic_steps=diagnostic_steps,
|
||||
)
|
||||
|
||||
target_type = selected_binding.get('target_type')
|
||||
target_uuid = str(selected_binding.get('target_uuid') or '')
|
||||
|
||||
if target_type == 'discard':
|
||||
return self._diagnostic_result(
|
||||
matched=True,
|
||||
binding=selected_binding,
|
||||
reason='Event route matched discard target',
|
||||
diagnostic_steps=diagnostic_steps,
|
||||
)
|
||||
|
||||
if target_type == 'pipeline':
|
||||
if not RuntimeBot._is_message_event_type(event_type):
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
reason='Pipeline targets only support message events',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
'reason': 'Pipeline targets only support message events',
|
||||
}
|
||||
],
|
||||
)
|
||||
pipeline = await self._get_pipeline_entity(target_uuid) if target_uuid else None
|
||||
if pipeline is None:
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_NOT_FOUND,
|
||||
reason='Pipeline target not found',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_NOT_FOUND,
|
||||
'reason': 'Pipeline target not found',
|
||||
}
|
||||
],
|
||||
)
|
||||
return self._diagnostic_result(
|
||||
matched=True,
|
||||
binding=selected_binding,
|
||||
target_name=getattr(pipeline, 'name', None),
|
||||
reason='Event route matched pipeline target',
|
||||
diagnostic_steps=diagnostic_steps,
|
||||
)
|
||||
|
||||
if target_type == 'agent':
|
||||
agent = await self._get_agent_entity(target_uuid)
|
||||
if agent is None or getattr(agent, 'kind', 'agent') != 'agent':
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_NOT_FOUND,
|
||||
reason='Agent target not found',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_NOT_FOUND,
|
||||
'reason': 'Agent target not found',
|
||||
}
|
||||
],
|
||||
)
|
||||
if not getattr(agent, 'enabled', True):
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_DISABLED,
|
||||
reason='Agent target is disabled',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_DISABLED,
|
||||
'reason': 'Agent target is disabled',
|
||||
}
|
||||
],
|
||||
)
|
||||
if not RuntimeBot._agent_supports_event_type(getattr(agent, 'supported_event_patterns', None), event_type):
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
reason='Agent target does not support this event type',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
'reason': 'Agent target does not support this event type',
|
||||
}
|
||||
],
|
||||
)
|
||||
return self._diagnostic_result(
|
||||
matched=True,
|
||||
binding=selected_binding,
|
||||
target_name=getattr(agent, 'name', None),
|
||||
target_kind=getattr(agent, 'kind', None),
|
||||
reason='Event route matched agent target',
|
||||
diagnostic_steps=diagnostic_steps,
|
||||
)
|
||||
|
||||
return self._diagnostic_result(
|
||||
matched=False,
|
||||
binding=selected_binding,
|
||||
failure_code=self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
reason=f'Unsupported event binding target type: {target_type}',
|
||||
diagnostic_steps=diagnostic_steps
|
||||
+ [
|
||||
{
|
||||
'step': 'validate_processor',
|
||||
'binding_id': selected_binding.get('id'),
|
||||
'target_type': target_type,
|
||||
'target_uuid': target_uuid,
|
||||
'matched': False,
|
||||
'failure_code': self.FAILURE_PROCESSOR_INCOMPATIBLE,
|
||||
'reason': f'Unsupported event binding target type: {target_type}',
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
async def _normalize_event_bindings(self, bindings: list[dict] | None) -> list[dict]:
|
||||
"""Validate and normalize Bot event bindings."""
|
||||
if not bindings:
|
||||
|
||||
@@ -208,8 +208,9 @@ class RuntimeBot:
|
||||
if isinstance(event_filter, dict)
|
||||
)
|
||||
|
||||
def _get_event_bindings(self) -> list[dict[str, typing.Any]]:
|
||||
raw_bindings = self.bot_entity.event_bindings or []
|
||||
@staticmethod
|
||||
def _get_event_bindings_from_value(raw_bindings: typing.Any) -> list[dict[str, typing.Any]]:
|
||||
raw_bindings = raw_bindings or []
|
||||
if isinstance(raw_bindings, str):
|
||||
try:
|
||||
raw_bindings = json.loads(raw_bindings)
|
||||
@@ -219,32 +220,90 @@ class RuntimeBot:
|
||||
return []
|
||||
return [binding for binding in raw_bindings if isinstance(binding, dict)]
|
||||
|
||||
def _get_event_bindings(self) -> list[dict[str, typing.Any]]:
|
||||
return self._get_event_bindings_from_value(self.bot_entity.event_bindings)
|
||||
|
||||
@classmethod
|
||||
def _evaluate_eba_event_bindings(
|
||||
cls,
|
||||
bindings: list[dict[str, typing.Any]],
|
||||
event: platform_events.EBAEvent,
|
||||
event_type: str,
|
||||
) -> tuple[dict[str, typing.Any] | None, list[dict[str, typing.Any]]]:
|
||||
"""Evaluate Bot event bindings with the same precedence used at runtime."""
|
||||
matched: list[tuple[int, int, dict[str, typing.Any], dict[str, typing.Any]]] = []
|
||||
diagnostic_steps: list[dict[str, typing.Any]] = []
|
||||
|
||||
for index, binding in enumerate(bindings):
|
||||
event_pattern = str(binding.get('event_pattern') or '')
|
||||
priority = int(binding.get('priority') or 0)
|
||||
order = int(binding.get('order', index))
|
||||
step = {
|
||||
'step': 'evaluate_binding',
|
||||
'binding_id': binding.get('id'),
|
||||
'event_pattern': event_pattern,
|
||||
'target_type': binding.get('target_type'),
|
||||
'target_uuid': binding.get('target_uuid') or '',
|
||||
'enabled': binding.get('enabled', True),
|
||||
'priority': priority,
|
||||
'order': order,
|
||||
'matched': False,
|
||||
'failure_code': None,
|
||||
'reason': '',
|
||||
}
|
||||
|
||||
if not binding.get('enabled', True):
|
||||
step['failure_code'] = 'binding_disabled'
|
||||
step['reason'] = 'Binding is disabled'
|
||||
diagnostic_steps.append(step)
|
||||
continue
|
||||
|
||||
if not cls._match_event_pattern(event_type, event_pattern):
|
||||
step['failure_code'] = 'event_pattern_mismatch'
|
||||
step['reason'] = 'Event type does not match binding event_pattern'
|
||||
diagnostic_steps.append(step)
|
||||
continue
|
||||
if not cls._match_event_filters(event, binding.get('filters')):
|
||||
step['failure_code'] = 'filters_mismatch'
|
||||
step['reason'] = 'Event data does not satisfy binding filters'
|
||||
diagnostic_steps.append(step)
|
||||
continue
|
||||
|
||||
step['matched'] = True
|
||||
step['reason'] = 'Binding matched event pattern and filters'
|
||||
diagnostic_steps.append(step)
|
||||
matched.append((priority, -order, binding, step))
|
||||
|
||||
if not matched:
|
||||
return None, diagnostic_steps
|
||||
|
||||
matched.sort(key=lambda item: (item[0], item[1]), reverse=True)
|
||||
selected_binding = matched[0][2]
|
||||
selected_step = matched[0][3]
|
||||
selected_step['selected'] = True
|
||||
selected_step['reason'] = 'Selected by priority and order'
|
||||
for _, _, _, step in matched[1:]:
|
||||
step['selected'] = False
|
||||
step['failure_code'] = 'lower_priority'
|
||||
step['reason'] = 'Another matching binding has higher priority or earlier order'
|
||||
return selected_binding, diagnostic_steps
|
||||
|
||||
def _resolve_eba_event_binding(
|
||||
self,
|
||||
event: platform_events.EBAEvent,
|
||||
event_type: str,
|
||||
) -> dict[str, typing.Any] | None:
|
||||
"""Resolve the highest priority Bot event binding for a platform event."""
|
||||
matched: list[tuple[int, int, dict[str, typing.Any]]] = []
|
||||
for index, binding in enumerate(self._get_event_bindings()):
|
||||
if not binding.get('enabled', True):
|
||||
continue
|
||||
selected, _ = self._evaluate_eba_event_bindings(self._get_event_bindings(), event, event_type)
|
||||
return selected
|
||||
|
||||
event_pattern = str(binding.get('event_pattern') or '')
|
||||
if not self._match_event_pattern(event_type, event_pattern):
|
||||
continue
|
||||
if not self._match_event_filters(event, binding.get('filters')):
|
||||
continue
|
||||
|
||||
priority = int(binding.get('priority') or 0)
|
||||
order = int(binding.get('order', index))
|
||||
matched.append((priority, -order, binding))
|
||||
|
||||
if not matched:
|
||||
return None
|
||||
|
||||
matched.sort(key=lambda item: (item[0], item[1]), reverse=True)
|
||||
return matched[0][2]
|
||||
def diagnose_eba_event_binding(
|
||||
self,
|
||||
event: platform_events.EBAEvent,
|
||||
event_type: str,
|
||||
) -> tuple[dict[str, typing.Any] | None, list[dict[str, typing.Any]]]:
|
||||
"""Return the selected event binding plus per-binding diagnostic steps."""
|
||||
return self._evaluate_eba_event_bindings(self._get_event_bindings(), event, event_type)
|
||||
|
||||
def get_pipeline_target_for_event_type(self, event_type: str = 'message.received') -> str | None:
|
||||
"""Return the first Pipeline target configured for an event type."""
|
||||
|
||||
@@ -97,6 +97,27 @@ def fake_bot_app():
|
||||
app.bot_service.update_bot = AsyncMock(return_value={})
|
||||
app.bot_service.delete_bot = AsyncMock()
|
||||
app.bot_service.list_event_logs = AsyncMock(return_value=([{'uuid': 'log-1', 'message': 'test log'}], 1))
|
||||
app.bot_service.dry_run_event_route = AsyncMock(
|
||||
return_value={
|
||||
'matched': True,
|
||||
'binding_id': 'binding-1',
|
||||
'matched_binding_id': 'binding-1',
|
||||
'matched_binding_index': 0,
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'target': {
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'target_name': 'Member Agent',
|
||||
'kind': 'agent',
|
||||
},
|
||||
'reason': 'Event route matched agent target',
|
||||
'failure_code': None,
|
||||
'diagnostic_steps': ['Route 1 (platform.member.joined) selected: Selected by priority and order'],
|
||||
'diagnostic_details': [{'step': 'evaluate_binding', 'binding_id': 'binding-1', 'matched': True}],
|
||||
}
|
||||
)
|
||||
app.bot_service.send_message = AsyncMock()
|
||||
|
||||
# Platform manager
|
||||
@@ -199,6 +220,54 @@ class TestBotLogsEndpoint:
|
||||
assert 'total_count' in data['data']
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('mock_circular_import_chain')
|
||||
class TestBotEventRouteDryRunEndpoint:
|
||||
"""Tests for bot event route dry-run endpoint."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dry_run_event_route_success(self, quart_test_client, fake_bot_app):
|
||||
"""POST dry_run returns route diagnostics."""
|
||||
response = await quart_test_client.post(
|
||||
'/api/v1/platform/bots/test-bot-uuid/event-routes/dry-run',
|
||||
headers={'Authorization': 'Bearer test_token'},
|
||||
json={
|
||||
'event_type': 'platform.member.joined',
|
||||
'payload': {'room': {'id': 'room-1'}},
|
||||
'context': {'source': 'ui'},
|
||||
'event_bindings': [
|
||||
{
|
||||
'id': 'binding-1',
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = await response.get_json()
|
||||
assert data['code'] == 0
|
||||
assert data['data']['matched'] is True
|
||||
assert data['data']['binding_id'] == 'binding-1'
|
||||
assert data['data']['target']['target_name'] == 'Member Agent'
|
||||
assert data['data']['diagnostic_steps'][0].startswith('Route 1')
|
||||
fake_bot_app.bot_service.dry_run_event_route.assert_awaited_with(
|
||||
bot_uuid='test-bot-uuid',
|
||||
event_type='platform.member.joined',
|
||||
event_data={'room': {'id': 'room-1'}},
|
||||
context={'source': 'ui'},
|
||||
event_bindings=[
|
||||
{
|
||||
'id': 'binding-1',
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('mock_circular_import_chain')
|
||||
class TestBotSendMessageEndpoint:
|
||||
"""Tests for bot send message endpoint."""
|
||||
|
||||
@@ -624,6 +624,299 @@ class TestBotServiceEventBindings:
|
||||
assert other_session.using_conversation.bot_uuid == 'other-bot'
|
||||
|
||||
|
||||
class TestBotServiceEventRouteDryRun:
|
||||
"""Tests for dry-run Bot event route diagnostics."""
|
||||
|
||||
@staticmethod
|
||||
def _make_service(
|
||||
event_bindings: list[dict],
|
||||
*,
|
||||
bot_uuid: str = 'bot-1',
|
||||
persistence_results: list[Mock] | None = None,
|
||||
) -> BotService:
|
||||
ap = SimpleNamespace()
|
||||
ap.persistence_mgr = SimpleNamespace()
|
||||
ap.persistence_mgr.execute_async = AsyncMock(side_effect=persistence_results or [])
|
||||
service = BotService(ap)
|
||||
service.get_bot = AsyncMock(
|
||||
return_value={
|
||||
'uuid': bot_uuid,
|
||||
'name': 'Dry Run Bot',
|
||||
'event_bindings': event_bindings,
|
||||
}
|
||||
)
|
||||
return service
|
||||
|
||||
async def test_dry_run_event_route_matches_agent(self):
|
||||
"""Matching Agent routes return the selected binding without running the Agent."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'agent-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'platform.member.*',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'filters': [{'field': 'room.id', 'operator': 'eq', 'value': 'room-1'}],
|
||||
'priority': 5,
|
||||
'order': 0,
|
||||
}
|
||||
],
|
||||
persistence_results=[
|
||||
_create_mock_result(
|
||||
first_item=SimpleNamespace(
|
||||
uuid='agent-1',
|
||||
kind='agent',
|
||||
enabled=True,
|
||||
supported_event_patterns=['platform.member.*'],
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route(
|
||||
'bot-1',
|
||||
'platform.member.joined',
|
||||
event_data={'room': {'id': 'room-1'}},
|
||||
)
|
||||
|
||||
assert result['matched'] is True
|
||||
assert result['binding_id'] == 'agent-binding'
|
||||
assert result['event_pattern'] == 'platform.member.*'
|
||||
assert result['target_type'] == 'agent'
|
||||
assert result['target_uuid'] == 'agent-1'
|
||||
assert result['target']['target_uuid'] == 'agent-1'
|
||||
assert result['target']['target_name'] is None
|
||||
assert result['failure_code'] is None
|
||||
assert result['matched_binding_id'] == 'agent-binding'
|
||||
assert result['matched_binding_index'] == 0
|
||||
assert result['diagnostic_details'][0]['selected'] is True
|
||||
assert result['diagnostic_steps'][0].startswith('Route 1')
|
||||
|
||||
async def test_dry_run_event_route_matches_discard(self):
|
||||
"""Discard routes are terminal dry-run matches and do not query processors."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'discard-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': '*',
|
||||
'target_type': 'discard',
|
||||
'target_uuid': '',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.left')
|
||||
|
||||
assert result['matched'] is True
|
||||
assert result['binding_id'] == 'discard-binding'
|
||||
assert result['target_type'] == 'discard'
|
||||
assert result['target']['kind'] == 'discard'
|
||||
assert result['failure_code'] is None
|
||||
service.ap.persistence_mgr.execute_async.assert_not_awaited()
|
||||
|
||||
async def test_dry_run_event_route_returns_route_not_found_when_no_binding_matches(self):
|
||||
"""Pattern/filter misses return route_not_found."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'wrong-event',
|
||||
'enabled': True,
|
||||
'event_pattern': 'message.received',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.joined')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['binding_id'] is None
|
||||
assert result['failure_code'] == 'route_not_found'
|
||||
assert result['target'] is None
|
||||
assert result['diagnostic_details'][0]['failure_code'] == 'event_pattern_mismatch'
|
||||
assert 'skipped' in result['diagnostic_steps'][0]
|
||||
service.ap.persistence_mgr.execute_async.assert_not_awaited()
|
||||
|
||||
async def test_dry_run_event_route_reports_disabled_binding_without_matching(self):
|
||||
"""Disabled bindings are diagnosed but never selected."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'disabled-binding',
|
||||
'enabled': False,
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'priority': 100,
|
||||
'order': 0,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.joined')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['failure_code'] == 'route_not_found'
|
||||
assert result['diagnostic_details'][0]['binding_id'] == 'disabled-binding'
|
||||
assert result['diagnostic_details'][0]['failure_code'] == 'binding_disabled'
|
||||
service.ap.persistence_mgr.execute_async.assert_not_awaited()
|
||||
|
||||
async def test_dry_run_event_route_rejects_pipeline_for_non_message_event(self):
|
||||
"""Pipeline targets cannot dry-run match non-message events."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'pipeline-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'pipeline',
|
||||
'target_uuid': 'pipeline-1',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.joined')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['binding_id'] == 'pipeline-binding'
|
||||
assert result['target_type'] == 'pipeline'
|
||||
assert result['failure_code'] == 'processor_incompatible'
|
||||
assert result['diagnostic_details'][-1]['step'] == 'validate_processor'
|
||||
service.ap.persistence_mgr.execute_async.assert_not_awaited()
|
||||
|
||||
async def test_dry_run_event_route_rejects_incompatible_agent(self):
|
||||
"""Agent targets must support the incoming event type."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'agent-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
],
|
||||
persistence_results=[
|
||||
_create_mock_result(
|
||||
first_item=SimpleNamespace(
|
||||
uuid='agent-1',
|
||||
kind='agent',
|
||||
enabled=True,
|
||||
supported_event_patterns=['message.*'],
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.joined')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['binding_id'] == 'agent-binding'
|
||||
assert result['target_type'] == 'agent'
|
||||
assert result['failure_code'] == 'processor_incompatible'
|
||||
assert result['diagnostic_details'][-1]['failure_code'] == 'processor_incompatible'
|
||||
|
||||
async def test_dry_run_event_route_reports_disabled_agent(self):
|
||||
"""Disabled Agent targets return processor_disabled."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'agent-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'agent',
|
||||
'target_uuid': 'agent-1',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
],
|
||||
persistence_results=[
|
||||
_create_mock_result(
|
||||
first_item=SimpleNamespace(
|
||||
uuid='agent-1',
|
||||
kind='agent',
|
||||
enabled=False,
|
||||
supported_event_patterns=['*'],
|
||||
)
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'platform.member.joined')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['failure_code'] == 'processor_disabled'
|
||||
assert result['diagnostic_details'][-1]['failure_code'] == 'processor_disabled'
|
||||
|
||||
async def test_dry_run_event_route_reports_missing_pipeline(self):
|
||||
"""Missing Pipeline targets return processor_not_found."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'pipeline-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'message.received',
|
||||
'target_type': 'pipeline',
|
||||
'target_uuid': 'pipeline-1',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
],
|
||||
persistence_results=[_create_mock_result(first_item=None)],
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route('bot-1', 'message.received')
|
||||
|
||||
assert result['matched'] is False
|
||||
assert result['failure_code'] == 'processor_not_found'
|
||||
assert result['diagnostic_details'][-1]['failure_code'] == 'processor_not_found'
|
||||
|
||||
async def test_dry_run_event_route_uses_draft_event_bindings(self):
|
||||
"""Draft bindings from the UI can be tested before saving the bot."""
|
||||
service = self._make_service(
|
||||
[
|
||||
{
|
||||
'id': 'saved-binding',
|
||||
'enabled': True,
|
||||
'event_pattern': 'message.received',
|
||||
'target_type': 'discard',
|
||||
'priority': 0,
|
||||
'order': 0,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
result = await service.dry_run_event_route(
|
||||
'bot-1',
|
||||
'platform.member.joined',
|
||||
event_bindings=[
|
||||
{
|
||||
'id': 'draft-binding',
|
||||
'event_pattern': 'platform.member.joined',
|
||||
'target_type': 'discard',
|
||||
'enabled': True,
|
||||
'priority': 0,
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
assert result['matched'] is True
|
||||
assert result['binding_id'] == 'draft-binding'
|
||||
assert result['matched_binding_index'] == 0
|
||||
assert result['target']['kind'] == 'discard'
|
||||
|
||||
|
||||
class TestBotServiceDeleteBot:
|
||||
"""Tests for delete_bot method."""
|
||||
|
||||
|
||||
@@ -456,6 +456,7 @@ export default function BotForm({
|
||||
<CardContent>
|
||||
<EventBindingsEditor
|
||||
form={form}
|
||||
botId={initBotId}
|
||||
supportedEvents={adapterSupportedEvents[currentAdapter] || []}
|
||||
agentOptions={agentNameList}
|
||||
/>
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { UseFormReturn } from 'react-hook-form';
|
||||
import {
|
||||
Activity,
|
||||
AlertCircle,
|
||||
ArrowRight,
|
||||
Ban,
|
||||
Bot,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ChevronsUpDown,
|
||||
GripVertical,
|
||||
ListChecks,
|
||||
Plus,
|
||||
Play,
|
||||
Trash2,
|
||||
Workflow,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -39,6 +45,15 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import {
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
@@ -59,7 +74,13 @@ import {
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { EventBinding, Agent } from '@/app/infra/entities/api';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
EventBinding,
|
||||
Agent,
|
||||
BotRouteDryRunResult,
|
||||
} from '@/app/infra/entities/api';
|
||||
import { backendClient } from '@/app/infra/http';
|
||||
|
||||
export const PIPELINE_DISCARD = '__discard__';
|
||||
|
||||
@@ -67,6 +88,7 @@ export const PIPELINE_DISCARD = '__discard__';
|
||||
|
||||
interface EventBindingsEditorProps {
|
||||
form: UseFormReturn<any>;
|
||||
botId?: string;
|
||||
supportedEvents: string[];
|
||||
agentOptions: Agent[];
|
||||
}
|
||||
@@ -170,10 +192,27 @@ function eventLabel(event: string, t: TFunction) {
|
||||
return label === key ? event : label;
|
||||
}
|
||||
|
||||
function eventDescription(event: string, t: TFunction) {
|
||||
if (event === '*') return t('bots.eventDescriptions.all');
|
||||
if (event.endsWith('.*')) return t('bots.eventDescriptions.namespace');
|
||||
const key = `bots.eventDescriptions.${event.replace(/\./g, '_')}`;
|
||||
const description = t(key);
|
||||
return description === key ? t('bots.eventDescriptions.custom') : description;
|
||||
}
|
||||
|
||||
function targetLabel(agent: Agent) {
|
||||
return `${agent.emoji ? `${agent.emoji} ` : ''}${agent.name}`;
|
||||
}
|
||||
|
||||
function targetTypeLabel(
|
||||
type: EventBinding['target_type'] | undefined,
|
||||
t: TFunction,
|
||||
) {
|
||||
if (type === 'pipeline') return t('bots.targetPipeline');
|
||||
if (type === 'discard') return t('bots.targetDiscard');
|
||||
return t('bots.targetAgent');
|
||||
}
|
||||
|
||||
// ── target combobox (type + target merged, with search + groups) ───────────────
|
||||
|
||||
// Encoded value: "discard", "agent:<uuid>", "pipeline:<uuid>"
|
||||
@@ -464,6 +503,341 @@ function FilterConditionsPanel({
|
||||
);
|
||||
}
|
||||
|
||||
// ── adapter capability summary ────────────────────────────────────────────────
|
||||
|
||||
function AdapterCapabilitySummary({
|
||||
supportedEvents,
|
||||
eventOptions,
|
||||
}: {
|
||||
supportedEvents: string[];
|
||||
eventOptions: string[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const concreteEvents =
|
||||
supportedEvents.length > 0 ? supportedEvents : DEFAULT_EVENTS;
|
||||
const previewEvents = concreteEvents.slice(0, 4);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-muted/20 p-3">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-background text-primary shadow-xs">
|
||||
<Activity className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium">
|
||||
{t('bots.adapterEventsTitle')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('bots.adapterEventsDescription', {
|
||||
count: concreteEvents.length,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{previewEvents.map((event) => (
|
||||
<Badge
|
||||
key={event}
|
||||
variant="secondary"
|
||||
className="max-w-full rounded-md px-2 py-0.5 font-normal"
|
||||
title={event}
|
||||
>
|
||||
<span className="truncate">{eventLabel(event, t)}</span>
|
||||
</Badge>
|
||||
))}
|
||||
{concreteEvents.length > previewEvents.length && (
|
||||
<Badge variant="outline" className="rounded-md px-2 py-0.5">
|
||||
{t('bots.adapterEventsMore', {
|
||||
count: concreteEvents.length - previewEvents.length,
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 shrink-0 px-2 text-xs"
|
||||
onClick={() => setAdvancedOpen((v) => !v)}
|
||||
>
|
||||
{advancedOpen ? (
|
||||
<ChevronDown className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
)}
|
||||
{t('bots.advancedEventValues')}
|
||||
</Button>
|
||||
</div>
|
||||
{advancedOpen && (
|
||||
<div className="mt-3 grid gap-2 border-t pt-3 sm:grid-cols-2">
|
||||
{eventOptions.map((event) => (
|
||||
<div key={event} className="min-w-0 rounded-md bg-background p-2">
|
||||
<div className="flex min-w-0 items-center justify-between gap-2">
|
||||
<span className="truncate text-xs font-medium">
|
||||
{eventLabel(event, t)}
|
||||
</span>
|
||||
{event.endsWith('.*') && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px]">
|
||||
{t('bots.eventGroup')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 line-clamp-2 text-[11px] leading-snug text-muted-foreground">
|
||||
{eventDescription(event, t)}
|
||||
</p>
|
||||
<code className="mt-1 block truncate text-[11px] text-muted-foreground">
|
||||
{event}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── route dry-run dialog ─────────────────────────────────────────────────────
|
||||
|
||||
function RouteDryRunDialog({
|
||||
botId,
|
||||
bindings,
|
||||
eventOptions,
|
||||
agentOptions,
|
||||
}: {
|
||||
botId?: string;
|
||||
bindings: EventBinding[];
|
||||
eventOptions: string[];
|
||||
agentOptions: Agent[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const firstEvent = eventOptions[0] ?? DEFAULT_EVENTS[0];
|
||||
const [open, setOpen] = useState(false);
|
||||
const [eventType, setEventType] = useState(firstEvent);
|
||||
const [payloadText, setPayloadText] = useState('{\n "message_text": ""\n}');
|
||||
const [isRunning, setIsRunning] = useState(false);
|
||||
const [payloadError, setPayloadError] = useState<string | null>(null);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<BotRouteDryRunResult | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!eventOptions.includes(eventType)) {
|
||||
setEventType(firstEvent);
|
||||
}
|
||||
}, [eventOptions, eventType, firstEvent]);
|
||||
|
||||
function resolveTargetName(resultTarget?: BotRouteDryRunResult['target']) {
|
||||
if (!resultTarget) return '';
|
||||
if (resultTarget.target_name) return resultTarget.target_name;
|
||||
if (resultTarget.target_type === 'discard') return t('bots.targetDiscard');
|
||||
const agent = agentOptions.find((a) => a.uuid === resultTarget.target_uuid);
|
||||
return agent ? targetLabel(agent) : (resultTarget.target_uuid ?? '');
|
||||
}
|
||||
|
||||
async function runDryRun() {
|
||||
setPayloadError(null);
|
||||
setRunError(null);
|
||||
setResult(null);
|
||||
|
||||
let payload: Record<string, unknown> = {};
|
||||
if (payloadText.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(payloadText);
|
||||
if (
|
||||
parsed === null ||
|
||||
typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed)
|
||||
) {
|
||||
setPayloadError(t('bots.dryRunPayloadObjectError'));
|
||||
return;
|
||||
}
|
||||
payload = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
setPayloadError(t('bots.dryRunPayloadJsonError'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!botId) {
|
||||
setRunError(t('bots.dryRunNeedsSavedBot'));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRunning(true);
|
||||
try {
|
||||
const dryRunResult = await backendClient.dryRunBotEventRoute(botId, {
|
||||
event_type: eventType,
|
||||
payload,
|
||||
event_bindings: bindings,
|
||||
});
|
||||
setResult({
|
||||
...dryRunResult,
|
||||
diagnostic_steps: dryRunResult.diagnostic_steps ?? [],
|
||||
});
|
||||
} catch (error) {
|
||||
const err = error as { msg?: string };
|
||||
setRunError(err.msg || t('bots.dryRunFailed'));
|
||||
} finally {
|
||||
setIsRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
const targetName = result ? resolveTargetName(result.target) : '';
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<Play className="h-4 w-4 mr-1" />
|
||||
{t('bots.testRoute')}
|
||||
</Button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('bots.dryRunTitle')}</DialogTitle>
|
||||
<DialogDescription>{t('bots.dryRunDescription')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-3 sm:grid-cols-[220px_1fr]">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium">
|
||||
{t('bots.dryRunEventType')}
|
||||
</label>
|
||||
<Select value={eventType} onValueChange={setEventType}>
|
||||
<SelectTrigger className="h-9">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{eventOptions.map((event) => (
|
||||
<SelectItem key={event} value={event}>
|
||||
{eventLabel(event, t)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-sm font-medium">
|
||||
{t('bots.dryRunPayload')}
|
||||
</label>
|
||||
<Textarea
|
||||
value={payloadText}
|
||||
onChange={(e) => setPayloadText(e.target.value)}
|
||||
className="min-h-[118px] font-mono text-xs"
|
||||
spellCheck={false}
|
||||
placeholder='{"message_text": "hello"}'
|
||||
/>
|
||||
{payloadError ? (
|
||||
<p className="text-xs text-destructive">{payloadError}</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('bots.dryRunPayloadHint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{runError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{runError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="rounded-lg border p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{result.matched ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-600" />
|
||||
) : (
|
||||
<XCircle className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span className="text-sm font-medium">
|
||||
{result.matched
|
||||
? t('bots.dryRunMatched')
|
||||
: t('bots.dryRunNotMatched')}
|
||||
</span>
|
||||
{result.failure_code && (
|
||||
<Badge variant="outline" className="font-mono text-[10px]">
|
||||
{result.failure_code}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<div className="rounded-md bg-muted/40 p-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('bots.dryRunTarget')}
|
||||
</p>
|
||||
<p className="mt-1 truncate text-sm font-medium">
|
||||
{result.target
|
||||
? `${targetTypeLabel(result.target.target_type, t)}${
|
||||
targetName ? ` · ${targetName}` : ''
|
||||
}`
|
||||
: t('bots.dryRunNoTarget')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-md bg-muted/40 p-2">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('bots.dryRunMatchedRule')}
|
||||
</p>
|
||||
<p className="mt-1 truncate text-sm font-medium">
|
||||
{result.matched_binding_index !== undefined &&
|
||||
result.matched_binding_index !== null
|
||||
? t('bots.dryRunRuleIndex', {
|
||||
index: result.matched_binding_index + 1,
|
||||
})
|
||||
: result.matched_binding_id || t('bots.dryRunNoRule')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{result.diagnostic_steps.length > 0 && (
|
||||
<div className="mt-3">
|
||||
<div className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
|
||||
<ListChecks className="h-3.5 w-3.5" />
|
||||
{t('bots.dryRunDiagnostics')}
|
||||
</div>
|
||||
<ol className="space-y-1 pl-5 text-xs text-muted-foreground">
|
||||
{result.diagnostic_steps.map((step, index) => (
|
||||
<li key={`${index}:${step}`} className="list-decimal">
|
||||
{step}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{t('common.close')}
|
||||
</Button>
|
||||
<Button type="button" onClick={runDryRun} disabled={isRunning}>
|
||||
<Play className="h-4 w-4 mr-1" />
|
||||
{isRunning ? t('bots.dryRunRunning') : t('bots.dryRunAction')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ── single binding card ───────────────────────────────────────────────────────
|
||||
|
||||
interface BindingCardProps {
|
||||
@@ -543,11 +917,9 @@ function BindingCardContent({
|
||||
<SelectItem key={event} value={event}>
|
||||
<span className="flex flex-col">
|
||||
<span>{label}</span>
|
||||
{label !== event && (
|
||||
<span className="text-[11px] text-muted-foreground font-mono">
|
||||
{event}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{eventDescription(event, t)}
|
||||
</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
);
|
||||
@@ -654,6 +1026,7 @@ function SortableBindingCard(props: BindingCardProps) {
|
||||
|
||||
export default function EventBindingsEditor({
|
||||
form,
|
||||
botId,
|
||||
supportedEvents,
|
||||
agentOptions,
|
||||
}: EventBindingsEditorProps) {
|
||||
@@ -681,6 +1054,10 @@ export default function EventBindingsEditor({
|
||||
(e, i, a) => a.indexOf(e) === i,
|
||||
);
|
||||
}, [supportedEvents]);
|
||||
const dryRunEventOptions = useMemo(
|
||||
() => (supportedEvents.length > 0 ? supportedEvents : DEFAULT_EVENTS),
|
||||
[supportedEvents],
|
||||
);
|
||||
|
||||
function updateBindings(next: EventBinding[]) {
|
||||
form.setValue('event_bindings', next, { shouldDirty: true });
|
||||
@@ -769,6 +1146,11 @@ export default function EventBindingsEditor({
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<AdapterCapabilitySummary
|
||||
supportedEvents={supportedEvents}
|
||||
eventOptions={eventOptions}
|
||||
/>
|
||||
|
||||
{/* enabled section */}
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
@@ -821,10 +1203,18 @@ export default function EventBindingsEditor({
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
|
||||
<Button type="button" variant="outline" size="sm" onClick={addBinding}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t('bots.addEventBinding')}
|
||||
</Button>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={addBinding}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
{t('bots.addEventBinding')}
|
||||
</Button>
|
||||
<RouteDryRunDialog
|
||||
botId={botId}
|
||||
bindings={bindings}
|
||||
eventOptions={dryRunEventOptions}
|
||||
agentOptions={agentOptions}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* disabled section */}
|
||||
{disabledBindings.length > 0 && (
|
||||
|
||||
@@ -246,6 +246,34 @@ export interface EventBinding {
|
||||
order?: number;
|
||||
}
|
||||
|
||||
export interface BotRouteDryRunRequest {
|
||||
event_type: string;
|
||||
payload?: Record<string, unknown>;
|
||||
event_bindings?: EventBinding[];
|
||||
}
|
||||
|
||||
export interface BotRouteDryRunTarget {
|
||||
target_type: EventBinding['target_type'];
|
||||
target_uuid?: string | null;
|
||||
target_name?: string | null;
|
||||
kind?: AgentKind | 'discard' | null;
|
||||
}
|
||||
|
||||
export interface BotRouteDryRunResult {
|
||||
matched: boolean;
|
||||
target?: BotRouteDryRunTarget | null;
|
||||
binding_id?: string | null;
|
||||
event_pattern?: string | null;
|
||||
target_type?: EventBinding['target_type'] | null;
|
||||
target_uuid?: string | null;
|
||||
reason?: string | null;
|
||||
failure_code?: string | null;
|
||||
diagnostic_steps: string[];
|
||||
diagnostic_details?: Array<Record<string, unknown>>;
|
||||
matched_binding_id?: string | null;
|
||||
matched_binding_index?: number | null;
|
||||
}
|
||||
|
||||
export interface ApiRespKnowledgeBases {
|
||||
bases: KnowledgeBase[];
|
||||
}
|
||||
|
||||
@@ -59,6 +59,8 @@ import {
|
||||
Skill,
|
||||
ApiRespSkills,
|
||||
ApiRespSkill,
|
||||
BotRouteDryRunRequest,
|
||||
BotRouteDryRunResult,
|
||||
} from '@/app/infra/entities/api';
|
||||
import { Plugin } from '@/app/infra/entities/plugin';
|
||||
import type { PluginLogEntry } from '@/app/infra/entities/plugin';
|
||||
@@ -454,6 +456,16 @@ export class BackendClient extends BaseHttpClient {
|
||||
return this.put(`/api/v1/platform/bots/${uuid}`, bot);
|
||||
}
|
||||
|
||||
public dryRunBotEventRoute(
|
||||
botId: string,
|
||||
request: BotRouteDryRunRequest,
|
||||
): Promise<BotRouteDryRunResult> {
|
||||
return this.post(
|
||||
`/api/v1/platform/bots/${botId}/event-routes/dry-run`,
|
||||
request,
|
||||
);
|
||||
}
|
||||
|
||||
public deleteBot(uuid: string): Promise<object> {
|
||||
return this.delete(`/api/v1/platform/bots/${uuid}`);
|
||||
}
|
||||
|
||||
@@ -385,6 +385,34 @@ const enUS = {
|
||||
disable: 'Disable',
|
||||
enable: 'Enable',
|
||||
disabledBindings: 'Disabled',
|
||||
adapterEventsTitle: 'Events this adapter can receive',
|
||||
adapterEventsDescription:
|
||||
'{{count}} event types are available. Routes are matched in order, and unmatched events are not sent to a processor.',
|
||||
adapterEventsMore: '{{count}} more',
|
||||
advancedEventValues: 'Advanced event values',
|
||||
eventGroup: 'Group',
|
||||
testRoute: 'Test route',
|
||||
dryRunTitle: 'Test event route',
|
||||
dryRunDescription:
|
||||
'Choose an event and provide a sample payload to see which processor the current route setup will use.',
|
||||
dryRunEventType: 'Event type',
|
||||
dryRunPayload: 'Sample payload JSON',
|
||||
dryRunPayloadHint:
|
||||
'Use simple fields such as message_text, chat_type, and chat_id to test conditions.',
|
||||
dryRunPayloadJsonError: 'Enter valid JSON.',
|
||||
dryRunPayloadObjectError: 'Payload must be a JSON object.',
|
||||
dryRunNeedsSavedBot: 'Save the bot before testing routes.',
|
||||
dryRunFailed: 'Route test failed. Try again later.',
|
||||
dryRunAction: 'Run test',
|
||||
dryRunRunning: 'Testing…',
|
||||
dryRunMatched: 'Route matched',
|
||||
dryRunNotMatched: 'No route matched',
|
||||
dryRunTarget: 'Target processor',
|
||||
dryRunNoTarget: 'No target',
|
||||
dryRunMatchedRule: 'Matched rule',
|
||||
dryRunRuleIndex: 'Route {{index}}',
|
||||
dryRunNoRule: 'No matched rule',
|
||||
dryRunDiagnostics: 'Diagnostic steps',
|
||||
eventCustom: 'Custom event',
|
||||
eventWildcard: 'All events',
|
||||
eventNamespaceWildcard: '{{namespace}}.*',
|
||||
@@ -405,6 +433,27 @@ const enUS = {
|
||||
bot_unmuted: 'Bot unmuted',
|
||||
platform_specific: 'Platform-specific event',
|
||||
},
|
||||
eventDescriptions: {
|
||||
all: 'Matches every event received by this adapter.',
|
||||
namespace: 'Matches several concrete events in the same event group.',
|
||||
custom: 'A custom event, or one without a description yet.',
|
||||
message_received: 'A user or group sends a new message to the bot.',
|
||||
message_edited: 'The platform reports that an existing message changed.',
|
||||
message_deleted:
|
||||
'The platform reports that an existing message was deleted.',
|
||||
message_reaction: 'A user adds or removes a reaction on a message.',
|
||||
feedback_received: 'Feedback is received from the platform or user.',
|
||||
friend_request_received: 'Someone requests to add the bot as a friend.',
|
||||
friend_added: 'A friend relationship was created.',
|
||||
group_member_joined: 'A member joins a group where the bot is present.',
|
||||
group_member_left: 'A member leaves a group where the bot is present.',
|
||||
group_member_banned: 'A group member is banned or removed.',
|
||||
bot_invited_to_group: 'The bot is invited to a group.',
|
||||
bot_removed_from_group: 'The bot is removed from a group.',
|
||||
bot_muted: 'The bot is muted in a group.',
|
||||
bot_unmuted: 'The bot is unmuted in a group.',
|
||||
platform_specific: 'An adapter-specific platform event.',
|
||||
},
|
||||
conditions: 'Conditions',
|
||||
conditionsDescription:
|
||||
'All conditions must match to trigger this binding. Leave empty to always trigger.',
|
||||
|
||||
@@ -381,12 +381,46 @@ const jaJP = {
|
||||
targetPipeline: 'Pipeline',
|
||||
targetDiscard: '破棄',
|
||||
selectTarget: 'プロセッサーを選択',
|
||||
searchTarget: 'プロセッサーを検索…',
|
||||
noTargetFound: '対応するプロセッサーが見つかりません',
|
||||
priority: '優先度',
|
||||
enabled: '有効',
|
||||
eventBindingDescriptionPlaceholder: 'ルール説明',
|
||||
noEventBindings: 'イベントルートはありません',
|
||||
unsupportedPipelineEvent:
|
||||
'Pipeline は message.* イベントにのみ使用できます',
|
||||
disable: '無効化',
|
||||
enable: '有効化',
|
||||
disabledBindings: '無効',
|
||||
adapterEventsTitle: 'このアダプターが受信できるイベント',
|
||||
adapterEventsDescription:
|
||||
'{{count}} 種類のイベントを利用できます。ルートは上から順に照合され、未一致のイベントはプロセッサーへ送られません。',
|
||||
adapterEventsMore: 'ほか {{count}} 件',
|
||||
advancedEventValues: '高度なイベント値',
|
||||
eventGroup: 'グループ',
|
||||
testRoute: 'ルートをテスト',
|
||||
dryRunTitle: 'イベントルートをテスト',
|
||||
dryRunDescription:
|
||||
'イベントとサンプルペイロードを指定し、現在のルート設定でどのプロセッサーに送られるか確認します。',
|
||||
dryRunEventType: 'イベントタイプ',
|
||||
dryRunPayload: 'サンプルペイロード JSON',
|
||||
dryRunPayloadHint:
|
||||
'message_text、chat_type、chat_id などの簡単なフィールドで条件をテストできます。',
|
||||
dryRunPayloadJsonError: '有効な JSON を入力してください。',
|
||||
dryRunPayloadObjectError:
|
||||
'ペイロードは JSON オブジェクトである必要があります。',
|
||||
dryRunNeedsSavedBot: 'ルートをテストする前にボットを保存してください。',
|
||||
dryRunFailed: 'ルートテストに失敗しました。後でもう一度お試しください。',
|
||||
dryRunAction: 'テスト実行',
|
||||
dryRunRunning: 'テスト中…',
|
||||
dryRunMatched: 'ルートに一致しました',
|
||||
dryRunNotMatched: '一致するルートはありません',
|
||||
dryRunTarget: '対象プロセッサー',
|
||||
dryRunNoTarget: '対象なし',
|
||||
dryRunMatchedRule: '一致したルール',
|
||||
dryRunRuleIndex: 'ルート {{index}}',
|
||||
dryRunNoRule: '一致したルールなし',
|
||||
dryRunDiagnostics: '診断ステップ',
|
||||
eventCustom: 'カスタムイベント',
|
||||
eventWildcard: 'すべてのイベント',
|
||||
eventNamespaceWildcard: '{{namespace}}.*',
|
||||
@@ -407,6 +441,46 @@ const jaJP = {
|
||||
bot_unmuted: 'ボットのミュート解除',
|
||||
platform_specific: 'プラットフォーム固有イベント',
|
||||
},
|
||||
eventDescriptions: {
|
||||
all: 'このアダプターが受信するすべてのイベントに一致します。',
|
||||
namespace: '同じイベントグループ内の複数の具体イベントに一致します。',
|
||||
custom: 'カスタムイベント、または説明がまだないイベントです。',
|
||||
message_received:
|
||||
'ユーザーまたはグループがボットへ新しいメッセージを送信します。',
|
||||
message_edited:
|
||||
'既存メッセージが変更されたことをプラットフォームが通知します。',
|
||||
message_deleted:
|
||||
'既存メッセージが削除されたことをプラットフォームが通知します。',
|
||||
message_reaction:
|
||||
'ユーザーがメッセージへのリアクションを追加または削除します。',
|
||||
feedback_received:
|
||||
'プラットフォームまたはユーザーからフィードバックを受信します。',
|
||||
friend_request_received: '誰かがボットを友達に追加しようとしています。',
|
||||
friend_added: '友達関係が作成されました。',
|
||||
group_member_joined: 'ボットがいるグループにメンバーが参加しました。',
|
||||
group_member_left: 'ボットがいるグループからメンバーが退出しました。',
|
||||
group_member_banned: 'グループメンバーがBANまたは削除されました。',
|
||||
bot_invited_to_group: 'ボットがグループに招待されました。',
|
||||
bot_removed_from_group: 'ボットがグループから削除されました。',
|
||||
bot_muted: 'ボットがグループでミュートされました。',
|
||||
bot_unmuted: 'ボットのグループでのミュートが解除されました。',
|
||||
platform_specific: 'アダプター固有のプラットフォームイベントです。',
|
||||
},
|
||||
conditions: '条件',
|
||||
conditionsDescription:
|
||||
'すべての条件に一致した場合のみこのバインディングが発火します。空の場合は常に発火します。',
|
||||
conditionsEmpty: '条件なし。常に発火します。',
|
||||
addFilter: '条件を追加',
|
||||
filterChatType: 'セッションタイプ',
|
||||
filterChatId: 'セッション ID',
|
||||
filterMessageText: 'メッセージ本文',
|
||||
filterMessageElement: 'メッセージ要素',
|
||||
operator_eq: '等しい',
|
||||
operator_neq: '等しくない',
|
||||
operator_contains: '含む',
|
||||
operator_not_contains: '含まない',
|
||||
operator_starts_with: '前方一致',
|
||||
operator_regex: '正規表現',
|
||||
routingRules: '条件付きルーティングルール',
|
||||
routingRulesDescription:
|
||||
'ルールは順番に評価され、最初に一致したルールのパイプラインにルーティングされます。一致しない場合はデフォルトパイプラインが使用されます。',
|
||||
|
||||
@@ -370,6 +370,34 @@ const zhHans = {
|
||||
disable: '禁用',
|
||||
enable: '启用',
|
||||
disabledBindings: '已禁用',
|
||||
adapterEventsTitle: '此适配器可接收的事件',
|
||||
adapterEventsDescription:
|
||||
'已识别 {{count}} 类事件。路由会按顺序匹配,未命中时不会交给处理器。',
|
||||
adapterEventsMore: '另有 {{count}} 类',
|
||||
advancedEventValues: '高级事件值',
|
||||
eventGroup: '事件组',
|
||||
testRoute: '测试路由',
|
||||
dryRunTitle: '测试事件路由',
|
||||
dryRunDescription:
|
||||
'选择一个事件并提供示例载荷,检查当前路由配置会命中哪个处理器。',
|
||||
dryRunEventType: '事件类型',
|
||||
dryRunPayload: '示例载荷 JSON',
|
||||
dryRunPayloadHint:
|
||||
'可填写 message_text、chat_type、chat_id 等简单字段,用于匹配触发条件。',
|
||||
dryRunPayloadJsonError: '请输入合法 JSON。',
|
||||
dryRunPayloadObjectError: '载荷必须是 JSON 对象。',
|
||||
dryRunNeedsSavedBot: '请先保存机器人后再测试路由。',
|
||||
dryRunFailed: '路由测试失败,请稍后重试。',
|
||||
dryRunAction: '开始测试',
|
||||
dryRunRunning: '测试中…',
|
||||
dryRunMatched: '已命中路由',
|
||||
dryRunNotMatched: '未命中路由',
|
||||
dryRunTarget: '目标处理器',
|
||||
dryRunNoTarget: '无目标',
|
||||
dryRunMatchedRule: '命中规则',
|
||||
dryRunRuleIndex: '第 {{index}} 条路由',
|
||||
dryRunNoRule: '无命中规则',
|
||||
dryRunDiagnostics: '诊断步骤',
|
||||
eventCustom: '自定义事件',
|
||||
eventWildcard: '全部事件',
|
||||
eventNamespaceWildcard: '{{namespace}}.*',
|
||||
@@ -390,6 +418,26 @@ const zhHans = {
|
||||
bot_unmuted: '机器人被解除禁言',
|
||||
platform_specific: '平台特定事件',
|
||||
},
|
||||
eventDescriptions: {
|
||||
all: '匹配此适配器收到的全部事件。',
|
||||
namespace: '匹配同一事件分组下的多个具体事件。',
|
||||
custom: '自定义或暂未提供说明的事件。',
|
||||
message_received: '用户或群组向机器人发送新消息。',
|
||||
message_edited: '平台通知已有消息内容发生变更。',
|
||||
message_deleted: '平台通知已有消息被删除。',
|
||||
message_reaction: '用户对消息添加或移除表态。',
|
||||
feedback_received: '收到来自平台或用户的反馈事件。',
|
||||
friend_request_received: '有人请求添加机器人为好友。',
|
||||
friend_added: '好友关系建立成功。',
|
||||
group_member_joined: '有成员加入机器人所在群组。',
|
||||
group_member_left: '有成员离开机器人所在群组。',
|
||||
group_member_banned: '群成员被封禁或移出。',
|
||||
bot_invited_to_group: '机器人被邀请加入群组。',
|
||||
bot_removed_from_group: '机器人被移出群组。',
|
||||
bot_muted: '机器人在群组中被禁言。',
|
||||
bot_unmuted: '机器人在群组中解除禁言。',
|
||||
platform_specific: '适配器保留的平台专属事件。',
|
||||
},
|
||||
conditions: '触发条件',
|
||||
conditionsDescription: '满足所有条件时才触发此绑定,不添加则无条件触发。',
|
||||
conditionsEmpty: '无条件,始终触发。',
|
||||
|
||||
Reference in New Issue
Block a user