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
@@ -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)
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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):
|
||||
"""
|
||||
通用意见反馈表
|
||||
|
||||
@@ -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
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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',
|
||||
]
|
||||
@@ -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',
|
||||
]
|
||||
@@ -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'),
|
||||
)
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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')
|
||||
@@ -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")
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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']
|
||||
@@ -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