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

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

No files matched your search

+4 -4
View File
@@ -56,10 +56,10 @@ def create_app(config_name='default'):
from app.api.schedule_admin import schedule_admin_bp
from app.api.workspace_schedule import workspace_schedule_bp
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.workspace_rohs_check import workspace_rohs_check_bp
from app.api.workspace_file_check import workspace_file_check_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_bp
from app.api.rohs_check_tools import rohs_check_bp
from app.api.file_check_tools import file_check_bp
from app.api.speech import speech_bp
# 聊天相关接口
@@ -77,10 +77,10 @@ def create_app(config_name='default'):
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_rohs_check_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(rohs_check_bp, url_prefix='/api/rohs-check')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
# Eagerly load persisted runtime settings so the very first request after
+21 -18
View File
@@ -1084,6 +1084,7 @@ def chat_completions():
name=getattr(agent, 'name', None),
dify_api_key=getattr(agent, 'dify_api_key', None),
api_base_url=getattr(agent, 'api_base_url', None),
extra_config=getattr(agent, 'extra_config', None) or {},
)
user_proxy = SimpleNamespace(
id=user_id,
@@ -1174,31 +1175,33 @@ def chat_completions():
else:
dify_inputs: dict[str, str] | None = None
hxops_turn_id: str | None = None
from app.services.rohs_check_tools.dify_inputs import (
build_dify_chat_inputs as build_rohs_dify_chat_inputs,
is_rohs_check_chat_agent,
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
is_shipping_notice_chat_agent,
)
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_shipping_dify_chat_inputs()
elif is_rohs_check_chat_agent(agent_proxy):
hxops_turn_id = uuid.uuid4().hex
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
elif declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
if is_file_check_agent:
hxops_turn_id = uuid.uuid4().hex
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
register_rohs_chat_turn(
turn_id=hxops_turn_id,
session_id=session.session_id,
user_id=user_proxy.id,
agent_id=agent_proxy.id,
query=query,
)
dify_inputs = build_rohs_dify_chat_inputs(
hxops_session_id=session.session_id,
hxops_turn_id=hxops_turn_id,
)
register_file_check_chat_turn(
turn_id=hxops_turn_id,
session_id=session.session_id,
user_id=user_proxy.id,
agent_id=agent_proxy.id,
query=query,
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
@@ -1206,7 +1209,7 @@ def chat_completions():
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
hxops_turn_id=hxops_turn_id if is_rohs_check_chat_agent(agent_proxy) else None,
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
files=normalized_files,
inputs=dify_inputs,
)
@@ -1,6 +1,9 @@
"""
backend/app/api/rohs_check_tools.py
文件用途:RoHS Chatflow 显式 HTTP Tool API。
backend/app/api/file_check_tools.py
用途:文件检核 Chatflow 显式 HTTP Tool API。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
"""
from __future__ import annotations
@@ -13,25 +16,24 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text
from app import db
from app.api.workspace_rohs_check import serialize_rohs_judgement
from app.api.workspace_file_check import serialize_file_judgement
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_ROHS_GLOBAL_LOCK_KEY = 8700000000
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
_TASK_LOCK_KEY_BASE = 8700000000
def _tool_token_secret() -> str:
return str(
current_app.config.get("ROHS_TOOLS_API_KEY")
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or current_app.config.get("SECRET_KEY")
or "default-secret"
@@ -48,19 +50,19 @@ def _decode_download_token(token: str | None) -> dict | None:
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
return payload if isinstance(payload, dict) else None
except Exception as exc:
current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc)
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
return None
def _require_tool_auth() -> None:
configured = str(
current_app.config.get("ROHS_TOOLS_API_KEY")
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
"FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
@@ -100,7 +102,7 @@ def _tool_error_code(exc: AppError) -> str:
return exc.code
@rohs_check_bp.errorhandler(AppError)
@file_check_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
status = exc.http_status
return jsonify({
@@ -114,39 +116,28 @@ def _public_base_url() -> str:
return resolve_HXOPS_TOOLS_API_BASE()
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def _acquire_rohs_start_lock() -> None:
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
def _acquire_task_start_lock(task_id: int) -> None:
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
bind = db.session.get_bind()
if bind.dialect.name != "postgresql":
return
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
def _build_excel_download_url(run: ScheduleRun) -> str:
import jwt
payload = {
"scope": "rohs_check_excel",
"scope": "file_check_excel",
"run_id": run.id,
"exp": int(time.time()) + 600,
}
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}"
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
@rohs_check_bp.before_request
@file_check_bp.before_request
def _verify_tool_access():
if request.path.endswith("/openapi.json"):
return None
@@ -166,7 +157,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
"success_count": payload["success_count"],
"failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"],
"judgement": serialize_rohs_judgement(payload),
"judgement": serialize_file_judgement(payload),
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"),
@@ -204,41 +195,37 @@ def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None)
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
if not task:
raise NotFoundError("task_not_found")
if not _is_rohs_check_task(task):
raise NotFoundError("task_not_found")
return task
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
def list_rohs_tasks():
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
tasks = []
for task in rows:
if not _is_rohs_check_task(task):
continue
latest = (
ScheduleRun.query.filter_by(schedule_task_id=task.id)
.order_by(ScheduleRun.id.desc())
.first()
)
tasks.append({
"task_id": task.id,
"task_no": task.schedule_no,
"name": task.name,
"enabled": bool(task.enabled),
"last_status": latest.status if latest else None,
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
})
@file_check_bp.route("/tools/tasks", methods=["GET"])
def list_file_check_tasks():
"""
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
"""
raw_task_id = request.args.get("task_id", type=int)
if raw_task_id is None:
raise ValidationError("task_id_required")
task = _resolve_check_task(task_id=raw_task_id)
latest = (
ScheduleRun.query.filter_by(schedule_task_id=task.id)
.order_by(ScheduleRun.id.desc())
.first()
)
tasks = [{
"task_id": task.id,
"task_no": task.schedule_no,
"name": task.name,
"enabled": bool(task.enabled),
"last_status": latest.status if latest else None,
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
}]
return jsonify({"ok": True, "tasks": tasks})
def _normalize_rohs_bind_payload(data: dict | None) -> dict:
"""
规范化启动检核 Body 中的绑定字段,兼容 Chatflow 漏传 hxops_session_id 的场景。
核心逻辑:若 hxops_session_id 为空但 conversation_id 实为 HXOPS session_id,则自动补齐。
"""
def _normalize_bind_payload(data: dict | None) -> dict:
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
payload = dict(data or {})
session_id = str(payload.get("hxops_session_id") or "").strip()
if session_id:
@@ -254,25 +241,19 @@ def _normalize_rohs_bind_payload(data: dict | None) -> dict:
return payload
def _prepare_rohs_bind_payload(data: dict | None) -> dict:
"""
合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。
def _prepare_bind_payload(data: dict | None) -> dict:
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
核心逻辑:Dify HTTP 漏传 hxops_turn_id / hxops_session_id 时,从 HXOPS 侧登记轮次补齐。
"""
from app.services.rohs_check_tools.chat_turn_registry import infer_bind_context_for_run_request
payload = _normalize_rohs_bind_payload(data)
payload = _normalize_bind_payload(data)
inferred = infer_bind_context_for_run_request(payload)
if inferred:
payload = {**payload, **inferred}
return payload
def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
"""写入 ScheduleRun 绑定上下文,并同步 turn 注册表。"""
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
from app.services.rohs_check_tools.chat_turn_registry import attach_run_to_turn
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_turn_registry import attach_run_to_turn
merge_chat_log_bind_context(run, data)
turn_id = str(data.get("hxops_turn_id") or "").strip()
@@ -280,31 +261,29 @@ def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
attach_run_to_turn(turn_id, int(run.id))
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_rohs_check():
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
perf_started = time.perf_counter()
data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {})
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
lock_started = time.perf_counter()
with _RUN_START_LOCK:
_acquire_rohs_start_lock()
_acquire_task_start_lock(task.id)
existing = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running")
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
.order_by(ScheduleRun.id.desc())
.all()
.first()
)
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
if existing:
_record_rohs_run_bind(existing, data)
_record_run_bind(existing, data)
db.session.commit()
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[rohs-tool-perf] run_rohs_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
@@ -333,7 +312,7 @@ def run_rohs_check():
)
db.session.add(run)
db.session.commit()
_record_rohs_run_bind(run, data)
_record_run_bind(run, data)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
@@ -348,7 +327,7 @@ def run_rohs_check():
try:
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
except Exception as exc:
current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
r = db.session.get(ScheduleRun, run_id)
if r and r.status == "running":
r.status = "failed"
@@ -356,12 +335,12 @@ def run_rohs_check():
r.finished_at = datetime.utcnow()
db.session.commit()
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
db.session.refresh(run)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[rohs-tool-perf] run_rohs_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
@@ -370,16 +349,16 @@ def run_rohs_check():
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
def get_rohs_run(run_id: int):
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
def get_file_check_run(run_id: int):
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@rohs_check_bp.route("/tools/runs", methods=["GET"])
def list_rohs_runs():
@file_check_bp.route("/tools/runs", methods=["GET"])
def list_file_check_runs():
raw_task_id = request.args.get("task_id", type=int)
raw_limit = request.args.get("limit", default=20, type=int)
limit = max(1, min(int(raw_limit or 20), 100))
@@ -389,12 +368,12 @@ def list_rohs_runs():
else:
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)]
runs = [_serialize_tool_run(row) for row in rows]
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_rohs_run_excel(run_id: int):
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_file_check_run_excel(run_id: int):
token_payload = _decode_download_token(request.args.get("token"))
if token_payload:
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
@@ -413,8 +392,8 @@ def download_rohs_run_excel(run_id: int):
)
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_rohs_run(task_id: int):
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_file_check_run(task_id: int):
task = _resolve_check_task(task_id=task_id)
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
if not run:
@@ -422,6 +401,6 @@ def get_latest_rohs_run(task_id: int):
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
def rohs_openapi_spec():
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
def file_check_openapi_spec():
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
+2 -4
View File
@@ -1624,11 +1624,9 @@ def get_agent_details(id):
raise ForbiddenError('Access denied')
extra_config = agent.extra_config or {}
if isinstance(extra_config, dict):
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.task_resolver import enrich_tool_run_progress_extra
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
if is_rohs_check_chat_agent(agent):
extra_config = enrich_tool_run_progress_extra(extra_config)
extra_config = enrich_agent_extra_if_file_check(agent)
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
dify_parameters = None
@@ -1,3 +1,10 @@
"""
backend/app/api/workspace_file_check.py
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
"""
from __future__ import annotations
from io import BytesIO
@@ -5,14 +12,12 @@ from io import BytesIO
from flask import Blueprint, jsonify, request, send_file
from app.auth_jwt import get_current_user
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
from app.errors import NotFoundError, UnauthorizedError
from app.models import ScheduleRun, ScheduleTask
from app.services.rohs_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
from app.services.schedule.query_service import get_run, serialize_run
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
def _require_user():
@@ -22,21 +27,12 @@ def _require_user():
return user
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def serialize_rohs_judgement(payload: dict) -> dict:
def serialize_file_judgement(payload: dict) -> dict:
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
judgement = response_summary.get("file_judgement")
if not isinstance(judgement, dict):
judgement = {}
return {
"qualified_count": int(judgement.get("qualified_count") or 0),
"unqualified_count": int(judgement.get("unqualified_count") or 0),
@@ -76,14 +72,14 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"run_id": payload["id"],
"run_no": payload["run_no"],
"task_id": payload["schedule_task_id"],
"title": payload.get("schedule_name") or "RoHS 文件检核",
"title": payload.get("schedule_name") or "",
"status": payload["status"],
"total_count": total,
"processed_count": processed,
"success_count": success,
"failed_count": failed,
"skipped_count": skipped,
"judgement": serialize_rohs_judgement(payload),
"judgement": serialize_file_judgement(payload),
"current_step": serialize_current_step(payload),
"progress_percent": percent,
"started_at": payload.get("started_at"),
@@ -93,7 +89,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"excel": {
"file_name": payload.get("excel_file_name"),
"file_size": payload.get("excel_file_size"),
"download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
},
"knowledge_base": {
"sync_status": payload.get("kb_sync_status"),
@@ -106,8 +102,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
}
@workspace_rohs_check_bp.route("/rohs-check/runs/for-log", methods=["GET"])
def workspace_rohs_run_for_log():
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
def workspace_file_check_run_for_log():
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
_require_user()
task_id = request.args.get("task_id", type=int)
@@ -125,16 +121,16 @@ def workspace_rohs_run_for_log():
})
@workspace_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"])
def workspace_rohs_run_for_session():
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
def workspace_file_check_run_for_session():
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
_require_user()
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
def workspace_rohs_active_run():
"""查询当前进行中的 RoHS 检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
def workspace_file_check_active_run():
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
_require_user()
task_id = request.args.get("task_id", type=int)
conversation_id = str(request.args.get("conversation_id") or "").strip()
@@ -146,13 +142,11 @@ def workspace_rohs_active_run():
query = query.filter(ScheduleRun.schedule_task_id == task_id)
rows = query.order_by(ScheduleRun.id.desc()).all()
if task_id is not None:
# 已按 schedule_task_id 过滤;不再比对 conversation_id(HXOPS session_id ≠ Dify sys.conversation_id)
run = next((row for row in rows if _is_rohs_check_task(row.task)), None)
run = rows[0] if rows else None
else:
run = next((
row for row in rows
if _is_rohs_check_task(row.task)
and (
if (
not conversation_id
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
)
@@ -160,25 +154,21 @@ def workspace_rohs_active_run():
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
def workspace_rohs_run_detail(run_id: int):
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
def workspace_file_check_run_detail(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden")
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
def workspace_rohs_run_excel(run_id: int):
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
def workspace_file_check_run_excel(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden")
if not run.excel_file_data:
raise NotFoundError("excel_not_found")
return send_file(
+3 -3
View File
@@ -109,14 +109,14 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 共用;无尾斜杠)
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RoHS 检核 Chatflow Tool API
ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_API_KEY')
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOLS_API_KEY = os.getenv('FILE_CHECK_TOOLS_API_KEY')
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
+8 -8
View File
@@ -577,10 +577,10 @@ class DifyService:
def _resolve_persist_run_id() -> int | None:
try:
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if not is_rohs_check_chat_agent(agent):
if not is_file_check_chat_agent(agent):
return None
return resolve_run_id_for_chat_log(
session_id=session_id,
@@ -604,7 +604,7 @@ class DifyService:
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
run_id = _resolve_persist_run_id()
if run_id and run_id != run_id_persisted:
from app.services.rohs_check_tools.chat_log_run_binding import update_chat_log_run_id
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
if update_chat_log_run_id(chat_log_id_persisted, run_id):
run_id_persisted = run_id
@@ -845,7 +845,7 @@ class DifyService:
latency: End-to-end latency in milliseconds.
retriever_resources: Source retrieval metadata list.
attribution_parts: Attribution/annotation list.
run_id: RoHS 检核批次 ID(按轮问答绑定,可选)。
run_id: 文件检核批次 ID(按轮问答绑定,可选)。
"""
try:
chat_log = ChatLog(
@@ -912,10 +912,10 @@ class DifyService:
db_write_started = time.time()
run_id = None
try:
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if is_rohs_check_chat_agent(agent):
if is_file_check_chat_agent(agent):
run_id = resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
@@ -1,6 +1,9 @@
"""
backend/app/services/rohs_check.py
文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。
backend/app/services/file_check.py
用途:文件检核统一判定入口,调用 ScheduleTask 绑定的 Dify Workflow。
依赖:DifyService.run_workflow_streaming。
逻辑:由 schedule/srm_service 检核循环逐条调用;RoHS/MSDS 等差异在 Workflow 与排程 SQL 配置。
"""
from __future__ import annotations
@@ -8,12 +11,11 @@ from typing import Any
from app.services.dify import DifyService
VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"}
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
class RoHSCheckService:
"""Wrap RoHS judgement behind a stable backend interface."""
class FileCheckService:
"""文件检核 Dify Workflow 调用与结果规范化。"""
PROVIDER = "dify_workflow"
@@ -29,6 +31,21 @@ class RoHSCheckService:
user: str = "schedule_system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
"""
对单条待检记录调用 Dify Workflow 并返回规范化判定。
Args:
agent: ScheduleTask.dify_agent 对应的 Agent 记录。
run_no: 当前检核批次号。
record: 待检记录文本(由排程 SQL 组装)。
attachment_url: 附件 URL,可选。
system_prompt: 排程配置的补充系统提示,可选。
user: Dify 用户标识。
timeout: HTTP 超时 (connect, read) 秒。
Returns:
含 dify_result、dify_message、workflow_run_id 等字段的 dict。
"""
inputs: dict[str, Any] = {
"run_no": run_no,
"record": record,
@@ -60,6 +77,7 @@ class RoHSCheckService:
@staticmethod
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
"""将 Dify Workflow 输出规范为合格/不合格/人工判定。"""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
output_data = outputs if isinstance(outputs, dict) else {}
@@ -78,7 +96,7 @@ class RoHSCheckService:
"raw_outputs": output_data,
}
if dify_result not in VALID_ROHS_RESULTS:
if dify_result not in VALID_FILE_CHECK_RESULTS:
bad_value = dify_result or "空"
extra = f" | {dify_message}" if dify_message else ""
return {
@@ -0,0 +1 @@
"""文件检核 Chatflow 工具包。"""
@@ -0,0 +1,60 @@
"""
services/file_check_tools/agent_resolver.py
用途:识别具备文件检核进度能力的对话 Agent。
依赖:Agent.extra_config(capabilities + tool_run_progress.schedule_task_id)。
逻辑:chat.py / dify.py / user.py 通过 capabilities 驱动;agent_declares_file_check_progress 用于缺参时快速失败。
"""
from __future__ import annotations
from app.models import Agent
def _resolve_task_id_from_mapping(mapping: dict | None) -> int | None:
if not isinstance(mapping, dict):
return None
raw = mapping.get("schedule_task_id", mapping.get("task_id"))
try:
task_id = int(raw)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def _extra_dict(agent) -> dict:
extra = getattr(agent, "extra_config", None) or {}
return extra if isinstance(extra, dict) else {}
def agent_declares_file_check_progress(agent) -> bool:
"""
判断 Agent 是否声明了文件检核进度能力(不要求 schedule_task_id 已配齐)。
用途:识别「已声明 tool_run_progress 但未配置 task_id」的 Agent,在调 Dify 前快速报错。
"""
extra = _extra_dict(agent)
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
return isinstance(extra.get("tool_run_progress"), dict)
def is_file_check_chat_agent(agent) -> bool:
"""
判断 Agent 是否为文件检核对话入口。
核心逻辑:extra_config.capabilities 含 tool_run_progress,且配置了 schedule_task_id。
"""
extra = _extra_dict(agent)
if not agent_declares_file_check_progress(agent):
return False
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict) and _resolve_task_id_from_mapping(tool_cfg):
return True
return bool(_resolve_task_id_from_mapping(extra))
def resolve_chat_agent() -> Agent | None:
"""返回第一个具备文件检核进度能力的活跃 Agent(测试/运维辅助)。"""
rows = Agent.query.filter(Agent.is_active.is_(True)).order_by(Agent.id.asc()).all()
return next((row for row in rows if is_file_check_chat_agent(row)), None)
@@ -1,11 +1,10 @@
"""
services/rohs_check_tools/chat_log_run_binding.py
services/file_check_tools/chat_log_run_binding.py
用途:将 RoHS 检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
用途:将文件检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
依赖:ChatLog、ScheduleRun、chat_turn_registry。
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
"""
from __future__ import annotations
import re
@@ -16,13 +15,11 @@ from flask import current_app
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.rohs_check_tools.chat_turn_registry import (
from app.services.file_check_tools.chat_turn_registry import (
attach_run_to_turn,
infer_bind_context_for_run_request,
resolve_run_id_by_session_query,
resolve_run_id_by_turn,
)
from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task
def _normalize_bind_text(text: str | None) -> str:
@@ -70,15 +67,10 @@ def resolve_run_id_for_chat_log(
turn_id: str | None = None,
) -> int | None:
"""
匹配本轮问答应对绑定的 RoHS 检核批次 ID。
匹配本轮问答应对绑定的检核批次 ID。
优先级:hxops_turn_id > session_id + 归一化 query > session_id + 近期 bind。
Args:
session_id: HXOPS ChatSession.session_id。
query: 本轮用户输入(ChatLog.query)。
turn_id: 本轮对话 turn 标识(HXOPS 注入 Dify inputs)。
Returns:
匹配到的 ScheduleRun.id,或 None。
"""
@@ -95,20 +87,18 @@ def resolve_run_id_for_chat_log(
def _req(run: ScheduleRun) -> dict:
return run.api_request_json if isinstance(run.api_request_json, dict) else {}
rohs_rows = [row for row in rows if is_rohs_check_schedule_task(row.task)]
if turn_key:
registry_run_id = resolve_run_id_by_turn(turn_key)
if registry_run_id:
return registry_run_id
for run in rohs_rows:
for run in rows:
req = _req(run)
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)
if session_key and query_key:
for run in rohs_rows:
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
@@ -116,7 +106,7 @@ def resolve_run_id_for_chat_log(
return int(run.id)
if session_key and query_key:
for run in rohs_rows:
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
bind_query = _normalize_bind_text(req.get("bind_user_message") or req.get("user_message"))
@@ -127,7 +117,7 @@ def resolve_run_id_for_chat_log(
if session_key:
cutoff = datetime.utcnow() - timedelta(minutes=15)
for run in rohs_rows:
for run in rows:
req = _req(run)
bind_session = str(req.get("bind_session_id") or req.get("hxops_session_id") or "").strip()
if bind_session != session_key:
@@ -146,7 +136,7 @@ def resolve_run_id_for_chat_log(
if current_app and (turn_key or session_key):
current_app.logger.warning(
"[rohs-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s",
"[file-check-bind] resolve run_id miss turn_id=%s session_id=%s query_len=%s",
turn_key or None,
session_key or None,
len(query_key),
@@ -155,12 +145,7 @@ def resolve_run_id_for_chat_log(
def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
"""
回写已有 ChatLog.run_id(workflow_finished 二次绑定)。
Returns:
是否成功更新。
"""
"""回写已有 ChatLog.run_id(workflow_finished 二次绑定)。"""
if not chat_log_id or not run_id or run_id <= 0:
return False
log = db.session.get(ChatLog, chat_log_id)
@@ -169,7 +154,7 @@ def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
if log.run_id == run_id:
return True
run = db.session.get(ScheduleRun, run_id)
if not run or not is_rohs_check_schedule_task(run.task):
if not run:
return False
log.run_id = run_id
db.session.commit()
@@ -177,16 +162,11 @@ def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool:
"""
将检核批次 ID 写入 ChatLog.run_id。
Returns:
是否成功写入并提交。
"""
"""将检核批次 ID 写入 ChatLog.run_id。"""
if not chat_log or not run_id or run_id <= 0:
return False
run = db.session.get(ScheduleRun, run_id)
if not run or not is_rohs_check_schedule_task(run.task):
if not run:
return False
chat_log.run_id = run_id
db.session.commit()
@@ -1,16 +1,14 @@
"""
services/rohs_check_tools/chat_log_run_resolver.py
services/file_check_tools/chat_log_run_resolver.py
用途:按 ChatLog.run_id 解析 RoHS 检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
用途:按 ChatLog.run_id 解析文件检核进度(按轮问答)。
依赖:ChatLog、ScheduleRun。
逻辑:由 for-log API 调用;run_id 在 message_end 写入 chat_logs 表。
"""
from __future__ import annotations
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task
def find_run_for_chat_log(
@@ -19,7 +17,7 @@ def find_run_for_chat_log(
chat_log_id: int,
) -> ScheduleRun | None:
"""
查询某条问答记录绑定的 RoHS 检核批次。
查询某条问答记录绑定的检核批次。
Args:
task_id: ScheduleTask.id。
@@ -36,11 +34,7 @@ def find_run_for_chat_log(
return None
run = db.session.get(ScheduleRun, log.run_id)
if (
run
and run.schedule_task_id == task_id
and is_rohs_check_schedule_task(run.task)
):
if run and run.schedule_task_id == task_id:
return run
return None
@@ -1,11 +1,10 @@
"""
services/rohs_check_tools/chat_turn_registry.py
services/file_check_tools/chat_turn_registry.py
用途:RoHS 对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。
用途:文件检核对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。
依赖:threading、datetime。
逻辑:chat.py 发消息时 register;run API 推断绑定并 attach_run;message_end 按 turn_id 解析 run_id。
"""
from __future__ import annotations
import re
@@ -24,8 +23,8 @@ def _normalize_text(text: str | None) -> str:
@dataclass
class RohsChatTurn:
"""单轮 RoHS 对话的绑定上下文。"""
class FileCheckChatTurn:
"""单轮文件检核对话的绑定上下文。"""
turn_id: str
session_id: str
@@ -37,7 +36,7 @@ class RohsChatTurn:
_lock = Lock()
_turns_by_id: dict[str, RohsChatTurn] = {}
_turns_by_id: dict[str, FileCheckChatTurn] = {}
def _prune_locked(now: datetime | None = None) -> None:
@@ -55,7 +54,7 @@ def _prune_locked(now: datetime | None = None) -> None:
_turns_by_id.pop(key, None)
def register_rohs_chat_turn(
def register_file_check_chat_turn(
*,
turn_id: str,
session_id: str,
@@ -64,7 +63,7 @@ def register_rohs_chat_turn(
query: str,
) -> None:
"""
登记本轮 RoHS 对话上下文(chat API 在调用 Dify 前执行)。
登记本轮文件检核对话上下文(chat API 在调用 Dify 前执行)。
Args:
turn_id: 本轮唯一标识(hxops_turn_id)。
@@ -77,7 +76,7 @@ def register_rohs_chat_turn(
session_key = str(session_id or "").strip()
if not turn_key or not session_key:
return
item = RohsChatTurn(
item = FileCheckChatTurn(
turn_id=turn_key,
session_id=session_key,
user_id=int(user_id),
@@ -91,12 +90,7 @@ def register_rohs_chat_turn(
def attach_run_to_turn(turn_id: str, run_id: int) -> bool:
"""
将检核批次 ID 关联到已登记轮次。
Returns:
是否成功关联。
"""
"""将检核批次 ID 关联到已登记轮次。"""
turn_key = str(turn_id or "").strip()
if not turn_key or run_id <= 0:
return False
@@ -124,8 +118,6 @@ def infer_bind_context_for_run_request(data: dict[str, Any] | None) -> dict[str,
"""
为启动检核 HTTP Body 推断缺失的 hxops_session_id / hxops_turn_id。
核心逻辑:Dify HTTP 常漏传绑定字段时,用近期未绑定轮次 + query 模糊匹配补齐。
Args:
data: 启动检核请求 Body。
@@ -219,7 +211,7 @@ __all__ = [
"attach_run_to_turn",
"clear_registry_for_tests",
"infer_bind_context_for_run_request",
"register_rohs_chat_turn",
"register_file_check_chat_turn",
"resolve_run_id_by_session_query",
"resolve_run_id_by_turn",
]
@@ -0,0 +1,93 @@
"""␍
services/file_check_tools/dify_inputs.py␍
␍
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。␍
依赖:task_resolver、agent_resolver、errors.ValidationError。␍
逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。␍
"""␍
from __future__ import annotations␍
␍
from app.errors import ValidationError␍
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent␍
␍
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致␍
FILE_CHECK_TASK_ID_INPUT = "task_id"␍
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"␍
␍
␍
def _missing_task_id_error(agent) -> ValidationError:␍
"""␍
构造 task_id 未配置时的业务异常。␍
␍
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。␍
"""␍
return ValidationError(␍
"文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。"␍
"请在管理后台编辑该 Agent,于 extra_config 中设置 "␍
"tool_run_progress.schedule_task_id(绑定排程任务 ID)。",␍
details={␍
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,␍
"agent_id": getattr(agent, "id", None),␍
"agent_name": getattr(agent, "name", None) or "",␍
"config_hint": {␍
"capabilities": ["tool_run_progress"],␍
"tool_run_progress": {␍
"type": "file_check",␍
"schedule_task_id": "<ScheduleTask.id>",␍
},␍
},␍
},␍
)␍
␍
␍
def ensure_file_check_task_id_configured(agent) -> int:␍
"""␍
解析并校验文件检核 Agent 绑定的 schedule_task_id。␍
␍
Args:␍
agent: 当前对话 Agent。␍
␍
Returns:␍
有效的 ScheduleTask.id。␍
␍
Raises:␍
ValidationError: extra_config 未配置或 schedule_task_id 非法。␍
"""␍
task_id = resolve_schedule_task_id_from_agent(agent)␍
if not task_id:␍
raise _missing_task_id_error(agent)␍
return task_id␍
␍
␍
def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]:␍
"""␍
构建文件检核 Chatflow 的 Dify chat inputs。␍
␍
仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表,␍
Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。␍
␍
Args:␍
agent: 当前对话 Agent;task_id 从其 extra_config 解析。␍
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。␍
␍
Returns:␍
含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。␍
␍
Raises:␍
ValidationError: required=True 且 schedule_task_id 未配置。␍
"""␍
task_id = resolve_schedule_task_id_from_agent(agent)␍
if not task_id:␍
if required:␍
raise _missing_task_id_error(agent)␍
return {}␍
return {FILE_CHECK_TASK_ID_INPUT: str(task_id)}␍
␍
␍
__all__ = [␍
"FILE_CHECK_TASK_ID_INPUT",␍
"FILE_CHECK_TASK_ID_MISSING_CODE",␍
"build_file_check_dify_inputs",␍
"ensure_file_check_task_id_configured",␍
]␍
␍
@@ -1,13 +1,13 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS RoHS Check Tool API",
"description": "RoHS 文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"title": "HXOPS File Check Tool API",
"description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://192.168.100.192:8890",
"url": "https://your-hxops-host",
"description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖"
}
],
@@ -20,12 +20,24 @@
}
],
"paths": {
"/api/rohs-check/tools/tasks": {
"/api/file-check/tools/tasks": {
"get": {
"operationId": "list_rohs_tasks",
"summary": "查询 RoHS 检核任务列表",
"operationId": "list_file_check_tasks",
"summary": "查询指定文件检核任务",
"tags": [
"RoHS Check"
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": true,
"schema": {
"type": "integer",
"example": 12
},
"description": "检核任务 ID(Agent 绑定的 schedule_task_id)"
}
],
"responses": {
"200": {
@@ -38,21 +50,27 @@
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/rohs-check/tools/tasks/run": {
"/api/file-check/tools/tasks/run": {
"post": {
"operationId": "run_rohs_check",
"summary": "异步启动 RoHS 检核",
"operationId": "run_file_check",
"summary": "异步启动 文件检核",
"tags": [
"RoHS Check"
"File Check"
],
"requestBody": {
"required": true,
@@ -66,7 +84,7 @@
},
"responses": {
"200": {
"description": "启动成功;或已有 RoHS 检核进行中,返回 ok=false/error_code=check_running",
"description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running",
"content": {
"application/json": {
"schema": {
@@ -94,12 +112,12 @@
}
}
},
"/api/rohs-check/tools/runs": {
"/api/file-check/tools/runs": {
"get": {
"operationId": "list_rohs_runs",
"summary": "查询 RoHS 检核批次列表",
"operationId": "list_file_check_runs",
"summary": "查询 文件检核批次列表",
"tags": [
"RoHS Check"
"File Check"
],
"parameters": [
{
@@ -145,12 +163,12 @@
}
}
},
"/api/rohs-check/tools/runs/{run_id}": {
"/api/file-check/tools/runs/{run_id}": {
"get": {
"operationId": "get_rohs_run",
"operationId": "get_file_check_run",
"summary": "查询指定检核批次",
"tags": [
"RoHS Check"
"File Check"
],
"parameters": [
{
@@ -183,12 +201,12 @@
}
}
},
"/api/rohs-check/tools/tasks/{task_id}/latest-run": {
"/api/file-check/tools/tasks/{task_id}/latest-run": {
"get": {
"operationId": "get_latest_rohs_run",
"operationId": "get_latest_file_check_run",
"summary": "查询检核任务最近一次检核",
"tags": [
"RoHS Check"
"File Check"
],
"parameters": [
{
@@ -221,12 +239,12 @@
}
}
},
"/api/rohs-check/tools/runs/{run_id}/excel": {
"/api/file-check/tools/runs/{run_id}/excel": {
"get": {
"operationId": "download_rohs_run_excel",
"operationId": "download_file_check_run_excel",
"summary": "下载检核报告 Excel(短期签名 token)",
"tags": [
"RoHS Check"
"File Check"
],
"security": [],
"parameters": [
@@ -243,7 +261,7 @@
"name": "token",
"in": "query",
"required": true,
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"description": "由 get_file_check_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"schema": {
"type": "string"
}
@@ -273,7 +291,7 @@
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "ROHS_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
"description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
},
"IntegrationKey": {
"type": "apiKey",
@@ -296,7 +314,7 @@
},
"name": {
"type": "string",
"example": "RoHS 自动检核"
"example": "文件自动检核"
},
"enabled": {
"type": "boolean"
@@ -334,7 +352,7 @@
"download_url": {
"type": "string",
"nullable": true,
"example": "http://192.168.100.192:8891/api/rohs-check/tools/runs/88/excel?token=..."
"example": "https://your-hxops-host/api/file-check/tools/runs/88/excel?token=..."
}
}
},
@@ -396,7 +414,7 @@
},
"task_name": {
"type": "string",
"example": "RoHS 自动检核"
"example": "文件自动检核"
},
"status": {
"type": "string",
@@ -473,10 +491,6 @@
"type": "integer",
"example": 12
},
"task_no": {
"type": "string",
"example": "CHK202606090001"
},
"trigger_source": {
"type": "string",
"default": "dify_chatflow"
@@ -493,7 +507,7 @@
"required": [
"task_id"
],
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
"description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配"
},
"RunCheckSuccessResponse": {
"type": "object",
@@ -631,7 +645,7 @@
}
},
"MissingAuth": {
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
"description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY",
"content": {
"application/json": {
"schema": {
@@ -640,7 +654,7 @@
"example": {
"ok": false,
"error_code": "missing_auth",
"message": "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
"message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
}
}
}
@@ -1,3 +1,10 @@
"""
services/file_check_tools/openapi_spec.py
用途:构建文件检核 Chatflow 的 OpenAPI 3.0 规范。
依赖:openapi_base.json。
逻辑:GET /api/file-check/tools/openapi.json 调用 build_file_check_openapi_spec。
"""
from __future__ import annotations
import copy
@@ -13,8 +20,8 @@ def _load_base_spec() -> dict[str, Any]:
return json.load(fp)
def build_rohs_openapi_spec(base_url: str) -> dict[str, Any]:
"""Build OpenAPI 3.0 spec for RoHS Chatflow HTTP tools."""
def build_file_check_openapi_spec(base_url: str) -> dict[str, Any]:
"""Build OpenAPI 3.0 spec for file-check Chatflow HTTP tools."""
spec = copy.deepcopy(_load_base_spec())
base = str(base_url or "").strip().rstrip("/")
servers = spec.get("servers")
@@ -0,0 +1,39 @@
"""
services/file_check_tools/progress_paths.py
用途:文件检核进度轮询 API 路径常量与展示标题解析。
依赖:ScheduleTask。
逻辑:前端/ enrich 由 schedule_task_id 推导 URL,管理员无需配置 log_progress_url。
"""
from __future__ import annotations
from app import db
from app.models import ScheduleTask
FILE_CHECK_LOG_PROGRESS_PATH = "/api/workspace/file-check/runs/for-log"
FILE_CHECK_DETAIL_PATH_TEMPLATE = "/api/workspace/file-check/runs/{run_id}"
def resolve_file_check_progress_title(task_id: int | None) -> str:
"""
从 ScheduleTask.name 解析进度卡片标题。
Args:
task_id: Agent extra_config 中的 schedule_task_id。
Returns:
排程任务名称;不存在时返回空字符串。
"""
if not task_id or task_id <= 0:
return ""
task = db.session.get(ScheduleTask, int(task_id))
if not task:
return ""
return str(getattr(task, "name", "") or "").strip()
__all__ = [
"FILE_CHECK_DETAIL_PATH_TEMPLATE",
"FILE_CHECK_LOG_PROGRESS_PATH",
"resolve_file_check_progress_title",
]
@@ -0,0 +1,117 @@
"""
services/file_check_tools/task_resolver.py
用途:解析文件检核 Chatflow 绑定的 ScheduleTask.id 与 Agent 进度配置。
依赖:ScheduleTask、Agent.extra_config、progress_paths、agent_resolver。
逻辑:task_id 来自 Agent extra_config;title 来自 ScheduleTask.name;轮询 URL 由代码推导。
"""
from __future__ import annotations
from app.models import Agent, ScheduleTask
from app.services.file_check_tools.agent_resolver import _resolve_task_id_from_mapping
from app.services.file_check_tools.progress_paths import resolve_file_check_progress_title
resolve_schedule_task_id_from_mapping = _resolve_task_id_from_mapping
def resolve_schedule_task_id_from_agent(agent) -> int | None:
"""从 Agent extra_config 解析绑定的检核排程 task_id。"""
extra = getattr(agent, "extra_config", None) or {}
if not isinstance(extra, dict):
return None
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
task_id = resolve_schedule_task_id_from_mapping(tool_cfg)
if task_id:
return task_id
return resolve_schedule_task_id_from_mapping(extra)
def is_file_check_schedule_task(task: ScheduleTask | None) -> bool:
"""判断排程任务是否存在(文件检核以 task_id 为准,不再按名称关键词过滤)。"""
return task is not None and int(getattr(task, "id", 0) or 0) > 0
def _has_tool_run_progress_capability(extra: dict) -> bool:
caps = extra.get("capabilities") or []
if isinstance(caps, list) and "tool_run_progress" in caps:
return True
if isinstance(extra.get("tool_run_progress"), dict):
return True
progress_type = str(extra.get("type") or "").strip().lower()
if progress_type == "file_check":
return True
tool_cfg = extra.get("tool_run_progress")
if isinstance(tool_cfg, dict):
nested_type = str(tool_cfg.get("type") or "").strip().lower()
if nested_type == "file_check":
return True
return False
def _apply_schedule_task_metadata(merged: dict) -> None:
"""按 schedule_task_id 写入展示 title(ScheduleTask.name)。"""
task_id = resolve_schedule_task_id_from_mapping(merged)
if not task_id:
return
schedule_title = resolve_file_check_progress_title(task_id)
if schedule_title:
merged["title"] = schedule_title
def enrich_tool_run_progress_extra(extra_config: dict | None, *, agent: Agent | None = None) -> dict:
"""
为文件检核 Agent 的 extra_config 补全 tool_run_progress 能力与轮询参数。
核心逻辑:管理员只需配置 schedule_task_id;进度轮询 URL 由前后端按 task_id 推导,无需 log_progress_url。
Returns:
新的 extra_config 副本。
"""
extra = dict(extra_config or {})
tool_cfg = extra.get("tool_run_progress")
merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else {
"type": "file_check",
"poll_interval_seconds": 2,
"lock_input_when_running": True,
}
merged.setdefault("poll_interval_seconds", 2)
merged.setdefault("type", "file_check")
merged.setdefault("lock_input_when_running", True)
if not resolve_schedule_task_id_from_mapping(merged) and agent is not None:
task_id = resolve_schedule_task_id_from_agent(agent)
if task_id:
merged["schedule_task_id"] = task_id
_apply_schedule_task_metadata(merged)
# 历史字段:若 DB 仍存有 URL,去掉以免误导运维重复维护
merged.pop("log_progress_url", None)
merged.pop("detail_url_template", None)
merged.pop("session_progress_url", None)
extra["tool_run_progress"] = merged
capabilities = list(extra.get("capabilities") or [])
if "tool_run_progress" not in capabilities:
capabilities.append("tool_run_progress")
extra["capabilities"] = capabilities
return extra
def enrich_agent_extra_if_file_check(agent: Agent) -> dict:
"""若 Agent 已声明 tool_run_progress 能力则 enrich extra_config,否则原样返回。"""
extra = dict(agent.extra_config or {}) if isinstance(agent.extra_config, dict) else {}
if _has_tool_run_progress_capability(extra):
return enrich_tool_run_progress_extra(extra, agent=agent)
return extra
__all__ = [
"enrich_agent_extra_if_file_check",
"enrich_tool_run_progress_extra",
"is_file_check_schedule_task",
"resolve_schedule_task_id_from_agent",
"resolve_schedule_task_id_from_mapping",
]
Whitespace-only changes.
@@ -1,21 +0,0 @@
from __future__ import annotations
from app.models import Agent
# Dify / HXOPS Agent.name 常见取值(含「助手」后缀)
CHAT_AGENT_NAMES = frozenset(
{
"RoHS文件检核",
"RoHS文件检核助手",
"RoHS 文件检核助手",
}
)
def is_rohs_check_chat_agent(agent) -> bool:
name = (getattr(agent, "name", None) or "").strip()
return name in CHAT_AGENT_NAMES
def resolve_chat_agent() -> Agent | None:
return Agent.query.filter(Agent.name.in_(CHAT_AGENT_NAMES), Agent.is_active.is_(True)).first()
@@ -1,59 +0,0 @@
from __future__ import annotations
from flask import current_app
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.rohs_check_tools.task_resolver import resolve_default_rohs_schedule_task_id
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致(见 docs/rohs_chatflow_guide.md §3.1)
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
HXOPS_TOOL_API_TOKEN_INPUT = "hxops_tool_api_token"
ROHS_TASK_ID_INPUT = "task_id"
HXOPS_SESSION_ID_INPUT = "hxops_session_id"
HXOPS_TURN_ID_INPUT = "hxops_turn_id"
def build_dify_chat_inputs(
hxops_session_id: str | None = None,
hxops_turn_id: str | None = None,
) -> dict[str, str]:
"""
构建 RoHS Chatflow 的 Dify chat inputs(HTTP 节点与启动检核 Body 共用变量名)。
Args:
hxops_session_id: 当前 HXOPS ChatSession.session_id。
hxops_turn_id: 本轮对话 turn 标识,用于 ChatLog.run_id 精确回写。
"""
base = resolve_HXOPS_TOOLS_API_BASE()
key = str(
current_app.config.get("ROHS_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_TOKEN_INPUT] = key
task_id = resolve_default_rohs_schedule_task_id()
if task_id:
inputs[ROHS_TASK_ID_INPUT] = str(task_id)
session_id = str(hxops_session_id or "").strip()
if session_id:
inputs[HXOPS_SESSION_ID_INPUT] = session_id
turn_id = str(hxops_turn_id or "").strip()
if turn_id:
inputs[HXOPS_TURN_ID_INPUT] = turn_id
return inputs
__all__ = [
"HXOPS_TOOLS_API_BASE_INPUT",
"HXOPS_TOOL_API_TOKEN_INPUT",
"HXOPS_SESSION_ID_INPUT",
"HXOPS_TURN_ID_INPUT",
"ROHS_TASK_ID_INPUT",
"build_dify_chat_inputs",
"is_rohs_check_chat_agent",
]
@@ -1,114 +0,0 @@
"""
services/rohs_check_tools/task_resolver.py
用途:解析 RoHS Chatflow 绑定的 ScheduleTask.id,供 Dify inputs、Agent 进度能力与 active 轮询使用。
依赖:ScheduleTask、rohs_check_tools 任务识别逻辑。
逻辑:优先读 Agent extra_config;否则在仅有一个 RoHS 检核任务时自动选用。
"""
from __future__ import annotations
from flask import current_app
from app.models import ScheduleTask
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
def is_rohs_check_schedule_task(task: ScheduleTask | None) -> bool:
"""判断排程任务是否为 RoHS 文件检核任务。"""
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def list_rohs_schedule_tasks() -> list[ScheduleTask]:
"""列出全部 RoHS 检核排程任务。"""
rows = ScheduleTask.query.order_by(ScheduleTask.id.asc()).all()
return [task for task in rows if is_rohs_check_schedule_task(task)]
def resolve_schedule_task_id_from_mapping(mapping: dict | None) -> int | None:
"""从 tool_run_progress 或等价 dict 解析 schedule_task_id / task_id。"""
if not isinstance(mapping, dict):
return None
raw = mapping.get("schedule_task_id", mapping.get("task_id"))
try:
task_id = int(raw)
except (TypeError, ValueError):
return None
return task_id if task_id > 0 else None
def resolve_default_rohs_schedule_task_id() -> int | None:
"""
解析默认 RoHS 检核 ScheduleTask.id。
优先级:环境变量/配置 ROHS_CHATFLOW_SCHEDULE_TASK_ID → 库内唯一 RoHS 任务 → None。
"""
configured = current_app.config.get("ROHS_CHATFLOW_SCHEDULE_TASK_ID")
if configured not in (None, "", 0, "0"):
try:
task_id = int(configured)
if task_id > 0:
return task_id
except (TypeError, ValueError):
pass
tasks = list_rohs_schedule_tasks()
if len(tasks) == 1:
return int(tasks[0].id)
return None
def enrich_tool_run_progress_extra(extra_config: dict | None) -> dict:
"""
为 RoHS Agent 的 extra_config 补全 tool_run_progress 能力与默认轮询配置。
核心逻辑:RoHS 对话 Agent 自动挂载 tool_run_progress 能力,避免漏配 capabilities 导致进度卡片不显示。
Returns:
新的 extra_config 副本。
"""
extra = dict(extra_config or {})
tool_cfg = extra.get("tool_run_progress")
merged = dict(tool_cfg) if isinstance(tool_cfg, dict) else {
"type": "rohs_check",
"title": "RoHS 文件检核",
"poll_interval_seconds": 2,
"lock_input_when_running": True,
}
merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log")
merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}")
merged.setdefault("poll_interval_seconds", 2)
merged.setdefault("title", "RoHS 文件检核")
merged.setdefault("type", "rohs_check")
merged.setdefault("lock_input_when_running", True)
if not resolve_schedule_task_id_from_mapping(merged):
task_id = resolve_default_rohs_schedule_task_id()
if task_id:
merged["schedule_task_id"] = task_id
extra["tool_run_progress"] = merged
capabilities = list(extra.get("capabilities") or [])
if "tool_run_progress" not in capabilities:
capabilities.append("tool_run_progress")
extra["capabilities"] = capabilities
return extra
__all__ = [
"enrich_tool_run_progress_extra",
"is_rohs_check_schedule_task",
"list_rohs_schedule_tasks",
"resolve_default_rohs_schedule_task_id",
"resolve_schedule_task_id_from_mapping",
]
+3 -3
View File
@@ -5,7 +5,7 @@ from typing import Any, Callable
from flask import current_app, has_app_context
from app.services.rohs_check import RoHSCheckService
from app.services.file_check import FileCheckService
try:
import pyodbc # type: ignore
@@ -213,7 +213,7 @@ def _run_check_job_loop(
progress_run.failed_count = failed_count
progress_run.skipped_count = skipped_count
summary = dict(progress_run.response_summary_json or {})
summary["rohs_judgement"] = dict(judgement_stats)
summary["file_judgement"] = dict(judgement_stats)
if current_step:
summary["current_step"] = dict(current_step)
progress_run.response_summary_json = summary
@@ -316,7 +316,7 @@ def _run_check_job_loop(
t_dify = _ts()
try:
_set_current_step("call_dify", row_id_value)
dify_res = RoHSCheckService.evaluate(
dify_res = FileCheckService.evaluate(
agent=agent,
run_no=run_no,
record=record_text,
@@ -1,4 +1,4 @@
"""Export Dify-compatible OpenAPI for RoHS Check tools paste/import."""
"""Export Dify-compatible OpenAPI for File Check tools paste/import."""
from __future__ import annotations
import json
@@ -9,7 +9,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "backend"))
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
def main() -> None:
@@ -18,13 +18,13 @@ def main() -> None:
or os.getenv("PUBLIC_BASE_URL")
or "http://127.0.0.1:5052"
).rstrip("/")
spec = build_rohs_openapi_spec(base)
spec = build_file_check_openapi_spec(base)
out_dir = ROOT / "docs" / "openapi"
out_dir.mkdir(parents=True, exist_ok=True)
json_path = out_dir / "rohs_check_tools_openapi.json"
json_path = out_dir / "file_check_tools_openapi.json"
json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Wrote {json_path}")
print(f"Import URL: {base}/api/rohs-check/tools/openapi.json")
print(f"Import URL: {base}/api/file-check/tools/openapi.json")
if __name__ == "__main__":
@@ -5,12 +5,12 @@ import pytest
from app import db
from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
from app.services.rohs_check import RoHSCheckService
from app.services.file_check import FileCheckService
@pytest.fixture(autouse=True)
def _clear_rohs_turn_registry():
from app.services.rohs_check_tools.chat_turn_registry import clear_registry_for_tests
def _clear_file_check_turn_registry():
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
clear_registry_for_tests()
yield
@@ -61,7 +61,7 @@ def _mk_check_task(owner_id: int, *, enabled=True):
return task
def _mk_non_rohs_task(owner_id: int):
def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
@@ -77,8 +77,8 @@ def _mk_non_rohs_task(owner_id: int):
return task
def test_rohs_service_normalizes_failed_workflow():
payload = RoHSCheckService.normalize_workflow_result({
def test_file_check_service_normalizes_failed_workflow():
payload = FileCheckService.normalize_workflow_result({
'status': 'failed',
'error': 'workflow timeout',
'workflow_run_id': 'wf-2',
@@ -88,15 +88,15 @@ def test_rohs_service_normalizes_failed_workflow():
assert payload['workflow_run_id'] == 'wf-2'
def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
def test_file_check_service_evaluate_degrades_on_dify_error(monkeypatch):
class _Agent:
id = 1
def _boom(**kwargs):
raise RuntimeError('dify down')
monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom)
payload = RoHSCheckService.evaluate(
monkeypatch.setattr('app.services.file_check.DifyService.run_workflow_streaming', _boom)
payload = FileCheckService.evaluate(
agent=_Agent(),
run_no='RUN-1',
record='Pb: 100ppm',
@@ -106,8 +106,8 @@ def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
assert payload['error'] == 'dify down'
def test_rohs_service_normalizes_invalid_result():
payload = RoHSCheckService.normalize_workflow_result({
def test_file_check_service_normalizes_invalid_result():
payload = FileCheckService.normalize_workflow_result({
'status': 'succeeded',
'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'},
'workflow_run_id': 'wf-1',
@@ -117,7 +117,7 @@ def test_rohs_service_normalizes_invalid_result():
assert payload['workflow_run_id'] == 'wf-1'
def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
def test_file_check_loop_splits_processing_and_judgement_counts(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
class _Agent:
@@ -134,7 +134,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
writebacks = []
monkeypatch.setattr('app.services.schedule.srm_service.RoHSCheckService.evaluate', _evaluate)
monkeypatch.setattr('app.services.schedule.srm_service.FileCheckService.evaluate', _evaluate)
with app.app_context():
admin = _mk_admin()
db.session.flush()
@@ -158,7 +158,7 @@ def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
log_prefix='row',
)
db.session.refresh(run)
judgement = (run.response_summary_json or {}).get('rohs_judgement') or {}
judgement = (run.response_summary_json or {}).get('file_judgement') or {}
assert total == 1
assert success == 1
@@ -216,55 +216,78 @@ def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch):
assert observed == {'connect_timeout': 7, 'cursor_timeout': 7}
def test_rohs_tool_requires_auth(app, client):
def test_file_check_tool_requires_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/rohs-check/tools/tasks')
res = client.get('/api/file-check/tools/tasks')
assert res.status_code == 401
assert res.get_json()['error_code'] == 'missing_auth'
def test_rohs_tool_rejects_invalid_auth(app, client):
def test_file_check_tool_rejects_invalid_auth(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
assert res.status_code == 401
assert res.get_json()['error_code'] == 'invalid_auth'
def test_rohs_tool_lists_tasks(app, client):
def test_file_check_tool_lists_tasks_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.get('/api/file-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 400
assert res.get_json()['error_code'] == 'task_id_required'
def test_file_check_tool_lists_task_by_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
_mk_check_task(admin.id)
_mk_non_rohs_task(admin.id)
other_task = _mk_other_check_task(admin.id)
task_id = other_task.id
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
res = client.get(
f'/api/file-check/tools/tasks?task_id={task_id}',
headers={'X-Integration-Key': 'secret'},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001']
assert len(data['tasks']) == 1
assert data['tasks'][0]['task_id'] == task_id
assert data['tasks'][0]['task_no'] == 'CHK-GENERAL-001'
def test_rohs_tool_rejects_non_rohs_task(app, client):
def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_non_rohs_task(admin.id)
task = _mk_other_check_task(admin.id)
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 404
assert res.get_json()['error_code'] == 'task_not_found'
assert res.status_code == 200
assert res.get_json()['ok'] is True
def test_rohs_tool_running_conflict(app, client):
def test_file_check_tool_running_conflict(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -276,7 +299,7 @@ def test_rohs_tool_running_conflict(app, client):
db.session.commit()
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
@@ -286,7 +309,7 @@ def test_rohs_tool_running_conflict(app, client):
assert data['error_code'] == 'check_running'
def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
def test_file_check_tool_check_running_records_chat_log_bind_context(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -304,7 +327,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
running_run_id = run.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -322,7 +345,7 @@ def test_rohs_tool_check_running_records_chat_log_bind_context(app, client):
assert req.get('bind_user_message') == '立即执行检核'
def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
@@ -332,7 +355,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
def start(self):
return None
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -342,7 +365,7 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -360,18 +383,18 @@ def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch)
assert req.get('bind_session_id') == 'bind-on-start'
assert req.get('bind_turn_id') == 'turn-abc-001'
assert req.get('bind_user_message') == '执行 RoHS 检核'
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='turn-abc-001') == run_id
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
def test_rohs_tool_requires_task_id(app, client):
def test_file_check_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={},
)
@@ -379,12 +402,12 @@ def test_rohs_tool_requires_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_required'
def test_rohs_tool_rejects_invalid_task_id(app, client):
def test_file_check_tool_rejects_invalid_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': 'abc'},
)
@@ -392,7 +415,15 @@ def test_rohs_tool_rejects_invalid_task_id(app, client):
assert res.get_json()['error_code'] == 'task_id_invalid'
def test_rohs_tool_running_conflict_is_global(app, client):
def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
class _Thread:
def __init__(self, *args, **kwargs):
pass
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -417,24 +448,23 @@ def test_rohs_tool_running_conflict_is_global(app, client):
running_id = running.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': second_task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'check_running'
assert data['run']['run_id'] == running_id
assert data['ok'] is True
assert data['run']['task_id'] == second_task_id
def test_rohs_tool_lists_all_rohs_runs(app, client):
def test_file_check_tool_lists_runs_without_task_filter(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
rohs_task = _mk_check_task(admin.id)
other_task = _mk_non_rohs_task(admin.id)
other_task = _mk_other_check_task(admin.id)
db.session.add_all([
ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3),
ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1),
@@ -442,15 +472,15 @@ def test_rohs_tool_lists_all_rohs_runs(app, client):
])
db.session.commit()
res = client.get('/api/rohs-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
res = client.get('/api/file-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
assert data['count'] == 2
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'}
assert data['count'] == 3
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002', 'RUN-OTHER-001'}
def test_workspace_rohs_active_run_returns_progress(app, client):
def test_workspace_file_check_active_run_returns_progress(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -480,7 +510,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
db.session.add(run)
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is True
@@ -491,7 +521,7 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
assert data['run']['current_step']['row_id'] == 'ROW-16'
def test_workspace_rohs_active_run_filters_by_task_id(app, client):
def test_workspace_file_check_active_run_filters_by_task_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -530,21 +560,21 @@ def test_workspace_rohs_active_run_filters_by_task_id(app, client):
task_b_id = task_b.id
hit = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_a_id}',
f'/api/workspace/file-check/runs/active?task_id={task_a_id}',
headers={'X-Username': 'admin'},
)
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-A'
miss = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_b_id}',
f'/api/workspace/file-check/runs/active?task_id={task_b_id}',
headers={'X-Username': 'admin'},
)
assert miss.status_code == 200
assert miss.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-B'
def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, client):
def test_workspace_file_check_active_run_ignores_conversation_when_task_id_set(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -563,14 +593,14 @@ def test_workspace_rohs_active_run_ignores_conversation_when_task_id_set(app, cl
task_id = task.id
res = client.get(
f'/api/workspace/rohs-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id',
f'/api/workspace/file-check/runs/active?task_id={task_id}&conversation_id=hxops-session-id',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-TASK-CONV-MISMATCH'
def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
def test_workspace_file_check_active_run_filters_by_conversation_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -587,16 +617,16 @@ def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
db.session.add(run)
db.session.commit()
miss = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
miss = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
assert miss.status_code == 200
assert miss.get_json()['run'] is None
hit = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
hit = client.get('/api/workspace/file-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
def test_workspace_file_check_run_for_log_returns_null_when_unbound(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -614,7 +644,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
@@ -623,7 +653,7 @@ def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
assert payload.get('match_source') is None
def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
def test_workspace_file_check_run_for_log_reads_bound_run_id(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -652,7 +682,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
@@ -661,7 +691,7 @@ def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
assert payload['match_source'] == 'chat_log'
def test_workspace_rohs_run_for_log_allows_different_user(app, client):
def test_workspace_file_check_run_for_log_allows_different_user(app, client):
with app.app_context():
owner = User(username='rohs-owner', email='owner-rohs@example.com', role='admin', status='active')
owner.set_password('x')
@@ -694,14 +724,14 @@ def test_workspace_rohs_run_for_log_allows_different_user(app, client):
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id={task_id}&chat_log_id={chat_log_id}',
headers={'X-Username': 'rohs-viewer'},
)
assert res.status_code == 200
assert res.get_json()['run']['run_no'] == 'RUN-ROHS-CROSS-USER'
def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client):
def test_workspace_file_check_run_for_log_returns_null_when_task_mismatch(app, client):
with app.app_context():
admin = _mk_admin()
db.session.commit()
@@ -727,24 +757,24 @@ def test_workspace_rohs_run_for_log_returns_null_when_task_mismatch(app, client)
chat_log_id = log.id
res = client.get(
f'/api/workspace/rohs-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}',
f'/api/workspace/file-check/runs/for-log?task_id=99999&chat_log_id={chat_log_id}',
headers={'X-Username': 'admin'},
)
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_workspace_rohs_active_run_returns_null_when_idle(app, client):
def test_workspace_file_check_active_run_returns_null_when_idle(app, client):
with app.app_context():
_mk_admin()
db.session.commit()
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
res = client.get('/api/workspace/file-check/runs/active', headers={'X-Username': 'admin'})
assert res.status_code == 200
assert res.get_json()['run'] is None
def test_rohs_tool_excel_download_uses_signed_token(app, client):
def test_file_check_tool_excel_download_uses_signed_token(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -763,19 +793,19 @@ def test_rohs_tool_excel_download_uses_signed_token(app, client):
db.session.commit()
run_id = run.id
query_res = client.get(f'/api/rohs-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
query_res = client.get(f'/api/file-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
token_url = query_res.get_json()['run']['excel']['download_url']
download_path = token_url[token_url.index('/api/rohs-check'):]
download_path = token_url[token_url.index('/api/file-check'):]
res = client.get(download_path)
assert res.status_code == 200
assert res.data == b'xlsx-bytes'
res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
res = client.get('/api/file-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
assert res.status_code == 401
def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
started_threads = []
class _Thread:
@@ -787,7 +817,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
def start(self):
started_threads.append(self.name)
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -797,7 +827,7 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
task_id = task.id
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
@@ -806,52 +836,199 @@ def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
assert data['ok'] is True
assert data['run']['task_id'] == task_id
assert data['run']['status'] == 'running'
assert started_threads == [f"rohs-check-run-{data['run']['run_id']}"]
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
def test_rohs_openapi_injects_tool_api_base(app, client):
def test_serialize_file_judgement_reads_file_key():
from app.api.workspace_file_check import serialize_file_judgement
payload = {
"response_summary_json": {
"file_judgement": {
"qualified_count": 2,
"unqualified_count": 1,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
}
}
result = serialize_file_judgement(payload)
assert result["qualified_count"] == 2
assert result["unqualified_count"] == 1
def test_file_check_openapi_injects_tool_api_base(app, client):
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
res = client.get('/api/rohs-check/tools/openapi.json')
app.config['HXOPS_TOOLS_API_BASE'] = 'https://file-check-tool.example.com'
res = client.get('/api/file-check/tools/openapi.json')
assert res.status_code == 200
assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com'
assert res.get_json()['servers'][0]['url'] == 'https://file-check-tool.example.com'
def test_rohs_dify_chat_inputs(app):
from app.services.rohs_check_tools.dify_inputs import (
HXOPS_TOOL_API_TOKEN_INPUT,
HXOPS_TOOLS_API_BASE_INPUT,
build_dify_chat_inputs,
def test_file_check_dify_chat_inputs(app):
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
)
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
class _Agent:
def __init__(self, name: str):
def __init__(self, name: str, *, extra_config=None):
self.name = name
self.extra_config = extra_config or {}
assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手'))
assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent'))
assert is_file_check_chat_agent(_Agent(
'RoHS文件检核助手',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
))
assert not is_file_check_chat_agent(_Agent('RoHS文件检核助手'))
assert not is_file_check_chat_agent(_Agent('货代发货通知 Agent'))
agent = _Agent(
'RoHS文件检核助手',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
)
with app.app_context():
inputs = build_file_check_dify_inputs(agent)
assert inputs[FILE_CHECK_TASK_ID_INPUT] == '12'
assert 'hxops_session_id' not in inputs
assert 'hxops_turn_id' not in inputs
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
import pytest
from app.errors import ValidationError
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
id = 26
name = 'RoHS文件检核助手'
extra_config = {}
with app.app_context():
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret'
inputs = build_dify_chat_inputs(hxops_session_id='sess-abc')
assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com'
assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret'
assert inputs['hxops_session_id'] == 'sess-abc'
assert build_file_check_dify_inputs(_Agent()) == {}
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(_Agent(), required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs
def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(app):
import pytest
from app.errors import ValidationError
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_MISSING_CODE,
build_file_check_dify_inputs,
)
class _Agent:
def __init__(self):
self.id = 26
self.name = 'RoHS文件检核助手'
self.extra_config = {
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
}
agent = _Agent()
assert agent_declares_file_check_progress(agent)
assert not is_file_check_chat_agent(agent)
with app.app_context():
app.config.pop('HXOPS_TOOLS_API_BASE', None)
app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com'
app.config.pop('ROHS_TOOLS_API_KEY', None)
app.config['INTEGRATION_API_KEY'] = 'integration-secret'
inputs = build_dify_chat_inputs()
assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com'
assert inputs['hxops_tool_api_token'] == 'integration-secret'
with pytest.raises(ValidationError) as exc:
build_file_check_dify_inputs(agent, required=True)
assert exc.value.details.get('error_code') == FILE_CHECK_TASK_ID_MISSING_CODE
assert 'schedule_task_id' in exc.value.message
def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker):
"""声明了文件检核能力但未配置 schedule_task_id 时,/completions 应立即 400 而非挂死。"""
from flask import g
from app.models import Agent, User
misconfigured = Agent(
id=26,
name='RoHS文件检核助手',
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
type='api',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'type': 'file_check'},
},
is_active=True,
)
user = User(id=1, username='admin', status='active', role='admin')
user.agents = [misconfigured]
def mock_get_user():
g.current_user = user
return user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
mocker.patch('app.models.Agent.query').get.return_value = misconfigured
mock_post = mocker.patch('requests.post')
mock_post.side_effect = AssertionError('Dify must not be called when task_id is missing')
res = client.post(
'/api/chat/completions',
json={'query': '立即执行RoHS文件检核', 'agent_id': 26},
headers={'Content-Type': 'application/json'},
)
assert res.status_code == 400
body = res.get_json()
assert body['error']['code'] == 'VALIDATION.INVALID_PARAM'
assert body['error']['details']['error_code'] == 'file_check_task_id_required'
mock_post.assert_not_called()
def test_chat_agent_proxy_passes_extra_config_for_task_id_injection():
"""chat.py agent_proxy 须携带 extra_config,否则 is_file_check_chat_agent / task_id 注入失效。"""
from types import SimpleNamespace
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.dify_inputs import (
FILE_CHECK_TASK_ID_INPUT,
build_file_check_dify_inputs,
)
agent_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
extra_config={
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': 12},
},
)
assert is_file_check_chat_agent(agent_proxy)
assert build_file_check_dify_inputs(agent_proxy)[FILE_CHECK_TASK_ID_INPUT] == '12'
bare_proxy = SimpleNamespace(
id=26,
name='RoHS文件检核助手',
dify_api_key='app-key',
api_base_url='http://dify.example/v1',
)
assert not is_file_check_chat_agent(bare_proxy)
assert build_file_check_dify_inputs(bare_proxy) == {}
def test_kb_sync_skips_failed_run(app):
@@ -1168,7 +1345,7 @@ def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path
assert run.kb_sync_status in ('success', 'ready', 'syncing')
def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
"""Dify HTTP 仅传 task_id + user_message 时,仍应通过 turn 注册表回写 run_id。"""
class _Thread:
def __init__(self, *, target, daemon, name):
@@ -1179,7 +1356,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
def start(self):
return None
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1189,10 +1366,10 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
task_id = task.id
admin_id = admin.id
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
register_rohs_chat_turn(
register_file_check_chat_turn(
turn_id='turn-registry-001',
session_id='sess-registry-001',
user_id=1,
@@ -1201,7 +1378,7 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
)
res = client.post(
'/api/rohs-check/tools/tasks/run',
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
@@ -1230,7 +1407,14 @@ def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypa
event_name='message_end',
request_id='req-bind-test',
user_id=admin_id,
agent=type('AgentProxy', (), {'id': 1, 'name': 'RoHS文件检核助手'})(),
agent=type('AgentProxy', (), {
'id': 1,
'name': 'RoHS文件检核助手',
'extra_config': {
'capabilities': ['tool_run_progress'],
'tool_run_progress': {'schedule_task_id': task_id},
},
})(),
session_id='sess-registry-001',
hxops_turn_id='turn-registry-001',
normalized_conversation_id='sess-registry-001',
+2 -1
View File
@@ -83,7 +83,8 @@ Scope 应对齐代码模块,便于从提交信息定位到目录。选取规
| --- | --- |
| `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` |
| `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` |
| `rohs-check` | `services/rohs_check*`、`api/rohs_check_tools` |
| `file-check` | `services/file_check*`、`api/file_check_tools` |
| `rohs-check` | RoHS 实例(历史 scope,新改动请用 `file-check`) |
| `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` |
| `chat` | `api/chat`、前端 chat 相关 |
| `auth` | 登录认证 |
+6 -7
View File
@@ -22,14 +22,13 @@
## 3. 范围说明
### 3.x RoHS 文件检核补充需求
### 3.x 文件检核(file_check)补充需求
- **核心目标**:提供 RoHS 文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。
- 新增 `RoHSCheckService` 作为统一判定入口,内部复用现有 Dify RoHS Workflow 中的 Prompt 与模型配置。
- 新增 Dify Chatflow 显式 HTTP Tool,用于对话中发起检核、查询检核状态与展示结果;不使用 Agent 节点做逐条判定。
- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 通过 Knowledge Retrieval 检索已入库历史报告(与 Tool API 实时查询并存)。
- 后台执行、定时触发、数据抓取与写回沿用现有任务引擎(实现细节对用户透明)。
- Dify Chatflow 编排与 OpenAPI 导入见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)。
- **核心目标**:提供通用文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。
- **通用域**:`FileCheckService` + `/api/file-check` Tool API + 单套 Dify Chatflow「文件检核助手」;RoHS、MSDS 等差异仅在排程 SQL、`task_id` 与判定 Workflow。
- **多 Agent**:RoHS / MSDS 等工作台 Agent 共用同一 `dify_app_id`,HXOPS 按 `extra_config.tool_run_progress.schedule_task_id` 注入 `task_id`。
- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 历史分支按 `task_id` 选择知识库 Dataset。
- Dify Chatflow 编排与 OpenAPI 导入见 [docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)。
### 3.1 本期范围
File diff suppressed because it is too large. Load diff
+11 -4
View File
@@ -16,14 +16,21 @@
## 2. 详细功能拆分
### RoHS 文件检核
### 文件检核(通用域)
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| RoHSCheckService 判定入口 | 已实现 | 检核执行链路统一调用,内部复用现有 Dify Workflow |
| Chatflow 发起与查询检核 | 已实现 | Tool API:查检核任务、启动检核、查检核批次、查最近检核、Excel 报告链接 |
| RoHS Chatflow 编排手册 | 已文档化 | 见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md) |
| FileCheckService 判定入口 | 已实现 | 检核执行链路统一调用 Dify Workflow(RoHS / MSDS 等按排程绑定不同 Workflow) |
| 文件检核 Chatflow Tool API | 已实现 | `/api/file-check/tools/*`:启动检核、查批次、Excel 报告链接 |
| 文件检核 Chatflow 编排手册 | 已文档化 | 见 [docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md) |
| 检核报告同步知识库 | 已实现 | 检核 success / partial_failed 且生成 Excel 后同步到所选知识库分组 |
| 多 Agent 共用 Chatflow | 已实现 | RoHS / MSDS 等 Agent 共用同一 Dify Chatflow,`task_id` 由 Agent extra_config 注入 |
### RoHS 文件检核(实例)
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| RoHS 排程检核 | 已实现 | 首个文件检核类型实例,复用通用 file_check 域 |
### F-01 本人假期查询
+724
View File
@@ -0,0 +1,724 @@
{
"openapi": "3.0.3",
"info": {
"title": "HXOPS File Check Tool API",
"description": "文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
"version": "1.0.0"
},
"servers": [
{
"url": "http://192.168.36.108:5052",
"description": "HXOPS_TOOLS_API_BASE"
}
],
"security": [
{
"BearerAuth": []
},
{
"IntegrationKey": []
}
],
"paths": {
"/api/file-check/tools/tasks": {
"get": {
"operationId": "list_file_check_tasks",
"summary": "查询指定文件检核任务",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": true,
"schema": {
"type": "integer",
"example": 12
},
"description": "检核任务 ID(Agent 绑定的 schedule_task_id)"
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ListTasksResponse"
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
}
}
},
"/api/file-check/tools/tasks/run": {
"post": {
"operationId": "run_file_check",
"summary": "异步启动 文件检核",
"tags": [
"File Check"
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/RunCheckRequest"
}
}
}
},
"responses": {
"200": {
"description": "启动成功;或已有 文件检核进行中,返回 ok=false/error_code=check_running",
"content": {
"application/json": {
"schema": {
"oneOf": [
{
"$ref": "#/components/schemas/RunCheckSuccessResponse"
},
{
"$ref": "#/components/schemas/CheckRunningResponse"
}
]
}
}
}
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
}
}
},
"/api/file-check/tools/runs": {
"get": {
"operationId": "list_file_check_runs",
"summary": "查询 文件检核批次列表",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"example": 12
},
"description": "可选;指定检核任务 ID 时只返回该任务批次"
},
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
},
"description": "返回条数,最大 100"
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ListRunsResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
}
}
},
"/api/file-check/tools/runs/{run_id}": {
"get": {
"operationId": "get_file_check_run",
"summary": "查询指定检核批次",
"tags": [
"File Check"
],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 88
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
}
}
},
"/api/file-check/tools/tasks/{task_id}/latest-run": {
"get": {
"operationId": "get_latest_file_check_run",
"summary": "查询检核任务最近一次检核",
"tags": [
"File Check"
],
"parameters": [
{
"name": "task_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 12
}
}
],
"responses": {
"200": {
"description": "成功",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
}
}
},
"401": {
"$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
}
}
},
"/api/file-check/tools/runs/{run_id}/excel": {
"get": {
"operationId": "download_file_check_run_excel",
"summary": "下载检核报告 Excel(短期签名 token)",
"tags": [
"File Check"
],
"security": [],
"parameters": [
{
"name": "run_id",
"in": "path",
"required": true,
"schema": {
"type": "integer",
"example": 88
}
},
{
"name": "token",
"in": "query",
"required": true,
"description": "由 get_file_check_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Excel 文件流",
"content": {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
},
"409": {
"$ref": "#/components/responses/ExcelNotReady"
}
}
}
}
},
"components": {
"securitySchemes": {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
},
"IntegrationKey": {
"type": "apiKey",
"in": "header",
"name": "X-Integration-Key",
"description": "与 Bearer 二选一"
}
},
"schemas": {
"TaskSummary": {
"type": "object",
"properties": {
"task_id": {
"type": "integer",
"example": 12
},
"task_no": {
"type": "string",
"example": "CHK202606090001"
},
"name": {
"type": "string",
"example": "文件自动检核"
},
"enabled": {
"type": "boolean"
},
"last_status": {
"type": "string",
"nullable": true,
"example": "success"
},
"last_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"next_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
}
}
},
"RunExcel": {
"type": "object",
"properties": {
"file_name": {
"type": "string",
"nullable": true,
"example": "RUN202606090001.xlsx"
},
"file_size": {
"type": "integer",
"nullable": true,
"example": 45678
},
"download_url": {
"type": "string",
"nullable": true,
"example": "https://your-hxops-host/api/file-check/tools/runs/88/excel?token=..."
}
}
},
"RunKnowledgeBase": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
},
"sync_status": {
"type": "string",
"nullable": true,
"enum": [
"skipped",
"queued",
"cleaning",
"syncing",
"ready",
"success",
"failed"
]
},
"group_id": {
"type": "integer",
"nullable": true
},
"document_id": {
"type": "integer",
"nullable": true
},
"document_version_id": {
"type": "integer",
"nullable": true
},
"sync_job_id": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
}
}
},
"RunDetail": {
"type": "object",
"properties": {
"run_id": {
"type": "integer",
"example": 88
},
"run_no": {
"type": "string",
"example": "RUN202606090001"
},
"task_id": {
"type": "integer",
"example": 12
},
"task_name": {
"type": "string",
"example": "文件自动检核"
},
"status": {
"type": "string",
"enum": [
"running",
"success",
"partial_failed",
"failed",
"queued",
"cancelled"
]
},
"total_count": {
"type": "integer"
},
"success_count": {
"type": "integer"
},
"failed_count": {
"type": "integer"
},
"skipped_count": {
"type": "integer"
},
"started_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"finished_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"duration_ms": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
},
"excel": {
"$ref": "#/components/schemas/RunExcel"
},
"knowledge_base": {
"$ref": "#/components/schemas/RunKnowledgeBase"
}
}
},
"ListTasksResponse": {
"type": "object",
"required": [
"ok",
"tasks"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"tasks": {
"type": "array",
"items": {
"$ref": "#/components/schemas/TaskSummary"
}
}
}
},
"RunCheckRequest": {
"type": "object",
"properties": {
"task_id": {
"type": "integer",
"example": 12
},
"trigger_source": {
"type": "string",
"default": "dify_chatflow"
},
"conversation_id": {
"type": "string",
"nullable": true
},
"user_message": {
"type": "string",
"nullable": true
}
},
"required": [
"task_id"
],
"description": "Chatflow Tool 节点绑定 task_id(来自 Start 用户输入);user_message 用于进度卡片 turn 匹配"
},
"RunCheckSuccessResponse": {
"type": "object",
"required": [
"ok",
"message",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"message": {
"type": "string",
"example": "检核已启动"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"CheckRunningResponse": {
"type": "object",
"required": [
"ok",
"error_code",
"message",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string",
"example": "check_running"
},
"message": {
"type": "string",
"example": "该检核任务正在执行中,请稍后查询结果"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"GetRunResponse": {
"type": "object",
"required": [
"ok",
"run"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
}
},
"ListRunsResponse": {
"type": "object",
"required": [
"ok",
"runs",
"count"
],
"properties": {
"ok": {
"type": "boolean",
"example": true
},
"count": {
"type": "integer",
"example": 2
},
"runs": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RunDetail"
}
}
}
},
"ErrorResponse": {
"type": "object",
"required": [
"ok",
"error_code",
"message"
],
"properties": {
"ok": {
"type": "boolean",
"example": false
},
"error_code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
},
"responses": {
"Unauthorized": {
"description": "鉴权失败",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"missing_auth": {
"value": {
"ok": false,
"error_code": "missing_auth",
"message": "missing_auth"
}
},
"invalid_auth": {
"value": {
"ok": false,
"error_code": "invalid_auth",
"message": "invalid_auth"
}
}
}
}
}
},
"MissingAuth": {
"description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "missing_auth",
"message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
}
}
}
},
"BadRequest": {
"description": "请求参数无效",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "invalid_request",
"message": "invalid_request"
}
}
}
},
"TaskNotFound": {
"description": "检核任务不存在",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "task_not_found",
"message": "task_not_found"
}
}
}
},
"RunNotFound": {
"description": "检核批次不存在",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "run_not_found",
"message": "run_not_found"
}
}
}
},
"ExcelNotReady": {
"description": "Excel 尚未生成",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"ok": false,
"error_code": "excel_not_ready",
"message": "excel_not_ready"
}
}
}
}
}
}
}
+6 -6
View File
@@ -10,13 +10,13 @@
## 2. 现有可复用能力
### 2.x RoHS 文件检核可复用能力
### 2.x 文件检核(file_check)可复用能力
- **产品语义**:对外统一为 RoHS 文件检核(发起、实时查询、报告、知识库同步、历史报告检索);Tool API 使用 `/api/rohs-check/tools/tasks` 与 `task_id` / `task_no` 字段;历史查询走 Dify Knowledge Retrieval(绑定检核报告同步的 Dataset);对外基地址由环境变量 `HXOPS_TOOLS_API_BASE` 配置。
- 通过 `RoHSCheckService.evaluate()` 包装现有 Dify Workflow 调用,保持 `dify_result / dify_message` 输出兼容。
- 新增 `/api/rohs-check/tools/*` 显式 HTTP Tool API,供 Dify Chatflow 发起检核、查询检核结果并返回 Excel 报告短期签名链接。
- Chatflow 完整编排、Dify 逐步配置与 OpenAPI 导入见 **[docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)**;OpenAPI 规范见 **[docs/openapi/rohs_check_tools_openapi.json](openapi/rohs_check_tools_openapi.json)**(`python backend/scripts/export_rohs_check_openapi.py` 重新生成)。
- 复用知识库 `KbDocument / KbDocumentVersion / KbJob` 清洗与 Dify 同步链路,将检核报告 Excel 作为独立文档入库。
- **产品语义**:对外统一为文件检核(RoHS / MSDS 等);Tool API 使用 `/api/file-check/tools/tasks` 与 `task_id` 字段;多 Agent 共用单套 Dify Chatflow,`task_id` 由 Agent `extra_config` 注入;历史查询按 `task_id` 分支走 Dify Knowledge Retrieval。
- 通过 `FileCheckService.evaluate()` 调用排程绑定的 Dify Workflow,保持 `dify_result / dify_message` 输出兼容。
- `/api/file-check/tools/*` 显式 HTTP Tool API,供 Chatflow 发起检核、查询结果并返回 Excel 短期签名链接。
- Chatflow 编排见 **[docs/file_check_chatflow_guide.md](file_check_chatflow_guide.md)**;OpenAPI 见 **[docs/openapi/file_check_tools_openapi.json](openapi/file_check_tools_openapi.json)**(`python backend/scripts/export_file_check_openapi.py`)。
- 复用知识库清洗与 Dify 同步链路,将检核报告 Excel 入库。
### 2.1 已有聊天路由能力
@@ -1,5 +1,5 @@
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
import { buildLogProgressUrl } from '../utils/toolRunProgressConfig';
import { buildFileCheckLogProgressUrl } from '../utils/toolRunProgressConfig';
import { getToolRunProgress, type ToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressMatchSource } from '../types/tool-run-progress.types';
@@ -124,10 +124,11 @@ export function useToolRunProgress(
return fetchProgressUrl(sessionUrl, silent);
}
const taskId = Number(cfg.schedule_task_id ?? cfg.task_id);
const sessionId = String(cfg.session_id || '').trim();
if (!Number.isFinite(taskId) || taskId <= 0 || !sessionId) return null;
const fallbackUrl = buildLogProgressUrl('/api/workspace/rohs-check/runs/for-log', taskId, Number(cfg.chat_log_id));
return fetchProgressUrl(fallbackUrl, silent);
const chatLogId = Number(cfg.chat_log_id);
if (!Number.isFinite(taskId) || taskId <= 0 || !Number.isFinite(chatLogId) || chatLogId <= 0) {
return null;
}
return fetchProgressUrl(buildFileCheckLogProgressUrl(taskId, chatLogId), silent);
};
const refresh = async () => {
@@ -1,6 +1,6 @@
/**
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。
* 对话页:Agent tool_run_progress 能力轮询(文件检核等异步任务进度卡片)。
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
@@ -24,22 +24,14 @@ import {
assistantMessageHasError,
buildLogProgressUrl,
buildFileCheckDetailUrl,
buildFileCheckLogProgressUrl,
collectAssistantProgressTargets,
getChatLogIdFromMessage,
getRunIdFromMessage,
isRunningToolRunStatus,
resolveLogProgressBaseUrl,
resolveScheduleTaskId,
resolveMessageAnchorKey,
} from '../utils/toolRunProgressConfig';
@@ -132,28 +124,12 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const resolveDetailUrl = (runId: number) => {
const template = String(rawToolRunConfig.value?.detail_url_template || '').trim();
if (!template) return '';
return template.replace('{run_id}', encodeURIComponent(String(runId)));
};
const resolveDetailUrl = (runId: number) => buildFileCheckDetailUrl(runId);
const resolveForLogUrl = (chatLogId: number) => {
const taskId = boundScheduleTaskId.value;
if (!taskId) return '';
const base = resolveLogProgressBaseUrl(rawToolRunConfig.value || {});
return buildLogProgressUrl(base, taskId, chatLogId);
return buildFileCheckLogProgressUrl(taskId, chatLogId);
};
@@ -22,7 +22,7 @@ export interface ChatMessage {
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
/** RoHS 等异步任务批次 ID(按轮问答绑定) */
/** 文件检核等异步任务批次 ID(按轮问答绑定) */
run_id?: number;
payload?: unknown;
local_id?: string;
@@ -2,7 +2,7 @@
* features/chat/utils/toolRunProgressConfig.ts
* 用途:解析 Agent tool_run_progress 配置;构建 for-log / detail 轮询 URL。
* 依赖:ToolRunProgressConfig、ChatMessage。
* 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动;执行中与已完成批次均展示。
* 逻辑:文件检核进度 URL 由 schedule_task_id + chat_log_id/run_id 推导,无需 Agent 配置 log_progress_url。
*/
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
@@ -11,8 +11,13 @@ export interface ResolvedToolRunProgressOptions {
empty_poll_max: number;
}
/** 文件检核 for-log 轮询路径(固定;query 带 task_id、chat_log_id) */
export const FILE_CHECK_LOG_PROGRESS_PATH = '/api/workspace/file-check/runs/for-log';
/** 文件检核 detail 轮询路径模板(固定;{run_id} 替换为批次 ID) */
export const FILE_CHECK_DETAIL_PATH_TEMPLATE = '/api/workspace/file-check/runs/{run_id}';
const DEFAULT_EMPTY_POLL_MAX = 30;
const DEFAULT_LOG_PROGRESS_URL = '/api/workspace/rohs-check/runs/for-log';
export function resolveToolRunProgressOptions(
raw: Record<string, unknown> | ToolRunProgressConfig | null | undefined,
@@ -46,10 +51,19 @@ export function resolveScheduleTaskId(cfg: ToolRunProgressConfig | null | undefi
return Number.isFinite(id) && id > 0 ? id : null;
}
export function resolveLogProgressBaseUrl(cfg: ToolRunProgressConfig): string {
const logUrl = String(cfg.log_progress_url || cfg.session_progress_url || '').trim();
if (logUrl) return logUrl.split('?')[0] || logUrl;
return DEFAULT_LOG_PROGRESS_URL;
/**
* 文件检核 for-log 基路径;不读 Agent 配置,避免运维维护 URL。
*/
export function resolveFileCheckLogProgressPath(): string {
return FILE_CHECK_LOG_PROGRESS_PATH;
}
/**
* 按 run_id 生成文件检核 detail 轮询 URL。
*/
export function buildFileCheckDetailUrl(runId: number): string {
if (!Number.isFinite(runId) || runId <= 0) return '';
return FILE_CHECK_DETAIL_PATH_TEMPLATE.replace('{run_id}', encodeURIComponent(String(runId)));
}
export function buildLogProgressUrl(
@@ -68,6 +82,15 @@ export function buildLogProgressUrl(
return qs ? `${path}?${qs}` : path;
}
export function buildFileCheckLogProgressUrl(taskId: number, chatLogId: number): string {
return buildLogProgressUrl(resolveFileCheckLogProgressPath(), taskId, chatLogId);
}
/** @deprecated 仅兼容旧调用;新逻辑请用 buildFileCheckLogProgressUrl */
export function resolveLogProgressBaseUrl(_cfg?: ToolRunProgressConfig): string {
return resolveFileCheckLogProgressPath();
}
export function getRunIdFromMessage(msg: ChatMessage | null | undefined): number | null {
const runId = Number(msg?.run_id);
return Number.isFinite(runId) && runId > 0 ? runId : null;