feat(agent): 增强 Agent 配置,新增结构化字段与聊天功能支持

This commit is contained in:
hugo committed 2026-07-07 11:10:32 +08:00
1 parent ac4262cd75
commit c8ce77199e
183 files changed
+11690 -2300

No files matched your search

+10
View File
@@ -12,6 +12,16 @@ def parse_api_error(body: dict) -> dict:
return error
def parse_api_data(body: dict):
"""
从标准 API 成功 envelope 中提取 data;legacy 裸 JSON 则原样返回。
"""
assert isinstance(body, dict)
if body.get('success') is True:
return body.get('data')
return body
def flatten_api_error(body: dict) -> dict:
"""
将 envelope 错误扁平化为 { error_code, error, ...details },便于 WeCom 等历史测试断言。
@@ -1,7 +1,7 @@
"""
tests/services/admin/test_agent_service.py
用途:agent_service CRUD 与权限绑定单元测试。
用途:agent_service CRUD 与权限绑定单元测试(Registry 结构化列)。
"""
import pytest
@@ -15,14 +15,17 @@ def test_agent_crud(app):
with app.app_context():
created = agent_service.create_agent({
'name': 'Test Agent',
'type': 'iframe',
'dify_app_id': 'app-1',
'extra_config': {'iframe_url': 'https://example.com'},
'runtime_provider': 'iframe',
'conversation_mode': 'embedded',
'iframe_url': 'https://example.com',
'dify_app_id': 'unused',
})
agent_id = created['id']
items = agent_service.list_agents()
assert any(item['id'] == agent_id for item in items)
row = next(item for item in items if item['id'] == agent_id)
assert row['runtime_provider'] == 'iframe'
assert row['iframe_url'] == 'https://example.com'
agent_service.update_agent(agent_id, {'description': 'updated'})
refreshed = db.session.get(Agent, agent_id)
@@ -32,15 +35,66 @@ def test_agent_crud(app):
assert db.session.get(Agent, agent_id) is None
def test_create_agent_requires_dify_app_id_for_api_type(app):
def test_create_agent_requires_dify_app_id_for_dify_provider(app):
with app.app_context():
with pytest.raises(ValidationError, match='App ID'):
agent_service.create_agent({'name': 'API Agent', 'type': 'api'})
with pytest.raises(ValidationError, match='dify_app_id'):
agent_service.create_agent({
'name': 'API Agent',
'runtime_provider': 'dify',
'dify_api_key': 'sk-test',
})
def test_create_file_check_agent_requires_schedule_task(app):
with app.app_context():
with pytest.raises(ValidationError, match='bound_schedule_task_id'):
agent_service.create_agent({
'name': 'File Check',
'agent_code': 'file_check',
'runtime_provider': 'dify',
'dify_app_id': 'app-fc',
'dify_api_key': 'sk-test',
})
def test_update_agent_clears_handler_config_when_explicit_null(app):
"""切换到空 schema 类型并传 handler_config=null 时应清空列。"""
with app.app_context():
created = agent_service.create_agent({
'name': 'Switch Target',
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'dify_app_id': 'app-switch',
'dify_api_key': 'sk-test',
'handler_config': {'intent_routes': ['text2sql'], 'content_profile': 'generic_entrance'},
})
agent_id = created['id']
agent_service.update_agent(agent_id, {
'name': 'Switch Target',
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': 'app-switch',
'handler_config': None,
})
refreshed = db.session.get(Agent, agent_id)
assert refreshed.agent_code == 'shipping_notice'
assert refreshed.handler_config is None
def test_update_agent_permissions(app):
with app.app_context():
agent = Agent(name='perm-agent', type='iframe', is_active=True)
agent = Agent(
name='perm-agent',
type='iframe',
runtime_provider='iframe',
conversation_mode='embedded',
iframe_url='https://example.com',
is_active=True,
)
user_a = User(username='u-a', email='a@test.com', status='active', role='user')
user_b = User(username='u-b', email='b@test.com', status='active', role='user')
db.session.add_all([agent, user_a, user_b])
+14 -11
View File
@@ -1,6 +1,7 @@
import pytest
from app.models import Agent, ChatLog, User, PermissionRequest
from app import db
from tests.conftest import parse_api_data, parse_api_error
def test_agent_lifecycle(client, admin_headers):
"""
@@ -17,15 +18,17 @@ def test_agent_lifecycle(client, admin_headers):
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
assert response.status_code == 201
agent_id = response.json['id']
agent_id = parse_api_data(response.json)['id']
# 2. Read Agent List
response = client.get('/api/admin/agents', headers=admin_headers)
assert response.status_code == 200
agents = response.json
agents = parse_api_data(response.json)
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key_masked']
# 3. Update Agent
updated_data = {
@@ -37,7 +40,7 @@ def test_agent_lifecycle(client, admin_headers):
# Verify Update
response = client.get('/api/admin/agents', headers=admin_headers)
agents = response.json
agents = parse_api_data(response.json)
assert agents[0]['name'] == "Updated Agent"
assert agents[0]['description'] == "Updated Description"
@@ -47,7 +50,7 @@ def test_agent_lifecycle(client, admin_headers):
# Verify Deletion
response = client.get('/api/admin/agents', headers=admin_headers)
assert len(response.json) == 0
assert len(parse_api_data(response.json)) == 0
def test_user_management(client, admin_headers):
"""
@@ -86,7 +89,7 @@ def test_user_management(client, admin_headers):
"dify_app_id": "p1",
"dify_api_key": "k1"
}, headers=admin_headers)
agent_id = agent_res.json['id']
agent_id = parse_api_data(agent_res.json)['id']
response = client.post(f'/api/admin/users/{user_id}/permissions', json={
"agent_ids": [agent_id]
@@ -155,7 +158,7 @@ def test_batch_delete_users_with_permissions(client, admin_headers):
'dify_api_key': 'del-key',
}, headers=admin_headers)
assert agent.status_code == 201
agent_id = agent.json['id']
agent_id = parse_api_data(agent.json)['id']
perm_res = client.post(f'/api/admin/users/{user_id}/permissions', json={
'agent_ids': [agent_id],
@@ -184,21 +187,21 @@ def test_agent_update_validation(client, admin_headers):
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
agent_id = response.json['id']
agent_id = parse_api_data(response.json)['id']
# 1. Update with Valid Data
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": "new-key"}, headers=admin_headers)
assert response.status_code == 200
# 2. Try to Clear Key for API Agent (Should Fail)
# 2. 空 key 视为未提交,保留已有 key(write-only)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify API Key" in response.json['error']
assert response.status_code == 200
# 3. Try to Clear App ID for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_app_id": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify App ID" in response.json['error']
error = parse_api_error(response.json)
assert 'dify_app_id' in error.get('message', '')
def test_permission_requests(client, app, admin_headers):
"""
@@ -0,0 +1,62 @@
"""
backend/tests/test_admin_agent_schema_api.py
用途:Admin Agent Registry schema / infer-content-profile API 集成测试。
依赖:conftest app/client、issue_local_access_token、parse_api_data。
逻辑:P3/P7 验收 — Admin 表单权威 schema 与 content_profile 推断接口。
"""
from __future__ import annotations
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import User
from tests.conftest import parse_api_data
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT(testing 环境 AUTH_JWT_REQUIRED=true)。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def test_get_agent_registry_schema(client, admin_jwt_headers):
"""GET /api/admin/agents/schema 应返回 success envelope 与三类 agent_types。"""
response = client.get('/api/admin/agents/schema', headers=admin_jwt_headers)
assert response.status_code == 200
body = response.json
assert body.get('success') is True
data = parse_api_data(body)
codes = {item['agent_code'] for item in data['agent_types']}
assert codes == {'generic', 'shipping_notice', 'file_check'}
assert 'dify' in data['platform']['runtime_providers']
def test_infer_content_profile_from_intent_routes(client, admin_jwt_headers):
"""POST infer-content-profile 应根据 intent_routes 返回 content_profile 建议。"""
response = client.post(
'/api/admin/agents/infer-content-profile',
headers=admin_jwt_headers,
json={'intent_routes': ['text2sql']},
)
assert response.status_code == 200
data = parse_api_data(response.json)
assert 'content_profile' in data
+7 -4
View File
@@ -70,23 +70,26 @@ def test_department_crud(client):
assert len(res.get_json()) == 0
def test_agent_crud(client):
from tests.conftest import parse_api_data
headers = get_headers(client)
# Create
res = client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123',
'dify_api_key': 'sk-test-key',
'description': 'Test Description'
}, headers=headers)
assert res.status_code == 201
agent_id = res.get_json()['id']
agent_id = parse_api_data(res.get_json())['id']
# List
res = client.get('/api/admin/agents', headers=headers)
assert res.status_code == 200
agents = res.get_json()
agents = parse_api_data(res.get_json())
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
assert 'dify_api_key' not in agents[0]
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
@@ -96,13 +99,13 @@ def test_agent_crud(client):
# Verify Update
res = client.get('/api/admin/agents', headers=headers)
assert res.get_json()[0]['name'] == 'Updated Agent'
assert parse_api_data(res.get_json())[0]['name'] == 'Updated Agent'
# Delete
res = client.delete(f'/api/admin/agents/{agent_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/agents', headers=headers)
assert len(res.get_json()) == 0
assert len(parse_api_data(res.get_json())) == 0
def test_permission_flow(client):
admin_headers = get_headers(client)
@@ -0,0 +1,152 @@
"""
tests/test_agent_registry_admin_payload.py
用途:Admin Agent Registry 载荷校验与 extra 清理单元测试。
"""
import pytest
from app.core.errors import ValidationError
from app.models import Agent
from app.services.agent_registry.admin_payload import (
MIGRATED_EXTRA_REGISTRY_KEYS,
apply_agent_payload,
strip_migrated_extra_registry_keys,
validate_agent_payload,
)
def test_validate_generic_dify_agent_payload():
normalized = validate_agent_payload({
'name': 'Generic Bot',
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'dify_app_id': 'app-123',
'dify_api_key': 'sk-test',
})
assert normalized['agent_code'] == 'generic'
assert normalized['runtime_provider'] == 'dify'
assert normalized['type'] == 'api'
def test_validate_rejects_unknown_agent_code():
with pytest.raises(ValidationError, match='agent_code'):
validate_agent_payload({'name': 'Bad', 'agent_code': 'unknown_type'})
def test_validate_file_check_requires_bound_schedule_task_id():
with pytest.raises(ValidationError, match='bound_schedule_task_id'):
validate_agent_payload({
'name': 'File Check',
'agent_code': 'file_check',
'runtime_provider': 'dify',
'dify_app_id': 'app-fc',
'bound_schedule_task_id': None,
})
def test_validate_iframe_requires_url():
with pytest.raises(ValidationError, match='iframe_url'):
validate_agent_payload({
'name': 'Embed',
'runtime_provider': 'iframe',
'conversation_mode': 'embedded',
})
def test_apply_file_check_writes_columns_and_strips_migrated_extra(app):
"""双写已关闭:结构化列写入 ORM,extra 不再 mirror Registry 键。"""
with app.app_context():
normalized = validate_agent_payload({
'name': 'RoHS Check',
'agent_code': 'file_check',
'runtime_provider': 'dify',
'dify_app_id': 'app-fc',
'bound_schedule_task_id': 42,
'handler_config': {
'poll_interval_seconds': 3,
'lock_input_when_running': False,
},
'extra_config': {
'agent_code': 'legacy-code',
'tool_run_progress': {'schedule_task_id': 1},
'training_workspace_enabled': True,
},
})
agent = Agent(name=normalized['name'], is_active=True)
apply_agent_payload(agent, normalized)
assert agent.agent_code == 'file_check'
assert agent.bound_schedule_task_id == 42
assert agent.capabilities['task_progress'] is True
extra = agent.extra_config or {}
for key in MIGRATED_EXTRA_REGISTRY_KEYS:
assert key not in extra
assert extra.get('training_workspace_enabled') is True
def test_validate_explicit_null_handler_config_clears_existing(app):
"""显式 handler_config=null 应清空旧配置,而非保留 existing。"""
with app.app_context():
agent = Agent(
name='Generic Bot',
is_active=True,
agent_code='generic',
runtime_provider='dify',
conversation_mode='chat',
dify_app_id='app-1',
handler_config={'intent_routes': ['text2sql'], 'content_profile': 'generic_entrance'},
)
normalized = validate_agent_payload({
'name': agent.name,
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': agent.dify_app_id,
'handler_config': None,
}, agent=agent, provided_fields=frozenset({
'name', 'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_id', 'handler_config',
}))
assert normalized['handler_config'] is None
def test_validate_omitted_handler_config_preserves_existing(app):
"""未传 handler_config 时应保留 ORM 现有值。"""
with app.app_context():
existing = {'intent_routes': ['text2sql']}
agent = Agent(
name='Generic Bot',
is_active=True,
agent_code='generic',
runtime_provider='dify',
conversation_mode='chat',
dify_app_id='app-1',
handler_config=existing,
)
normalized = validate_agent_payload({
'name': 'Renamed',
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'dify_app_id': 'app-1',
}, agent=agent, provided_fields=frozenset({'name'}))
assert normalized['handler_config']['intent_routes'] == ['text2sql']
def test_strip_migrated_extra_registry_keys_preserves_training(app):
with app.app_context():
agent = Agent(
name='Training Bot',
is_active=True,
agent_code='generic',
extra_config={
'agent_code': 'generic',
'welcome_message': 'old',
'training_pass_score': 80,
},
)
strip_migrated_extra_registry_keys(agent)
extra = agent.extra_config or {}
assert 'agent_code' not in extra
assert 'welcome_message' not in extra
assert extra.get('training_pass_score') == 80
@@ -0,0 +1,39 @@
"""
backend/tests/test_agent_registry_admin_schema.py
用途:Admin Agent Registry schema 组装单元测试。
依赖:admin_schema、catalog manifest。
逻辑:P3 验收 — build_agent_registry_schema 返回平台枚举、Catalog 扩展字段与 handler_config_schemas。
"""
from __future__ import annotations
from app.services.agent_registry.admin_schema import build_agent_registry_schema
def test_build_agent_registry_schema_includes_platform_enums():
"""platform 段应含 runtime_providers、conversation_modes 与 default_capabilities。"""
schema = build_agent_registry_schema()
platform = schema['platform']
assert 'dify' in platform['runtime_providers']
assert 'chat' in platform['conversation_modes']
assert platform['default_capabilities']['streaming'] is True
assert platform['tool_run_progress_defaults']['poll_interval_seconds'] == 2
assert platform['tool_run_progress_defaults']['progress_type'] == 'file_check'
def test_build_agent_registry_schema_agent_types_include_validation_rules():
"""agent_types 每条应含 required_fields 与 forced_capabilities。"""
schema = build_agent_registry_schema()
by_code = {item['agent_code']: item for item in schema['agent_types']}
assert by_code['file_check']['required_fields'] == ['bound_schedule_task_id']
assert by_code['file_check']['forced_capabilities']['task_progress'] is True
assert by_code['generic']['required_fields'] == []
def test_build_agent_registry_schema_handler_config_schemas():
"""handler_config_schemas 应按 agent_code 暴露 manifest schema。"""
schema = build_agent_registry_schema()
assert 'file_check' in schema['handler_config_schemas']
assert schema['handler_config_schemas']['file_check']['poll_interval_seconds']['maximum'] == 30
assert 'generic' in schema['handler_config_schemas']
@@ -0,0 +1,103 @@
"""
backend/tests/test_agent_registry_backfill_mapping.py
用途:验证存量 Agent 回填映射(名称/legacy extra → Registry 列),仅运维脚本使用。
依赖:agent_registry.backfill_mapping、pytest。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.agent_registry.backfill_mapping import infer_registry_fields_from_legacy
def _agent(**kwargs):
defaults = {
'name': '测试 Agent',
'type': 'api',
'extra_config': {},
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_backfill_maps_shipping_notice_by_name():
"""回填脚本应把历史发货通知 Agent 名称映射为 shipping_notice。"""
agent = _agent(name='货代发货通知 Agent', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
assert inferred['agent_code'] == 'shipping_notice'
assert inferred['runtime_provider'] == 'hybrid'
assert inferred['conversation_mode'] == 'task_chat'
def test_backfill_maps_file_check_from_tool_run_progress():
"""回填脚本应把 tool_run_progress 能力映射为 file_check + bound_schedule_task_id。"""
agent = _agent(
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {
'schedule_task_id': 99,
'poll_interval_seconds': 3,
},
},
)
inferred = infer_registry_fields_from_legacy(agent)
assert inferred['agent_code'] == 'file_check'
assert inferred['bound_schedule_task_id'] == 99
assert inferred['capabilities']['task_progress'] is True
def test_backfill_maps_generic_entrance_intent_routes_and_content_profile():
"""回填脚本应把通用入口映射为 hr_leave_sql + plm_oracle 与 generic_entrance profile。"""
agent = _agent(name='通用入口', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
routes = inferred.get('handler_config', {}).get('intent_routes', [])
assert 'hr_leave_sql' in routes
assert 'plm_oracle' in routes
assert inferred.get('handler_config', {}).get('content_profile') == 'generic_entrance'
assert inferred.get('welcome_message')
assert inferred.get('suggested_questions')
def test_backfill_maps_hr_policy_content_profile():
"""回填脚本应把人事规章映射为 hr_policy profile 与默认文案。"""
agent = _agent(name='人事规章', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
assert inferred.get('handler_config', {}).get('content_profile') == 'hr_policy'
assert inferred.get('welcome_message')
assert inferred.get('suggested_questions_style') == 'styled'
def test_backfill_maps_asset_management_erp_kb_and_text2sql():
"""回填脚本应把固资管理映射为 text2sql route 与 erp_kb capability。"""
agent = _agent(name='固资管理', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
routes = inferred.get('handler_config', {}).get('intent_routes', [])
assert routes == ['text2sql']
assert inferred['capabilities']['erp_kb'] is True
def test_backfill_maps_maintenance_chat_route():
"""回填脚本应把设备维保助手映射为 maintenance_chat route。"""
agent = _agent(name='设备维保助手', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
routes = inferred.get('handler_config', {}).get('intent_routes', [])
assert routes == ['maintenance_chat']
def test_backfill_maps_training_content_profile():
"""回填脚本应把培训类 Agent 名称映射为 content_profile=training。"""
agent = _agent(name='新人培训助手', extra_config={})
inferred = infer_registry_fields_from_legacy(agent)
assert inferred.get('handler_config', {}).get('content_profile') == 'training'
def test_backfill_maps_iframe_type():
"""回填脚本应把 legacy type=iframe 映射为 iframe provider + embedded。"""
agent = _agent(type='iframe', extra_config={'iframe_url': 'https://example.com/embed'})
inferred = infer_registry_fields_from_legacy(agent)
assert inferred['agent_code'] == 'generic'
assert inferred['runtime_provider'] == 'iframe'
assert inferred['conversation_mode'] == 'embedded'
assert inferred['iframe_url'] == 'https://example.com/embed'
@@ -0,0 +1,49 @@
"""
backend/tests/test_agent_registry_catalog.py
用途:验证 Agent 类型 Catalog 条目、label 与 runtime_handler 声明。
依赖:agent_registry.catalog、pytest。
逻辑:迭代 1 验收 — list_type_catalog 返回首批 3 类型且 handler 与设计方案一致。
"""
from __future__ import annotations
from app.services.agent_registry.catalog import (
AGENT_TYPE_CATALOG,
get_catalog_entry,
list_type_catalog,
)
def test_agent_type_catalog_contains_three_seed_types():
"""首批 Catalog 应包含 generic、shipping_notice、file_check 三类。"""
assert set(AGENT_TYPE_CATALOG.keys()) == {'generic', 'shipping_notice', 'file_check'}
def test_list_type_catalog_includes_agent_code_and_label():
"""Admin 下拉列表每条须含 agent_code 与人类可读 label。"""
catalog = list_type_catalog()
assert len(catalog) == 3
codes = {entry['agent_code'] for entry in catalog}
assert codes == {'generic', 'shipping_notice', 'file_check'}
labels = {entry['label'] for entry in catalog}
assert '通用问答 / 知识库' in labels
assert '货代发货通知' in labels
assert '文件检核' in labels
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
"""shipping_notice / file_check 须声明 runtime_handler;generic 为 None。"""
generic = get_catalog_entry('generic')
shipping = get_catalog_entry('shipping_notice')
file_check = get_catalog_entry('file_check')
assert generic is not None and generic['runtime_handler'] is None
assert shipping is not None and shipping['runtime_handler'] == 'shipping_notice'
assert file_check is not None and file_check['runtime_handler'] == 'file_check'
def test_get_catalog_entry_returns_none_for_unknown_code():
"""未知 agent_code 应返回 None,避免 Admin 误绑。"""
assert get_catalog_entry('unknown_type') is None
assert get_catalog_entry('') is None
@@ -0,0 +1,66 @@
"""
backend/tests/test_agent_registry_catalog_loader.py
用途:Catalog loader 布尔归一化与缓存行为单测。
"""
from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.services.agent_registry.catalog_loader import (
clear_catalog_cache,
coerce_manifest_boolean,
get_default_capabilities,
)
def test_coerce_manifest_boolean_parses_string_false():
assert coerce_manifest_boolean('false') is False
assert coerce_manifest_boolean('true') is True
def test_coerce_manifest_boolean_rejects_invalid_string():
with pytest.raises(ValidationError, match='布尔'):
coerce_manifest_boolean('maybe')
def test_get_default_capabilities_uses_manifest_boolean_coercion(monkeypatch):
"""default_capabilities 不得对字符串 'false' 使用裸 bool()。"""
from app.services.agent_registry import catalog_loader
monkeypatch.setattr(
catalog_loader,
'get_platform_config',
lambda: {
'default_capabilities': {
'streaming': 'false',
'task_progress': False,
},
},
)
caps = get_default_capabilities()
assert caps['streaming'] is False
assert caps['task_progress'] is False
def test_get_tool_run_progress_defaults_coerces_boolean_string(monkeypatch):
from app.services.agent_registry import catalog_loader
from app.services.agent_registry.catalog_loader import get_tool_run_progress_defaults
monkeypatch.setattr(
catalog_loader,
'get_platform_config',
lambda: {
'tool_run_progress_defaults': {
'progress_type': 'file_check',
'poll_interval_seconds': 3,
'lock_input_when_running': 'false',
},
},
)
defaults = get_tool_run_progress_defaults()
assert defaults['lock_input_when_running'] is False
assert defaults['poll_interval_seconds'] == 3
@@ -0,0 +1,146 @@
"""
backend/tests/test_agent_registry_catalog_validation.py
用途:Catalog manifest 校验规则单元测试(required_fields、forced_capabilities、handler_config)。
依赖:catalog_validation、pytest。
逻辑:P4/P5 验收 — manifest 声明的规则在 validate/normalize 路径生效。
"""
from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.services.agent_registry.admin_payload import validate_agent_payload
from app.services.agent_registry.catalog import AGENT_TYPE_CATALOG, clear_catalog_cache
from app.services.agent_registry.catalog_loader import list_agent_type_codes
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
normalize_handler_config,
validate_required_fields,
)
def test_apply_catalog_capabilities_forces_file_check_task_progress():
"""manifest forced_capabilities 应强制 task_progress=true。"""
merged = apply_catalog_capabilities('file_check', {'task_progress': False})
assert merged['task_progress'] is True
def test_validate_agent_payload_parses_is_active_string_false():
normalized = validate_agent_payload({
'name': 'Bot',
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'dify_app_id': 'app-1',
'is_active': 'false',
})
assert normalized['is_active'] is False
def test_validate_agent_payload_applies_forced_capabilities_from_manifest():
"""validate_agent_payload 路径应合并 manifest forced_capabilities。"""
normalized = validate_agent_payload({
'name': 'File Check Bot',
'agent_code': 'file_check',
'runtime_provider': 'dify',
'dify_app_id': 'app-fc',
'bound_schedule_task_id': 42,
'capabilities': {'task_progress': False},
})
assert normalized['capabilities']['task_progress'] is True
def test_validate_required_fields_file_check_requires_schedule_task():
"""file_check 缺少 bound_schedule_task_id 时应抛出 ValidationError。"""
with pytest.raises(ValidationError, match='bound_schedule_task_id'):
validate_required_fields('file_check', bound_schedule_task_id=None)
def test_validate_required_fields_generic_has_no_required():
"""generic 无 required_fields,不应抛错。"""
validate_required_fields('generic', bound_schedule_task_id=None)
def test_normalize_handler_config_applies_defaults_for_file_check():
"""file_check handler_config 应按 schema 补 default 并裁剪未知键。"""
normalized = normalize_handler_config('file_check', {'unknown_key': 99})
assert normalized == {
'poll_interval_seconds': 2,
'lock_input_when_running': True,
}
def test_normalize_handler_config_default_value_coerced(monkeypatch):
"""schema default 字段也应经 _coerce_handler_value 归一化。"""
from app.services.agent_registry import catalog_validation
monkeypatch.setattr(
catalog_validation,
'get_catalog_entry',
lambda _code: {
'handler_config_schema': {
'lock_input_when_running': {
'type': 'boolean',
'default': 'false',
},
},
},
)
normalized = normalize_handler_config('file_check', {})
assert normalized == {'lock_input_when_running': False}
def test_normalize_handler_config_clamps_poll_interval():
"""poll_interval_seconds 超出 maximum 时应拒绝。"""
with pytest.raises(ValidationError, match='不得大于'):
normalize_handler_config('file_check', {'poll_interval_seconds': 99})
def test_normalize_handler_config_string_false_coerces_to_false():
"""handler_config.lock_input_when_running='false' 应归一为 False。"""
normalized = normalize_handler_config('file_check', {'lock_input_when_running': 'false'})
assert normalized is not None
assert normalized['lock_input_when_running'] is False
def test_normalize_handler_config_rejects_invalid_boolean_string():
with pytest.raises(ValidationError, match='布尔'):
normalize_handler_config('file_check', {'lock_input_when_running': 'maybe'})
def test_normalize_handler_config_empty_schema_rejects_any_field():
"""空 handler_config_schema 表示不允许任何 handler_config 字段。"""
with pytest.raises(ValidationError, match='不允许配置 handler_config'):
normalize_handler_config('shipping_notice', {'intent_routes': ['text2sql']})
def test_normalize_handler_config_empty_schema_allows_null():
assert normalize_handler_config('shipping_notice', None) is None
assert normalize_handler_config('shipping_notice', {}) is None
def test_clear_catalog_cache_keeps_catalog_access_consistent():
"""clear_catalog_cache 后 AGENT_TYPE_CATALOG 与 loader 仍一致。"""
clear_catalog_cache()
loader_codes = set(list_agent_type_codes())
proxy_codes = set(AGENT_TYPE_CATALOG.keys())
assert loader_codes == proxy_codes
assert 'generic' in proxy_codes
clear_catalog_cache()
assert set(AGENT_TYPE_CATALOG.keys()) == set(list_agent_type_codes())
def test_normalize_handler_config_generic_preserves_intent_routes():
"""generic handler_config_schema 应归一化 intent_routes 与 content_profile。"""
normalized = normalize_handler_config('generic', {
'intent_routes': ['text2sql', ''],
'content_profile': 'generic_entrance',
'extra': 'ignored',
})
assert normalized == {
'intent_routes': ['text2sql'],
'content_profile': 'generic_entrance',
}
@@ -0,0 +1,38 @@
"""
backend/tests/test_agent_registry_content_profiles.py
用途:验证 content_profile 目录、intent 推断与回填默认文案合并。
"""
from __future__ import annotations
from app.services.agent_registry.content_profiles import (
infer_content_profile_from_intent_routes,
list_content_profiles,
merge_profile_defaults_into_fields,
)
def test_list_content_profiles_includes_generic_and_hr():
keys = {item['key'] for item in list_content_profiles()}
assert 'generic_entrance' in keys
assert 'hr_policy' in keys
assert 'training' in keys
def test_infer_content_profile_from_intent_routes():
assert infer_content_profile_from_intent_routes(['hr_leave_sql', 'plm_oracle']) == 'generic_entrance'
assert infer_content_profile_from_intent_routes(['hr_leave_sql']) == 'hr_policy'
assert infer_content_profile_from_intent_routes(['plm_oracle']) is None
def test_merge_profile_defaults_into_fields_only_fills_empty():
fields: dict = {}
merge_profile_defaults_into_fields(fields, 'hr_policy')
assert fields['welcome_message']
assert fields['suggested_questions_style'] == 'styled'
assert len(fields['suggested_questions']) >= 1
fields_with_welcome = {'welcome_message': '自定义欢迎语'}
merge_profile_defaults_into_fields(fields_with_welcome, 'hr_policy')
assert fields_with_welcome['welcome_message'] == '自定义欢迎语'
@@ -0,0 +1,32 @@
"""
tests/test_agent_registry_handlers.py
用途:ShippingNoticeHandler UI State 事件构造测试。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_registry.handlers.bootstrap import load_handlers
from app.services.agent_registry.handlers.registry import get_handler
def test_shipping_handler_builds_ui_state_event(app):
with app.app_context():
load_handlers()
handler = get_handler('shipping_notice')
assert handler is not None
ctx = ChatStreamContext(
query='test',
display_query='test',
user=SimpleNamespace(id=1),
agent=SimpleNamespace(agent_code='shipping_notice'),
session=SimpleNamespace(session_id='conv-1'),
external_conversation_id=None,
request_id='req-1',
shipping_task_id='SN-TEST-001',
shipping_batch_no='SB-TEST',
)
event = handler.build_ui_state_event(ctx)
assert event is None or event.get('event') == 'shipping_ui_state'
@@ -0,0 +1,37 @@
"""
backend/tests/test_agent_registry_intent_metadata.py
用途:验证 resolve_agent_intent_metadata 只读 handler_config.content_profile。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.chat.intent_route_registry import resolve_agent_intent_metadata
def _agent(**kwargs):
return SimpleNamespace(**kwargs)
def test_content_profile_key_reads_handler_config_only():
"""intent routes 组合不再推断 content_profile;只读 handler_config.content_profile。"""
agent = _agent(
handler_config={
'intent_routes': ['hr_leave_sql', 'plm_oracle'],
'content_profile': 'hr_policy',
},
)
meta = resolve_agent_intent_metadata(agent)
assert meta['content_profile_key'] == 'hr_policy'
assert meta['leave_feature_enabled'] is True
def test_content_profile_key_none_without_handler_config():
"""未显式配置 content_profile 时返回 None,即使 intent routes 暗示 generic_entrance。"""
agent = _agent(
handler_config={'intent_routes': ['hr_leave_sql', 'plm_oracle']},
)
meta = resolve_agent_intent_metadata(agent)
assert meta['content_profile_key'] is None
@@ -0,0 +1,75 @@
"""
backend/tests/test_agent_registry_intent_routes.py
用途:验证 Intent route 注册表与 normalize/validate 契约。
依赖:agent_registry.intent_routes、chat.intent_route_registry、pytest。
"""
from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.services.agent_registry.intent_routes import (
IntentRouteDefinition,
get_intent_route_keys,
list_intent_routes,
normalize_intent_routes_list,
register_intent_route,
validate_intent_routes,
)
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
@pytest.fixture(autouse=True)
def _load_builtin_routes():
ensure_intent_routes_loaded()
def test_builtin_intent_routes_registered():
"""内置四个 route 应在 chat route 加载后注册。"""
keys = get_intent_route_keys()
assert 'hr_leave_sql' in keys
assert 'plm_oracle' in keys
assert len(keys) >= 4
def test_list_intent_routes_returns_admin_catalog_shape():
"""Admin catalog 应返回 key/label/description 等字段。"""
rows = list_intent_routes()
assert rows
hr = next(item for item in rows if item['key'] == 'hr_leave_sql')
assert hr['label']
assert hr['description']
assert hr['enabled'] is True
assert isinstance(hr['sort_order'], int)
def test_validate_intent_routes_rejects_unknown():
"""Admin 写入应拒绝未注册 route。"""
with pytest.raises(ValidationError, match='无效的 intent_route'):
validate_intent_routes(['not_a_route'])
def test_normalize_intent_routes_list_skips_unknown():
"""回填场景应静默跳过未知 route。"""
normalized = normalize_intent_routes_list(['hr_leave_sql', 'unknown', 'plm_oracle'])
assert normalized == ['hr_leave_sql', 'plm_oracle']
def test_register_intent_route_rejects_empty_key():
"""空 key 注册应失败。"""
with pytest.raises(ValidationError, match='不能为空'):
register_intent_route(IntentRouteDefinition(key='', label='x', description='y'))
def test_register_intent_route_rejects_duplicate():
"""重复注册同一 key 应失败。"""
from app.services.agent_registry import intent_routes as module
key = '__pytest_intent_route_dup__'
module._INTENT_ROUTE_REGISTRY.pop(key, None)
register_intent_route(IntentRouteDefinition(key=key, label='t', description='d'))
with pytest.raises(ValidationError, match='重复'):
register_intent_route(IntentRouteDefinition(key=key, label='t2', description='d2'))
module._INTENT_ROUTE_REGISTRY.pop(key, None)
@@ -0,0 +1,198 @@
"""
backend/tests/test_agent_registry_resolver.py
用途:验证 Agent Registry Resolver 只读结构化列,无任何 legacy/extra 兜底。
依赖:agent_registry.resolver、file_check_tools.task_resolver、pytest。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.agent_registry.resolver import (
agent_declares_task_progress,
agent_has_erp_kb,
agent_has_intent_route,
is_file_check_runtime_ready,
normalize_capabilities,
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_handler_key,
resolve_intent_routes,
resolve_runtime_provider,
)
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
def _agent(**kwargs):
defaults = {
'name': '测试 Agent',
'type': 'api',
'extra_config': {},
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'capabilities': None,
'bound_schedule_task_id': None,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_resolve_agent_code_reads_column_value():
"""运行时须信任 agents.agent_code 列,含 generic 默认值。"""
agent = _agent(agent_code='shipping_notice', extra_config={'agent_code': 'generic'})
assert resolve_agent_code(agent) == 'shipping_notice'
def test_resolve_agent_code_defaults_when_column_missing():
"""无 agent_code 列时回退 ORM 默认 generic,不读 extra_config。"""
agent = SimpleNamespace(name='测试', type='api', extra_config={'agent_code': 'kb_faq_agent'})
assert resolve_agent_code(agent) == 'generic'
def test_resolve_agent_code_does_not_infer_from_name():
"""名称含发货通知但列仍为 generic 时,不得运行时改判为 shipping_notice。"""
agent = _agent(name='货代发货通知 Agent', agent_code='generic', extra_config={})
assert resolve_agent_code(agent) == 'generic'
assert resolve_runtime_provider(agent) == 'dify'
assert resolve_conversation_mode(agent) == 'chat'
def test_resolve_agent_code_does_not_infer_file_check_from_capabilities_list():
"""extra capabilities 列表不得触发运行时改判 file_check。"""
agent = _agent(
name='RoHS 检核',
agent_code='generic',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 42},
},
)
assert resolve_agent_code(agent) == 'generic'
assert resolve_capabilities(agent)['task_progress'] is False
def test_resolve_registered_file_check_columns():
"""回填后的 file_check 列应被 resolver 原样读出。"""
agent = _agent(
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
capabilities={'task_progress': True},
bound_schedule_task_id=42,
)
assert resolve_agent_code(agent) == 'file_check'
assert resolve_runtime_provider(agent) == 'dify'
assert resolve_conversation_mode(agent) == 'task_chat'
assert resolve_capabilities(agent)['task_progress'] is True
def test_resolve_runtime_provider_reads_column_not_legacy_type():
"""legacy type=iframe 不得覆盖已注册列;无列时默认 dify。"""
iframe_type_agent = SimpleNamespace(name='iframe app', type='iframe', extra_config={})
assert resolve_runtime_provider(iframe_type_agent) == 'dify'
registered_iframe = _agent(runtime_provider='iframe', type='iframe')
assert resolve_runtime_provider(registered_iframe) == 'iframe'
def test_resolve_capabilities_normalizes_schema():
"""capabilities 列 dict 应归一化为固定 schema 布尔键。"""
agent = _agent(
capabilities={'task_progress': True, 'file_upload': True},
)
caps = resolve_capabilities(agent)
assert caps['task_progress'] is True
assert caps['file_upload'] is True
assert caps['streaming'] is True
assert caps['human_confirm'] is False
def test_normalize_capabilities_string_false_strict():
"""Admin strict 模式下 capabilities.task_progress='false' 应归一为 False。"""
caps = normalize_capabilities({'task_progress': 'false'}, strict=True)
assert caps['task_progress'] is False
def test_normalize_capabilities_string_false_lenient_db_read():
"""读库 lenient 模式下 capabilities.task_progress='false' 应归一为 False。"""
caps = normalize_capabilities({'task_progress': 'false'}, strict=False)
assert caps['task_progress'] is False
def test_normalize_capabilities_applies_defaults():
"""空输入应返回 DEFAULT_CAPABILITIES 全量默认值。"""
caps = normalize_capabilities(None)
assert caps['streaming'] is True
assert caps['task_progress'] is False
def test_resolve_handler_key_reads_catalog():
"""resolve_handler_key 应返回 Catalog 声明的 runtime_handler。"""
assert resolve_handler_key('shipping_notice') == 'shipping_notice'
assert resolve_handler_key('generic') is None
def test_resolve_schedule_task_id_reads_bound_column_only():
"""task_resolver 只读 bound_schedule_task_id 列,忽略 extra_config。"""
column_agent = _agent(
bound_schedule_task_id=10,
extra_config={'tool_run_progress': {'schedule_task_id': 20}},
)
unregistered_agent = _agent(
bound_schedule_task_id=None,
extra_config={'tool_run_progress': {'schedule_task_id': 20}},
)
assert resolve_schedule_task_id_from_agent(column_agent) == 10
assert resolve_schedule_task_id_from_agent(unregistered_agent) is None
def test_resolve_intent_routes_reads_handler_config_column():
"""intent_routes 应只读 handler_config 列,不按名称推断。"""
agent = _agent(
name='通用入口',
handler_config={'intent_routes': ['hr_leave_sql', 'plm_oracle']},
)
routes = resolve_intent_routes(agent)
assert routes == frozenset({'hr_leave_sql', 'plm_oracle'})
assert agent_has_intent_route(agent, 'hr_leave_sql') is True
assert agent_has_intent_route(agent, 'plm_oracle') is True
assert agent_has_intent_route(agent, 'unknown') is False
def test_agent_has_erp_kb_reads_capabilities_column():
"""erp_kb 应只读 capabilities 列。"""
agent = _agent(capabilities={'erp_kb': True})
assert agent_has_erp_kb(agent) is True
assert agent_has_erp_kb(_agent(capabilities={})) is False
def test_agent_declares_task_progress_reads_registry_columns():
"""task_progress 声明应只读 capabilities.task_progress === true。"""
assert agent_declares_task_progress(_agent(agent_code='file_check')) is False
assert agent_declares_task_progress(_agent(
agent_code='file_check',
capabilities={'task_progress': True},
)) is True
assert agent_declares_task_progress(_agent(capabilities={'task_progress': True})) is True
assert agent_declares_task_progress(_agent(
extra_config={'capabilities': ['tool_run_progress']},
)) is False
def test_is_file_check_runtime_ready_requires_bound_task_id():
"""完整 file_check 入口须 capabilities.task_progress 与 bound_schedule_task_id。"""
ready = _agent(
agent_code='file_check',
capabilities={'task_progress': True},
bound_schedule_task_id=12,
)
misconfigured = _agent(
agent_code='file_check',
capabilities={'task_progress': True},
)
assert is_file_check_runtime_ready(ready) is True
assert is_file_check_runtime_ready(misconfigured) is False
@@ -0,0 +1,48 @@
"""
tests/test_agent_registry_serialization.py
用途:Agent Registry 序列化契约(Admin API Key 脱敏等)。
"""
from types import SimpleNamespace
from app.services.agent_registry.serialization import mask_dify_api_key, serialize_agent_for_admin
def test_mask_dify_api_key():
assert mask_dify_api_key('') == ''
assert mask_dify_api_key('short') == '****'
assert mask_dify_api_key('sk-abcdefghijklmnop') == 'sk-a****mnop'
def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
agent = SimpleNamespace(
id=1,
name='Bot',
description='',
icon_url=None,
is_active=True,
type='api',
dify_app_id='app-1',
dify_api_key='sk-secret-key-12345678',
api_base_url=None,
extra_config={},
agent_code='generic',
runtime_provider='dify',
conversation_mode='chat',
dify_app_type='chatflow',
iframe_url=None,
category=None,
sub_category=None,
sort_order=0,
welcome_message=None,
suggested_questions_style='plain',
suggested_questions=[],
capabilities={'streaming': True},
file_upload_policy=None,
bound_schedule_task_id=None,
handler_config=None,
)
payload = serialize_agent_for_admin(agent)
assert 'dify_api_key' not in payload
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
@@ -0,0 +1,16 @@
"""
tests/test_agent_registry_type_catalog_api.py
用途:Admin type-catalog API 集成测试。
"""
from app.services.agent_registry.catalog import AGENT_TYPE_CATALOG, list_type_catalog
def test_list_type_catalog_returns_registered_types():
catalog = list_type_catalog()
codes = {item['agent_code'] for item in catalog}
assert codes == set(AGENT_TYPE_CATALOG.keys())
for item in catalog:
assert item.get('label')
assert item.get('runtime_provider_default')
assert item.get('conversation_mode_default')
@@ -2,8 +2,8 @@
backend/tests/test_agent_runtime_context_generic_adapter.py
用途:验证 generic adapter 与统一 Dify inputs 分发入口的兜底行为。
依赖:agent_runtime_context.adapters.generic、agent_runtime_context.dify_inputs、pytest。
逻辑:覆盖通用 Agent 的最小 runtime_context 序列化,以及 shipping/file_check/generic 三类分发路径。
依赖:agent_runtime_context.adapters.generic、agent_runtime_context.registry、pytest。
逻辑:覆盖通用 Agent 的最小 runtime_context 序列化,以及 shipping/file_check/generic 三类 Registry 分发路径。
"""
from __future__ import annotations
@@ -11,178 +11,194 @@ from __future__ import annotations
import json
from types import SimpleNamespace
import app.services.agent_runtime_context.dify_inputs as dify_inputs_module
import pytest
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.agent_runtime_context.adapters.generic import (
build_generic_dify_inputs,
resolve_agent_code,
)
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.agent_runtime_context.bootstrap import load_context_adapters
from app.services.agent_runtime_context.registry import build_chat_dify_inputs
def test_resolve_agent_code_reads_extra_config_or_falls_back_to_generic():
"""通用 adapter 应优先读取 extra_config.agent_code,缺省时回退为 generic。"""
configured_agent = SimpleNamespace(extra_config={"agent_code": "kb_faq_agent"})
default_agent = SimpleNamespace(extra_config={})
assert resolve_agent_code(configured_agent) == "kb_faq_agent"
assert resolve_agent_code(default_agent) == "generic"
@pytest.fixture(autouse=True)
def _load_context_adapters():
"""每条用例前确保 Context Adapter Registry 已加载。"""
load_context_adapters()
def test_build_generic_dify_inputs_outputs_only_agent_runtime_context_json():
"""generic adapter 应只输出 agent_runtime_context,且其内容必须可解析。"""
agent = SimpleNamespace(
description="知识库常见问题问答",
def _agent(**kwargs):
defaults = {
'type': 'api',
'agent_code': 'generic',
'runtime_provider': 'dify',
'conversation_mode': 'chat',
'bound_schedule_task_id': None,
'capabilities': None,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_resolve_agent_code_reads_column_not_extra_config():
"""只读 agent_code 列;extra_config 中的 agent_code 不参与运行时解析。"""
column_agent = _agent(agent_code='kb_faq_agent', extra_config={'agent_code': 'generic'})
default_agent = _agent(extra_config={})
assert resolve_agent_code(column_agent) == 'kb_faq_agent'
assert resolve_agent_code(default_agent) == 'generic'
def test_build_generic_dify_inputs_uses_description_not_extra_summary():
"""domain.summary 应只读 description 列,忽略 extra_config.runtime_context_summary。"""
agent = _agent(
description='知识库常见问题问答',
agent_code='kb_faq_agent',
extra_config={
"agent_code": "kb_faq_agent",
"runtime_context_summary": "知识库问答助手",
'runtime_context_summary': 'extra 摘要不应生效',
},
)
inputs = build_generic_dify_inputs(
session_id="conv-generic-001",
session_id='conv-generic-001',
agent=agent,
request_id="req-generic-001",
trigger_source="frontend_chat",
request_id='req-generic-001',
trigger_source='frontend_chat',
)
assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
assert payload["agent_code"] == "kb_faq_agent"
assert payload["platform"]["session_id"] == "conv-generic-001"
assert payload["platform"]["request_id"] == "req-generic-001"
assert payload["domain"] == {
"type": "generic",
"summary": "知识库问答助手",
assert payload['agent_code'] == 'kb_faq_agent'
assert payload['platform']['session_id'] == 'conv-generic-001'
assert payload['domain'] == {
'type': 'generic',
'summary': '知识库常见问题问答',
}
def test_build_chat_dify_inputs_dispatches_shipping_adapter(monkeypatch):
"""shipping Agent 应从 adapter_hints 读取业务提示,而不是暴露平台级 task/batch 参数。"""
agent = SimpleNamespace(name="货代发货通知 Agent", extra_config={})
agent = _agent(
name='货代发货通知 Agent',
agent_code='shipping_notice',
runtime_provider='hybrid',
conversation_mode='task_chat',
extra_config={},
)
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_shipping_notice_dify_inputs",
'app.services.shipping_notice.context_adapter.build_dify_chat_inputs',
lambda conversation_id, **kwargs: {
"adapter": "shipping",
"conversation_id": conversation_id,
"task_id": kwargs.get("task_id"),
"batch_no": kwargs.get("batch_no"),
'adapter': 'shipping',
'conversation_id': conversation_id,
'task_id': kwargs.get('task_id'),
'batch_no': kwargs.get('batch_no'),
},
)
inputs = build_chat_dify_inputs(
agent,
session_id="conv-shipping-001",
session_id='conv-shipping-001',
adapter_hints={
"shipping_notice": {
"task_id": "SN-001",
"batch_no": "BATCH-001",
'shipping_notice': {
'task_id': 'SN-001',
'batch_no': 'BATCH-001',
}
},
)
assert inputs == {
"adapter": "shipping",
"conversation_id": "conv-shipping-001",
"task_id": "SN-001",
"batch_no": "BATCH-001",
'adapter': 'shipping',
'conversation_id': 'conv-shipping-001',
'task_id': 'SN-001',
'batch_no': 'BATCH-001',
}
def test_build_chat_dify_inputs_dispatches_file_check_adapter(monkeypatch):
"""file_check Agent 应继续沿用 task_id 专用 inputs,不自动混入 generic 上下文。"""
agent = SimpleNamespace(name="文件检核 Agent", extra_config={})
agent = _agent(
name='文件检核 Agent',
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
extra_config={'capabilities': ['tool_run_progress']},
)
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_file_check_dify_inputs",
lambda current_agent, required: {
"adapter": "file_check",
"agent_name": current_agent.name,
"required": required,
'app.services.file_check_tools.context_adapter.build_file_check_dify_inputs',
lambda current_agent, required, **kwargs: {
'adapter': 'file_check',
'agent_name': current_agent.name,
'required': required,
'session_id': kwargs.get('session_id'),
},
)
inputs = build_chat_dify_inputs(agent, session_id="conv-file-check-001")
inputs = build_chat_dify_inputs(agent, session_id='conv-file-check-001')
assert inputs == {
"adapter": "file_check",
"agent_name": "文件检核 Agent",
"required": True,
'adapter': 'file_check',
'agent_name': '文件检核 Agent',
'required': True,
'session_id': 'conv-file-check-001',
}
def test_build_chat_dify_inputs_falls_back_to_generic_adapter(monkeypatch):
"""未命中专用 adapter 的 Agent 应统一走 generic 兜底。"""
agent = SimpleNamespace(name="知识库问答 Agent", extra_config={})
agent = _agent(name='知识库问答 Agent', extra_config={})
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_generic_dify_inputs",
'app.services.agent_runtime_context.adapters.generic.build_generic_dify_inputs',
lambda **kwargs: {
"adapter": "generic",
"session_id": kwargs["session_id"],
'adapter': 'generic',
'session_id': kwargs['session_id'],
},
)
inputs = build_chat_dify_inputs(agent, session_id="conv-generic-002")
inputs = build_chat_dify_inputs(agent, session_id='conv-generic-002')
assert inputs == {
"adapter": "generic",
"session_id": "conv-generic-002",
'adapter': 'generic',
'session_id': 'conv-generic-002',
}
def test_build_chat_dify_inputs_ignores_invalid_shipping_hints(monkeypatch):
"""shipping hints 非字典时应安全回退为空,避免平台入口依赖脏业务结构。"""
agent = SimpleNamespace(name="货代发货通知 Agent", extra_config={})
agent = _agent(
name='货代发货通知 Agent',
agent_code='shipping_notice',
runtime_provider='hybrid',
conversation_mode='task_chat',
extra_config={},
)
monkeypatch.setattr(dify_inputs_module, "is_shipping_notice_chat_agent", lambda _: True)
monkeypatch.setattr(dify_inputs_module, "agent_declares_file_check_progress", lambda _: False)
monkeypatch.setattr(dify_inputs_module, "is_file_check_chat_agent", lambda _: False)
monkeypatch.setattr(
dify_inputs_module,
"build_shipping_notice_dify_inputs",
'app.services.shipping_notice.context_adapter.build_dify_chat_inputs',
lambda conversation_id, **kwargs: {
"conversation_id": conversation_id,
"task_id": kwargs.get("task_id"),
"batch_no": kwargs.get("batch_no"),
'conversation_id': conversation_id,
'task_id': kwargs.get('task_id'),
'batch_no': kwargs.get('batch_no'),
},
)
inputs = build_chat_dify_inputs(
agent,
session_id="conv-shipping-002",
adapter_hints={"shipping_notice": "invalid"},
session_id='conv-shipping-002',
adapter_hints={'shipping_notice': 'invalid'},
)
assert inputs == {
"conversation_id": "conv-shipping-002",
"task_id": None,
"batch_no": None,
'conversation_id': 'conv-shipping-002',
'task_id': None,
'batch_no': None,
}
def test_build_chat_dify_inputs_returns_empty_when_session_id_missing(monkeypatch):
def test_build_chat_dify_inputs_returns_empty_when_session_id_missing():
"""统一分发入口在缺少 session_id 时应直接返回空 dict。"""
agent = SimpleNamespace(name="任意 Agent", extra_config={})
monkeypatch.setattr(
dify_inputs_module,
"is_shipping_notice_chat_agent",
lambda _: (_ for _ in ()).throw(AssertionError("should not dispatch when session_id is empty")),
)
assert build_chat_dify_inputs(agent, session_id=" ") == {}
agent = _agent(name='任意 Agent', extra_config={})
assert build_chat_dify_inputs(agent, session_id=' ') == {}
@@ -0,0 +1,97 @@
"""
backend/tests/test_agent_runtime_context_registry.py
用途:验证 Context Adapter Registry 注册、code 解析与 build_chat_dify_inputs 分发。
依赖:agent_runtime_context.bootstrap、registry、pytest。
逻辑:迭代 2 验收 — Registry 含三类 adapter;未知 code 回退 generic;不再依赖名称 if/elif。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.agent_registry.resolver import resolve_agent_code
from app.services.agent_runtime_context.bootstrap import load_context_adapters
from app.services.agent_runtime_context.registry import (
CONTEXT_ADAPTER_REGISTRY,
build_chat_dify_inputs,
register_context_adapter,
resolve_context_adapter_code,
)
@pytest.fixture(autouse=True)
def _load_context_adapters():
"""每条用例前确保 adapter 已注册。"""
load_context_adapters()
def test_context_adapter_registry_contains_seed_adapters():
"""启动加载后 Registry 须含 generic、shipping_notice、file_check。"""
assert {'generic', 'shipping_notice', 'file_check'}.issubset(set(CONTEXT_ADAPTER_REGISTRY.keys()))
def test_resolve_context_adapter_code_falls_back_to_generic():
"""未知 agent_code 应回退 generic adapter。"""
assert resolve_context_adapter_code('kb_faq_agent') == 'generic'
assert resolve_context_adapter_code('') == 'generic'
def test_build_chat_dify_inputs_routes_by_agent_code_not_agent_name(monkeypatch):
"""分发应基于 resolve_agent_code,而非 is_shipping_notice_chat_agent 名称判断。"""
agent = SimpleNamespace(
name='知识库问答 Agent',
type='api',
extra_config={'agent_code': 'shipping_notice'},
agent_code='shipping_notice',
runtime_provider='hybrid',
conversation_mode='task_chat',
)
monkeypatch.setattr(
'app.services.shipping_notice.context_adapter.build_dify_chat_inputs',
lambda conversation_id, **kwargs: {'adapter': 'shipping', 'conversation_id': conversation_id},
)
inputs = build_chat_dify_inputs(agent, session_id='conv-by-code-001')
assert inputs == {'adapter': 'shipping', 'conversation_id': 'conv-by-code-001'}
def test_build_chat_dify_inputs_routes_file_check_by_registered_agent_code(monkeypatch):
"""agent_code=file_check 列已注册时应走 file_check adapter。"""
agent = SimpleNamespace(
name='RoHS 检核',
type='api',
extra_config={},
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
bound_schedule_task_id=7,
)
assert resolve_agent_code(agent) == 'file_check'
monkeypatch.setattr(
'app.services.file_check_tools.context_adapter.build_file_check_dify_inputs',
lambda current_agent, required, **kwargs: {
'adapter': 'file_check',
'task_id': '7',
'required': required,
},
)
inputs = build_chat_dify_inputs(agent, session_id='conv-file-check-002')
assert inputs['adapter'] == 'file_check'
assert inputs['task_id'] == '7'
def test_register_context_adapter_allows_custom_code():
"""register_context_adapter 装饰器应写入 Registry。"""
@register_context_adapter('custom_test_adapter')
def _custom_adapter(**kwargs):
return {'custom': True}
assert 'custom_test_adapter' in CONTEXT_ADAPTER_REGISTRY
assert CONTEXT_ADAPTER_REGISTRY['custom_test_adapter'](agent=None, session_id='x') == {'custom': True}
@@ -0,0 +1,166 @@
"""
tests/test_chat_dify_start_inputs.py
用途:迭代 5 验收 — Executor / completions 向 Dify Start 注入 agent_runtime_context。
依赖:agent_runtime_context.bootstrap、chat.executors、models、pytest。
逻辑:覆盖 generic / shipping_notice / file_check 三类 Agent 的 Dify inputs 契约。
"""
from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
from app.models import ShippingBatch, ShippingTask, User
from app.services.agent_registry.handlers.base import ChatStreamContext
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.agent_runtime_context.bootstrap import load_context_adapters
from app.services.agent_runtime_context.registry import build_chat_dify_inputs
from app.services.chat.executors import stream_chat_via_executor
from app.services.file_check_tools.dify_inputs import FILE_CHECK_TASK_ID_INPUT
@pytest.fixture(autouse=True)
def _load_adapters():
load_context_adapters()
def _agent(**kwargs):
defaults = {
'id': 1,
'name': 'Test Agent',
'dify_api_key': 'sk-test',
'agent_code': 'generic',
'runtime_provider': 'dify',
'dify_app_type': 'chatflow',
'capabilities': None,
'extra_config': {},
'bound_schedule_task_id': None,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_dify_executor_injects_generic_agent_runtime_context(app, monkeypatch):
"""generic Agent 经 Executor 调用 Dify 时应携带 agent_runtime_context Start 变量。"""
captured: dict = {}
def fake_stream_chat(*args, **kwargs):
captured['inputs'] = kwargs.get('inputs')
yield 'data: {"event":"message_end"}\n\n'
monkeypatch.setattr(
'app.services.chat.executors.dify_chat.DifyService.stream_chat',
staticmethod(fake_stream_chat),
)
with app.app_context():
ctx = ChatStreamContext(
query='平台能力说明',
display_query='平台能力说明',
user=SimpleNamespace(id=1),
agent=_agent(agent_code='generic', description='通用问答'),
session=SimpleNamespace(session_id='conv-generic-start-001'),
external_conversation_id=None,
request_id='req-generic-start-001',
)
list(stream_chat_via_executor(ctx))
assert isinstance(captured.get('inputs'), dict)
assert set(captured['inputs'].keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
payload = json.loads(captured['inputs'][AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['agent_code'] == 'generic'
assert payload['platform']['session_id'] == 'conv-generic-start-001'
assert payload['platform']['request_id'] == 'req-generic-start-001'
assert payload['domain']['type'] == 'generic'
def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch):
"""shipping_notice hybrid Agent 应注入含 refs 的 agent_runtime_context。"""
from app import db
from app.services.agent_registry.handlers.bootstrap import load_handlers
captured: dict = {}
def fake_stream_chat(*args, **kwargs):
captured['inputs'] = kwargs.get('inputs')
yield 'data: {"event":"message_end"}\n\n'
monkeypatch.setattr(
'app.services.chat.executors.dify_chat.DifyService.stream_chat',
staticmethod(fake_stream_chat),
)
with app.app_context():
load_handlers()
batch = ShippingBatch(
batch_no='SB-START-001',
conversation_id='conv-shipping-start-001',
current_focus_task_no='SN-START-001',
file_count=1,
)
task = ShippingTask(
task_no='SN-START-001',
batch=batch,
conversation_id='conv-shipping-start-001',
source_type='manual',
process_status='created',
)
db.session.add_all([batch, task])
db.session.commit()
ctx = ChatStreamContext(
query='继续',
display_query='继续',
user=SimpleNamespace(id=1),
agent=_agent(
agent_code='shipping_notice',
runtime_provider='hybrid',
conversation_mode='task_chat',
),
session=SimpleNamespace(session_id='conv-shipping-start-001'),
external_conversation_id=None,
request_id='req-shipping-start-001',
adapter_hints={
'shipping_notice': {
'task_id': 'SN-START-001',
'batch_no': 'SB-START-001',
}
},
shipping_task_id='SN-START-001',
shipping_batch_no='SB-START-001',
)
list(stream_chat_via_executor(ctx))
payload = json.loads(captured['inputs'][AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['agent_code'] == 'shipping_notice'
assert payload['refs']['task_no'] == 'SN-START-001'
assert payload['refs']['batch_no'] == 'SB-START-001'
assert payload['reference_context']['focus_object']['id'] == 'SN-START-001'
def test_file_check_adapter_outputs_task_id_and_runtime_context(app):
"""file_check Agent 应同时输出 task_id 与 agent_runtime_context(迭代 5)。"""
agent = _agent(
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
name='RoHS 检核 Agent',
bound_schedule_task_id=42,
)
with app.app_context():
inputs = build_chat_dify_inputs(
agent,
session_id='conv-file-check-start-001',
request_id='req-file-check-001',
)
assert inputs[FILE_CHECK_TASK_ID_INPUT] == '42'
assert AGENT_RUNTIME_CONTEXT_INPUT in inputs
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
assert payload['agent_code'] == 'file_check'
assert payload['refs']['schedule_task_id'] == '42'
assert payload['domain']['state_hint']['schedule_task_id'] == '42'
@@ -0,0 +1,95 @@
"""
tests/test_chat_executors_registry.py
用途:RUNTIME_PROVIDER_REGISTRY 与 Hybrid Executor 单元测试。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.core.errors import AgentHandlerNotConfiguredError
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
from app.services.agent_runtime_context.bootstrap import load_context_adapters
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
from app.services.agent_registry.resolver import resolve_handler, resolve_runtime_provider
from app.services.chat.executors import resolve_chat_executor, stream_chat_via_executor
from app.services.agent_registry.handlers.base import ChatStreamContext
def _agent(**kwargs):
defaults = {
'id': 1,
'name': 'Test',
'dify_api_key': 'sk-test',
'agent_code': 'generic',
'runtime_provider': 'dify',
'dify_app_type': 'chatflow',
'capabilities': None,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_resolve_chat_executor_dify():
executor = resolve_chat_executor(_agent(runtime_provider='dify'))
assert executor.provider_key == 'dify'
def test_resolve_chat_executor_rejects_iframe():
from app.core.errors import ValidationError
with pytest.raises(ValidationError, match='iframe'):
resolve_chat_executor(_agent(runtime_provider='iframe'))
def test_hybrid_requires_registered_handler(app):
with app.app_context():
load_handlers()
agent = _agent(agent_code='shipping_notice', runtime_provider='hybrid')
handler = resolve_handler(agent)
assert handler is not None
assert handler.handler_key == 'shipping_notice'
def test_hybrid_missing_handler_raises(app):
with app.app_context():
reset_handlers_for_tests()
agent = _agent(agent_code='shipping_notice', runtime_provider='hybrid')
with pytest.raises(AgentHandlerNotConfiguredError) as exc_info:
resolve_handler(agent)
# AppError 为 dataclass,str(exc) 为空;断言 code 与 message 字段。
assert exc_info.value.code == 'AGENT.HANDLER_NOT_CONFIGURED'
assert 'Handler' in exc_info.value.message
load_handlers()
def test_stream_chat_via_executor_delegates_to_dify(app, monkeypatch):
with app.app_context():
load_handlers()
load_context_adapters()
captured = {}
def fake_stream_chat(*args, **kwargs):
captured['kwargs'] = kwargs
yield 'data: {"event":"message_end"}\n\n'
monkeypatch.setattr(
'app.services.chat.executors.dify_chat.DifyService.stream_chat',
staticmethod(fake_stream_chat),
)
ctx = ChatStreamContext(
query='hello',
display_query='hello',
user=SimpleNamespace(id=1),
agent=_agent(),
session=SimpleNamespace(session_id='sess-1'),
external_conversation_id=None,
request_id='req-1',
)
lines = list(stream_chat_via_executor(ctx))
assert lines
assert captured['kwargs']['session_id'] == 'sess-1'
inputs = captured['kwargs'].get('inputs') or {}
assert 'agent_runtime_context' in inputs
+271
View File
@@ -0,0 +1,271 @@
"""
tests/test_chat_router.py
用途:Chat Intent Router 快路径分发与 intent_routes 门控契约。
依赖:chat.router、pytest monkeypatch。
逻辑:验证 try_fast_route 优先级、未命中回退 None、附件校验与 route_name。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
from app.services.chat.router import FastRouteResult, try_fast_route
@pytest.fixture(autouse=True)
def _load_builtin_routes():
ensure_intent_routes_loaded()
def _agent(**kwargs):
defaults = {
'id': 1,
'name': '测试 Agent',
'agent_code': 'generic',
'runtime_provider': 'dify',
'handler_config': {},
'extra_config': {},
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def _user(**kwargs):
defaults = {'id': 10, 'username': 'tester'}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_try_fast_route_faq_cache(monkeypatch):
"""FAQ 命中时应返回 faq_cache 路由。"""
faq_entry = object()
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: faq_entry),
)
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.stream_chat',
staticmethod(lambda *args, **kwargs: iter(['data: {"event":"message","answer":"cached"}\n\n'])),
)
result = try_fast_route(
user=_user(),
agent=_agent(),
query='常见问题',
agent_id=1,
session_id='sess-faq',
)
assert isinstance(result, FastRouteResult)
assert result.route_name == 'faq_cache'
assert list(result.generator)
def test_try_fast_route_maintenance(monkeypatch):
"""声明 maintenance_chat route 且问句命中时应返回 maintenance_chat 路由。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: True),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.stream_chat',
staticmethod(lambda *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
)
result = try_fast_route(
user=_user(),
agent=_agent(handler_config={'intent_routes': ['maintenance_chat']}),
query='查设备 D001',
agent_id=1,
session_id='sess-maint',
)
assert result is not None
assert result.route_name == 'maintenance_chat'
def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
"""声明 hr_leave_sql route + 假期问句应走 hr_leave_sql。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
monkeypatch.setattr(
'app.services.hr_leave_sqlserver.HRLeaveSQLServerService.stream_chat',
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
)
result = try_fast_route(
user=_user(),
agent=_agent(handler_config={'intent_routes': ['hr_leave_sql']}),
query='我还有多少年假',
agent_id=1,
session_id='sess-hr',
leave_supported=True,
)
assert result is not None
assert result.route_name == 'hr_leave_sql'
def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
"""ERP 知识库且声明 text2sql route 时应走 text2sql 快路径。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
monkeypatch.setattr(
'app.services.text2sql.Text2SQLService.stream_chat',
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
)
result = try_fast_route(
user=_user(),
agent=_agent(
handler_config={'intent_routes': ['text2sql']},
capabilities={'erp_kb': True},
),
query='本月销售额',
agent_id=1,
session_id='sess-erp',
leave_supported=False,
kb_type='ERP知识库',
)
assert result is not None
assert result.route_name == 'text2sql'
def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
"""未命中任何快路径时应返回 None,由 Executor 接管。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
result = try_fast_route(
user=_user(),
agent=_agent(),
query='HXOPS 平台介绍',
agent_id=1,
session_id='sess-generic',
leave_supported=False,
kb_type='企业知识库',
)
assert result is None
def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
"""PLM 快路径携带附件时应跳过 match,回退 Executor。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: True),
)
result = try_fast_route(
user=_user(),
agent=_agent(handler_config={'intent_routes': ['plm_oracle']}),
query='查 BOM',
agent_id=1,
session_id='sess-plm',
normalized_files=[{'type': 'document', 'transfer_method': 'local_file', 'upload_file_id': 'f1'}],
)
assert result is None
def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
"""假期问句但 Agent 未声明 hr_leave_sql 时不应走 HR 快路径。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
result = try_fast_route(
user=_user(),
agent=_agent(handler_config={}),
query='我还有多少年假',
agent_id=1,
session_id='sess-leave-fallback',
leave_supported=True,
)
assert result is None
def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
"""ERP 知识库但未声明 text2sql route 时不应走 Text2SQL 快路径。"""
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: None),
)
monkeypatch.setattr(
'app.services.maintenance_chat_service.MaintenanceChatService.supports',
staticmethod(lambda query, agent: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
result = try_fast_route(
user=_user(),
agent=_agent(handler_config={}),
query='查资产',
agent_id=1,
session_id='sess-erp-fallback',
leave_supported=False,
kb_type='ERP知识库',
)
assert result is None
+158
View File
@@ -0,0 +1,158 @@
"""
backend/tests/test_chat_turn_runtime.py
覆盖 Chat Turn Runtime 平台层:SSE 生命周期、action 路由、ChatLog 落库与权限校验。
"""
from __future__ import annotations
import json
from app import db
from app.models import Agent, ChatLog, User
def _parse_sse_events(raw: str) -> list[dict]:
events: list[dict] = []
for frame in raw.split("\n\n"):
for line in frame.split("\n"):
if not line.startswith("data: "):
continue
payload = line[6:].strip()
if payload:
events.append(json.loads(payload))
return events
def _create_shipping_agent() -> Agent:
agent = Agent(
name="货代发货通知 Agent",
description="test",
dify_api_key="test-key",
api_base_url="http://example.com",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
return agent
def _create_user() -> User:
user = User(username="chat_turn_user", email="chat_turn_user@example.com", role="admin", status="active")
user.set_password("password")
db.session.add(user)
db.session.commit()
return user
def _create_task_for_user(user_id: int) -> str:
from app.models import ShippingBatch, ShippingTask
batch = ShippingBatch(
batch_no="BATCH-TURN-001",
user_id=user_id,
file_count=1,
)
task = ShippingTask(
task_no="SN-20260706-ABCD1234",
batch=batch,
user_id=user_id,
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
return task.task_no
def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch):
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
monkeypatch.setattr(
"app.services.shipping_notice.chat_action_handlers.submit_decision",
lambda payload: {
"status": "ok",
"message": "已确认,请继续下一步。",
"task_id": task_no,
"data": {},
},
)
res = client.post(
"/api/chat/turns/stream",
headers={
"X-Username": user.username,
"X-Role": user.role,
"Content-Type": "application/json",
},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.submit_decision",
"payload": {"task_no": task_no, "decision": "confirm"},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "step.started" in event_names
assert "message.completed" in event_names or "message_end" in event_names
assert "run.completed" in event_names
logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
assert len(logs) == 1
assert logs[0].query == "确认"
assert "已确认" in logs[0].answer
def test_chat_turn_unknown_action_returns_failed(app, client):
user = _create_user()
agent = _create_shipping_agent()
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "未知动作",
"action_type": "shipping.not_exists",
"payload": {},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
user = _create_user()
agent = Agent(name="通用入口", description="test", dify_api_key="k", api_base_url="http://example.com")
db.session.add(agent)
db.session.commit()
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role, "Content-Type": "application/json"},
json={
"agent_id": agent.id,
"input": {
"type": "action",
"display_text": "确认",
"action_type": "shipping.submit_decision",
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
},
},
)
assert res.status_code == 200
events = _parse_sse_events(res.get_data(as_text=True))
assert any(item.get("event") == "run.failed" for item in events)
+38 -32
View File
@@ -992,33 +992,34 @@ def test_file_check_openapi_injects_tool_api_base(app, client):
def test_file_check_dify_chat_inputs(app):
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
)
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
class _Agent:
def __init__(self, name: str, *, extra_config=None):
def __init__(self, name: str, *, agent_code='file_check', capabilities=None, bound_schedule_task_id=None):
self.name = name
self.extra_config = extra_config or {}
self.agent_code = agent_code
self.capabilities = capabilities or {'task_progress': True}
self.bound_schedule_task_id = bound_schedule_task_id
self.extra_config = {}
assert is_file_check_chat_agent(_Agent(
assert is_file_check_runtime_ready(_Agent(
'RoHS文件检核助手',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
bound_schedule_task_id=12,
))
assert not is_file_check_runtime_ready(_Agent('RoHS文件检核助手'))
assert not is_file_check_runtime_ready(_Agent(
'货代发货通知 Agent',
agent_code='shipping_notice',
capabilities={},
))
assert not is_file_check_chat_agent(_Agent('RoHS文件检核助手'))
assert not is_file_check_chat_agent(_Agent('货代发货通知 Agent'))
agent = _Agent(
'RoHS文件检核助手',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
bound_schedule_task_id=12,
)
with app.app_context():
inputs = build_file_check_dify_inputs(agent)
@@ -1052,9 +1053,9 @@ def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(
import pytest
from app.core.errors import ValidationError
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
from app.services.agent_registry.resolver import (
agent_declares_task_progress,
is_file_check_runtime_ready,
)
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
@@ -1065,14 +1066,14 @@ def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(
def __init__(self):
self.id = 26
self.name = 'RoHS文件检核助手'
self.extra_config = {
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
}
self.agent_code = 'file_check'
self.capabilities = {'task_progress': True}
self.bound_schedule_task_id = None
self.extra_config = {}
agent = _Agent()
assert agent_declares_file_check_progress(agent)
assert not is_file_check_chat_agent(agent)
assert agent_declares_task_progress(agent)
assert not is_file_check_runtime_ready(agent)
with app.app_context():
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(agent, required=True)
@@ -1092,6 +1093,8 @@ def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
type='api',
agent_code='file_check',
capabilities={'task_progress': True},
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
@@ -1123,11 +1126,11 @@ def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker
mock_post.assert_not_called()
def test_chat_agent_proxy_passes_extra_config_for_task_id_injection():
"""chat.py agent_proxy 须携带 extra_config,否则 is_file_check_chat_agent / task_id 注入失效。"""
def test_chat_agent_proxy_passes_registry_columns_for_task_id_injection():
"""chat.py agent_proxy 须携带 Registry 列,否则 task_id 注入失效。"""
from types import SimpleNamespace
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.agent_registry.resolver import is_file_check_runtime_ready
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
@@ -1136,23 +1139,26 @@ def test_chat_agent_proxy_passes_extra_config_for_task_id_injection():
agent_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
agent_code='file_check',
capabilities={'task_progress': True},
bound_schedule_task_id=12,
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
extra_config={},
)
assert is_file_check_chat_agent(agent_proxy)
assert is_file_check_runtime_ready(agent_proxy)
assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12'
bare_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
agent_code='generic',
capabilities={},
bound_schedule_task_id=None,
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
)
assert not is_file_check_chat_agent(bare_proxy)
assert not is_file_check_runtime_ready(bare_proxy)
assert build_file_check_dify_inputs(bare_proxy) == {}
+2
View File
@@ -208,6 +208,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
"task_no": "SN-20260629-2EDADC77",
"success": True,
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
"rpa_mode": "browser",
"source_code": "DSV360_AWSDU",
},
)
@@ -259,6 +260,7 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
"task_no": "SN-20260629-2EDADC77",
"success": True,
"file_path": str(exported),
"rpa_mode": "mock",
"source_code": "DSV360_AWSDU",
},
)
@@ -0,0 +1,78 @@
"""
backend/tests/test_shipping_chat_action_handlers.py
覆盖货代 Chat Action Handler 与业务 workflow 的集成(不依赖 Dify)。
"""
from __future__ import annotations
from app import db
from app.models import Agent, User
from app.services.chat.action_schema import TurnInput
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice.chat_action_handlers import ShippingGenerateExcelAction
def _create_task(user_id: int) -> str:
from app.models import ShippingBatch, ShippingTask
batch = ShippingBatch(batch_no="BATCH-HANDLER-001", user_id=user_id, file_count=1)
task = ShippingTask(
task_no="SN-20260706-EFGH5678",
batch=batch,
user_id=user_id,
source_type="manual",
process_status="matched",
match_status="ok",
)
db.session.add_all([batch, task])
db.session.commit()
return task.task_no
def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
user = User(username="handler_user", email="handler_user@example.com", role="admin", status="active")
user.set_password("password")
db.session.add(user)
db.session.commit()
task_no = _create_task(user.id)
agent = Agent(
name="货代发货通知 Agent",
description="t",
dify_api_key="k",
api_base_url="http://example.com",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
monkeypatch.setattr(
"app.services.shipping_notice.chat_action_handlers.shipping_tools.generate_excel",
lambda payload: {"status": "ok", "message": "Excel 已生成。", "task_id": task_no, "data": {}},
)
ctx = TurnContext(
turn_id="turn-001",
run_id="turn-001",
session_id="sess-001",
request_id="req-001",
user=user,
agent=agent,
input=TurnInput(
type="action",
display_text="生成发货 Excel",
action_type="shipping.generate_excel",
payload={"task_no": task_no},
),
refs={"task_no": task_no},
)
handler = ShippingGenerateExcelAction()
events = list(handler.stream(ctx))
event_names = [event.event for event in events]
assert "step.started" in event_names
assert "ui_state.updated" in event_names
assert "message.completed" in event_names
completed = next(item for item in events if item.event == "message.completed")
assert "Excel 已生成" in str(completed.data.get("content") or "")
+21 -3
View File
@@ -938,6 +938,12 @@ def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client)
batch_state = _unwrap_ok(batch_state_res)
assert task_state["checkpoint"] == "shortage_review"
assert [item["id"] for item in task_state["action_buttons"]] == [
"reparse_inventory",
"rematch",
"reject",
]
assert "correct_inventory_mapping" not in [item["id"] for item in task_state["action_buttons"]]
assert task_detail["ui_state"]["action_buttons"] == task_state["action_buttons"]
assert task_state["current_step"]["status"] == "blocked"
assert batch_detail["focus_task_ui_state"]["task_no"] == "SN-UI-STATE-001"
@@ -959,6 +965,9 @@ def test_chat_completions_streams_shipping_ui_state(app, client, monkeypatch):
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
dify_api_key="test-dify-key",
api_base_url="http://dify.example/v1",
type="api",
@@ -1610,12 +1619,21 @@ def test_build_dify_chat_inputs_does_not_fallback_to_latest_task_without_explici
assert runtime_context["refs"] == {"run_purpose": "chat_turn"}
def test_is_shipping_notice_chat_agent_accepts_current_dify_app_name():
"""兼容 Dify 侧当前使用的智能发货通知Agent命名。"""
def test_shipping_notice_agent_code_from_resolver():
"""发货通知识别应基于 resolve_agent_code,不再提供 dify_inputs 名称启发式。"""
from app.services.agent_registry.resolver import resolve_agent_code
class AgentLike:
name = "智能发货通知Agent"
agent_code = "shipping_notice"
assert dify_inputs.is_shipping_notice_chat_agent(AgentLike()) is True
assert resolve_agent_code(AgentLike()) == "shipping_notice"
class GenericLike:
name = "智能发货通知Agent"
agent_code = "generic"
assert resolve_agent_code(GenericLike()) != "shipping_notice"
def test_create_empty_batch_returns_batch_shell(app, client):
@@ -25,15 +25,15 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
)
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=False) == "当前配置为单次自动尝试"
assert _inventory_rpa_running_prefix(attempt_no=1, max_attempts=1) == "RPA 库存导出进行中。"
assert _inventory_rpa_triggered_prefix(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发 RPA 库存导出。"
assert _inventory_rpa_running_prefix(attempt_no=1, max_attempts=1) == "库存获取进行中。"
assert _inventory_rpa_triggered_prefix(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发库存获取。"
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=True) == "手动第 1 次尝试"
assert _inventory_rpa_running_message(attempt_no=1, max_attempts=1) == "RPA 库存导出进行中。请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
assert _inventory_rpa_running_message(attempt_no=1, max_attempts=1) == "库存获取进行中。请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
assert _inventory_rpa_triggered_message(
attempt_no=1,
max_attempts=1,
manual_retry_round=False,
) == "已触发 RPA 库存导出。若长时间无结果,可手动重试,或上传库存 Excel。"
) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。"
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
@@ -123,16 +123,19 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
json={"task_no": task_id, "success": True, "file_path": str(inv_file), "rpa_mode": "browser"},
)
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") in {"align_review", "map_infer"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
assert data.get("data", {}).get("rpa_runtime", {}).get("mode") == "browser"
assert data.get("data", {}).get("rpa_runtime", {}).get("label") == "真实 RPA"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert (task.step_payload_json or {})["last_inventory_rpa_runtime"]["mode"] == "browser"
assert task.process_status == "inventory_ready"
stored = Path(app.config["SHIPPING_NOTICE_STORAGE_ROOT"]) / "inventory_uploads" / task_id / "inventory.xlsx"
assert stored.is_file()
@@ -183,7 +186,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path):
db.session.refresh(task)
assert result["status"] == "running"
assert "已触发 RPA 库存导出" in result["message"]
assert "已触发库存获取" in result["message"]
assert "长时间无结果" in result["message"]
assert "360s" not in result["message"]
assert task.process_status == "waiting_inventory"
+94 -14
View File
@@ -242,7 +242,8 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
assert confirm_res.get_json()["status"] == "failed"
def test_submit_decision_rematch_reopens_shortage_for_worker(app, client, monkeypatch):
def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client, monkeypatch):
"""重新匹配应同步重算库存,仍有缺口时直接回到库存不足检查点。"""
headers = _tool_headers(app)
started: list[str] = []
@@ -289,22 +290,25 @@ def test_submit_decision_rematch_reopens_shortage_for_worker(app, client, monkey
headers=headers,
json={"task_id": task_id, "decision": "rematch"},
)
data = rematch_res.get_json()
assert rematch_res.status_code == 200
assert rematch_res.get_json()["status"] == "running"
assert started == [task_id]
assert data["status"] == "needs_human"
assert "已重新完成库存匹配" in data["message"]
assert "缺口" in data["message"]
assert started == []
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).one()
assert task.process_status == "inventory_ready"
assert task.review_status is None
assert task.pending_human_reason is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.process_status == "pending_review"
assert task.review_status == "shortage_review"
assert task.pending_human_reason == "shortage"
assert task.match_status is not None
assert task.shortage_json is not None
assert task.line_results_json is not None
def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client, monkeypatch):
"""契约:重新匹配必须通过 submit_decision(rematch) 恢复当前任务,不经 Agent 自由续写。"""
"""契约:重新匹配必须通过 submit_decision(rematch) 同步完成匹配,不经后台 orchestrator 二次点击。"""
headers = _tool_headers(app)
started: list[str] = []
@@ -354,9 +358,10 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client,
data = rematch_res.get_json()
assert rematch_res.status_code == 200
assert data["status"] == "running"
assert data["status"] == "needs_human"
assert data["task_id"] == task_id
assert started == [task_id]
assert "已重新完成库存匹配" in data["message"]
assert started == []
def test_openapi_spec_public(app, client):
@@ -462,6 +467,7 @@ def test_parse_inventory_from_chat_text(app, client):
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
assert "retry_rpa" in [button["id"] for button in data.get("action_buttons") or []]
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
@@ -1430,6 +1436,80 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
assert called.get("task_no") == task_id
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp_path):
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
task.inventory_lines_json = [{"sku": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"sku": "OLD", "status": "ok"}]
task.export_file_path = str(tmp_path / "old.xlsx")
task.export_file_name = "old.xlsx"
task.upload_status = "failed"
task.upload_mode = "rpa"
task.upload_error_message = "old upload failed"
task.freight_ref_no = "OLD-REF"
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"source_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
db.session.commit()
retry_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa"},
)
retry_data = retry_res.get_json()
assert retry_data["status"] == "running"
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "rpa_pending"
assert task.review_status is None
assert task.inventory_lines_json is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.export_file_path is None
assert task.export_file_name is None
assert task.upload_status is None
assert task.upload_error_message is None
assert task.freight_ref_no is None
event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first()
assert event is not None
assert event.detail_json.get("force_refresh") is True
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path):
from datetime import datetime, timedelta
@@ -1741,7 +1821,7 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
return {
"status": "running",
"task_id": payload["task_id"],
"message": "已触发 RPA 库存导出(测试桩)",
"message": "已触发库存获取(测试桩)",
}
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
@@ -1754,7 +1834,7 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已触发 RPA 库存导出(测试桩)"
assert data["message"] == "已触发库存获取(测试桩)"
assert captured["task_id"] == task_id
assert captured["mode"] == "retry_rpa"