From f4e74f7b07253eb9cface832e196d738939f2e5c Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 9 Jul 2026 18:38:03 +0800 Subject: [PATCH] =?UTF-8?q?feat(file-check):=20=E6=8C=81=E4=B9=85=E5=8C=96?= =?UTF-8?q?=20chat=5Ftool=5Fruns=20=E5=B9=B6=E7=BB=9F=E4=B8=80=20agent=5Fr?= =?UTF-8?q?untime=5Fcontext=20=E6=B3=A8=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增跨 worker 进度绑定表与显式 hxops_turn_id 链路;Dify Start 仅注入 agent_runtime_context,task_id/turn_id 写入 refs 供画布解析后回传 Tool。 Co-authored-by: Cursor --- .gitignore | 5 +- backend/app/api/file_check_tools.py | 27 +- backend/app/api/workspace/file_check.py | 10 +- backend/app/models/__init__.py | 3 +- backend/app/models/chat.py | 31 + .../agent_registry/handlers/file_check.py | 14 +- .../services/agent_runtime_context/parser.py | 3 + backend/app/services/chat/executors/base.py | 4 +- backend/app/services/dify.py | 20 + .../file_check_tools/chat_log_run_binding.py | 19 +- .../file_check_tools/chat_log_run_resolver.py | 64 +- .../file_check_tools/chat_tool_run_binding.py | 407 ++++++++++++ .../file_check_tools/context_adapter.py | 13 +- .../services/file_check_tools/dify_inputs.py | 103 ++- .../file_check_tools/openapi_base.json | 12 +- .../e2f3a4b5c6d7_add_chat_tool_runs.py | 78 +++ backend/scripts/export_file_check_openapi.py | 2 + .../test_agent_runtime_context_registry.py | 5 +- backend/tests/test_chat_dify_start_inputs.py | 54 +- backend/tests/test_file_check_tools.py | 628 ++++++++++++++++-- .../dify/agent_runtime_context_integration.md | 2 + docs/features/file-check/technical.md | 256 +++++-- docs/openapi/file_check_tools_openapi.json | 16 +- 23 files changed, 1580 insertions(+), 196 deletions(-) create mode 100644 backend/app/services/file_check_tools/chat_tool_run_binding.py create mode 100644 backend/migrations/versions/e2f3a4b5c6d7_add_chat_tool_runs.py diff --git a/.gitignore b/.gitignore index a788faaa..70ab0889 100644 --- a/.gitignore +++ b/.gitignore @@ -26,8 +26,9 @@ share/python-wheels/ *.egg MANIFEST -# Python -__pycache__/ +# Pytest / local temp +backend/.pytest_tmp/ +.pytest_tmp/ *.py[cod] *$py.class diff --git a/backend/app/api/file_check_tools.py b/backend/app/api/file_check_tools.py index 6e2e8949..1de3a883 100644 --- a/backend/app/api/file_check_tools.py +++ b/backend/app/api/file_check_tools.py @@ -268,11 +268,31 @@ def _prepare_bind_payload(data: dict | None) -> dict: def _record_run_bind(run: ScheduleRun, data: dict) -> None: from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context + from app.services.file_check_tools.chat_tool_run_binding import ( + _has_ambiguous_pending_turns, + bind_schedule_run, + ) from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn - merge_chat_log_bind_context(run, data) turn_id = str(data.get("hxops_turn_id") or "").strip() - if turn_id: + session_id = str(data.get("hxops_session_id") or "").strip() or None + user_message = str(data.get("user_message") or "").strip() or None + bound = bind_schedule_run( + schedule_run_id=int(run.id), + turn_id=turn_id or None, + session_id=session_id, + user_message=user_message, + schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None, + bind_source='tool_start', + ) + ambiguous = _has_ambiguous_pending_turns( + session_id=session_id, + user_message=user_message, + schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None, + ) + if bound or (not ambiguous and (turn_id or session_id)): + merge_chat_log_bind_context(run, data) + if bound and turn_id: attach_run_to_turn(turn_id, int(run.id)) @@ -371,9 +391,6 @@ def run_file_check(): api_request_json={ "trigger_source": data.get("trigger_source") or "dify_chatflow", "conversation_id": data.get("conversation_id"), - "hxops_session_id": data.get("hxops_session_id"), - "hxops_turn_id": data.get("hxops_turn_id"), - "user_message": data.get("user_message"), }, ) db.session.add(run) diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py index 2b7a4c0b..2a6e47e1 100644 --- a/backend/app/api/workspace/file_check.py +++ b/backend/app/api/workspace/file_check.py @@ -14,7 +14,7 @@ from flask import Blueprint, jsonify, request, send_file from app.core.auth.jwt import get_current_user from app.core.errors import NotFoundError, UnauthorizedError, ValidationError from app.models import ScheduleRun, ScheduleTask -from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log +from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log_with_source from app.services.schedule.query_service import get_run, serialize_run workspace_file_check_bp = Blueprint("workspace_file_check", __name__) @@ -78,8 +78,12 @@ def workspace_file_check_run_for_log(): raise ValidationError("task_id_required") if not chat_log_id or chat_log_id <= 0: raise ValidationError("chat_log_id_required") - run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id) - return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None, 'match_source': 'chat_log' if run else None}) + match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id) + return jsonify({ + 'ok': True, + 'run': _serialize_progress_run(match.run) if match.run else None, + 'match_source': match.match_source, + }) @workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET']) def workspace_file_check_run_for_session(): diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f566654c..e09f6cd2 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -8,7 +8,7 @@ backend/app/models/__init__.py from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest from app.models.base import Base, user_agent_permissions -from app.models.chat import ChatLog, ChatSession, Feedback, GeneralFeedback +from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage from app.models.department import Department from app.models.job import Job @@ -40,6 +40,7 @@ __all__ = [ 'Agent', 'ChatSession', 'ChatLog', + 'ChatToolRun', 'Feedback', 'GeneralFeedback', 'PermissionRequest', diff --git a/backend/app/models/chat.py b/backend/app/models/chat.py index 86b442d2..dd09ba3b 100644 --- a/backend/app/models/chat.py +++ b/backend/app/models/chat.py @@ -83,6 +83,37 @@ class Feedback(Base): chat_log: Mapped['ChatLog'] = relationship(back_populates='feedback') +class ChatToolRun(Base): + """ + 对话轮次 Tool 运行绑定表(chat-turn binding)。 + + 用途:持久化 hxops_turn_id / chat_log_id / schedule_run_id 绑定,支撑跨 worker 与异步时序的稳定进度显示。 + 约束:turn_id 非空且唯一,仅适用于经 chat API 触发的检核轮次;非聊天入口勿复用本表。 + """ + + __tablename__ = 'chat_tool_runs' + __table_args__ = ( + Index('ix_chat_tool_runs_chat_log_id', 'chat_log_id'), + Index('ix_chat_tool_runs_schedule_run_id', 'schedule_run_id'), + Index('ix_chat_tool_runs_session_task_created', 'session_id', 'schedule_task_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + tool_name: Mapped[str] = mapped_column(String(64), default='run_file_check') + agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), index=True, nullable=True) + user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) + session_id: Mapped[str] = mapped_column(String(100), index=True) + turn_id: Mapped[str] = mapped_column(String(64), unique=True) + chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True) + schedule_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_tasks.id'), nullable=True) + schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True) + user_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + status: Mapped[str] = mapped_column(String(20), default='pending') + bind_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + class GeneralFeedback(Base): """ 通用意见反馈表 diff --git a/backend/app/services/agent_registry/handlers/file_check.py b/backend/app/services/agent_registry/handlers/file_check.py index e54f0cfe..ec21cf9d 100644 --- a/backend/app/services/agent_registry/handlers/file_check.py +++ b/backend/app/services/agent_registry/handlers/file_check.py @@ -2,8 +2,8 @@ backend/app/services/agent_registry/handlers/file_check.py 用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。 -依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry、resolver。 -逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。 +依赖:file_check_tools.chat_tool_run_binding、chat_turn_registry、agent_registry.handlers.registry、resolver。 +逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id 并写入 chat_tool_runs。 """ from __future__ import annotations @@ -38,7 +38,9 @@ class FileCheckHandler(AgentHandler): return ctx turn_id = uuid.uuid4().hex + from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn + from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent register_file_check_chat_turn( turn_id=turn_id, @@ -47,5 +49,13 @@ class FileCheckHandler(AgentHandler): agent_id=int(getattr(ctx.agent, 'id', 0) or 0), query=ctx.query, ) + register_pending_turn( + turn_id=turn_id, + session_id=str(getattr(ctx.session, 'session_id', '') or ''), + user_id=int(getattr(ctx.user, 'id', 0) or 0), + agent_id=int(getattr(ctx.agent, 'id', 0) or 0), + user_message=ctx.query, + schedule_task_id=resolve_schedule_task_id_from_agent(ctx.agent), + ) ctx.hxops_turn_id = turn_id return ctx diff --git a/backend/app/services/agent_runtime_context/parser.py b/backend/app/services/agent_runtime_context/parser.py index 714f969c..940d4f6b 100644 --- a/backend/app/services/agent_runtime_context/parser.py +++ b/backend/app/services/agent_runtime_context/parser.py @@ -33,10 +33,13 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset( "refs.run_purpose", "refs.file_name", "refs.schedule_task_id", + "refs.hxops_turn_id", "domain.type", "domain.summary", "domain.state_hint.batch_no", "domain.state_hint.focus_task_no", + "domain.state_hint.schedule_task_id", + "domain.state_hint.hxops_turn_id", "domain.state_hint.current_step", "domain.state_hint.status", "domain.state_hint.review_status", diff --git a/backend/app/services/chat/executors/base.py b/backend/app/services/chat/executors/base.py index a080e3b7..0a21164b 100644 --- a/backend/app/services/chat/executors/base.py +++ b/backend/app/services/chat/executors/base.py @@ -38,9 +38,9 @@ def build_dify_inputs_for_context(ctx: ChatStreamContext) -> dict[str, Any]: session_id=str(getattr(ctx.session, 'session_id', '') or ''), request_id=ctx.request_id, trigger_source='frontend_chat', - user_role=str(getattr(ctx.user, 'role', '') or '').strip() or None, adapter_hints=ctx.adapter_hints, - user_role=getattr(ctx.user, 'role', None), + hxops_turn_id=ctx.hxops_turn_id, + user_role=str(getattr(ctx.user, 'role', '') or '').strip() or None, ) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 6b568307..c2189762 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -1276,6 +1276,26 @@ class DifyService: ) if not chat_log_id: return None + try: + from app.services.file_check_tools.chat_tool_run_binding import bind_chat_log + + bind_chat_log( + chat_log_id=int(chat_log_id), + turn_id=hxops_turn_id, + session_id=session_id, + query=query, + schedule_run_id=run_id, + ) + except Exception as exc: + if current_app: + current_app.logger.warning( + '[file-check-bind] bind_chat_log failed chat_log_id=%s session_id=%s turn_id=%s request_id=%s err=%s', + chat_log_id, + session_id or None, + hxops_turn_id or None, + request_id, + exc, + ) return {"chat_log_id": chat_log_id, "run_id": run_id} @staticmethod diff --git a/backend/app/services/file_check_tools/chat_log_run_binding.py b/backend/app/services/file_check_tools/chat_log_run_binding.py index 8783b49c..b72c126d 100644 --- a/backend/app/services/file_check_tools/chat_log_run_binding.py +++ b/backend/app/services/file_check_tools/chat_log_run_binding.py @@ -2,7 +2,7 @@ services/file_check_tools/chat_log_run_binding.py 用途:将文件检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。 -依赖:ChatLog、ScheduleRun、chat_turn_registry。 +依赖:ChatLog、ScheduleRun、chat_tool_run_binding、chat_turn_registry。 逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。 """ from __future__ import annotations @@ -15,6 +15,10 @@ from flask import current_app from app import db from app.models import ChatLog, ScheduleRun +from app.services.file_check_tools.chat_tool_run_binding import ( + resolve_schedule_run_id_by_turn, + resolve_schedule_run_id_for_session, +) from app.services.file_check_tools.chat_turn_registry import ( attach_run_to_turn, resolve_run_id_by_session_query, @@ -69,7 +73,8 @@ def resolve_run_id_for_chat_log( """ 匹配本轮问答应对绑定的检核批次 ID。 - 优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。 + 优先级:chat_tool_runs(turn_id)> 内存 registry > session_id + 归一化 query > ScheduleRun.api_request_json 兜底。 + 有 turn_id 时仅走 turn 路径,禁止降级到 session/query,避免同文案误绑。 Returns: 匹配到的 ScheduleRun.id,或 None。 @@ -88,6 +93,9 @@ def resolve_run_id_for_chat_log( return run.api_request_json if isinstance(run.api_request_json, dict) else {} if turn_key: + persisted_run_id = resolve_schedule_run_id_by_turn(turn_key) + if persisted_run_id: + return persisted_run_id registry_run_id = resolve_run_id_by_turn(turn_key) if registry_run_id: return registry_run_id @@ -96,8 +104,15 @@ def resolve_run_id_for_chat_log( bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip() if bind_turn == turn_key: return int(run.id) + return None if session_key and query_key: + persisted_run_id = resolve_schedule_run_id_for_session( + session_id=session_key, + user_message=query_key, + ) + if persisted_run_id: + return persisted_run_id for run in rows: req = _req(run) bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip() diff --git a/backend/app/services/file_check_tools/chat_log_run_resolver.py b/backend/app/services/file_check_tools/chat_log_run_resolver.py index 2ee5d402..87054a17 100644 --- a/backend/app/services/file_check_tools/chat_log_run_resolver.py +++ b/backend/app/services/file_check_tools/chat_log_run_resolver.py @@ -2,17 +2,30 @@ services/file_check_tools/chat_log_run_resolver.py 用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。 -依赖:ChatLog、ScheduleRun、chat_log_run_binding、chat_turn_registry。 -逻辑:for-log API 调用;优先读 chat_logs.run_id,缺失时按 session/query 兜底匹配并懒回写。 +依赖:ChatLog、ScheduleRun、chat_tool_run_binding、chat_log_run_binding。 +逻辑:for-log API 调用;优先读 chat_logs.run_id,其次 chat_tool_runs,最后 session/query 兜底。 """ from __future__ import annotations +from dataclasses import dataclass + from app import db from app.models import ChatLog, ScheduleRun from app.services.file_check_tools.chat_log_run_binding import ( resolve_run_id_for_chat_log, update_chat_log_run_id, ) +from app.services.file_check_tools.chat_tool_run_binding import ( + resolve_schedule_run_id_by_chat_log, +) + + +@dataclass +class ChatLogRunMatch: + """ChatLog 与 ScheduleRun 的解析结果。""" + + run: ScheduleRun | None + match_source: str | None = None def find_run_for_chat_log( @@ -30,16 +43,46 @@ def find_run_for_chat_log( Returns: 绑定的 ScheduleRun,或 None。 """ + return find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id).run + + +def find_run_for_chat_log_with_source( + *, + task_id: int, + chat_log_id: int, +) -> ChatLogRunMatch: + """ + 查询某条问答记录绑定的检核批次,并返回匹配来源。 + + 优先级:chat_logs.run_id > chat_tool_runs > session/query 兜底。 + + Args: + task_id: ScheduleTask.id。 + chat_log_id: ChatLog.id。 + + Returns: + ChatLogRunMatch(含 run 与 match_source)。 + """ if chat_log_id <= 0 or task_id <= 0: - return None + return ChatLogRunMatch(run=None, match_source=None) log = db.session.get(ChatLog, chat_log_id) if not log: - return None + return ChatLogRunMatch(run=None, match_source=None) run_id = int(log.run_id) if log.run_id else None + match_source = 'chat_log' if run_id else None + if not run_id: - # [STEP 1] message_end 可能早于 Tool 启动完成,按 session/query 从注册表或 ScheduleRun 兜底 + # [STEP 1] 持久绑定表兜底(Tool 先启动、ChatLog 后落库) + persisted = resolve_schedule_run_id_by_chat_log(chat_log_id) + if persisted: + update_chat_log_run_id(chat_log_id, persisted) + run_id = persisted + match_source = 'chat_tool_runs' + + if not run_id: + # [STEP 2] message_end 可能早于 Tool 启动完成,按 session/query 从注册表或 ScheduleRun 兜底 resolved = resolve_run_id_for_chat_log( session_id=log.session_id, query=log.query, @@ -47,16 +90,19 @@ def find_run_for_chat_log( if resolved: update_chat_log_run_id(chat_log_id, resolved) run_id = resolved + match_source = 'legacy' if not run_id: - return None + return ChatLogRunMatch(run=None, match_source=None) run = db.session.get(ScheduleRun, run_id) if run and run.schedule_task_id == task_id: - return run - return None + return ChatLogRunMatch(run=run, match_source=match_source) + return ChatLogRunMatch(run=None, match_source=None) __all__ = [ - "find_run_for_chat_log", + 'ChatLogRunMatch', + 'find_run_for_chat_log', + 'find_run_for_chat_log_with_source', ] diff --git a/backend/app/services/file_check_tools/chat_tool_run_binding.py b/backend/app/services/file_check_tools/chat_tool_run_binding.py new file mode 100644 index 00000000..c3abe328 --- /dev/null +++ b/backend/app/services/file_check_tools/chat_tool_run_binding.py @@ -0,0 +1,407 @@ +""" +services/file_check_tools/chat_tool_run_binding.py + +用途:持久化 hxops_turn_id / chat_log_id / schedule_run_id 绑定关系。 +依赖:ChatToolRun、ChatLog、ScheduleRun。 +逻辑:file_check Handler 登记 turn;Tool API 绑定 run;Dify 落 ChatLog 回写 chat_log_id。 +""" +from __future__ import annotations + +import re +from datetime import datetime, timedelta +from typing import Any + +from app import db +from app.models import ChatLog, ChatToolRun, ScheduleRun + +try: + from flask import current_app +except ImportError: # pragma: no cover + current_app = None # type: ignore + +_STATUS_PENDING = 'pending' +_STATUS_RUN_BOUND = 'run_bound' +_STATUS_COMPLETE = 'complete' +_RECENT_WINDOW = timedelta(minutes=30) + + +def _normalize_text(text: str | None) -> str: + """折叠空白,便于 user_message 与 ChatLog.query 对齐。""" + return re.sub(r'\s+', ' ', str(text or '').strip()) + + +def _derive_status(row: ChatToolRun) -> str: + """根据已绑定字段推导状态。""" + if row.chat_log_id and row.schedule_run_id: + return _STATUS_COMPLETE + if row.schedule_run_id: + return _STATUS_RUN_BOUND + return _STATUS_PENDING + + +def register_pending_turn( + *, + turn_id: str, + session_id: str, + user_id: int, + agent_id: int, + user_message: str, + tool_name: str = 'run_file_check', + schedule_task_id: int | None = None, + bind_source: str = 'turn_register', +) -> ChatToolRun | None: + """ + 登记本轮对话的 pending 绑定记录(chat API 在调用 Dify 前执行)。 + + Args: + turn_id: 本轮唯一标识(hxops_turn_id)。 + session_id: ChatSession.session_id。 + user_id: 当前用户 ID。 + agent_id: 当前 Agent ID。 + user_message: 用户输入原文。 + tool_name: Tool 名称,默认 run_file_check。 + schedule_task_id: 绑定的 ScheduleTask.id(可选)。 + bind_source: 绑定来源标记。 + + Returns: + 新建或已存在的 ChatToolRun;turn_id/session_id 无效时返回 None。 + """ + turn_key = str(turn_id or '').strip() + session_key = str(session_id or '').strip() + if not turn_key or not session_key: + return None + + existing = ChatToolRun.query.filter_by(turn_id=turn_key).first() + if existing: + changed = False + if not existing.user_message and user_message: + existing.user_message = str(user_message) + changed = True + if schedule_task_id and not existing.schedule_task_id: + existing.schedule_task_id = int(schedule_task_id) + changed = True + if changed: + existing.updated_at = datetime.utcnow() + db.session.commit() + return existing + + row = ChatToolRun( + tool_name=str(tool_name or 'run_file_check'), + agent_id=int(agent_id) if agent_id else None, + user_id=int(user_id) if user_id else None, + session_id=session_key, + turn_id=turn_key, + user_message=str(user_message or ''), + schedule_task_id=int(schedule_task_id) if schedule_task_id else None, + status=_STATUS_PENDING, + bind_source=bind_source, + ) + db.session.add(row) + db.session.commit() + return row + + +def _has_ambiguous_pending_turns( + *, + session_id: str | None, + user_message: str | None, + schedule_task_id: int | None = None, + tool_name: str = 'run_file_check', +) -> bool: + """同会话同文案存在多个未绑定 run 的 pending turn 时返回 True。""" + session_key = str(session_id or '').strip() + query_key = _normalize_text(user_message) + if not session_key or not query_key: + return False + cutoff = datetime.utcnow() - _RECENT_WINDOW + query = ChatToolRun.query.filter( + ChatToolRun.session_id == session_key, + ChatToolRun.created_at >= cutoff, + ChatToolRun.schedule_run_id.is_(None), + ) + if schedule_task_id and schedule_task_id > 0: + query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id)) + if tool_name: + query = query.filter(ChatToolRun.tool_name == str(tool_name)) + rows = query.order_by(ChatToolRun.id.desc()).limit(20).all() + return len(_message_matches(rows, query_key)) > 1 + + +def bind_schedule_run( + *, + schedule_run_id: int, + turn_id: str | None = None, + session_id: str | None = None, + user_message: str | None = None, + schedule_task_id: int | None = None, + tool_name: str = 'run_file_check', + bind_source: str = 'tool_start', +) -> bool: + """ + 将检核批次 ID 写入 chat_tool_runs(Tool 启动成功或复用 running run 后执行)。 + + Args: + schedule_run_id: ScheduleRun.id。 + turn_id: hxops_turn_id(优先匹配)。 + session_id: 会话 ID(turn_id 缺失时兜底)。 + user_message: 用户输入(session 兜底时用于消歧)。 + schedule_task_id: ScheduleTask.id。 + tool_name: Tool 名称。 + bind_source: 绑定来源标记。 + + Returns: + 是否成功绑定。 + """ + if schedule_run_id <= 0: + return False + run = db.session.get(ScheduleRun, schedule_run_id) + if not run: + return False + + turn_key = str(turn_id or '').strip() + session_key = str(session_id or '').strip() + if turn_key and session_key and not ChatToolRun.query.filter_by(turn_id=turn_key).first(): + db.session.add( + ChatToolRun( + tool_name=str(tool_name or 'run_file_check'), + session_id=session_key, + turn_id=turn_key, + user_message=str(user_message or ''), + schedule_task_id=int(schedule_task_id or run.schedule_task_id or 0) or None, + status=_STATUS_PENDING, + bind_source='tool_start_lazy', + ) + ) + db.session.commit() + + row = _find_binding_row( + turn_id=turn_id, + session_id=session_id, + user_message=user_message, + schedule_task_id=schedule_task_id or run.schedule_task_id, + tool_name=tool_name, + require_unbound_run=True, + ) + if not row: + if current_app: + current_app.logger.warning( + '[file-check-bind] bind_schedule_run skipped schedule_run_id=%s turn_id=%s session_id=%s message_len=%s', + schedule_run_id, + str(turn_id or '').strip() or None, + str(session_id or '').strip() or None, + len(str(user_message or '')), + ) + return False + + row.schedule_run_id = int(schedule_run_id) + if schedule_task_id: + row.schedule_task_id = int(schedule_task_id) + elif not row.schedule_task_id: + row.schedule_task_id = int(run.schedule_task_id) + row.bind_source = bind_source + row.status = _derive_status(row) + row.updated_at = datetime.utcnow() + + if row.chat_log_id: + log = db.session.get(ChatLog, row.chat_log_id) + if log and not log.run_id: + log.run_id = int(schedule_run_id) + + db.session.commit() + return True + + +def bind_chat_log( + *, + chat_log_id: int, + turn_id: str | None = None, + session_id: str | None = None, + query: str | None = None, + schedule_run_id: int | None = None, + bind_source: str = 'chat_log', +) -> bool: + """ + ChatLog 落库后回写 chat_log_id,并同步 chat_logs.run_id。 + + Args: + chat_log_id: ChatLog.id。 + turn_id: hxops_turn_id(优先匹配)。 + session_id: 会话 ID。 + query: 用户输入(session 兜底消歧)。 + schedule_run_id: 已解析的 run_id(可选,用于同步 chat_logs.run_id)。 + bind_source: 绑定来源标记。 + + Returns: + 是否成功绑定。 + """ + if chat_log_id <= 0: + return False + log = db.session.get(ChatLog, chat_log_id) + if not log: + return False + + row = _find_binding_row( + turn_id=turn_id, + session_id=session_id or log.session_id, + user_message=query or log.query, + schedule_task_id=None, + tool_name='run_file_check', + require_unbound_run=False, + ) + if not row: + return False + + row.chat_log_id = int(chat_log_id) + row.bind_source = bind_source + if schedule_run_id and schedule_run_id > 0: + row.schedule_run_id = int(schedule_run_id) + elif row.schedule_run_id and not log.run_id: + log.run_id = int(row.schedule_run_id) + elif log.run_id and not row.schedule_run_id: + row.schedule_run_id = int(log.run_id) + row.status = _derive_status(row) + row.updated_at = datetime.utcnow() + db.session.commit() + return True + + +def resolve_schedule_run_id_by_turn(turn_id: str | None) -> int | None: + """按 turn_id 读取已绑定的 schedule_run_id。""" + turn_key = str(turn_id or '').strip() + if not turn_key: + return None + row = ChatToolRun.query.filter_by(turn_id=turn_key).first() + if not row or not row.schedule_run_id or row.schedule_run_id <= 0: + return None + return int(row.schedule_run_id) + + +def resolve_schedule_run_id_by_chat_log(chat_log_id: int) -> int | None: + """按 chat_log_id 读取已绑定的 schedule_run_id。""" + if chat_log_id <= 0: + return None + row = ( + ChatToolRun.query.filter_by(chat_log_id=chat_log_id) + .order_by(ChatToolRun.id.desc()) + .first() + ) + if not row or not row.schedule_run_id or row.schedule_run_id <= 0: + return None + return int(row.schedule_run_id) + + +def resolve_schedule_run_id_for_session( + *, + session_id: str | None, + schedule_task_id: int | None = None, + user_message: str | None = None, +) -> int | None: + """ + 按 session_id + user_message 从 chat_tool_runs 解析 schedule_run_id。 + + 核心逻辑:优先精确匹配 user_message,其次取近期唯一 run_bound 记录。 + """ + session_key = str(session_id or '').strip() + if not session_key: + return None + query_key = _normalize_text(user_message) + cutoff = datetime.utcnow() - _RECENT_WINDOW + + query = ChatToolRun.query.filter( + ChatToolRun.session_id == session_key, + ChatToolRun.created_at >= cutoff, + ChatToolRun.schedule_run_id.isnot(None), + ) + if schedule_task_id and schedule_task_id > 0: + query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id)) + + rows = query.order_by(ChatToolRun.id.desc()).limit(20).all() + if not rows: + return None + + if query_key: + exact_matches = [ + row for row in rows + if _normalize_text(row.user_message) == query_key and row.schedule_run_id + ] + if len(exact_matches) > 1: + return None + if len(exact_matches) == 1 and exact_matches[0].schedule_run_id: + return int(exact_matches[0].schedule_run_id) + + if len(rows) == 1 and rows[0].schedule_run_id: + return int(rows[0].schedule_run_id) + return None + + +def _message_matches(rows: list[ChatToolRun], query_key: str) -> list[ChatToolRun]: + """按归一化 user_message 过滤候选行。""" + if not query_key: + return [] + return [row for row in rows if _normalize_text(row.user_message) == query_key] + + +def _find_binding_row( + *, + turn_id: str | None, + session_id: str | None, + user_message: str | None, + schedule_task_id: int | None, + tool_name: str, + require_unbound_run: bool, +) -> ChatToolRun | None: + """内部:按 turn_id 或 session+message 查找可更新的绑定行。""" + turn_key = str(turn_id or '').strip() + if turn_key: + row = ChatToolRun.query.filter_by(turn_id=turn_key).first() + if row: + if require_unbound_run and row.schedule_run_id: + return None + return row + + session_key = str(session_id or '').strip() + if not session_key: + return None + + query_key = _normalize_text(user_message) + cutoff = datetime.utcnow() - _RECENT_WINDOW + query = ChatToolRun.query.filter( + ChatToolRun.session_id == session_key, + ChatToolRun.created_at >= cutoff, + ) + if schedule_task_id and schedule_task_id > 0: + query = query.filter(ChatToolRun.schedule_task_id == int(schedule_task_id)) + if tool_name: + query = query.filter(ChatToolRun.tool_name == str(tool_name)) + + rows = query.order_by(ChatToolRun.id.desc()).limit(20).all() + if require_unbound_run: + rows = [row for row in rows if not row.schedule_run_id] + + if query_key: + matches = _message_matches(rows, query_key) + if len(matches) > 1 and not turn_key: + return None + if len(matches) == 1: + return matches[0] + + if len(rows) == 1: + return rows[0] + return None + + +def clear_chat_tool_runs_for_tests() -> None: + """测试专用:清空 chat_tool_runs 表。""" + ChatToolRun.query.delete() + db.session.commit() + + +__all__ = [ + 'bind_chat_log', + 'bind_schedule_run', + 'clear_chat_tool_runs_for_tests', + 'register_pending_turn', + 'resolve_schedule_run_id_by_chat_log', + 'resolve_schedule_run_id_by_turn', + 'resolve_schedule_run_id_for_session', +] diff --git a/backend/app/services/file_check_tools/context_adapter.py b/backend/app/services/file_check_tools/context_adapter.py index 2fc71d52..b27727d7 100644 --- a/backend/app/services/file_check_tools/context_adapter.py +++ b/backend/app/services/file_check_tools/context_adapter.py @@ -1,7 +1,7 @@ """ backend/app/services/file_check_tools/context_adapter.py -用途:文件检核 Agent 的 Context Adapter,构建 task_id Dify inputs。 +用途:文件检核 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。 依赖:file_check_tools.dify_inputs、agent_runtime_context.registry。 逻辑:agent_code=file_check 时由 build_chat_dify_inputs 分发;缺失 bound_schedule_task_id 时抛 ValidationError。 """ @@ -28,17 +28,17 @@ def build_file_check_context_adapter( """ 构建文件检核 Chatflow Dify Start inputs。 - 核心逻辑:从 bound_schedule_task_id 列注入 task_id; - session_id 存在时附带 agent_runtime_context(迭代 5 Dify Start 联调); - required=True 时未配置 bound_schedule_task_id 立即失败,避免 Dify 长连接挂死。 + 核心逻辑:仅输出 agent_runtime_context;refs.schedule_task_id / refs.hxops_turn_id + 供 Dify parse_agent_runtime_context 或 Code 解析后传给 RUN_FILE_CHECK。 Args: agent: 当前对话 Agent。 - session_id: HXOPS 会话 ID(检核 Tool 链路由 turn 注册表推断,不传入 Dify)。 + session_id: HXOPS 会话 ID。 + hxops_turn_id: 本轮对话唯一标识(由 Handler.prepare_stream 生成)。 adapter_hints: 预留;检核当前不消费领域 hints。 Returns: - 含 task_id 与可选 agent_runtime_context 的 inputs dict。 + 仅含 agent_runtime_context 的 inputs dict。 Raises: ValidationError: bound_schedule_task_id 未配置或非法。 @@ -50,4 +50,5 @@ def build_file_check_context_adapter( request_id=request_id, trigger_source=trigger_source, locale=locale, + hxops_turn_id=kwargs.get('hxops_turn_id'), ) diff --git a/backend/app/services/file_check_tools/dify_inputs.py b/backend/app/services/file_check_tools/dify_inputs.py index 00993540..dd854991 100644 --- a/backend/app/services/file_check_tools/dify_inputs.py +++ b/backend/app/services/file_check_tools/dify_inputs.py @@ -3,7 +3,8 @@ services/file_check_tools/dify_inputs.py 用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。 依赖:task_resolver、agent_runtime_context.builder、errors.ValidationError。 -逻辑:Context Adapter 调用本模块;必注入 task_id;session_id 存在时可选附带 agent_runtime_context(迭代 5 Dify Start 联调)。 +逻辑:Context Adapter 调用本模块;仅输出 agent_runtime_context(与 shipping_notice 等平台 Agent 一致)。 + schedule_task_id / hxops_turn_id 写入 refs,由 parse_agent_runtime_context 或画布 Code 解析后传给 Tool。 """ from __future__ import annotations @@ -12,8 +13,12 @@ from app.services.agent_runtime_context.builder import build_agent_runtime_conte from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent -# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致 +# refs 内字段名(非 Dify Start 顶层变量;Start 仅配置 agent_runtime_context) +FILE_CHECK_SCHEDULE_TASK_REF = "schedule_task_id" +FILE_CHECK_TURN_REF = "hxops_turn_id" +# 历史文档/画布曾用 Start 变量名 task_id,新画布请改读 refs.schedule_task_id FILE_CHECK_TASK_ID_INPUT = "task_id" +FILE_CHECK_TURN_ID_INPUT = "hxops_turn_id" FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required" @@ -58,40 +63,6 @@ def ensure_file_check_task_id_configured(agent) -> int: return task_id -def _build_file_check_runtime_context( - *, - session_id: str, - schedule_task_id: int, - agent, - request_id: str | None = None, - trigger_source: str | None = None, - locale: str | None = None, -) -> dict[str, str]: - """ - 构建 file_check 可选 agent_runtime_context 快照。 - - 核心逻辑:refs 携带 schedule_task_id;domain.state_hint 供 Dify 理解检核任务锚点。 - """ - agent_name = str(getattr(agent, 'name', None) or '').strip() or '文件检核' - runtime_context = build_agent_runtime_context( - agent_code='file_check', - scope='chat_turn', - session_id=session_id, - request_id=request_id, - trigger_source=trigger_source or 'frontend_chat', - locale=locale, - refs={'schedule_task_id': str(schedule_task_id)}, - domain={ - 'type': 'file_check', - 'summary': agent_name, - 'state_hint': {'schedule_task_id': str(schedule_task_id)}, - }, - ) - if not runtime_context: - return {} - return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context)} - - def build_file_check_dify_inputs( agent, *, @@ -100,25 +71,25 @@ def build_file_check_dify_inputs( request_id: str | None = None, trigger_source: str | None = None, locale: str | None = None, - include_runtime_context: bool = True, + hxops_turn_id: str | None = None, ) -> dict[str, str]: """ 构建文件检核 Chatflow 的 Dify chat inputs。 - 核心逻辑:必注入 task_id(Start 节点变量);session_id 存在且 include_runtime_context 时附带 agent_runtime_context。 - hxops_turn_id 由 Executor 注册 turn 注册表,不传入 Dify 画布。 + 核心逻辑:仅注入 agent_runtime_context JSON 字符串;refs.schedule_task_id、refs.hxops_turn_id + 供 Dify parse_agent_runtime_context Tool 或 Code 节点解析后传入 RUN_FILE_CHECK。 Args: - agent: 当前对话 Agent;task_id 从 bound_schedule_task_id 列解析。 + agent: 当前对话 Agent;schedule_task_id 从 bound_schedule_task_id 列解析。 required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。 - session_id: HXOPS 会话 ID;存在时可生成 agent_runtime_context。 + session_id: HXOPS 会话 ID;为空时返回空 dict。 request_id: 请求追踪 ID。 trigger_source: 触发来源。 locale: 用户语言。 - include_runtime_context: 是否在 task_id 之外附带 agent_runtime_context。 + hxops_turn_id: 本轮对话唯一标识;由 Handler.prepare_stream 生成后传入。 Returns: - 含 task_id(及可选 agent_runtime_context)的 inputs;required=False 且未配置时返回空 dict。 + 仅含 agent_runtime_context 的 inputs;session_id 为空或未配置 task 且 required=False 时返回 {}。 Raises: ValidationError: required=True 且 bound_schedule_task_id 未配置或非法。 @@ -129,26 +100,44 @@ def build_file_check_dify_inputs( raise _missing_task_id_error(agent) return {} - inputs: dict[str, str] = {FILE_CHECK_TASK_ID_INPUT: str(task_id)} normalized_session_id = str(session_id or '').strip() - if include_runtime_context and normalized_session_id: - inputs.update( - _build_file_check_runtime_context( - session_id=normalized_session_id, - schedule_task_id=task_id, - agent=agent, - request_id=request_id, - trigger_source=trigger_source, - locale=locale, - ) - ) - return inputs + if not normalized_session_id: + return {} + + agent_name = str(getattr(agent, 'name', None) or '').strip() or '文件检核' + refs: dict[str, str] = {FILE_CHECK_SCHEDULE_TASK_REF: str(task_id)} + turn_key = str(hxops_turn_id or '').strip() + if turn_key: + refs[FILE_CHECK_TURN_REF] = turn_key + state_hint: dict[str, str] = {FILE_CHECK_SCHEDULE_TASK_REF: str(task_id)} + if turn_key: + state_hint[FILE_CHECK_TURN_REF] = turn_key + + runtime_context = build_agent_runtime_context( + agent_code='file_check', + scope='chat_turn', + session_id=normalized_session_id, + request_id=request_id, + trigger_source=trigger_source or 'frontend_chat', + locale=locale, + refs=refs, + domain={ + 'type': 'file_check', + 'summary': agent_name, + 'state_hint': state_hint, + }, + ) + if not runtime_context: + return {} + return {AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context)} __all__ = [ + "FILE_CHECK_SCHEDULE_TASK_REF", + "FILE_CHECK_TURN_REF", "FILE_CHECK_TASK_ID_INPUT", + "FILE_CHECK_TURN_ID_INPUT", "FILE_CHECK_TASK_ID_MISSING_CODE", "build_file_check_dify_inputs", "ensure_file_check_task_id_configured", ] - diff --git a/backend/app/services/file_check_tools/openapi_base.json b/backend/app/services/file_check_tools/openapi_base.json index 02018b8e..8bba81df 100644 --- a/backend/app/services/file_check_tools/openapi_base.json +++ b/backend/app/services/file_check_tools/openapi_base.json @@ -546,12 +546,22 @@ "user_message": { "type": "string", "nullable": true + }, + "hxops_turn_id": { + "type": "string", + "nullable": true, + "description": "本轮对话唯一标识;须与 agent_runtime_context.refs.hxops_turn_id(经画布 §3.1A 解析)一致,Tool 原样回传" + }, + "hxops_session_id": { + "type": "string", + "nullable": true, + "description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入" } }, "required": [ "task_id" ], - "description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配" + "description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底" }, "RunCheckSuccessResponse": { "type": "object", diff --git a/backend/migrations/versions/e2f3a4b5c6d7_add_chat_tool_runs.py b/backend/migrations/versions/e2f3a4b5c6d7_add_chat_tool_runs.py new file mode 100644 index 00000000..4b9693bf --- /dev/null +++ b/backend/migrations/versions/e2f3a4b5c6d7_add_chat_tool_runs.py @@ -0,0 +1,78 @@ +"""add chat_tool_runs table + +Revision ID: e2f3a4b5c6d7 +Revises: d1e2f3a4b5c6, ff6a7b8c9d0e +Create Date: 2026-07-09 15:40:00.000000 + +Purpose: + Persist hxops_turn_id / chat_log_id / schedule_run_id bindings for stable + file-check progress display across workers and async ordering. +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'e2f3a4b5c6d7' +down_revision = ('d1e2f3a4b5c6', 'ff6a7b8c9d0e') +branch_labels = None +depends_on = None + + +def upgrade(): + bind = op.get_bind() + insp = sa.inspect(bind) + if 'chat_tool_runs' in set(insp.get_table_names()): + return + + op.create_table( + 'chat_tool_runs', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('tool_name', sa.String(length=64), nullable=False, server_default='run_file_check'), + sa.Column('agent_id', sa.Integer(), nullable=True), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('session_id', sa.String(length=100), nullable=False), + sa.Column('turn_id', sa.String(length=64), nullable=False), + sa.Column('chat_log_id', sa.Integer(), nullable=True), + sa.Column('schedule_task_id', sa.Integer(), nullable=True), + sa.Column('schedule_run_id', sa.Integer(), nullable=True), + sa.Column('user_message', sa.Text(), nullable=True), + sa.Column('status', sa.String(length=20), nullable=False, server_default='pending'), + sa.Column('bind_source', sa.String(length=32), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['agent_id'], ['agents.id']), + sa.ForeignKeyConstraint(['chat_log_id'], ['chat_logs.id']), + sa.ForeignKeyConstraint(['schedule_run_id'], ['schedule_runs.id']), + sa.ForeignKeyConstraint(['schedule_task_id'], ['schedule_tasks.id']), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('turn_id'), + ) + op.create_index('ix_chat_tool_runs_chat_log_id', 'chat_tool_runs', ['chat_log_id'], unique=False) + op.create_index('ix_chat_tool_runs_schedule_run_id', 'chat_tool_runs', ['schedule_run_id'], unique=False) + op.create_index( + 'ix_chat_tool_runs_session_task_created', + 'chat_tool_runs', + ['session_id', 'schedule_task_id', 'created_at'], + unique=False, + ) + op.create_index(op.f('ix_chat_tool_runs_agent_id'), 'chat_tool_runs', ['agent_id'], unique=False) + op.create_index(op.f('ix_chat_tool_runs_created_at'), 'chat_tool_runs', ['created_at'], unique=False) + op.create_index(op.f('ix_chat_tool_runs_session_id'), 'chat_tool_runs', ['session_id'], unique=False) + op.create_index(op.f('ix_chat_tool_runs_user_id'), 'chat_tool_runs', ['user_id'], unique=False) + + +def downgrade(): + bind = op.get_bind() + insp = sa.inspect(bind) + if 'chat_tool_runs' not in set(insp.get_table_names()): + return + op.drop_index(op.f('ix_chat_tool_runs_user_id'), table_name='chat_tool_runs') + op.drop_index(op.f('ix_chat_tool_runs_session_id'), table_name='chat_tool_runs') + op.drop_index(op.f('ix_chat_tool_runs_created_at'), table_name='chat_tool_runs') + op.drop_index(op.f('ix_chat_tool_runs_agent_id'), table_name='chat_tool_runs') + op.drop_index('ix_chat_tool_runs_session_task_created', table_name='chat_tool_runs') + op.drop_index('ix_chat_tool_runs_schedule_run_id', table_name='chat_tool_runs') + op.drop_index('ix_chat_tool_runs_chat_log_id', table_name='chat_tool_runs') + op.drop_table('chat_tool_runs') diff --git a/backend/scripts/export_file_check_openapi.py b/backend/scripts/export_file_check_openapi.py index 26a33d46..857cb3fd 100644 --- a/backend/scripts/export_file_check_openapi.py +++ b/backend/scripts/export_file_check_openapi.py @@ -13,6 +13,8 @@ from app.services.file_check_tools.openapi_spec import build_file_check_openapi_ def main() -> None: + # 仓库内静态 JSON 使用占位地址;各环境请用 URL 导入 GET /api/file-check/tools/openapi.json + # 或导出前设置 HXOPS_TOOLS_API_BASE。勿将个人/测试机 IP 提交进 docs/openapi/。 base = ( os.getenv("HXOPS_TOOLS_API_BASE") or os.getenv("PUBLIC_BASE_URL") diff --git a/backend/tests/test_agent_runtime_context_registry.py b/backend/tests/test_agent_runtime_context_registry.py index 805cadeb..6944d837 100644 --- a/backend/tests/test_agent_runtime_context_registry.py +++ b/backend/tests/test_agent_runtime_context_registry.py @@ -13,6 +13,7 @@ from types import SimpleNamespace import pytest from app.services.agent_registry.resolver import resolve_agent_code +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 ( CONTEXT_ADAPTER_REGISTRY, @@ -76,14 +77,14 @@ def test_build_chat_dify_inputs_routes_file_check_by_registered_agent_code(monke 'app.services.file_check_tools.context_adapter.build_file_check_dify_inputs', lambda current_agent, required, **kwargs: { 'adapter': 'file_check', - 'task_id': '7', + AGENT_RUNTIME_CONTEXT_INPUT: '{"refs":{"schedule_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' + assert AGENT_RUNTIME_CONTEXT_INPUT in inputs def test_register_context_adapter_allows_custom_code(): diff --git a/backend/tests/test_chat_dify_start_inputs.py b/backend/tests/test_chat_dify_start_inputs.py index 376ed6bf..e560c9bf 100644 --- a/backend/tests/test_chat_dify_start_inputs.py +++ b/backend/tests/test_chat_dify_start_inputs.py @@ -19,7 +19,6 @@ 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) @@ -142,7 +141,7 @@ def test_hybrid_executor_injects_shipping_agent_runtime_context(app, monkeypatch def test_file_check_adapter_outputs_task_id_and_runtime_context(app): - """file_check Agent 应同时输出 task_id 与 agent_runtime_context(迭代 5)。""" + """file_check Agent 仅输出 agent_runtime_context;task_id / turn_id 在 refs 内。""" agent = _agent( agent_code='file_check', runtime_provider='dify', @@ -156,11 +155,58 @@ def test_file_check_adapter_outputs_task_id_and_runtime_context(app): agent, session_id='conv-file-check-start-001', request_id='req-file-check-001', + hxops_turn_id='turn-file-check-start-001', ) - assert inputs[FILE_CHECK_TASK_ID_INPUT] == '42' - assert AGENT_RUNTIME_CONTEXT_INPUT in inputs + assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT} payload = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT]) assert payload['agent_code'] == 'file_check' assert payload['refs']['schedule_task_id'] == '42' + assert payload['refs']['hxops_turn_id'] == 'turn-file-check-start-001' assert payload['domain']['state_hint']['schedule_task_id'] == '42' + assert payload['domain']['state_hint']['hxops_turn_id'] == 'turn-file-check-start-001' + + +def test_file_check_executor_injects_turn_id_via_handler(app, monkeypatch): + """file_check Handler.prepare_stream 生成 turn 后,Executor 应向 Dify 注入 hxops_turn_id。""" + from app.services.agent_registry.handlers.bootstrap import load_handlers + + captured: dict = {} + + def fake_stream_chat(*args, **kwargs): + captured['inputs'] = kwargs.get('inputs') + captured['hxops_turn_id'] = kwargs.get('hxops_turn_id') + 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() + ctx = ChatStreamContext( + query='立即执行检核', + display_query='立即执行检核', + user=SimpleNamespace(id=1), + agent=_agent( + agent_code='file_check', + runtime_provider='dify', + conversation_mode='task_chat', + name='RoHS 检核 Agent', + bound_schedule_task_id=42, + capabilities={'task_progress': True}, + ), + session=SimpleNamespace(session_id='conv-file-check-exec-001'), + external_conversation_id=None, + request_id='req-file-check-exec-001', + ) + from app.services.chat.executors import stream_chat_via_executor + + list(stream_chat_via_executor(ctx)) + + assert captured.get('hxops_turn_id') + inputs = captured.get('inputs') or {} + assert set(inputs.keys()) == {AGENT_RUNTIME_CONTEXT_INPUT} + runtime_context = json.loads(inputs[AGENT_RUNTIME_CONTEXT_INPUT]) + assert runtime_context['refs']['hxops_turn_id'] == captured['hxops_turn_id'] diff --git a/backend/tests/test_file_check_tools.py b/backend/tests/test_file_check_tools.py index ee264315..73e76aec 100644 --- a/backend/tests/test_file_check_tools.py +++ b/backend/tests/test_file_check_tools.py @@ -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 diff --git a/docs/dify/agent_runtime_context_integration.md b/docs/dify/agent_runtime_context_integration.md index aba68422..21b08c81 100644 --- a/docs/dify/agent_runtime_context_integration.md +++ b/docs/dify/agent_runtime_context_integration.md @@ -91,6 +91,8 @@ - `reference_context.candidates` - `refs.task_no` - `refs.batch_no` +- `refs.schedule_task_id`(文件检核 Agent) +- `refs.hxops_turn_id`(文件检核进度绑定) - `domain.state_hint.status` 推荐顺序: diff --git a/docs/features/file-check/technical.md b/docs/features/file-check/technical.md index 4995714e..1db9e0ce 100644 --- a/docs/features/file-check/technical.md +++ b/docs/features/file-check/technical.md @@ -2,7 +2,7 @@ > **唯一维护文档**:产品原型、Chatflow 编排、OpenAPI Tool 配置、部署、Agent 配置、验证与排错 **均在本文件**(`docs/features/file-check/technical.md`)。 > -> **通用化说明**:本手册适用于 RoHS、MSDS 等所有文件检核类型。多个 Agent 共用同一 Dify Chatflow;HXOPS 按 Agent Registry 列 `bound_schedule_task_id` 注入不同 `task_id`(`capabilities.task_progress=true`)。历史查询通过 Tool API `search_file_check_history` 按运行时 `task_id` 解析 Dataset,画布无需 Knowledge Retrieval 节点。 +> **通用化说明**:本手册适用于 RoHS、MSDS 等所有文件检核类型。多个 Agent 共用同一 Dify Chatflow;HXOPS 按 Agent Registry 列 `bound_schedule_task_id` 写入 `agent_runtime_context.refs.schedule_task_id`(`capabilities.task_progress=true`)。历史查询通过 Tool API `search_file_check_history` 按运行时 `task_id` 解析 Dataset,画布无需 Knowledge Retrieval 节点。 > > **同步维护**:Tool API 契约变更时,须同时更新本文件、`backend/app/services/file_check_tools/openapi_base.json`,并执行 `python backend/scripts/export_file_check_openapi.py` 重新生成 [`docs/openapi/file_check_tools_openapi.json`](../../openapi/file_check_tools_openapi.json)。 @@ -155,7 +155,7 @@ flowchart LR ##### 原型范围内 - AI 对话主入口:自然语言发起检核、查询状态、获取报告、能力说明 -- 固定检核任务:Chatflow Start 节点配置唯一 `task_id`,**不做任务列表选择**(一期简化) +- 固定检核任务:HXOPS 经 `agent_runtime_context.refs.schedule_task_id` 注入检核任务 ID,**不做任务列表选择**(一期简化) - 异步检核执行:后台逐条「查 SRM 未检核 → 读取 SRM 检核数据(含 PLM 推送字段)→ AI 字段检核 → 输出字段提示 → 汇总 Excel」 - **AI 辅助、人工终审**:检核报告与对话提供字段级 AI 结论;**SRM 审核/驳回由品质人员在 SRM 手工完成** - **按轮问答绑定进度**:每条「发起检核」助手消息下展示独立进度卡片(`chat_logs.run_id`) @@ -224,7 +224,7 @@ flowchart TB 1. **对话驱动、后台异步**:发起检核立即返回,进度由前端卡片轮询,不阻塞对话流。 2. **实时与历史分流**:最新状态/批次 ID/Excel 必须走 Tool API;历史报告总结必须走知识库,不可混用。 3. **按轮问答隔离批次**:同一会话多次「执行检核」,每条助手消息独立绑定 `run_id`,进度卡片互不干扰。 -4. **单一检核任务**:一期 Start 节点固定 `task_id`,降低业务人员选择成本。 +4. **单一检核任务**:一期由 HXOPS 注入 `refs.schedule_task_id`,画布解析后使用,降低业务人员选择成本。 5. **进行中可查询、不可重复启**:同一任务已有 `running` 批次时,启动 API 返回 `check_running`,对话引导查进度。 6. **AI 辅助、人工终审**:AI 输出字段级检核结论与提示;**SRM 审核/驳回始终由品质人员在 SRM 手工完成**,Agent 不自动审核或驳回。 7. **单一数据源(Agent)**:检核输入**仅来自 SRM**(含 PLM 改造后推送的比对字段);Agent **不直连、不加载 PLM**。 @@ -373,15 +373,16 @@ flowchart TD | 步骤 | 参与方 | 说明 | |------|--------|------| | 1. 用户发消息 | 用户 / HXOPS 前端 | 如「执行 RoHS 检核」 | -| 2. 注入上下文 | HXOPS `/api/chat/completions` | 写入 `hxops_session_id`、`hxops_turn_id`(每轮 UUID) | -| 3. 意图识别 | Dify LLM | 分类为 `run_check` | -| 4. 启动检核 | Dify HTTP → Tool API | `POST /api/file-check/tools/tasks/run`,Body 含 `task_id`、`hxops_session_id`、`hxops_turn_id`、`user_message` | -| 5. 创建/复用批次 | HXOPS 后端 | 创建 `ScheduleRun` 或返回已有 running(`check_running`);写入 bind 上下文 | -| 6. 助手回复 | Dify Answer | 「检核已启动」+ 批次号(如有) | -| 7. 绑定 run_id | HXOPS `message_end` | 按 `turn_id` 优先匹配,写入 `chat_logs.run_id` | -| 8. 进度轮询 | HXOPS 前端 | 从助手消息 `run_id` 轮询 `GET /api/workspace/file-check/runs/{run_id}` | -| 9. 后台执行 | 任务引擎 | 见 §2.3.3 | -| 10. 完成展示 | 进度卡片 + Answer | 100%、Excel 下载、知识库状态;输入解锁 | +| 2. 注入上下文 | HXOPS `/api/chat/completions` | 登记 `chat_tool_runs`;向 Dify Start 注入 `agent_runtime_context`(含 `refs.schedule_task_id`、`refs.hxops_turn_id`) | +| 3. 解析上下文 | Dify Code / `parse_agent_runtime_context` | 从 `refs` 提取 `schedule_task_id`、`hxops_turn_id` | +| 4. 意图识别 | Dify LLM | 分类为 `run_check` | +| 5. 启动检核 | Dify Tool API | `POST /api/file-check/tools/tasks/run`,Body 含 `task_id`、`hxops_turn_id`、`user_message` | +| 6. 创建/复用批次 | HXOPS 后端 | 创建 `ScheduleRun` 或返回已有 running(`check_running`);按 `hxops_turn_id` 绑定 | +| 7. 助手回复 | Dify Answer | 「检核已启动」+ 批次号(如有) | +| 8. 绑定 run_id | HXOPS `message_end` | 按 `turn_id` 优先匹配,写入 `chat_logs.run_id` | +| 9. 进度轮询 | HXOPS 前端 | 从助手消息 `run_id` 轮询 `GET /api/workspace/file-check/runs/{run_id}` | +| 10. 后台执行 | 任务引擎 | 见 §2.3.3 | +| 11. 完成展示 | 进度卡片 + Answer | 100%、Excel 下载、知识库状态;输入解锁 | ```mermaid sequenceDiagram @@ -510,8 +511,8 @@ sequenceDiagram | 项 | 说明 | |----|------| | 触发 | 用户表达立即检核意图,如「执行 RoHS 检核」「开始文件检核」 | -| 配置 | Dify Start 固定 `task_id`;与 Agent `extra_config.tool_run_progress.schedule_task_id` 一致 | -| 处理 | Tool API 异步启动 `run_task_now`;Body 必传 `hxops_session_id`、`hxops_turn_id` | +| 配置 | HXOPS 注入 `agent_runtime_context.refs.schedule_task_id`;与 Agent `bound_schedule_task_id` / `extra_config.tool_run_progress.schedule_task_id` 一致 | +| 处理 | Tool API 异步启动 `run_task_now`;Body 必传 `hxops_turn_id`(来自 `refs.hxops_turn_id`) | | 输出 | Answer 确认启动;前端进度卡片挂于该轮助手消息下 | | 异常 | 任务不存在、鉴权失败 → 错误兜底 Answer | @@ -580,7 +581,7 @@ sequenceDiagram **关键业务规则汇总** - 实时状态与历史检索严格分流(§2.3.4)。 -- 一期不做任务选择,Start 固定单一 `task_id`。 +- 一期不做任务选择,任务 ID 由 HXOPS 写入 `agent_runtime_context.refs.schedule_task_id`。 - 同任务 running 时不可重复启动。 - 进度卡片按 ChatLog 绑定,非 Session 级。 - Agent **仅消费 SRM 数据**(含 PLM 推送字段),不直连 PLM。 @@ -792,7 +793,7 @@ sequenceDiagram - **Dify 检核 Workflow** + `FileCheckService`:逐条判定合格 / 不合格 / 人工判定 - **本 Chatflow**:编排对话,调用 HXOPS Tool API 发起检核、查结果、展示报告链接;对历史报告类问题调用 **历史检索 Tool API**;**不自行做合格判定** -- **当前有效启动方式**:每个 Agent 绑定一个 `task_id`(HXOPS 对话 API 注入);Chatflow 通过 **OpenAPI Tool 节点**调用 `run_file_check`,不再使用 HTTP Request 节点,也不做任务列表选择。 +- **当前有效启动方式**:每个 Agent 绑定一个 `schedule_task_id`(HXOPS 写入 `agent_runtime_context.refs`);Chatflow 解析后通过 **OpenAPI Tool 节点**调用 `run_file_check`,不再使用 HTTP Request 节点,也不做任务列表选择。 - **前端进度展示**:HXOPS 前端通过 Agent `extra_config.capabilities=["tool_run_progress"]` 挂载通用任务进度卡片,不按 Agent 名称硬编码。 **Tool API 基路径**:`/api/file-check` @@ -809,6 +810,7 @@ sequenceDiagram 3. [按节点顺序配置(核心维护区)](#3-按节点顺序配置核心维护区) - [3.0 Dify 变量类型约定](#30-dify-变量类型约定) - [3.1 用户输入](#31-用户输入) + - [3.1A Code:解析运行态上下文](#31a-code解析运行态上下文) - [3.2 LLM:意图识别](#32-llm意图识别) - [3.3 IF:意图分类](#33-if意图分类) - [3.7 Answer:Tool 调用失败](#37-answer-tool-调用失败) @@ -852,7 +854,70 @@ cd backend flask db upgrade ``` -需已应用 文件检核知识库同步相关迁移(`kb_sync_enabled`、`kb_group_id` 等字段)。 +需已应用文件检核知识库同步相关迁移(`kb_sync_enabled`、`kb_group_id` 等字段)。 + +**`chat_tool_runs` 迁移(进度持久绑定)**:修订 `e2f3a4b5c6d7` 合并 Alembic 双 head(`d1e2f3a4b5c6`、`ff6a7b8c9d0e`)并建表。部署前建议确认: + +```bash +flask db heads # 升级前若仍为多 head,upgrade 后应只剩一个 +flask db upgrade +flask db current # 应包含 e2f3a4b5c6d7 +``` + +`chat_tool_runs` 为 **聊天轮次(chat-turn)绑定表**:`turn_id` 非空且唯一,仅适用于「用户经 `/api/chat/completions` 发起检核」场景;非聊天入口若未来写入须另行设计。 + +### 1.1A 进度绑定:`hxops_turn_id` 显式传递(重要) + +| 能力 | 实现 | +| --- | --- | +| 跨 worker 持久化 | `chat_tool_runs` 表 | +| HXOPS → Dify Start | **仅**注入 `agent_runtime_context`(与货代发货等平台 Agent 一致);`refs.schedule_task_id`、`refs.hxops_turn_id` 写入 JSON 快照 | +| Dify → Tool API | RUN_FILE_CHECK 入参须传 `task_id`(= `refs.schedule_task_id`)与 `hxops_turn_id`(= `refs.hxops_turn_id`),经 `parse_agent_runtime_context` 或 Code 节点解析后传入 | +| Tool 绑定优先级 | `hxops_turn_id` > 内存 registry > `session_id` + `user_message`(多候选时不绑定) | +| 进度轮询 | `chat_logs.run_id` → `chat_tool_runs` → legacy 兜底 | + +**Dify 画布必配 Start 变量**:**仅** `agent_runtime_context`(字符串)。HXOPS `FileCheckHandler.prepare_stream` 每轮生成 UUID 并写入 `chat_tool_runs`;`build_file_check_dify_inputs` 将 `schedule_task_id` / `hxops_turn_id` 写入 `refs`。 + +**RUN_FILE_CHECK Tool 推荐入参**(经 Code 或 `parse_agent_runtime_context` 解析后映射): + +```json +{ + "task_id": "", + "hxops_turn_id": "", + "conversation_id": "{{#sys.conversation_id#}}", + "trigger_source": "dify_chatflow", + "user_message": "{{#sys.query#}}" +} +``` + +**歧义保护**:无 `hxops_turn_id` 且同会话存在多个同文案 pending turn 时,**不绑定**(宁可未绑定 + 服务端 warning),避免误绑。画布未解析 `refs.hxops_turn_id` 或 Tool 未回传时,进度卡片可能无法显示。 + +**`agent_runtime_context` 对齐**:与货代发货等 Agent 共用平台协议;`refs.schedule_task_id` / `refs.hxops_turn_id` 及 `domain.state_hint` 镜像字段供 Dify `parse_agent_runtime_context` Tool 或 Code 节点读取。**勿**再在 Start 配置顶层 `task_id` / `hxops_turn_id`。 + +#### 1.1B Dify 画布改造清单(`agent_runtime_context` 单一 Start) + +| 步骤 | 操作 | +| --- | --- | +| 1 | Start(`用户输入`)**删除** `task_id`、`hxops_turn_id` 等 HXOPS 业务变量 | +| 2 | Start **新增/保留** `agent_runtime_context`(Paragraph / Long Text);`query` 继续绑定 `sys.query` | +| 3 | Start 与 LLM 之间 **新增** [§3.1A Code:解析运行态上下文](#31a-code解析运行态上下文) | +| 4 | 原引用 `用户输入.task_id` 的节点改为 `解析运行态上下文.task_id` | +| 5 | RUN_FILE_CHECK(§3.8)入参绑定 `解析运行态上下文.task_id` 与 `解析运行态上下文.hxops_turn_id` | +| 6 | (可选)导入 `docs/openapi/agent_runtime_context_tools.dify.json`,用 Tool `parse_agent_runtime_context` 替代 Code 节点 | +| 7 | Dify 直连调试时,Start 的 `agent_runtime_context` 手工填含 `refs` 的 JSON(见 §3.1A 示例) | + +**Dify 直连调试 `agent_runtime_context` 示例**: + +```json +{ + "agent_code": "file_check", + "refs": { + "schedule_task_id": "12", + "hxops_turn_id": "debug-turn-001" + }, + "platform": { "session_id": "conv-debug-001" } +} +``` ### 1.2 环境变量 @@ -864,8 +929,8 @@ flask db upgrade **注意**:token 仅放在 Dify Secret/Credential,不要写入前端或导出 YAML。 -**HXOPS 对话 API**(`/api/chat/completions`):向 Dify 仅注入 **`task_id`**;`conversation_id` 由 Dify 系统变量提供。 -**进度卡片绑定**(服务端,不在 Dify 画布配置):`chat.py` 每轮登记 `chat_turn_registry`,Tool `run_file_check` 传 `user_message`(+ `task_id`)即可,后端推断 session/turn 并回写 `chat_logs.run_id`。 +**HXOPS 对话 API**(`/api/chat/completions`):向 Dify Start **仅**注入 **`agent_runtime_context`**(内含 `refs.schedule_task_id`、`refs.hxops_turn_id`);`conversation_id` 由 Dify 系统变量提供。 +**进度卡片绑定**:HXOPS 登记 turn 并写入 `chat_tool_runs`;Tool `run_file_check` **必须**回传 `hxops_turn_id`(见 §1.1A);`message_end` 回写 `chat_log_id` 与 `chat_logs.run_id`。 **OpenAPI 工具托管**:Base URL 与 Bearer token 在 §1.4–§1.5 配置,画布内勿使用 HTTP Request 节点。 ### 1.3 创建 Chatflow 应用 @@ -887,6 +952,8 @@ GET {HXOPS_TOOLS_API_BASE}/api/file-check/tools/openapi.json 该端点**无需鉴权**;响应中 `servers[0].url` 已按服务端 `HXOPS_TOOLS_API_BASE` 填充。换环境时重新 URL 导入或改工具 Server URL,**不必改 Chatflow 连线**。 +> 仓库内静态文件 `docs/openapi/file_check_tools_openapi.json` 的 `servers[0].url` 为占位地址 `http://127.0.0.1:5052`,**勿**将个人/测试机 IP 提交进仓库;生产/测试请用 URL 导入获取当前环境地址。 + **方式 B — 上传文件** 1. 下载 [`docs/openapi/file_check_tools_openapi.json`](../../openapi/file_check_tools_openapi.json)(或执行 `python backend/scripts/export_file_check_openapi.py`)。 @@ -973,13 +1040,13 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ 说明: - 前端只判断 `tool_run_progress` 能力,不判断 Agent 名称。 -- **`schedule_task_id` 必填**:与排程 `ScheduleTask.id` 一致;HXOPS 对话 API 将其作为 Dify `inputs.task_id` 注入。 +- **`schedule_task_id` 必填**:与排程 `ScheduleTask.id` 一致;HXOPS 对话 API 将其写入 `agent_runtime_context.refs.schedule_task_id`。 - 也可用别名 `task_id`(与 `schedule_task_id` 二选一,含义相同)。 - **无需配置 `log_progress_url` / `detail_url_template`**:前端与后端按固定路径 + `schedule_task_id` / `run_id` 自动拼接轮询 URL。 - **卡片标题**:优先使用 `ScheduleTask.name`(enrich 时写入 `tool_run_progress.title`);进度 API 返回的 `run.title` 亦来自排程名称。 - `poll_interval_seconds` 默认 2 秒,前端限制在 1-30 秒。 - 运行中若 `lock_input_when_running=true`,当前 Agent 对话输入、发送和附件上传会被锁定。 -- **进度卡片权威来源**:`chat.py` 登记 turn → Tool 启动时写入 `ScheduleRun.api_request_json` 绑定字段 → `message_end` 按 turn/query 匹配并写入 **`chat_logs.run_id`**。Dify 画布**无需**传递 `hxops_session_id` / `hxops_turn_id`。 +- **进度卡片权威来源**:`chat.py` 登记 turn 并写入 `chat_tool_runs` → HXOPS 向 Dify Start 注入 `agent_runtime_context`(含 `refs.hxops_turn_id`)→ Tool 回传 `hxops_turn_id` 绑定 `schedule_run_id` → `message_end` 回写 `chat_log_id` 与 **`chat_logs.run_id`**。`for-log` 优先读 `chat_logs.run_id`,其次 `chat_tool_runs`,最后 legacy 兜底。 - **查询类分支**不调用启动检核 API,对应 `ChatLog` 无 `run_id`,不会出现进度条。 - 纯问答/查询与「立即执行」由 LLM 路由到不同 **Tool** 节点区分,**不要**在前端或 Agent 配置里硬编码意图关键词。 @@ -999,7 +1066,7 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ - 环境变量 `ROHS_TOOLS_API_KEY` 已更名为 `FILE_CHECK_TOOL_API_KEY`(未配则回退 `INTEGRATION_API_KEY`)。 - RoHS / MSDS 等 Agent **共用同一 Chatflow**;差异仅在 Agent `schedule_task_id` 与排程绑定的知识库分组(历史 Tool 自动解析 Dataset)。 - Dify:在**工具管理**重新 URL 导入 OpenAPI(§1.4),画布使用 **Tool 节点**(§3.8 起),**删除**旧 HTTP Request 检核节点。 -- Start:**不要**写死各环境 `task_id`(HXOPS 对话 API 注入);**不要**再配 `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token`(OpenAPI 工具 Credential 托管)。 +- Start:**仅**保留 `agent_runtime_context`(及 `query` 等系统变量);**不要**写死 `task_id` / `hxops_turn_id`;**不要**再配 `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token`(OpenAPI 工具 Credential 托管)。 --- @@ -1009,7 +1076,8 @@ curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/ ```mermaid flowchart TD - A[用户输入] --> B[LLM: 意图识别] + A[用户输入] --> A2[Code: 解析运行态上下文] + A2 --> B[LLM: 意图识别] B --> C{IF: 意图分类} C -->|run_check| G[Tool: 启动检核] @@ -1052,6 +1120,7 @@ flowchart TD | # | 节点类型 | 节点名 | 配置章节 | | --- | --- | --- | --- | | 1 | Start | 用户输入 | [§3.1](#31-用户输入) | +| 1A | Code | 解析运行态上下文 | [§3.1A](#31a-code解析运行态上下文) | | 2 | LLM | 意图识别 | [§3.2](#32-llm意图识别) | | 3 | IF | 意图分类 | [§3.3](#33-if意图分类) | | 7 | Answer | Tool 调用失败 | [§3.7](#37-answer-tool-调用失败) | @@ -1206,7 +1275,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 {{#用户输入.query#}} 文件检核任务 ID: -{{#用户输入.task_id#}} +{{#解析运行态上下文.task_id#}} ``` > 注意:不要使用 `{{节点名.变量名}}`,必须使用 `{{#节点名.变量名#}}`。 @@ -1215,7 +1284,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 | 节点名 | 入参(名 · Dify 类型 · 必填 · 绑定) | 出参(名 · Dify 类型 · 说明) | | --- | --- | --- | -| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `用户输入.task_id`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** | +| `检索历史检核报告` | Tool · `task_id` · **Integer** · 是 · `解析运行态上下文.task_id`;`query` · **String** · 是 · `用户输入.query` | `json` · **Object**;`text` · **String** | | `解析历史检索响应` | `tool_json` · **Object** · 是 · `检索历史检核报告.json`;`tool_text` · **String** · 否 | `count` · **Number**;`segments_text` · **String** | | `生成历史报告回答` | Prompt · `用户输入.query`;`解析历史检索响应.segments_text` | `text` · **String** | @@ -1229,7 +1298,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 | 节点名 | `用户输入` | | 用户输入 | **开启** | | 文件上传 | 关闭(文件检核不依赖对话附件) | -| 下一节点 | [§3.2 LLM:意图识别](#32-llm意图识别) | +| 下一节点 | [§3.1A Code:解析运行态上下文](#31a-code解析运行态上下文) | **系统传出**(Start 开启用户输入后自动可用) @@ -1238,21 +1307,20 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 | `sys.query` | String | 用户当轮话术 | | `sys.conversation_id` | String | 会话 ID | -**输入变量**(在 `用户输入` 节点「变量」页配置;`query` / `conversation_id` 绑定系统变量) +**输入变量**(在 `用户输入` 节点「变量」页配置) | 变量名 | Dify 类型 | 必填 | 绑定 / 默认值 | 说明 | | --- | --- | --- | --- | --- | | `query` | String | 是 | `sys.query` | 用户话术 | -| `task_id` | String | 是 | HXOPS 注入或 Dify 直连调试手工填 | 检核任务 ID(`ScheduleTask.id`) | -| `conversation_id` | String | 否 | `sys.conversation_id` | 可选,传给 `run_file_check` | +| `agent_runtime_context` | Paragraph | 是 | HXOPS 对话 API 注入;Dify 直连调试时手工填 JSON | 平台运行态快照;含 `refs.schedule_task_id`、`refs.hxops_turn_id` | -**传出(供下游引用)**:`用户输入.query` / `task_id` / `conversation_id` · String。 +**传出(供下游引用)**:`用户输入.query` · String;`用户输入.agent_runtime_context` · String。 -**无效变量(勿在 Start 配置、勿在 Prompt/IF/Tool 引用)** +**无效变量(勿在 Start 配置、勿在 Prompt/IF/Tool 直接引用)** | 无效引用 | 原因 | | --- | --- | -| `hxops_session_id` / `hxops_turn_id` | 由 HXOPS 内存注册表 + Tool API 推断,不必出现在 Dify | +| `task_id` / `hxops_turn_id` / `hxops_session_id`(Start 顶层) | 已迁入 `agent_runtime_context.refs`;须经 §3.1A 解析 | | `用户输入.HXOPS_TOOLS_API_BASE` / `hxops_tool_api_token` | OpenAPI 工具已托管 Base URL 与 Bearer token | | `用户输入.default_task_id` / `default_task_no` | 任务选择分支已移除 | | `选择检核任务.*` / `解析检核任务列表响应.*` / `查询检核任务列表.*` | 历史任务选择分支,当前编排不存在 | @@ -1262,23 +1330,86 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 --- +### 3.1A Code:解析运行态上下文 + +**上游**:用户输入(Start) + +**用途**:从 `agent_runtime_context` JSON 提取文件检核画布所需的 `task_id`(= `refs.schedule_task_id`)与 `hxops_turn_id`(= `refs.hxops_turn_id`)。本节点是画布**唯一**解析入口(与货代发货 `parse_agent_runtime_context` 职责等价;Chatflow 推荐 Code 节点以降低 Tool 调用成本)。 + +| 项 | 配置 | +| --- | --- | +| 类型 | Code | +| 节点名 | `解析运行态上下文` | +| 下一节点 | [§3.2 LLM:意图识别](#32-llm意图识别) | + +**输入变量** + +| 变量名 | Dify 类型 | 必填 | 绑定来源 | +| --- | --- | --- | --- | +| `agent_runtime_context` | String | 是 | `用户输入.agent_runtime_context` | + +**输出变量** + +| 输出名 | Dify 类型 | 说明 | +| --- | --- | --- | +| `task_id` | String | 检核任务 ID(`ScheduleTask.id`),供下游 Tool / LLM 复用 | +| `schedule_task_id` | String | 与 `task_id` 相同,显式命名便于对照平台协议 | +| `hxops_turn_id` | String | 本轮对话唯一标识;RUN_FILE_CHECK **必须**回传 | + +**完整 Python 代码** + +```python +import json + + +def main(agent_runtime_context: str) -> dict: + ctx: dict = {} + raw = str(agent_runtime_context or "").strip() + if raw: + try: + parsed = json.loads(raw) + if isinstance(parsed, dict): + ctx = parsed + except json.JSONDecodeError: + pass + + refs = ctx.get("refs") if isinstance(ctx.get("refs"), dict) else {} + schedule_task_id = str(refs.get("schedule_task_id") or "").strip() + hxops_turn_id = str(refs.get("hxops_turn_id") or "").strip() + + return { + "task_id": schedule_task_id, + "schedule_task_id": schedule_task_id, + "hxops_turn_id": hxops_turn_id, + } +``` + +**可选:Tool 方式**(与 Code 二选一) + +- 导入 `docs/openapi/agent_runtime_context_tools.dify.json` +- 节点名建议 `Tool 解析运行态上下文`;调用 `parse_agent_runtime_context` +- 推荐 paths:`refs.schedule_task_id`、`refs.hxops_turn_id`、`platform.session_id` +- 将 Tool 输出映射为与本节相同的 `task_id` / `hxops_turn_id` 变量名,供 §3.8 使用 + +--- + ### 3.2 LLM:意图识别 -**上游**:用户输入 +**上游**:解析运行态上下文、用户输入 **Prompt 引用变量**(在 Prompt 中插入,见 §3.0.2) | Dify 引用 | 说明 | | --- | --- | | `{{#用户输入.query#}}` | 用户当轮话术 | -| `{{#用户输入.task_id#}}` | 当前 Agent 绑定的检核任务 ID | +| `{{#解析运行态上下文.task_id#}}` | 当前 Agent 绑定的检核任务 ID(来自 `refs.schedule_task_id`) | **结构化输出**(LLM 节点开启 JSON / 结构化输出) | 输出名 | Dify 类型 | 说明 | | --- | --- | --- | | `intent` | String | `run_check` / `check_status` / `history_report_query` / `explain_capability` / `other` | -| `task_id` | String | 用户话术中抽取的任务 ID;无则 `""`(通常用 Start 的 `task_id` 即可) | +| `task_id` | String | 用户话术中抽取的任务 ID;无则 `""`(通常用 `解析运行态上下文.task_id` 即可) | | `run_id` | String | 检核批次 ID,无则 `""` | | `confidence` | Number | 0–1 | @@ -1344,7 +1475,7 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 {{#用户输入.query#}} 文件检核任务 ID: -{{#用户输入.task_id#}} +{{#解析运行态上下文.task_id#}} ``` **下游**:→ [§3.3 IF:意图分类](#33-if意图分类) @@ -1416,14 +1547,27 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输 | 参数 | 类型 | 绑定 / 固定值 | | --- | --- | --- | -| `task_id` | Number | `用户输入.task_id` | +| `task_id` | Number | `解析运行态上下文.task_id` | +| `hxops_turn_id` | String | `解析运行态上下文.hxops_turn_id` | | `trigger_source` | String | 固定 `dify_chatflow` | -| `conversation_id` | String | `用户输入.conversation_id`(可选) | +| `conversation_id` | String | `sys.conversation_id`(系统变量) | | `user_message` | String | `用户输入.query`(**必填**,用于 turn 注册表匹配) | -> **不必**绑定 `hxops_session_id` / `hxops_turn_id`。HXOPS 在调用 Dify 前已登记本轮 turn;Tool API 通过 `user_message` 与注册表推断绑定(见 `chat_turn_registry.infer_bind_context_for_run_request`)。 +> **进度绑定**:HXOPS 在调用 Dify 前已登记本轮 turn 并写入 `chat_tool_runs`;RUN_FILE_CHECK **必须**回传 `hxops_turn_id`(来自 `refs.hxops_turn_id`,经 §3.1A 解析)。`user_message` 仅作展示与无 turn_id 时的受限兜底(多候选时不绑定)。 > **`task_no` 勿填**:OpenAPI 已移除该入参;若 Dify 仍显示,请重新 URL 导入 OpenAPI(§1.4)后删除节点上的 `task_no` 绑定。 +**等效 JSON Body 示例**: + +```json +{ + "task_id": "<解析运行态上下文.task_id>", + "hxops_turn_id": "<解析运行态上下文.hxops_turn_id>", + "conversation_id": "{{#sys.conversation_id#}}", + "trigger_source": "dify_chatflow", + "user_message": "{{#用户输入.query#}}" +} +``` + **Tool 节点出参**(Dify 固定) | 输出名 | Dify 类型 | 说明 | @@ -1612,7 +1756,7 @@ def main(tool_json, tool_text: str = "") -> dict: **下游**:→ [§3.10 IF:启动业务分支](#310-if启动业务分支) -**HXOPS 进度绑定(自动)**:Tool 启动检核成功或 `check_running` 时,HXOPS 记录 session + user_message;同轮 `message_end` 落 `ChatLog` 时写入 `run_id`。Dify **不必**在 Answer 输出 `tool_run_id`。 +**HXOPS 进度绑定(自动)**:`chat.py` 每轮生成 `hxops_turn_id` 并写入 `chat_tool_runs`;HXOPS 向 Dify Start 注入 `agent_runtime_context`(含 `refs.hxops_turn_id`);画布解析后 Tool 回传 `hxops_turn_id` 绑定 `schedule_run_id`;`message_end` 回写 `chat_log_id` 与 `run_id`。Dify **不必**在 Answer 输出 `tool_run_id`。 --- @@ -1703,7 +1847,7 @@ def main(tool_json, tool_text: str = "") -> dict: | `user_query` | String | 是 | `用户输入.query` | | `intent_run_id` | String | 否 | `意图识别.run_id` | | `intent_task_id` | String | 否 | `意图识别.task_id` | -| `task_id` | String | 是 | `用户输入.task_id` | +| `task_id` | String | 是 | `解析运行态上下文.task_id` | **输出变量** @@ -2178,7 +2322,7 @@ def main(tool_json, tool_text) -> dict: | 配置项 | 绑定 | | --- | --- | | 工具 | OpenAPI 自定义工具 `search_file_check_history` | -| `task_id` | `{{#用户输入.task_id#}}` | +| `task_id` | `{{#解析运行态上下文.task_id#}}` | | `query` | `{{#用户输入.query#}}` | | `top_k`(可选) | 默认 5,可不填 | | 异常处理 | **Fail Branch** → §3.7 | @@ -2391,6 +2535,32 @@ def main(tool_json: dict, tool_text: str) -> dict: | `你能做什么` | §3.22 | | 无法识别意图 | §3.23 | +### C.1 服务端绑定验证(部署后) + +在 HXOPS 前端发起一次「执行文件检核」后,于 PostgreSQL 执行: + +```sql +select id, turn_id, chat_log_id, schedule_task_id, schedule_run_id, status, bind_source, created_at +from chat_tool_runs +order by id desc +limit 20; + +select id, query, run_id, created_at +from chat_logs +order by id desc +limit 20; +``` + +**预期**: + +| 检查项 | 预期 | +| --- | --- | +| `chat_tool_runs.turn_id` | 非空 UUID;与当轮 `refs.hxops_turn_id` 一致 | +| `chat_tool_runs.schedule_run_id` | Tool 启动后非空 | +| `chat_tool_runs.chat_log_id` | `message_end` 后非空 | +| `chat_tool_runs.bind_source` | 含 `turn_id` 或 `chat_log` | +| `chat_logs.run_id` | 与 `schedule_run_id` 一致 | + --- ## 附录 D:相关代码 @@ -2440,6 +2610,8 @@ def main(tool_json: dict, tool_text: str) -> dict: ### E.3 迁移后画布检查 +- [ ] Start **仅**含 `agent_runtime_context`(及 `query`);无顶层 `task_id` / `hxops_turn_id` +- [ ] 存在 §3.1A `解析运行态上下文` 节点,且 RUN_FILE_CHECK 绑定其 `task_id` / `hxops_turn_id` - [ ] 不存在调用 `/api/file-check/tools/*` 的 HTTP Request 节点 - [ ] 不存在手写 `Authorization` Header - [ ] Start 无 Tool API token / base URL diff --git a/docs/openapi/file_check_tools_openapi.json b/docs/openapi/file_check_tools_openapi.json index 0653ec7f..b413d781 100644 --- a/docs/openapi/file_check_tools_openapi.json +++ b/docs/openapi/file_check_tools_openapi.json @@ -7,7 +7,7 @@ }, "servers": [ { - "url": "http://192.168.36.108:5052", + "url": "http://127.0.0.1:5052", "description": "HXOPS_TOOLS_API_BASE" } ], @@ -546,12 +546,22 @@ "user_message": { "type": "string", "nullable": true + }, + "hxops_turn_id": { + "type": "string", + "nullable": true, + "description": "本轮对话唯一标识;须与 agent_runtime_context.refs.hxops_turn_id(经画布 §3.1A 解析)一致,Tool 原样回传" + }, + "hxops_session_id": { + "type": "string", + "nullable": true, + "description": "HXOPS 会话 ID;可与 sys.conversation_id 二选一,优先显式传入" } }, "required": [ "task_id" ], - "description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配" + "description": "Chatflow Tool 节点绑定 task_id、hxops_turn_id(经 agent_runtime_context 解析后传入);user_message 用于展示与兼容兜底" }, "RunCheckSuccessResponse": { "type": "object", @@ -880,4 +890,4 @@ } } } -} +} \ No newline at end of file