feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能

This commit is contained in:
hugo committed 2026-06-16 09:28:37 +08:00
1 parent fa0cdee8df
commit 24310b63b3
35 files changed
+3066 -659

No files matched your search

@@ -5,12 +5,12 @@ import pytest
from app import db
from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
from app.services.rohs_check import RoHSCheckService
from app.services.file_check import FileCheckService
@pytest.fixture(autouse=True)
def _clear_rohs_turn_registry():
from app.services.rohs_check_tools.chat_turn_registry import clear_registry_for_tests
def _clear_file_check_turn_registry():
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
clear_registry_for_tests()
yield
@@ -61,7 +61,7 @@ def _mk_check_task(owner_id: int, *, enabled=True):
return task
def _mk_non_rohs_task(owner_id: int):
def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
@@ -77,8 +77,8 @@ def _mk_non_rohs_task(owner_id: int):
return task
def test_rohs_service_normalizes_failed_workflow():
payload = RoHSCheckService.normalize_workflow_result({
def test_file_check_service_normalizes_failed_workflow():
payload = FileCheckService.normalize_workflow_result({
'status': 'failed',
'error': 'workflow timeout',
'workflow_run_id': 'wf-2',
@@ -88,15 +88,15 @@ def test_rohs_service_normalizes_failed_workflow():
assert payload['workflow_run_id'] == 'wf-2'
def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
class _Agent:
id = 1
def _boom(**kwargs):
raise RuntimeError('dify down')
monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom)
payload = RoHSCheckService.evaluate(
monkeypatch.setattr('app.services.file_check.DifyService.run_workflow_streaming', _boom)
payload = FileCheckService.evaluate(
agent=_Agent(),
run_no='RUN-1',
record='Pb: 100ppm',
@@ -106,8 +106,8 @@ def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
assert payload['error'] == 'dify down'
def test_rohs_service_normalizes_invalid_result():
payload = RoHSCheckService.normalize_workflow_result({
def test_file_check_service_normalizes_invalid_result():
payload = FileCheckService.normalize_workflow_result({
'status': 'succeeded',
'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'},
'workflow_run_id': 'wf-1',
@@ -117,7 +117,7 @@ def test_rohs_service_normalizes_invalid_result():
assert payload['workflow_run_id'] == 'wf-1'
def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
class _Agent:
@@ -134,7 +134,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
writebacks = []
monkeypatch.setattr('app.services.schedule.srm_service.RoHSCheckService.evaluate', _evaluate)
monkeypatch.setattr('app.services.schedule.srm_service.FileCheckService.evaluate', _evaluate)
with app.app_context():
admin = _mk_admin()
db.session.flush()
@@ -158,7 +158,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
log_prefix='row',
)
db.session.refresh(run)
judgement = (run.response_summary_json or {}).get('rohs_judgement') or {}
judgement = (run.response_summary_json or {}).get('file_judgement') or {}
assert total == 1
assert success == 1
@@ -216,55 +216,78 @@ def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch):
assert observed == {'connect_timeout': 7, 'cursor_timeout': 7}
def test_rohs_tool_requires_auth(app, client):
def test_file_check_tool_requires_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/rohs-check/tools/tasks')
res = client.get('/api/file-check/tools/tasks')
assert res.status_code == 401
assert res.get_json()['error_code'] == 'missing_auth'
def test_rohs_tool_rejects_invalid_auth(app, client):
def test_file_check_tool_rejects_invalid_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
assert res.status_code == 401
assert res.get_json()['error_code'] == 'invalid_auth'
def test_rohs_tool_lists_tasks(app, client):
def test_file_check_tool_lists_tasks_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
def test_file_check_tool_lists_task_by_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
_mk_check_task(admin.id)
_mk_non_rohs_task(admin.id)
other_task = _mk_other_check_task(admin.id)
task_id = other_task.id
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
res = client.get(
f'/api/file-check/tools/tasks?task_id={task_id}',
headers={'X-Integration-Key': 'secret'},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001']
assert len(data['tasks']) == 1
assert data['tasks'][0]['task_id'] == task_id
assert data['tasks'][0]['task_no'] == 'CHK-GENERAL-001'
def test_rohs_tool_rejects_non_rohs_task(app, client):
def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_non_rohs_task(admin.id)
task = _mk_other_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 404
assert res.get_json()['error_code'] == 'task_not_found'
assert res.status_code == 200
assert res.get_json()['ok'] is True
def test_rohs_tool_running_conflict(app, client):
def test_file_check_tool_running_conflict(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -276,7 +299,7 @@ def test_rohs_tool_running_conflict(app, client):
db.session.commit()
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
@@ -286,7 +309,7 @@ def test_rohs_tool_running_conflict(app, client):
assert data['error_code'] == 'check_running'
def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
def test_file_check_tool_check_running_records_chat_log_bind_context(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -304,7 +327,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
running_run_id = run.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -322,7 +345,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
assert req.get('bind_user_message') == '立即执行检核'
def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
@@ -332,7 +355,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
def start(self):
return None
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -342,7 +365,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -360,18 +383,18 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
assert req.get('bind_session_id') == 'bind-on-start'
assert req.get('bind_turn_id') == 'turn-abc-001'
assert req.get('bind_user_message') == '执行 RoHS 检核'
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='turn-abc-001') == run_id
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
def test_rohs_tool_requires_task_id(app, client):
def test_file_check_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={},
)
@@ -379,12 +402,12 @@ def test_rohs_tool_requires_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_required'
def test_rohs_tool_rejects_invalid_task_id(app, client):
def test_file_check_tool_rejects_invalid_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': 'abc'},
)
@@ -392,7 +415,15 @@ def test_rohs_tool_rejects_invalid_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_invalid'
def test_rohs_tool_running_conflict_is_global(app, client):
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -417,24 +448,23 @@ def test_rohs_tool_running_conflict_is_global(app, client):
running_id = running.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': second_task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'check_running'
assert data['run']['run_id'] == running_id
assert data['ok'] is True
assert data['run']['task_id'] == second_task_id
def test_rohs_tool_lists_all_rohs_runs(app, client):
def test_file_check_tool_lists_runs_without_task_filter(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
rohs_task = _mk_check_task(admin.id)
other_task = _mk_non_rohs_task(admin.id)
other_task = _mk_other_check_task(admin.id)
db.session.add_all([
ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3),
ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1),
@@ -442,15 +472,15 @@ def test_rohs_tool_lists_all_rohs_runs(app, client):
])
db.session.commit()
res = client.get('/api/rohs-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
res = client.get('/api/file-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['count'] == 2
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'}
assert data['count'] == 3
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002', 'RUN-OTHER-001'}
def test_workspace_rohs_active_run_returns_progress(app, client):
def test_workspace_file_check_active_run_returns_progress(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -480,7 +510,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
db.session.add(run)
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
@@ -491,7 +521,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
assert data['run']['current_step']['row_id'] == 'ROW-16'
def test_workspace_rohs_active_run_filters_by_task_id(app, client):
def test_workspace_file_check_active_run_filters_by_task_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -530,21 +560,21 @@ def test_workspace_rohs_active_run_filters_by_task_id(app, client):
task_b_id = task_b.id
hit = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_a_id}',
f'/api/workspace/file-check/runs/active?task_id={task_a_id}',
headers={'X-Username': 'admin'},
)
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-A'
miss = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_b_id}',
f'/api/workspace/file-check/runs/active?task_id={task_b_id}',
headers={'X-Username': 'admin'},
)
assert miss.status_code == 200
assert miss.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-B'
def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, client):
def test_workspace_file_check_active_run_ignores_conversation_when_task_id_set(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -563,14 +593,14 @@ def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, cl
task_id = task.id
res = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id',
f'/api/workspace/file-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-CONV-MISMATCH'
def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
def test_workspace_file_check_active_run_filters_by_conversation_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -587,16 +617,16 @@ def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
db.session.add(run)
db.session.commit()
miss = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
miss = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
assert miss.status_code == 200
assert miss.get_json()['run'] is None
hit = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
hit = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
def test_workspace_file_check_run_for_log_returns_null_when_unbound(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -614,7 +644,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
@@ -623,7 +653,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
assert payload.get('match_source') is None
def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
def test_workspace_file_check_run_for_log_reads_bound_run_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -652,7 +682,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
@@ -661,7 +691,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
assert payload['match_source'] == 'chat_log'
def test_workspace_rohs_run_for_log_allows_different_user(app, client):
def test_workspace_file_check_run_for_log_allows_different_user(app, client):
with app.app_context():
owner = User(username='rohs-owner', email='owner-rohs@example.com', role='admin', status='active')
owner.set_password('x')
@@ -694,14 +724,14 @@ def test_workspace_rohs_run_for_log_allows_different_user(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'rohs-viewer'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-CROSS-USER'
def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client):
def test_workspace_file_check_run_for_log_returns_null_when_task_mismatch(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -727,24 +757,24 @@ def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client)
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_workspace_rohs_active_run_returns_null_when_idle(app, client):
def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
with app.app_context():
_mk_admin()
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_rohs_tool_excel_download_uses_signed_token(app, client):
def test_file_check_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -763,19 +793,19 @@ def test_rohs_tool_excel_download_uses_signed_token(app, client):
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/rohs-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
token_url = query_res.get_json()['run']['excel']['download_url']
download_path = token_url[token_url.index('/api/rohs-check'):]
download_path = token_url[token_url.index('/api/file-check'):]
res = client.get(download_path)
assert res.status_code == 200
assert res.data == b'xlsx-bytes'
res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
res = client.get('/api/file-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
assert res.status_code == 401
def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
started_threads = []
class _Thread:
@@ -787,7 +817,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
def start(self):
started_threads.append(self.name)
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -797,7 +827,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
@@ -806,52 +836,199 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
assert data['ok'] is True
assert data['run']['task_id'] == task_id
assert data['run']['status'] == 'running'
assert started_threads == [f"rohs-check-run-{data['run']['run_id']}"]
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
def test_rohs_openapi_injects_tool_api_base(app, client):
def test_serialize_file_judgement_reads_file_key():
from app.api.workspace_file_check import serialize_file_judgement
payload = {
"response_summary_json": {
"file_judgement": {
"qualified_count": 2,
"unqualified_count": 1,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
}
}
result = serialize_file_judgement(payload)
assert result["qualified_count"] == 2
assert result["unqualified_count"] == 1
def test_file_check_openapi_injects_tool_api_base(app, client):
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
res = client.get('/api/rohs-check/tools/openapi.json')
app.config['HXOPS_TOOLS_API_BASE'] = 'https://file-check-tool.example.com'
res = client.get('/api/file-check/tools/openapi.json')
assert res.status_code == 200
assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com'
assert res.get_json()['servers'][0]['url'] == 'https://file-check-tool.example.com'
def test_rohs_dify_chat_inputs(app):
from app.services.rohs_check_tools.dify_inputs import (
HXOPS_TOOL_API_TOKEN_INPUT,
HXOPS_TOOLS_API_BASE_INPUT,
build_dify_chat_inputs,
def test_file_check_dify_chat_inputs(app):
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
)
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
class _Agent:
def __init__(self, name: str):
def __init__(self, name: str, *, extra_config=None):
self.name = name
self.extra_config = extra_config or {}
assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手'))
assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent'))
assert is_file_check_chat_agent(_Agent(
'RoHS文件检核助手',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
))
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},
},
)
with app.app_context():
inputs = build_file_check_dify_inputs(agent)
assert inputs[FILE_CHECK_TASK_ID_INPUT] == '12'
assert 'hxops_session_id' not in inputs
assert 'hxops_turn_id' not in inputs
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
import pytest
from app.errors import ValidationError
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
id = 26
name = 'RoHS文件检核助手'
extra_config = {}
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret'
inputs = build_dify_chat_inputs(hxops_session_id='sess-abc')
assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com'
assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret'
assert inputs['hxops_session_id'] == 'sess-abc'
assert build_file_check_dify_inputs(_Agent()) == {}
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(_Agent(), required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs
def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(app):
import pytest
from app.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.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
def __init__(self):
self.id = 26
self.name = 'RoHS文件检核助手'
self.extra_config = {
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
}
agent = _Agent()
assert agent_declares_file_check_progress(agent)
assert not is_file_check_chat_agent(agent)
with app.app_context():
app.config.pop('HXOPS_TOOLS_API_BASE', None)
app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com'
app.config.pop('ROHS_TOOLS_API_KEY', None)
app.config['INTEGRATION_API_KEY'] = 'integration-secret'
inputs = build_dify_chat_inputs()
assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com'
assert inputs['hxops_tool_api_token'] == 'integration-secret'
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(agent, required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
assert 'schedule_task_id' in exc.value.message
def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker):
"""声明了文件检核能力但未配置 schedule_task_id 时,/completions 应立即 400 而非挂死。"""
from flask import g
from app.models import Agent, User
misconfigured = Agent(
id=26,
name='RoHS文件检核助手',
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
type='api',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
},
is_active=True,
)
user = User(id=1, username='admin', status='active', role='admin')
user.agents = [misconfigured]
def mock_get_user():
g.current_user = user
return user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
mocker.patch('app.models.Agent.query').get.return_value = misconfigured
mock_post = mocker.patch('requests.post')
mock_post.side_effect = AssertionError('Dify must not be called when task_id is missing')
res = client.post(
'/api/chat/completions',
json={'query': '立即执行RoHS文件检核', 'agent_id': 26},
headers={'Content-Type': 'application/json'},
)
assert res.status_code == 400
body = res.get_json()
assert body['error']['code'] == 'VALIDATION.INVALID_PARAM'
assert body['error']['details']['error_code'] == 'file_check_task_id_required'
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 注入失效。"""
from types import SimpleNamespace
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
)
agent_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
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},
},
)
assert is_file_check_chat_agent(agent_proxy)
assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12'
bare_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
)
assert not is_file_check_chat_agent(bare_proxy)
assert build_file_check_dify_inputs(bare_proxy) == {}
def test_kb_sync_skips_failed_run(app):
@@ -1168,7 +1345,7 @@ def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path
assert run.kb_sync_status in ('success', 'ready', 'syncing')
def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
"""Dify HTTP 仅传 task_id + user_message 时,仍应通过 turn 注册表回写 run_id。"""
class _Thread:
def __init__(self, *, target, daemon, name):
@@ -1179,7 +1356,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
def start(self):
return None
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1189,10 +1366,10 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
task_id = task.id
admin_id = admin.id
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
register_rohs_chat_turn(
register_file_check_chat_turn(
turn_id='turn-registry-001',
session_id='sess-registry-001',
user_id=1,
@@ -1201,7 +1378,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
)
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -1230,7 +1407,14 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
event_name='message_end',
request_id='req-bind-test',
user_id=admin_id,
agent=type('AgentProxy', (), {'id': 1, 'name': 'RoHS文件检核助手'})(),
agent=type('AgentProxy', (), {
'id': 1,
'name': 'RoHS文件检核助手',
'extra_config': {
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': task_id},
},
})(),
session_id='sess-registry-001',
hxops_turn_id='turn-registry-001',
normalized_conversation_id='sess-registry-001',