feat(file-check): 持久化 chat_tool_runs 并统一 agent_runtime_context 注入
新增跨 worker 进度绑定表与显式 hxops_turn_id 链路;Dify Start 仅注入 agent_runtime_context,task_id/turn_id 写入 refs 供画布解析后回传 Tool。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
c778f40fbc
commit
f4e74f7b07
23 files changed
+1580
-196
No files matched your search
@@ -8,6 +8,15 @@ from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
|
||||
from app.services.file_check import FileCheckService
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _file_check_tool_auth_config(app):
|
||||
"""避免本机 .env 中 FILE_CHECK_TOOL_API_KEY 覆盖测试用 INTEGRATION_API_KEY。"""
|
||||
with app.app_context():
|
||||
app.config['FILE_CHECK_TOOL_API_KEY'] = ''
|
||||
app.config.setdefault('INTEGRATION_API_KEY', 'secret')
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_file_check_turn_registry():
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
@@ -17,6 +26,17 @@ def _clear_file_check_turn_registry():
|
||||
clear_registry_for_tests()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_chat_tool_runs(app):
|
||||
from app.services.file_check_tools.chat_tool_run_binding import clear_chat_tool_runs_for_tests
|
||||
|
||||
with app.app_context():
|
||||
clear_chat_tool_runs_for_tests()
|
||||
yield
|
||||
with app.app_context():
|
||||
clear_chat_tool_runs_for_tests()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stub_minio(monkeypatch):
|
||||
minio_module = types.ModuleType('minio')
|
||||
@@ -773,7 +793,7 @@ def test_workspace_file_check_run_for_log_lazy_binds_via_session_query(app, clie
|
||||
assert res.status_code == 200
|
||||
payload = res.get_json()
|
||||
assert payload['run']['run_id'] == run_id
|
||||
assert payload['match_source'] == 'chat_log'
|
||||
assert payload['match_source'] == 'legacy'
|
||||
|
||||
with app.app_context():
|
||||
rebound = db.session.get(ChatLog, chat_log_id)
|
||||
@@ -994,9 +1014,13 @@ def test_file_check_openapi_injects_tool_api_base(app, client):
|
||||
|
||||
|
||||
def test_file_check_dify_chat_inputs(app):
|
||||
import json
|
||||
|
||||
from app.services.agent_registry.resolver import is_file_check_runtime_ready
|
||||
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
|
||||
from app.services.file_check_tools.dify_inputs import (
|
||||
FILE_CHECK_TASK_ID_INPUT,
|
||||
FILE_CHECK_SCHEDULE_TASK_REF,
|
||||
FILE_CHECK_TURN_REF,
|
||||
build_file_check_dify_inputs,
|
||||
)
|
||||
|
||||
@@ -1024,10 +1048,27 @@ def test_file_check_dify_chat_inputs(app):
|
||||
bound_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
|
||||
inputs = build_file_check_dify_inputs(
|
||||
agent,
|
||||
session_id='conv-file-check-001',
|
||||
request_id='req-turn-001',
|
||||
)
|
||||
assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
|
||||
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
|
||||
assert payload['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
|
||||
assert FILE_CHECK_TURN_REF not in payload['refs']
|
||||
|
||||
with app.app_context():
|
||||
inputs_with_turn = build_file_check_dify_inputs(
|
||||
agent,
|
||||
session_id='conv-file-check-001',
|
||||
request_id='req-turn-001',
|
||||
hxops_turn_id='turn-file-check-001',
|
||||
)
|
||||
assert set(inputs_with_turn.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT}
|
||||
runtime_context = json.loads(inputs_with_turn[AGENT_RUNTIME_CONTEXT_INPUT])
|
||||
assert runtime_context['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
|
||||
assert runtime_context['refs'][FILE_CHECK_TURN_REF] == 'turn-file-check-001'
|
||||
|
||||
|
||||
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
|
||||
@@ -1083,58 +1124,71 @@ def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(
|
||||
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
|
||||
def test_file_check_executor_rejects_missing_schedule_task_id(app, monkeypatch):
|
||||
"""未配置 bound_schedule_task_id 时,Executor 构建 inputs 应立即 ValidationError,不调用 Dify。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.models import Agent, User
|
||||
import pytest
|
||||
|
||||
misconfigured = Agent(
|
||||
id=26,
|
||||
name='RoHS文件检核助手',
|
||||
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'},
|
||||
},
|
||||
is_active=True,
|
||||
)
|
||||
user = User(id=1, username='admin', status='active', role='admin')
|
||||
user.agents = [misconfigured]
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
def mock_get_user():
|
||||
g.current_user = user
|
||||
return user
|
||||
dify_called = {'value': False}
|
||||
|
||||
mocker.patch('app.core.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')
|
||||
def fake_stream_chat(*args, **kwargs):
|
||||
dify_called['value'] = True
|
||||
yield 'data: {"event":"message_end"}\n\n'
|
||||
|
||||
res = client.post(
|
||||
'/api/chat/completions',
|
||||
json={'query': '立即执行RoHS文件检核', 'agent_id': 26},
|
||||
headers={'Content-Type': 'application/json'},
|
||||
monkeypatch.setattr(
|
||||
'app.services.chat.executors.dify_chat.DifyService.stream_chat',
|
||||
staticmethod(fake_stream_chat),
|
||||
)
|
||||
|
||||
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()
|
||||
with app.app_context():
|
||||
load_handlers()
|
||||
ctx = ChatStreamContext(
|
||||
query='立即执行RoHS文件检核',
|
||||
display_query='立即执行RoHS文件检核',
|
||||
user=SimpleNamespace(id=1, role='admin'),
|
||||
agent=SimpleNamespace(
|
||||
id=26,
|
||||
name='RoHS文件检核助手',
|
||||
agent_code='file_check',
|
||||
runtime_provider='dify',
|
||||
conversation_mode='task_chat',
|
||||
dify_app_type='chatflow',
|
||||
capabilities={'task_progress': True},
|
||||
bound_schedule_task_id=None,
|
||||
extra_config={
|
||||
'capabilities': ['tool_run_progress'],
|
||||
'tool_run_progress': {'type': 'file_check'},
|
||||
},
|
||||
dify_api_key='app-key',
|
||||
api_base_url='http://dify.example/v1',
|
||||
),
|
||||
session=SimpleNamespace(session_id='conv-missing-task-001'),
|
||||
external_conversation_id=None,
|
||||
request_id='req-missing-task-001',
|
||||
)
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
list(stream_chat_via_executor(ctx))
|
||||
|
||||
assert exc.value.details.get('error_code') == 'file_check_task_id_required'
|
||||
assert dify_called['value'] is False
|
||||
|
||||
|
||||
def test_chat_agent_proxy_passes_registry_columns_for_task_id_injection():
|
||||
"""chat.py agent_proxy 须携带 Registry 列,否则 task_id 注入失效。"""
|
||||
"""chat.py agent_proxy 须携带 Registry 列,否则 agent_runtime_context.refs 注入失效。"""
|
||||
import json
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.agent_registry.resolver import is_file_check_runtime_ready
|
||||
from app.services.agent_runtime_context import AGENT_RUNTIME_CONTEXT_INPUT
|
||||
from app.services.file_check_tools.dify_inputs import (
|
||||
FILE_CHECK_TASK_ID_INPUT,
|
||||
FILE_CHECK_SCHEDULE_TASK_REF,
|
||||
build_file_check_dify_inputs,
|
||||
)
|
||||
|
||||
@@ -1149,7 +1203,9 @@ def test_chat_agent_proxy_passes_registry_columns_for_task_id_injection():
|
||||
extra_config={},
|
||||
)
|
||||
assert is_file_check_runtime_ready(agent_proxy)
|
||||
assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12'
|
||||
inputs = build_file_check_dify_inputs(agent_proxy, session_id='conv-proxy-001')
|
||||
payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT])
|
||||
assert payload['refs'][FILE_CHECK_SCHEDULE_TASK_REF] == '12'
|
||||
|
||||
bare_proxy = SimpleNamespace(
|
||||
id=26,
|
||||
@@ -1304,7 +1360,7 @@ def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeyp
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
lambda self, dataset_id, name, text, **kwargs: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
@@ -1373,7 +1429,7 @@ def test_kb_sync_queues_test_run_excel(app, monkeypatch, tmp_path):
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
enqueued: list[int] = []
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.enqueue_clean_job',
|
||||
'app.services.schedule.kb_sync.enqueue_clean_job',
|
||||
lambda job_id: enqueued.append(job_id),
|
||||
)
|
||||
|
||||
@@ -1540,14 +1596,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
event_name='message_end',
|
||||
request_id='req-bind-test',
|
||||
user_id=admin_id,
|
||||
agent=type('AgentProxy', (), {
|
||||
'id': 1,
|
||||
'name': 'RoHS文件检核助手',
|
||||
'extra_config': {
|
||||
'capabilities': ['tool_run_progress'],
|
||||
'tool_run_progress': {'schedule_task_id': task_id},
|
||||
},
|
||||
})(),
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-registry-001',
|
||||
hxops_turn_id='turn-registry-001',
|
||||
normalized_conversation_id='sess-registry-001',
|
||||
@@ -1666,3 +1715,472 @@ def test_history_search_tool_success(app, client, monkeypatch):
|
||||
assert data['count'] == 1
|
||||
assert data['segments'][0]['content'] == '供应商 A 铅含量不合格'
|
||||
assert data['dify_dataset_id'] == 'ds-search-001'
|
||||
|
||||
|
||||
def _stub_file_check_thread(monkeypatch):
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
|
||||
|
||||
def _file_check_agent_proxy(task_id: int):
|
||||
return type('AgentProxy', (), {
|
||||
'id': 1,
|
||||
'name': 'RoHS文件检核助手',
|
||||
'agent_code': 'file_check',
|
||||
'capabilities': {'task_progress': True},
|
||||
'bound_schedule_task_id': task_id,
|
||||
'extra_config': {},
|
||||
})()
|
||||
|
||||
|
||||
def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
|
||||
"""Tool 先启动、ChatLog 后落库时,chat_tool_runs 应能绑定进度。"""
|
||||
_stub_file_check_thread(monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-tool-first',
|
||||
session_id='sess-tool-first',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行 RoHS 检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-tool-first',
|
||||
'hxops_turn_id': 'turn-tool-first',
|
||||
'user_message': '立即执行 RoHS 检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-tool-first'},
|
||||
event_name='message_end',
|
||||
request_id='req-tool-first',
|
||||
user_id=admin_id,
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-tool-first',
|
||||
hxops_turn_id='turn-tool-first',
|
||||
normalized_conversation_id='sess-tool-first',
|
||||
query='立即执行 RoHS 检核',
|
||||
answer_text='检核已启动',
|
||||
latency=10,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_id = result['chat_log_id']
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
assert log.run_id == run_id
|
||||
|
||||
poll = client.get(
|
||||
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert poll.status_code == 200
|
||||
payload = poll.get_json()
|
||||
assert payload['run']['run_id'] == run_id
|
||||
assert payload['match_source'] == 'chat_log'
|
||||
|
||||
|
||||
def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
|
||||
"""ChatLog 先落库、Tool 后启动时,for-log 应通过 chat_tool_runs 懒绑定。"""
|
||||
_stub_file_check_thread(monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-log-first',
|
||||
session_id='sess-log-first',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行 RoHS 检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-log-first'},
|
||||
event_name='message_end',
|
||||
request_id='req-log-first',
|
||||
user_id=admin_id,
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-log-first',
|
||||
hxops_turn_id='turn-log-first',
|
||||
normalized_conversation_id='sess-log-first',
|
||||
query='立即执行 RoHS 检核',
|
||||
answer_text='检核已启动',
|
||||
latency=10,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_id = result['chat_log_id']
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
assert log.run_id is None
|
||||
|
||||
miss = client.get(
|
||||
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert miss.status_code == 200
|
||||
assert miss.get_json()['run'] is None
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-log-first',
|
||||
'hxops_turn_id': 'turn-log-first',
|
||||
'user_message': '立即执行 RoHS 检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
poll = client.get(
|
||||
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert poll.status_code == 200
|
||||
payload = poll.get_json()
|
||||
assert payload['run']['run_id'] == run_id
|
||||
assert payload['match_source'] == 'chat_log'
|
||||
|
||||
with app.app_context():
|
||||
rebound = db.session.get(ChatLog, chat_log_id)
|
||||
assert rebound.run_id == run_id
|
||||
|
||||
|
||||
def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatch):
|
||||
"""同文案多轮触发时,应按 turn_id 区分 run,避免串批次。"""
|
||||
_stub_file_check_thread(monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-same-msg-a',
|
||||
session_id='sess-same-msg',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
res_a = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-same-msg',
|
||||
'hxops_turn_id': 'turn-same-msg-a',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
run_a = res_a.get_json()['run']['run_id']
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-same-msg-b',
|
||||
session_id='sess-same-msg',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
res_b = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-same-msg',
|
||||
'hxops_turn_id': 'turn-same-msg-b',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
assert res_b.status_code == 200
|
||||
assert res_b.get_json().get('error_code') == 'check_running'
|
||||
run_b = res_b.get_json()['run']['run_id']
|
||||
assert run_b == run_a
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result_b = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-same-msg'},
|
||||
event_name='message_end',
|
||||
request_id='req-same-msg-b',
|
||||
user_id=admin_id,
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-same-msg',
|
||||
hxops_turn_id='turn-same-msg-b',
|
||||
normalized_conversation_id='sess-same-msg',
|
||||
query='立即执行检核',
|
||||
answer_text='检核已启动',
|
||||
latency=10,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_b = result_b['chat_log_id']
|
||||
log_b = db.session.get(ChatLog, chat_log_b)
|
||||
assert log_b.run_id == run_a
|
||||
|
||||
result_a = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-same-msg'},
|
||||
event_name='message_end',
|
||||
request_id='req-same-msg-a',
|
||||
user_id=admin_id,
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-same-msg',
|
||||
hxops_turn_id='turn-same-msg-a',
|
||||
normalized_conversation_id='sess-same-msg',
|
||||
query='立即执行检核',
|
||||
answer_text='检核已启动',
|
||||
latency=8,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_a = result_a['chat_log_id']
|
||||
log_a = db.session.get(ChatLog, chat_log_a)
|
||||
assert log_a.run_id == run_a
|
||||
assert log_a.id != log_b.id
|
||||
|
||||
|
||||
def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, client, monkeypatch):
|
||||
"""
|
||||
无 hxops_turn_id 且存在多个同文案 pending turn 时,不得绑定到任一 turn(宁可未绑定)。
|
||||
"""
|
||||
_stub_file_check_thread(monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
admin_id = admin.id
|
||||
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
from app.services.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-ambig-a',
|
||||
session_id='sess-ambig',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
register_pending_turn(
|
||||
turn_id='turn-ambig-b',
|
||||
session_id='sess-ambig',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
|
||||
clear_registry_for_tests()
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-ambig',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
with app.app_context():
|
||||
row_a = ChatToolRun.query.filter_by(turn_id='turn-ambig-a').first()
|
||||
row_b = ChatToolRun.query.filter_by(turn_id='turn-ambig-b').first()
|
||||
assert row_a.schedule_run_id is None
|
||||
assert row_b.schedule_run_id is None
|
||||
|
||||
result_a = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-ambig'},
|
||||
event_name='message_end',
|
||||
request_id='req-ambig-a',
|
||||
user_id=admin_id,
|
||||
agent=_file_check_agent_proxy(task_id),
|
||||
session_id='sess-ambig',
|
||||
hxops_turn_id='turn-ambig-a',
|
||||
normalized_conversation_id='sess-ambig',
|
||||
query='立即执行检核',
|
||||
answer_text='检核已启动',
|
||||
latency=10,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
log_a = db.session.get(ChatLog, result_a['chat_log_id'])
|
||||
assert log_a.run_id is None
|
||||
|
||||
poll = client.get(
|
||||
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={log_a.id}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert poll.status_code == 200
|
||||
assert poll.get_json()['run'] is None
|
||||
|
||||
|
||||
def test_chat_tool_runs_with_turn_id_binds_exact_pending_turn(app, client, monkeypatch):
|
||||
"""显式 hxops_turn_id 时必须准确绑定对应 turn。"""
|
||||
_stub_file_check_thread(monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
admin_id = admin.id
|
||||
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
turn_id='turn-explicit-a',
|
||||
session_id='sess-explicit',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
register_pending_turn(
|
||||
turn_id='turn-explicit-b',
|
||||
session_id='sess-explicit',
|
||||
user_id=admin_id,
|
||||
agent_id=1,
|
||||
user_message='立即执行检核',
|
||||
schedule_task_id=task_id,
|
||||
)
|
||||
|
||||
clear_registry_for_tests()
|
||||
|
||||
res = client.post(
|
||||
'/api/file-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'sess-explicit',
|
||||
'hxops_turn_id': 'turn-explicit-a',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
with app.app_context():
|
||||
row_a = ChatToolRun.query.filter_by(turn_id='turn-explicit-a').first()
|
||||
row_b = ChatToolRun.query.filter_by(turn_id='turn-explicit-b').first()
|
||||
assert row_a.schedule_run_id == run_id
|
||||
assert row_b.schedule_run_id is None
|
||||
|
||||
|
||||
def test_chat_tool_runs_for_log_lazy_resolves_from_binding_table(app, client):
|
||||
"""chat_logs.run_id 为空但 chat_tool_runs 已绑定时,for-log 应走 chat_tool_runs 并回写。"""
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-BIND-TABLE',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
log = ChatLog(
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
query='立即执行检核',
|
||||
answer='检核已启动',
|
||||
session_id='sess-bind-table',
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
from app.models import ChatToolRun
|
||||
|
||||
row = ChatToolRun(
|
||||
tool_name='run_file_check',
|
||||
session_id='sess-bind-table',
|
||||
turn_id='turn-bind-table',
|
||||
chat_log_id=log.id,
|
||||
schedule_task_id=task.id,
|
||||
schedule_run_id=run.id,
|
||||
user_message='立即执行检核',
|
||||
status='complete',
|
||||
bind_source='tool_start',
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
chat_log_id = log.id
|
||||
run_id = run.id
|
||||
|
||||
res = client.get(
|
||||
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
|
||||
payload = res.get_json()
|
||||
assert payload['run']['run_id'] == run_id
|
||||
assert payload['match_source'] == 'chat_tool_runs'
|
||||
|
||||
with app.app_context():
|
||||
rebound = db.session.get(ChatLog, chat_log_id)
|
||||
assert rebound.run_id == run_id
|
||||
Reference in new issue
Block a user