feat(schedule):cron支持图形,RoHS检核增加进度显示
This commit is contained in:
1 parent
6d0e78be81
commit
f5aac9c893
46 files changed
+1987
-221
No files matched your search
+16
-2
@@ -902,7 +902,15 @@ def get_chat_messages():
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
assistant_msg = {'role': 'assistant', 'content': log.answer, 'chat_log_id': log.id, 'retriever_resources': log.retriever_resources or [], 'attribution_parts': log.attribution_parts or []}
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
}
|
||||
if log.run_id:
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
@@ -1165,6 +1173,7 @@ def chat_completions():
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
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,
|
||||
@@ -1176,7 +1185,11 @@ def chat_completions():
|
||||
if is_shipping_notice_chat_agent(agent_proxy):
|
||||
dify_inputs = build_shipping_dify_chat_inputs()
|
||||
elif is_rohs_check_chat_agent(agent_proxy):
|
||||
dify_inputs = build_rohs_dify_chat_inputs()
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
dify_inputs = build_rohs_dify_chat_inputs(
|
||||
hxops_session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
@@ -1184,6 +1197,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,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
)
|
||||
|
||||
@@ -252,6 +252,9 @@ def run_rohs_check():
|
||||
)
|
||||
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
||||
if existing:
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
|
||||
merge_chat_log_bind_context(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
@@ -278,11 +281,17 @@ def run_rohs_check():
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
"hxops_session_id": data.get("hxops_session_id"),
|
||||
"hxops_turn_id": data.get("hxops_turn_id"),
|
||||
"user_message": data.get("user_message"),
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
@@ -301,7 +301,7 @@ def import_schedules():
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
@@ -309,7 +309,7 @@ def import_schedules():
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
@@ -329,7 +329,7 @@ def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||
raw_kb_group_id = data.get('kb_group_id')
|
||||
@@ -403,16 +403,19 @@ def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
from app.services.schedule.timezone_util import normalize_schedule_timezone
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
try:
|
||||
from croniter import croniter
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -421,6 +424,7 @@ def disable_schedule(task_id: int):
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@@ -1623,6 +1623,12 @@ def get_agent_details(id):
|
||||
if not has_permission:
|
||||
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
|
||||
|
||||
if is_rohs_check_chat_agent(agent):
|
||||
extra_config = enrich_tool_run_progress_extra(extra_config)
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
|
||||
dify_parameters = None
|
||||
|
||||
@@ -7,6 +7,7 @@ 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.models import ScheduleRun, ScheduleTask
|
||||
from app.services.rohs_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__)
|
||||
@@ -105,24 +106,57 @@ 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():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
chat_log_id = request.args.get("chat_log_id", type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||||
|
||||
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"run": _serialize_progress_run(run) if run else None,
|
||||
"match_source": "chat_log" if run else None,
|
||||
})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/for-session", methods=["GET"])
|
||||
def workspace_rohs_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)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
rows = (
|
||||
query = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.all()
|
||||
)
|
||||
run = next((
|
||||
row for row in rows
|
||||
if _is_rohs_check_task(row.task)
|
||||
and (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
), None)
|
||||
if task_id is not None:
|
||||
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)
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if _is_rohs_check_task(row.task)
|
||||
and (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
), None)
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
|
||||
|
||||
|
||||
|
||||
@@ -223,6 +223,8 @@ class Config:
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
|
||||
@@ -214,6 +214,7 @@ class ChatLog(Base):
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), index=True, nullable=True)
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
@@ -581,6 +582,7 @@ class ScheduleTask(Base):
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
|
||||
@@ -508,6 +508,7 @@ class DifyService:
|
||||
conversation_id: str = None,
|
||||
request_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
hxops_turn_id: str | None = None,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
):
|
||||
@@ -571,14 +572,47 @@ class DifyService:
|
||||
attribution_parts: List[str] = []
|
||||
chat_persist_started = False
|
||||
has_sent_answer = False
|
||||
chat_log_id_persisted: int | None = None
|
||||
run_id_persisted: int | None = None
|
||||
|
||||
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
|
||||
|
||||
if not is_rohs_check_chat_agent(agent):
|
||||
return None
|
||||
return resolve_run_id_for_chat_log(
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
turn_id=hxops_turn_id,
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def persist_stream_chat(data: dict, event_name: str) -> None:
|
||||
persist_stream_chat_async(data, event_name)
|
||||
result = persist_stream_chat_async(data, event_name)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id") is not None:
|
||||
data["chat_log_id"] = result["chat_log_id"]
|
||||
if result.get("run_id") is not None:
|
||||
data["run_id"] = result["run_id"]
|
||||
|
||||
def persist_stream_chat_async(data: dict, event_name: str) -> dict | None:
|
||||
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
|
||||
|
||||
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
|
||||
|
||||
if update_chat_log_run_id(chat_log_id_persisted, run_id):
|
||||
run_id_persisted = run_id
|
||||
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted}
|
||||
|
||||
def persist_stream_chat_async(data: dict, event_name: str) -> None:
|
||||
nonlocal chat_persist_started
|
||||
if chat_persist_started:
|
||||
return
|
||||
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted} if chat_log_id_persisted else None
|
||||
|
||||
chat_persist_started = True
|
||||
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
@@ -587,27 +621,33 @@ class DifyService:
|
||||
attribution_snapshot = list(attribution_parts)
|
||||
answer_snapshot = build_final_answer_text(persist_data, event_name)
|
||||
latency_snapshot = int((time.time() - start_time) * 1000)
|
||||
message_payload = persist_data.get('message_payload')
|
||||
|
||||
def _persist() -> None:
|
||||
if not app_obj:
|
||||
return
|
||||
with app_obj.app_context():
|
||||
DifyService._persist_stream_chat_record(
|
||||
data=persist_data,
|
||||
event_name=event_name,
|
||||
request_id=request_id,
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
attribution_parts=attribution_snapshot,
|
||||
)
|
||||
|
||||
Thread(target=_persist, daemon=True, name=f"dify-chat-persist-{request_id or 'unknown'}").start()
|
||||
if not app_obj:
|
||||
return None
|
||||
with app_obj.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data=persist_data,
|
||||
event_name=event_name,
|
||||
request_id=request_id,
|
||||
user_id=user_id,
|
||||
agent=agent,
|
||||
session_id=session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
attribution_parts=attribution_snapshot,
|
||||
message_payload=message_payload if isinstance(message_payload, dict) else None,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id"):
|
||||
chat_log_id_persisted = int(result["chat_log_id"])
|
||||
if result.get("run_id"):
|
||||
run_id_persisted = int(result["run_id"])
|
||||
return result
|
||||
|
||||
def build_final_answer_text(data: dict, event_name: str) -> str:
|
||||
answer_text = ''.join(full_answer).strip()
|
||||
@@ -790,6 +830,8 @@ class DifyService:
|
||||
latency,
|
||||
retriever_resources=None,
|
||||
attribution_parts=None,
|
||||
payload=None,
|
||||
run_id: int | None = None,
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
把最终问答和元数据写入 ChatLog
|
||||
@@ -803,6 +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(按轮问答绑定,可选)。
|
||||
"""
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
@@ -816,6 +859,8 @@ class DifyService:
|
||||
latency=latency or 0,
|
||||
retriever_resources=retriever_resources or [],
|
||||
attribution_parts=attribution_parts or [],
|
||||
payload=payload if isinstance(payload, dict) else None,
|
||||
run_id=run_id if run_id and run_id > 0 else None,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
@@ -835,17 +880,19 @@ class DifyService:
|
||||
event_name: str,
|
||||
request_id: str | None,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
agent,
|
||||
session_id: str | None,
|
||||
hxops_turn_id: str | None,
|
||||
normalized_conversation_id: str | None,
|
||||
query: str,
|
||||
answer_text: str,
|
||||
latency: int,
|
||||
retriever_resources: List[Any],
|
||||
attribution_parts: List[str],
|
||||
) -> None:
|
||||
message_payload: dict | None = None,
|
||||
) -> dict | None:
|
||||
if not answer_text and not str(query or '').strip():
|
||||
return
|
||||
return None
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
@@ -863,9 +910,23 @@ class DifyService:
|
||||
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
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
|
||||
|
||||
if is_rohs_check_chat_agent(agent):
|
||||
run_id = resolve_run_id_for_chat_log(
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
turn_id=hxops_turn_id,
|
||||
)
|
||||
except Exception:
|
||||
run_id = None
|
||||
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
@@ -874,17 +935,24 @@ class DifyService:
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
payload=message_payload,
|
||||
run_id=run_id,
|
||||
)
|
||||
if chat_log_id and current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s chat_log_id=%s run_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
chat_log_id,
|
||||
run_id,
|
||||
)
|
||||
if not chat_log_id:
|
||||
return None
|
||||
return {"chat_log_id": chat_log_id, "run_id": run_id}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""
|
||||
services/rohs_check_tools/chat_log_run_binding.py
|
||||
|
||||
用途:将 RoHS 检核批次 ID 写入 ChatLog.run_id(按轮问答绑定)。
|
||||
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
|
||||
逻辑:启动检核 API 写入 ScheduleRun.api_request_json;message_end 落 ChatLog 时解析并绑定 run_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
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 _normalize_bind_text(text: str | None) -> str:
|
||||
"""折叠空白,便于 user_message 与 ChatLog.query 对齐。"""
|
||||
return re.sub(r"\s+", " ", str(text or "").strip())
|
||||
|
||||
|
||||
def merge_chat_log_bind_context(run: ScheduleRun | None, data: dict[str, Any] | None) -> None:
|
||||
"""
|
||||
在 ScheduleRun 上记录本轮问答的绑定上下文,供 ChatLog 落库时匹配。
|
||||
|
||||
Args:
|
||||
run: 新建或复用的检核批次。
|
||||
data: 启动检核 HTTP Body。
|
||||
"""
|
||||
if not run:
|
||||
return
|
||||
payload = data if isinstance(data, dict) else {}
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
turn_id = str(payload.get("hxops_turn_id") or "").strip()
|
||||
user_message = str(payload.get("user_message") or "").strip()
|
||||
if not session_id and not turn_id and not user_message:
|
||||
return
|
||||
|
||||
req = dict(run.api_request_json or {}) if isinstance(run.api_request_json, dict) else {}
|
||||
if session_id:
|
||||
req["bind_session_id"] = session_id
|
||||
req["hxops_session_id"] = session_id
|
||||
if turn_id:
|
||||
req["bind_turn_id"] = turn_id
|
||||
req["hxops_turn_id"] = turn_id
|
||||
if user_message:
|
||||
req["bind_user_message"] = user_message
|
||||
req["user_message"] = user_message
|
||||
if payload.get("conversation_id"):
|
||||
req["conversation_id"] = payload.get("conversation_id")
|
||||
req["bind_requested_at"] = datetime.utcnow().isoformat()
|
||||
run.api_request_json = req
|
||||
|
||||
|
||||
def resolve_run_id_for_chat_log(
|
||||
*,
|
||||
session_id: str | None = None,
|
||||
query: str | None = None,
|
||||
turn_id: str | None = None,
|
||||
) -> int | None:
|
||||
"""
|
||||
匹配本轮问答应对绑定的 RoHS 检核批次 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。
|
||||
"""
|
||||
session_key = str(session_id or "").strip()
|
||||
turn_key = str(turn_id or "").strip()
|
||||
query_key = _normalize_bind_text(query)
|
||||
|
||||
rows = (
|
||||
ScheduleRun.query.order_by(ScheduleRun.id.desc())
|
||||
.limit(120)
|
||||
.all()
|
||||
)
|
||||
|
||||
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:
|
||||
for run in rohs_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:
|
||||
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"))
|
||||
if bind_session == session_key and bind_query == query_key:
|
||||
return int(run.id)
|
||||
|
||||
if session_key and query_key:
|
||||
for run in rohs_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"))
|
||||
if bind_session == session_key and bind_query and (
|
||||
query_key in bind_query or bind_query in query_key
|
||||
):
|
||||
return int(run.id)
|
||||
|
||||
if session_key:
|
||||
cutoff = datetime.utcnow() - timedelta(minutes=15)
|
||||
for run in rohs_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:
|
||||
continue
|
||||
bind_at_raw = str(req.get("bind_requested_at") or run.started_at or "")
|
||||
try:
|
||||
bind_at = datetime.fromisoformat(bind_at_raw.replace("Z", ""))
|
||||
except ValueError:
|
||||
bind_at = run.started_at
|
||||
if bind_at and bind_at >= cutoff and run.status == "running":
|
||||
return int(run.id)
|
||||
|
||||
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",
|
||||
turn_key or None,
|
||||
session_key or None,
|
||||
len(query_key),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def update_chat_log_run_id(chat_log_id: int, run_id: int | None) -> bool:
|
||||
"""
|
||||
回写已有 ChatLog.run_id(workflow_finished 二次绑定)。
|
||||
|
||||
Returns:
|
||||
是否成功更新。
|
||||
"""
|
||||
if not chat_log_id or not run_id or run_id <= 0:
|
||||
return False
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log:
|
||||
return False
|
||||
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):
|
||||
return False
|
||||
log.run_id = run_id
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def bind_run_id_to_chat_log(*, chat_log: ChatLog | None, run_id: int | None) -> bool:
|
||||
"""
|
||||
将检核批次 ID 写入 ChatLog.run_id。
|
||||
|
||||
Returns:
|
||||
是否成功写入并提交。
|
||||
"""
|
||||
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):
|
||||
return False
|
||||
chat_log.run_id = run_id
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
__all__ = [
|
||||
"bind_run_id_to_chat_log",
|
||||
"merge_chat_log_bind_context",
|
||||
"resolve_run_id_for_chat_log",
|
||||
"update_chat_log_run_id",
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
services/rohs_check_tools/chat_log_run_resolver.py
|
||||
|
||||
用途:按 ChatLog.run_id 解析 RoHS 检核进度(按轮问答)。
|
||||
依赖:ChatLog、ScheduleRun、task_resolver.is_rohs_check_schedule_task。
|
||||
逻辑:由 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(
|
||||
*,
|
||||
task_id: int,
|
||||
chat_log_id: int,
|
||||
) -> ScheduleRun | None:
|
||||
"""
|
||||
查询某条问答记录绑定的 RoHS 检核批次。
|
||||
|
||||
Args:
|
||||
task_id: ScheduleTask.id。
|
||||
chat_log_id: ChatLog.id。
|
||||
|
||||
Returns:
|
||||
绑定的 ScheduleRun,或 None。
|
||||
"""
|
||||
if chat_log_id <= 0 or task_id <= 0:
|
||||
return None
|
||||
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log or not log.run_id:
|
||||
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)
|
||||
):
|
||||
return run
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"find_run_for_chat_log",
|
||||
]
|
||||
@@ -4,14 +4,27 @@ 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() -> dict[str, str]:
|
||||
"""Build Dify chat API inputs for RoHS Chatflow HTTP nodes."""
|
||||
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")
|
||||
@@ -23,12 +36,24 @@ def build_dify_chat_inputs() -> dict[str, str]:
|
||||
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",
|
||||
]
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
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.schedule_task_id(若缺失)。
|
||||
|
||||
Returns:
|
||||
新的 extra_config 副本;无变更时返回原 dict 浅拷贝。
|
||||
"""
|
||||
extra = dict(extra_config or {})
|
||||
tool_cfg = extra.get("tool_run_progress")
|
||||
if not isinstance(tool_cfg, dict):
|
||||
return extra
|
||||
|
||||
merged = dict(tool_cfg)
|
||||
merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log")
|
||||
merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}")
|
||||
|
||||
if not resolve_schedule_task_id_from_mapping(tool_cfg):
|
||||
task_id = resolve_default_rohs_schedule_task_id()
|
||||
if task_id:
|
||||
merged["schedule_task_id"] = task_id
|
||||
|
||||
extra["tool_run_progress"] = merged
|
||||
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",
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
backend/app/services/schedule/cron_util.py
|
||||
排程 Cron 表达式规范化与校验辅助。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def normalize_cron_expr(expr: str | None) -> str:
|
||||
"""
|
||||
修正常见笔误:* 12,17 * * *(小时内每分钟)→ 0 12,17 * * *(整点)。
|
||||
"""
|
||||
text = str(expr or '').strip()
|
||||
parts = text.split()
|
||||
if len(parts) == 5 and parts[0] == '*' and parts[1] != '*':
|
||||
parts[0] = '0'
|
||||
return ' '.join(parts)
|
||||
return text
|
||||
|
||||
|
||||
def is_risky_cron_expr(expr: str | None) -> bool:
|
||||
"""分钟为 * 且小时已限定时,会在该小时内每分钟触发。"""
|
||||
text = str(expr or '').strip()
|
||||
parts = text.split()
|
||||
return len(parts) == 5 and parts[0] == '*' and parts[1] != '*'
|
||||
@@ -9,6 +9,17 @@ from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.response_utils import utc_iso
|
||||
from app.services.schedule.timezone_util import (
|
||||
DEFAULT_SCHEDULE_TIMEZONE,
|
||||
compute_next_run_at,
|
||||
normalize_schedule_timezone,
|
||||
)
|
||||
|
||||
|
||||
def _schedule_timezone_label(task: ScheduleTask | None = None) -> str:
|
||||
if task is not None:
|
||||
return normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
||||
return DEFAULT_SCHEDULE_TIMEZONE
|
||||
|
||||
|
||||
def _as_naive_utc(dt: datetime | None) -> datetime | None:
|
||||
@@ -28,6 +39,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
|
||||
'owner_user_id': task.owner_user_id,
|
||||
'owner_username': task.owner.username if task.owner else None,
|
||||
'cron_expr': task.cron_expr,
|
||||
'schedule_timezone': _schedule_timezone_label(task),
|
||||
'wait_seconds': task.wait_seconds,
|
||||
'dify_agent_id': task.dify_agent_id,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
@@ -82,6 +94,17 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _repair_next_run_if_needed(task: ScheduleTask) -> bool:
|
||||
"""启用中但 next_run_at 为空时补算,返回是否发生修改。"""
|
||||
if not task.enabled or not str(task.cron_expr or '').strip():
|
||||
return False
|
||||
if task.next_run_at is not None:
|
||||
return False
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
return task.next_run_at is not None
|
||||
|
||||
|
||||
def list_tasks() -> list[dict]:
|
||||
latest_run_subquery = (
|
||||
db.session.query(
|
||||
@@ -99,6 +122,13 @@ def list_tasks() -> list[dict]:
|
||||
.order_by(ScheduleTask.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
repaired = False
|
||||
for task, _last_status in rows:
|
||||
if _repair_next_run_if_needed(task):
|
||||
repaired = True
|
||||
if repaired:
|
||||
db.session.commit()
|
||||
|
||||
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from croniter import croniter
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
@@ -15,6 +14,8 @@ from app.services.schedule import normalize_platform_api_path, resolve_schedule_
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
@@ -160,6 +161,7 @@ def create_task(
|
||||
schedule_type: str,
|
||||
owner_user_id: int,
|
||||
cron_expr: str,
|
||||
schedule_timezone: str | None = None,
|
||||
wait_seconds: int,
|
||||
dify_agent_id: int | None,
|
||||
platform_api_path: str | None,
|
||||
@@ -168,12 +170,14 @@ def create_task(
|
||||
enabled: bool,
|
||||
actor_id: int | None,
|
||||
) -> ScheduleTask:
|
||||
cron_expr = normalize_cron_expr(cron_expr)
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
schedule_type="platform_app",
|
||||
owner_user_id=owner_user_id,
|
||||
cron_expr=cron_expr,
|
||||
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
|
||||
wait_seconds=max(0, int(wait_seconds or 0)),
|
||||
dify_agent_id=dify_agent_id,
|
||||
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
|
||||
@@ -184,11 +188,8 @@ def create_task(
|
||||
updated_by=actor_id,
|
||||
)
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
if task.next_run_at is None:
|
||||
task.enabled = False
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
@@ -200,13 +201,20 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
"name",
|
||||
"owner_user_id",
|
||||
"cron_expr",
|
||||
"schedule_timezone",
|
||||
"wait_seconds",
|
||||
"dify_agent_id",
|
||||
"notify_enabled",
|
||||
"enabled",
|
||||
]:
|
||||
if key in payload:
|
||||
setattr(task, key, payload[key])
|
||||
if key == "schedule_timezone":
|
||||
value = normalize_schedule_timezone(payload[key])
|
||||
elif key == "cron_expr":
|
||||
value = normalize_cron_expr(str(payload[key] or ""))
|
||||
else:
|
||||
value = payload[key]
|
||||
setattr(task, key, value)
|
||||
if "platform_api_path" in payload:
|
||||
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
|
||||
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
|
||||
@@ -222,11 +230,8 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
task.schedule_type = "platform_app"
|
||||
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
@@ -258,11 +263,7 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
db.session.commit()
|
||||
|
||||
if task.cron_expr and trigger_type == "cron":
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
db.session.commit()
|
||||
|
||||
start_ts = time.time()
|
||||
@@ -402,15 +403,12 @@ def start_scheduler(app):
|
||||
stale = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
ScheduleTask.next_run_at <= datetime.utcnow(),
|
||||
ScheduleTask.next_run_at <= utc_now_naive(),
|
||||
).all()
|
||||
for t in stale:
|
||||
if t.cron_expr:
|
||||
try:
|
||||
it = croniter(t.cron_expr, datetime.utcnow())
|
||||
t.next_run_at = it.get_next(datetime)
|
||||
except Exception:
|
||||
t.next_run_at = None
|
||||
t.next_run_at = compute_next_run_at(t.cron_expr, timezone_name=getattr(t, "schedule_timezone", None))
|
||||
if t.next_run_at is None:
|
||||
t.enabled = False
|
||||
else:
|
||||
t.next_run_at = None
|
||||
@@ -431,7 +429,7 @@ def start_scheduler(app):
|
||||
|
||||
while True:
|
||||
try:
|
||||
now = datetime.utcnow()
|
||||
now = utc_now_naive()
|
||||
due_tasks = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
@@ -444,11 +442,7 @@ def start_scheduler(app):
|
||||
).first()
|
||||
if has_running:
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
@@ -458,11 +452,8 @@ def start_scheduler(app):
|
||||
db.session.rollback()
|
||||
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
||||
if task.next_run_at is None:
|
||||
task.enabled = False
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/services/schedule/timezone_util.py
|
||||
排程 Cron 时区:优先按任务自己的 IANA 时区解析表达式,数据库存储 UTC naive。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone, tzinfo
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from croniter import croniter
|
||||
from flask import current_app
|
||||
|
||||
DEFAULT_SCHEDULE_TIMEZONE = 'Asia/Shanghai'
|
||||
|
||||
# 环境未安装 tzdata 时,用固定 UTC 偏移回退(不含夏令时)
|
||||
_FIXED_TZ_FALLBACKS: dict[str, tzinfo] = {
|
||||
'Asia/Shanghai': timezone(timedelta(hours=8)),
|
||||
'Asia/Taipei': timezone(timedelta(hours=8)),
|
||||
'Asia/Hong_Kong': timezone(timedelta(hours=8)),
|
||||
'UTC': timezone.utc,
|
||||
}
|
||||
|
||||
|
||||
def get_schedule_timezone_name(timezone_name: str | None = None) -> str:
|
||||
"""解析排程时区名称;优先使用任务时区,其次回退到系统默认时区。"""
|
||||
return (timezone_name or current_app.config.get('SCHEDULE_TIMEZONE') or DEFAULT_SCHEDULE_TIMEZONE).strip()
|
||||
|
||||
|
||||
def resolve_schedule_tzinfo(timezone_name: str | None = None) -> tzinfo:
|
||||
"""
|
||||
将 IANA 时区名解析为 tzinfo。
|
||||
|
||||
优先使用 zoneinfo;若运行环境缺少 tzdata(常见于未 pip install tzdata 的容器/venv),
|
||||
对常用业务时区回退到固定 UTC 偏移。
|
||||
"""
|
||||
name = get_schedule_timezone_name(timezone_name)
|
||||
try:
|
||||
return ZoneInfo(name)
|
||||
except Exception:
|
||||
fallback = _FIXED_TZ_FALLBACKS.get(name)
|
||||
if fallback is not None:
|
||||
_log_tz_fallback_once(name)
|
||||
return fallback
|
||||
default_fallback = _FIXED_TZ_FALLBACKS[DEFAULT_SCHEDULE_TIMEZONE]
|
||||
_log_tz_fallback_once(name, fallback_to=DEFAULT_SCHEDULE_TIMEZONE)
|
||||
return default_fallback
|
||||
|
||||
|
||||
def get_schedule_timezone(timezone_name: str | None = None) -> tzinfo:
|
||||
"""将排程时区名称转换为 tzinfo,供 croniter 计算当地执行时间。"""
|
||||
return resolve_schedule_tzinfo(timezone_name)
|
||||
|
||||
|
||||
def normalize_schedule_timezone(timezone_name: str | None) -> str:
|
||||
"""校验并标准化 IANA 时区名;无法通过 zoneinfo 校验时仍保留可回退的名称。"""
|
||||
text = get_schedule_timezone_name(timezone_name)
|
||||
try:
|
||||
ZoneInfo(text)
|
||||
return text
|
||||
except Exception:
|
||||
if text in _FIXED_TZ_FALLBACKS:
|
||||
return text
|
||||
return DEFAULT_SCHEDULE_TIMEZONE
|
||||
|
||||
|
||||
def utc_now_naive() -> datetime:
|
||||
"""返回 UTC naive datetime,统一用于数据库字段比较。"""
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def to_utc_naive(dt: datetime) -> datetime:
|
||||
"""将 aware datetime 转为 UTC naive;naive 输入保持不变。"""
|
||||
if dt.tzinfo is None:
|
||||
return dt
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def compute_next_run_at(
|
||||
cron_expr: str,
|
||||
*,
|
||||
base_utc_naive: datetime | None = None,
|
||||
timezone_name: str | None = None,
|
||||
) -> datetime | None:
|
||||
"""
|
||||
按排程业务时区计算下次执行时刻,返回 UTC naive 供入库与 worker 比较。
|
||||
|
||||
:param cron_expr: 5 段标准 Cron
|
||||
:param base_utc_naive: 基准时刻(UTC naive);默认取当前时刻
|
||||
"""
|
||||
text = str(cron_expr or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
tz_name = normalize_schedule_timezone(timezone_name)
|
||||
try:
|
||||
tz = resolve_schedule_tzinfo(tz_name)
|
||||
if base_utc_naive is None:
|
||||
base_aware = datetime.now(tz)
|
||||
else:
|
||||
base_aware = base_utc_naive.replace(tzinfo=timezone.utc).astimezone(tz)
|
||||
itr = croniter(text, base_aware)
|
||||
return to_utc_naive(itr.get_next(datetime))
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
"compute_next_run_at failed: %s cron=%s tz=%s",
|
||||
exc,
|
||||
text,
|
||||
tz_name,
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
_logged_tz_fallbacks: set[str] = set()
|
||||
|
||||
|
||||
def _log_tz_fallback_once(requested: str, *, fallback_to: str | None = None) -> None:
|
||||
"""缺少 tzdata 时仅记录一次回退日志,避免刷屏。"""
|
||||
key = f'{requested}->{fallback_to or requested}'
|
||||
if key in _logged_tz_fallbacks:
|
||||
return
|
||||
_logged_tz_fallbacks.add(key)
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
"tzdata unavailable; using fixed UTC offset fallback for schedule timezone %s%s. "
|
||||
"Install backend dependency tzdata (pip install tzdata).",
|
||||
requested,
|
||||
f' (fallback {fallback_to})' if fallback_to else '',
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
@@ -0,0 +1,51 @@
|
||||
"""add schedule_timezone to schedule_tasks
|
||||
|
||||
Revision ID: c9d0e1f2a3b4
|
||||
Revises: b8c9d0e1f2a3
|
||||
Create Date: 2026-06-12 00:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "c9d0e1f2a3b4"
|
||||
down_revision = "b8c9d0e1f2a3"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "schedule_tasks" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("schedule_tasks")}
|
||||
if "schedule_timezone" not in columns:
|
||||
with op.batch_alter_table("schedule_tasks", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
"schedule_timezone",
|
||||
sa.String(length=64),
|
||||
nullable=True,
|
||||
)
|
||||
)
|
||||
op.execute("UPDATE schedule_tasks SET schedule_timezone = 'Asia/Shanghai' WHERE schedule_timezone IS NULL")
|
||||
with op.batch_alter_table("schedule_tasks", schema=None) as batch_op:
|
||||
batch_op.alter_column(
|
||||
"schedule_timezone",
|
||||
existing_type=sa.String(length=64),
|
||||
server_default=sa.text("'Asia/Shanghai'"),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "schedule_tasks" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("schedule_tasks")}
|
||||
if "schedule_timezone" in columns:
|
||||
with op.batch_alter_table("schedule_tasks", schema=None) as batch_op:
|
||||
batch_op.drop_column("schedule_timezone")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""add run_id to chat_sessions
|
||||
|
||||
Revision ID: d0e2f3a4b5c6
|
||||
Revises: c9d0e1f2a3b4
|
||||
Create Date: 2026-06-12 12:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "d0e2f3a4b5c6"
|
||||
down_revision = "c9d0e1f2a3b4"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_sessions" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_sessions")}
|
||||
if "run_id" not in columns:
|
||||
with op.batch_alter_table("chat_sessions", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("run_id", sa.Integer(), nullable=True))
|
||||
batch_op.create_foreign_key(
|
||||
"fk_chat_sessions_run_id_schedule_runs",
|
||||
"schedule_runs",
|
||||
["run_id"],
|
||||
["id"],
|
||||
)
|
||||
batch_op.create_index("ix_chat_sessions_run_id", ["run_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_sessions" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_sessions")}
|
||||
if "run_id" in columns:
|
||||
with op.batch_alter_table("chat_sessions", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_chat_sessions_run_id")
|
||||
batch_op.drop_constraint("fk_chat_sessions_run_id_schedule_runs", type_="foreignkey")
|
||||
batch_op.drop_column("run_id")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""add run_id to chat_logs
|
||||
|
||||
Revision ID: e1f2a3b4c5d7
|
||||
Revises: d0e2f3a4b5c6
|
||||
Create Date: 2026-06-12 14:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "e1f2a3b4c5d7"
|
||||
down_revision = "d0e2f3a4b5c6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_logs" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_logs")}
|
||||
if "run_id" not in columns:
|
||||
with op.batch_alter_table("chat_logs", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("run_id", sa.Integer(), nullable=True))
|
||||
batch_op.create_foreign_key(
|
||||
"fk_chat_logs_run_id_schedule_runs",
|
||||
"schedule_runs",
|
||||
["run_id"],
|
||||
["id"],
|
||||
)
|
||||
batch_op.create_index("ix_chat_logs_run_id", ["run_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_logs" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_logs")}
|
||||
if "run_id" in columns:
|
||||
with op.batch_alter_table("chat_logs", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_chat_logs_run_id")
|
||||
batch_op.drop_constraint("fk_chat_logs_run_id_schedule_runs", type_="foreignkey")
|
||||
batch_op.drop_column("run_id")
|
||||
@@ -0,0 +1,48 @@
|
||||
"""drop run_id from chat_sessions
|
||||
|
||||
Revision ID: f2a3b4c5d6e8
|
||||
Revises: e1f2a3b4c5d7
|
||||
Create Date: 2026-06-12 16:00:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "f2a3b4c5d6e8"
|
||||
down_revision = "e1f2a3b4c5d7"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_sessions" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_sessions")}
|
||||
if "run_id" not in columns:
|
||||
return
|
||||
with op.batch_alter_table("chat_sessions", schema=None) as batch_op:
|
||||
batch_op.drop_index("ix_chat_sessions_run_id")
|
||||
batch_op.drop_constraint("fk_chat_sessions_run_id_schedule_runs", type_="foreignkey")
|
||||
batch_op.drop_column("run_id")
|
||||
|
||||
|
||||
def downgrade():
|
||||
bind = op.get_bind()
|
||||
insp = sa.inspect(bind)
|
||||
if "chat_sessions" not in set(insp.get_table_names()):
|
||||
return
|
||||
columns = {col["name"] for col in insp.get_columns("chat_sessions")}
|
||||
if "run_id" in columns:
|
||||
return
|
||||
with op.batch_alter_table("chat_sessions", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("run_id", sa.Integer(), nullable=True))
|
||||
batch_op.create_foreign_key(
|
||||
"fk_chat_sessions_run_id_schedule_runs",
|
||||
"schedule_runs",
|
||||
["run_id"],
|
||||
["id"],
|
||||
)
|
||||
batch_op.create_index("ix_chat_sessions_run_id", ["run_id"], unique=False)
|
||||
@@ -34,5 +34,6 @@ beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
typer==0.17.4
|
||||
croniter
|
||||
tzdata
|
||||
pyyaml
|
||||
minio==7.2.20
|
||||
@@ -4,7 +4,7 @@ import types
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
|
||||
from app.services.rohs_check import RoHSCheckService
|
||||
|
||||
|
||||
@@ -277,6 +277,86 @@ 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):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-BIND-CONFLICT',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='manual',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
running_run_id = run.id
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'bind-on-conflict',
|
||||
'user_message': '立即执行检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()['error_code'] == 'check_running'
|
||||
|
||||
with app.app_context():
|
||||
bound = db.session.get(ScheduleRun, running_run_id)
|
||||
req = bound.api_request_json or {}
|
||||
assert req.get('bind_session_id') == 'bind-on-conflict'
|
||||
assert req.get('bind_user_message') == '立即执行检核'
|
||||
|
||||
|
||||
def test_rohs_tool_start_records_chat_log_bind_context(app, client, monkeypatch):
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={
|
||||
'task_id': task_id,
|
||||
'hxops_session_id': 'bind-on-start',
|
||||
'hxops_turn_id': 'turn-abc-001',
|
||||
'user_message': '执行 RoHS 检核',
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
with app.app_context():
|
||||
run = db.session.get(ScheduleRun, run_id)
|
||||
req = run.api_request_json or {}
|
||||
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
|
||||
|
||||
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):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -402,6 +482,85 @@ 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):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task_a = _mk_check_task(admin.id)
|
||||
task_b = ScheduleTask(
|
||||
schedule_no='CHK-ROHS-002',
|
||||
name='RoHS 文件检核 B',
|
||||
schedule_type='platform_app',
|
||||
owner_user_id=admin.id,
|
||||
cron_expr='0 * * * *',
|
||||
wait_seconds=5,
|
||||
platform_api_path='/2',
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(task_b)
|
||||
db.session.commit()
|
||||
run_a = ScheduleRun(
|
||||
run_no='RUN-ROHS-TASK-A',
|
||||
schedule_task_id=task_a.id,
|
||||
status='running',
|
||||
trigger_type='manual',
|
||||
total_count=10,
|
||||
success_count=1,
|
||||
)
|
||||
run_b = ScheduleRun(
|
||||
run_no='RUN-ROHS-TASK-B',
|
||||
schedule_task_id=task_b.id,
|
||||
status='running',
|
||||
trigger_type='manual',
|
||||
total_count=8,
|
||||
success_count=2,
|
||||
)
|
||||
db.session.add_all([run_a, run_b])
|
||||
db.session.commit()
|
||||
task_a_id = task_a.id
|
||||
task_b_id = task_b.id
|
||||
|
||||
hit = client.get(
|
||||
f'/api/workspace/rohs-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}',
|
||||
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):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-TASK-CONV-MISMATCH',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
total_count=10,
|
||||
success_count=1,
|
||||
api_request_json={'conversation_id': 'dify-conv-uuid'},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
|
||||
res = client.get(
|
||||
f'/api/workspace/rohs-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):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
@@ -428,6 +587,144 @@ def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
|
||||
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
|
||||
|
||||
|
||||
def test_workspace_rohs_run_for_log_returns_null_when_unbound(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
log = ChatLog(
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
query='查询最新结果',
|
||||
answer='查询结果',
|
||||
session_id='sess-query-only',
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
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}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
payload = res.get_json()
|
||||
assert payload['run'] is None
|
||||
assert payload.get('match_source') is None
|
||||
|
||||
|
||||
def test_workspace_rohs_run_for_log_reads_bound_run_id(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-BOUND',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
total_count=5,
|
||||
success_count=1,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
log = ChatLog(
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
query='立即执行检核',
|
||||
answer='检核已启动',
|
||||
session_id='hxops-sess-002',
|
||||
run_id=run.id,
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
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}',
|
||||
headers={'X-Username': 'admin'},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
payload = res.get_json()
|
||||
assert payload['run']['run_no'] == 'RUN-ROHS-BOUND'
|
||||
assert payload['match_source'] == 'chat_log'
|
||||
|
||||
|
||||
def test_workspace_rohs_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')
|
||||
viewer = User(username='rohs-viewer', email='viewer-rohs@example.com', role='user', status='active')
|
||||
viewer.set_password('x')
|
||||
db.session.add_all([owner, viewer])
|
||||
db.session.commit()
|
||||
task = _mk_check_task(owner.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-CROSS-USER',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
total_count=3,
|
||||
success_count=1,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
log = ChatLog(
|
||||
user_id=owner.id,
|
||||
agent_id=1,
|
||||
query='立即执行检核',
|
||||
answer='检核已启动',
|
||||
session_id='hxops-sess-cross-user',
|
||||
run_id=run.id,
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
task_id = task.id
|
||||
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}',
|
||||
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):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-OTHER-TASK',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
log = ChatLog(
|
||||
user_id=admin.id,
|
||||
agent_id=1,
|
||||
query='立即执行检核',
|
||||
answer='检核已启动',
|
||||
session_id='hxops-sess-empty',
|
||||
run_id=run.id,
|
||||
)
|
||||
db.session.add(log)
|
||||
db.session.commit()
|
||||
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}',
|
||||
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):
|
||||
with app.app_context():
|
||||
_mk_admin()
|
||||
@@ -529,9 +826,10 @@ def test_rohs_dify_chat_inputs(app):
|
||||
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()
|
||||
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'
|
||||
|
||||
|
||||
def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""排程 Cron 业务时区计算测试。"""
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
def test_compute_next_run_at_uses_shanghai_timezone(app):
|
||||
"""0 12,17 * * * 在 01:00 北京时间后,下次应为当日 12:00(非 UTC 12:00)。"""
|
||||
with app.app_context():
|
||||
# 2026-06-12 01:00:15 CST = 2026-06-11 17:00:15 UTC
|
||||
base_utc = datetime(2026, 6, 11, 17, 0, 15)
|
||||
nxt = compute_next_run_at('0 12,17 * * *', base_utc_naive=base_utc)
|
||||
assert nxt == datetime(2026, 6, 12, 4, 0, 0)
|
||||
|
||||
|
||||
def test_compute_next_run_at_after_noon(app):
|
||||
with app.app_context():
|
||||
# 2026-06-12 12:30 CST = 2026-06-12 04:30 UTC
|
||||
base_utc = datetime(2026, 6, 12, 4, 30, 0)
|
||||
nxt = compute_next_run_at('0 12,17 * * *', base_utc_naive=base_utc)
|
||||
assert nxt == datetime(2026, 6, 12, 9, 0, 0)
|
||||
|
||||
|
||||
def test_compute_next_run_at_without_tzdata(app):
|
||||
"""缺少 tzdata 时仍应通过固定 UTC+8 回退计算下次执行。"""
|
||||
with app.app_context():
|
||||
with patch('app.services.schedule.timezone_util.ZoneInfo', side_effect=Exception('no tzdata')):
|
||||
base_utc = datetime(2026, 6, 11, 17, 0, 15)
|
||||
nxt = compute_next_run_at('0 12,17 * * *', base_utc_naive=base_utc)
|
||||
assert nxt == datetime(2026, 6, 12, 4, 0, 0)
|
||||
Reference in new issue
Block a user