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)
|
||||
@@ -45,9 +45,12 @@ export interface ToolRunProgress {
|
||||
};
|
||||
}
|
||||
|
||||
export type ToolRunProgressMatchSource = 'chat_log';
|
||||
|
||||
export interface ToolRunProgressResponse {
|
||||
ok: boolean;
|
||||
run: ToolRunProgress | null;
|
||||
match_source?: ToolRunProgressMatchSource | null;
|
||||
}
|
||||
|
||||
export const getToolRunProgress = (url: string) =>
|
||||
|
||||
@@ -151,7 +151,11 @@ const {
|
||||
{{ $t('admin.schedule.lastRun') }}:{{ formatDateTime(s.last_run_at) }}
|
||||
</div>
|
||||
<div class="mb-3 text-sm text-muted">
|
||||
{{ $t('admin.schedule.nextRun') }}:{{ formatDateTime(s.next_run_at) }}
|
||||
{{ $t('admin.schedule.nextRun') }}:{{
|
||||
!s.enabled
|
||||
? $t('admin.schedule.nextRunDisabled')
|
||||
: (s.next_run_at ? formatDateTime(s.next_run_at) : $t('admin.schedule.nextRunPending'))
|
||||
}}
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
|
||||
@@ -11,7 +11,7 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const d = props.designer;
|
||||
const { state, cronExpr, isValid, nextRunAt, weekdayOptions } = d;
|
||||
const { state, timezone, cronExpr, cronRisky, isValid, nextRunAt, weekdayOptions } = d;
|
||||
|
||||
const handleSwitchVisual = () => {
|
||||
if (state.value.editorMode === 'visual') return;
|
||||
@@ -30,6 +30,7 @@ const handleSwitchAdvanced = () => {
|
||||
<div class="min-w-0">
|
||||
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.cronTitle') }}</h4>
|
||||
<p class="mt-1 text-sm leading-relaxed text-muted">{{ $t('admin.schedule.form.cronHint') }}</p>
|
||||
<p class="mt-1 text-xs text-muted">{{ $t('admin.schedule.form.cronTimezoneHint', { tz: timezone }) }}</p>
|
||||
</div>
|
||||
<div
|
||||
class="segment-control segment-control--cols-2 segment-control--sm w-full max-w-xs"
|
||||
@@ -84,6 +85,13 @@ const handleSwitchAdvanced = () => {
|
||||
<button type="button" class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary" @click="d.setPreset('weekly')">
|
||||
{{ $t('admin.schedule.form.weekly') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default bg-surface px-3 py-1.5 text-xs font-medium text-secondary transition hover:border-blue-300 hover:text-primary"
|
||||
@click="d.applyAdvancedCron('0 12,17 * * *')"
|
||||
>
|
||||
{{ $t('admin.schedule.form.twiceDaily') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -231,6 +239,13 @@ const handleSwitchAdvanced = () => {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p
|
||||
v-if="cronRisky"
|
||||
class="mb-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800"
|
||||
>
|
||||
{{ $t('admin.schedule.form.cronRiskyHint') }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="mt-4 flex flex-col gap-1.5 rounded-xl border border-dashed px-4 py-3 text-xs sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-4"
|
||||
:class="isValid ? 'border-default bg-surface-soft text-secondary' : 'border-red-200 bg-red-50 text-red-700'"
|
||||
|
||||
+5
@@ -9,6 +9,7 @@ import {
|
||||
defaultCronDesignerState,
|
||||
parseCronExpr,
|
||||
toCronField,
|
||||
normalizeCronExpr,
|
||||
validateCronDesignerState,
|
||||
} from './scheduleCronDesigner.utils';
|
||||
|
||||
@@ -91,4 +92,8 @@ describe('scheduleCronDesigner.utils', () => {
|
||||
state.months = [];
|
||||
expect(validateCronDesignerState(state)).toBe(false);
|
||||
});
|
||||
|
||||
it('normalizes risky cron to fixed minute zero', () => {
|
||||
expect(normalizeCronExpr('* 12,17 * * *')).toBe('0 12,17 * * *');
|
||||
});
|
||||
});
|
||||
+20
-2
@@ -101,6 +101,24 @@ export function parseCronFieldToArray(field: string, min: number, max: number):
|
||||
return Array.from(result).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修正常见 Cron 笔误:分钟为 * 且小时已限定(如 * 12,17 * * *)时改为整点 0 分。
|
||||
*/
|
||||
export function normalizeCronExpr(expr: string): string {
|
||||
const parts = String(expr || '').trim().split(/\s+/);
|
||||
if (parts.length === 5 && parts[0] === '*' && parts[1] && parts[1] !== '*') {
|
||||
parts[0] = '0';
|
||||
return parts.join(' ');
|
||||
}
|
||||
return String(expr || '').trim();
|
||||
}
|
||||
|
||||
/** 分钟为 * 且小时非 *:会在指定小时内每分钟执行。 */
|
||||
export function isRiskyCronExpr(expr: string): boolean {
|
||||
const parts = String(expr || '').trim().split(/\s+/);
|
||||
return parts.length === 5 && parts[0] === '*' && !!parts[1] && parts[1] !== '*';
|
||||
}
|
||||
|
||||
export function buildCronExpr(state: ScheduleCronDesignerState): string {
|
||||
const dom = toCronField(state.daysOfMonth, 1, 31);
|
||||
const month = toCronField(state.months, 1, 12);
|
||||
@@ -237,8 +255,8 @@ function isCalendarValid(values: number[] | null): boolean {
|
||||
|
||||
export function validateCronDesignerState(state: ScheduleCronDesignerState): boolean {
|
||||
if (state.editorMode === 'advanced') {
|
||||
const text = state.advancedCronExpr.trim();
|
||||
return text.length > 0 && text.split(/\s+/).length === 5;
|
||||
const text = normalizeCronExpr(state.advancedCronExpr);
|
||||
return text.length > 0 && text.split(/\s+/).length === 5 && !isRiskyCronExpr(state.advancedCronExpr);
|
||||
}
|
||||
|
||||
if (!isCalendarValid(state.months) || !isCalendarValid(state.weekdays) || !isCalendarValid(state.daysOfMonth)) {
|
||||
|
||||
+31
-2
@@ -5,11 +5,14 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CronExpressionParser } from 'cron-parser';
|
||||
import { DEFAULT_SCHEDULE_TIMEZONE } from '../constants';
|
||||
import {
|
||||
applyPreset,
|
||||
buildCronExpr,
|
||||
computeNextRunAt,
|
||||
defaultCronDesignerState,
|
||||
isRiskyCronExpr,
|
||||
normalizeCronExpr,
|
||||
parseCronExpr,
|
||||
validateCronDesignerState,
|
||||
type CronPreset,
|
||||
@@ -19,23 +22,36 @@ import {
|
||||
export function useScheduleCronDesigner() {
|
||||
const { t } = useI18n();
|
||||
const state = ref<ScheduleCronDesignerState>(defaultCronDesignerState());
|
||||
const timezone = ref(DEFAULT_SCHEDULE_TIMEZONE);
|
||||
|
||||
const cronExpr = computed(() => {
|
||||
if (state.value.editorMode === 'advanced') {
|
||||
return state.value.advancedCronExpr.trim();
|
||||
return normalizeCronExpr(state.value.advancedCronExpr);
|
||||
}
|
||||
return buildCronExpr(state.value);
|
||||
});
|
||||
|
||||
const cronRisky = computed(() =>
|
||||
state.value.editorMode === 'advanced' && isRiskyCronExpr(state.value.advancedCronExpr),
|
||||
);
|
||||
|
||||
const isValid = computed(() => validateCronDesignerState(state.value));
|
||||
|
||||
const nextRunAt = computed(() =>
|
||||
computeNextRunAt(cronExpr.value, (expr) => {
|
||||
const normalized = normalizeCronForParser(expr);
|
||||
return CronExpressionParser.parse(normalized);
|
||||
return CronExpressionParser.parse(normalized, { tz: timezone.value || DEFAULT_SCHEDULE_TIMEZONE });
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* 更新 Cron 预览计算时区。
|
||||
* @param value 排程保存的 IANA 时区;为空时回退默认业务时区。
|
||||
*/
|
||||
const setTimezone = (value: string | null | undefined) => {
|
||||
timezone.value = String(value || '').trim() || DEFAULT_SCHEDULE_TIMEZONE;
|
||||
};
|
||||
|
||||
const loadFromExpr = (expr: string | null | undefined) => {
|
||||
const result = parseCronExpr(expr);
|
||||
if (result.ok && result.state) {
|
||||
@@ -82,6 +98,15 @@ export function useScheduleCronDesigner() {
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyAdvancedCron = (expr: string) => {
|
||||
state.value = {
|
||||
...defaultCronDesignerState(),
|
||||
editorMode: 'advanced',
|
||||
advancedCronExpr: normalizeCronExpr(expr),
|
||||
parseFailed: false,
|
||||
};
|
||||
};
|
||||
|
||||
const setPreset = (preset: CronPreset, options?: { everyMinutes?: number; weeklyDay?: number }) => {
|
||||
state.value = applyPreset(preset, state.value, options);
|
||||
state.value.editorMode = 'visual';
|
||||
@@ -145,13 +170,17 @@ export function useScheduleCronDesigner() {
|
||||
|
||||
return {
|
||||
state,
|
||||
timezone,
|
||||
cronExpr,
|
||||
cronRisky,
|
||||
isValid,
|
||||
nextRunAt,
|
||||
setTimezone,
|
||||
loadFromExpr,
|
||||
reset,
|
||||
switchToAdvanced,
|
||||
switchToVisual,
|
||||
applyAdvancedCron,
|
||||
setPreset,
|
||||
toggleMonth,
|
||||
toggleWeekday,
|
||||
|
||||
@@ -26,6 +26,7 @@ import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
|
||||
import { useScheduleCronDesigner } from './useScheduleCronDesigner';
|
||||
import { DEFAULT_SCHEDULE_TIMEZONE } from '../constants';
|
||||
|
||||
export function useSchedulesAdmin() {
|
||||
const { t, locale } = useI18n();
|
||||
@@ -186,6 +187,18 @@ const scheduleCronDesigner = useScheduleCronDesigner();
|
||||
const scheduleCronPreview = scheduleCronDesigner.cronExpr;
|
||||
const scheduleCronValid = scheduleCronDesigner.isValid;
|
||||
|
||||
/**
|
||||
* 读取浏览器 IANA 时区,作为新建排程的 Cron 当地时间口径。
|
||||
* @returns 浏览器时区;读取失败时回退默认业务时区。
|
||||
*/
|
||||
const detectBrowserTimezone = (): string => {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || DEFAULT_SCHEDULE_TIMEZONE;
|
||||
} catch {
|
||||
return DEFAULT_SCHEDULE_TIMEZONE;
|
||||
}
|
||||
};
|
||||
|
||||
const resetScheduleCreateForm = () => {
|
||||
scheduleEditingId.value = null;
|
||||
scheduleCreateForm.value = {
|
||||
@@ -228,6 +241,7 @@ const resetScheduleCreateForm = () => {
|
||||
dify_system_prompt: '',
|
||||
};
|
||||
scheduleTestResult.value = null;
|
||||
scheduleCronDesigner.setTimezone(detectBrowserTimezone());
|
||||
scheduleNotifyUserQuery.value = '';
|
||||
scheduleNotifyDropdownOpen.value = false;
|
||||
scheduleOwnerQuery.value = '';
|
||||
@@ -262,6 +276,7 @@ const openScheduleEditModal = async (task: ScheduleTask) => {
|
||||
enabled: !!task.enabled,
|
||||
data_source_type: (task.data_source_type || 'database') as 'database' | 'external_api',
|
||||
};
|
||||
scheduleCronDesigner.setTimezone(task.schedule_timezone || detectBrowserTimezone());
|
||||
|
||||
try {
|
||||
const result = await getAdminScheduleTaskConfig(task.id);
|
||||
@@ -724,6 +739,7 @@ const createSchedule = async () => {
|
||||
schedule_type: 'platform_app',
|
||||
owner_user_id: scheduleCreateForm.value.owner_user_id,
|
||||
cron_expr: scheduleCronPreview.value,
|
||||
schedule_timezone: scheduleCronDesigner.timezone.value || detectBrowserTimezone(),
|
||||
wait_seconds: Math.max(0, Number(scheduleCreateForm.value.wait_seconds || 0)),
|
||||
dify_agent_id: scheduleCreateForm.value.dify_agent_id || undefined,
|
||||
notify_user_ids_json: scheduleCreateForm.value.notify_enabled ? scheduleCreateForm.value.notify_user_ids_json : [],
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
/** 与后端 SCHEDULE_TIMEZONE 默认值保持一致 */
|
||||
export const DEFAULT_SCHEDULE_TIMEZONE = 'Asia/Shanghai';
|
||||
@@ -32,10 +32,11 @@ const {
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
shouldRenderMessage: (msg: ChatMessage) => boolean;
|
||||
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage) => boolean;
|
||||
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage, index: number) => boolean;
|
||||
getMessageRunProgress: (msg: ChatMessage) => ToolRunProgress | null;
|
||||
getMessageRunProgressError: (msg: ChatMessage) => string;
|
||||
isMessageRunProgressLoading: (msg: ChatMessage) => boolean;
|
||||
toolRunProgress: ToolRunProgress | null;
|
||||
toolRunProgressLoading: boolean;
|
||||
toolRunProgressError: string;
|
||||
toolRunProgressTitle: string;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
@@ -91,10 +92,11 @@ const bindScrollContainer = (node: unknown) => {
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
/>
|
||||
<ToolRunProgressCard
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg)"
|
||||
:run="toolRunProgress"
|
||||
:loading="toolRunProgressLoading"
|
||||
:error="toolRunProgressError"
|
||||
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
|
||||
:run="getMessageRunProgress(msg)"
|
||||
:loading="isMessageRunProgressLoading(msg)"
|
||||
:waiting="false"
|
||||
:error="getMessageRunProgressError(msg)"
|
||||
:fallback-title="toolRunProgressTitle"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -96,9 +96,10 @@ const page = useChatPageContext();
|
||||
:shipping-handlers="page.shippingMappingHandlers"
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
|
||||
:get-message-run-progress="page.getMessageRunProgress"
|
||||
:get-message-run-progress-error="page.getMessageRunProgressError"
|
||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||
:tool-run-progress="page.toolRunProgress"
|
||||
:tool-run-progress-loading="page.toolRunProgressLoading"
|
||||
:tool-run-progress-error="page.toolRunProgressError"
|
||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
const props = defineProps<{
|
||||
run: ToolRunProgress | null;
|
||||
loading?: boolean;
|
||||
waiting?: boolean;
|
||||
error?: string;
|
||||
fallbackTitle?: string;
|
||||
}>();
|
||||
@@ -45,7 +46,11 @@ const formatTime = (value?: string | null) => {
|
||||
].join(':');
|
||||
};
|
||||
|
||||
const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent || 0), 100));
|
||||
const percent = () => {
|
||||
const value = Number(props.run?.progress_percent ?? 0);
|
||||
if (!Number.isFinite(value)) return 0;
|
||||
return Math.max(0, Math.min(value, 100));
|
||||
};
|
||||
|
||||
const kbSyncMeta = (status?: string | null) => {
|
||||
const value = String(status || '').toLowerCase();
|
||||
@@ -119,7 +124,6 @@ const downloadExcel = async () => {
|
||||
|
||||
<template>
|
||||
<section
|
||||
v-if="run || loading || error"
|
||||
class="mx-auto mb-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-sky-100/80 px-4 py-3">
|
||||
@@ -136,8 +140,8 @@ const downloadExcel = async () => {
|
||||
批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}
|
||||
<span v-if="run.error_message" class="ml-2 text-rose-700">错误信息:{{ run.error_message }}</span>
|
||||
</template>
|
||||
<template v-else-if="loading">正在查询任务进度...</template>
|
||||
<template v-else>{{ error }}</template>
|
||||
<template v-else-if="loading || waiting">正在等待检核任务启动...</template>
|
||||
<template v-else-if="error">{{ error }}</template>
|
||||
</p>
|
||||
<p v-if="run?.status === 'running' && run.current_step" class="mt-1 text-xs text-sky-700">
|
||||
当前阶段:{{ run.current_step.label || run.current_step.step }}
|
||||
@@ -173,47 +177,54 @@ const downloadExcel = async () => {
|
||||
</div>
|
||||
|
||||
<div v-if="run" class="space-y-3 px-4 py-4">
|
||||
<div v-if="downloadError" class="rounded-xl bg-rose-50 px-3 py-2 text-xs text-rose-700">
|
||||
{{ downloadError }}
|
||||
</div>
|
||||
<div v-if="downloadError" class="rounded-xl bg-rose-50 px-3 py-2 text-xs text-rose-700">
|
||||
{{ downloadError }}
|
||||
</div>
|
||||
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
|
||||
:style="{ width: `${percent()}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
|
||||
<span>进度 {{ percent() }}%</span>
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">总数</div>
|
||||
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">已处理</div>
|
||||
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">成功</div>
|
||||
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">失败</div>
|
||||
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">跳过</div>
|
||||
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
|
||||
知识库同步错误:{{ run.knowledge_base.error_message }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="waiting || loading" class="space-y-3 px-4 py-4">
|
||||
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
|
||||
:style="{ width: `${percent()}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-slate-500">
|
||||
<span>进度 {{ percent() }}%</span>
|
||||
<span>开始:{{ formatTime(run.started_at) }} · 完成:{{ formatTime(run.finished_at) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">总数</div>
|
||||
<div class="text-lg font-bold text-slate-800">{{ run.total_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">已处理</div>
|
||||
<div class="text-lg font-bold text-sky-700">{{ run.processed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">成功</div>
|
||||
<div class="text-lg font-bold text-emerald-700">{{ run.success_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">失败</div>
|
||||
<div class="text-lg font-bold text-rose-700">{{ run.failed_count }}</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/80 px-3 py-2">
|
||||
<div class="text-xs text-slate-500">跳过</div>
|
||||
<div class="text-lg font-bold text-amber-700">{{ run.skipped_count }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
|
||||
知识库同步错误:{{ run.knowledge_base.error_message }}
|
||||
<div class="h-full w-1/3 animate-pulse rounded-full bg-gradient-to-r from-sky-400 to-emerald-400" />
|
||||
</div>
|
||||
<p class="text-xs text-slate-500">检核启动后,这里会显示实时进度。</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -83,6 +83,11 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
|
||||
addAttributionParts(msg, metadata?.annotation_reply);
|
||||
addAttributionParts(msg, data?.citation);
|
||||
addAttributionParts(msg, metadata?.citation);
|
||||
|
||||
const messagePayload = data?.message_payload;
|
||||
if (messagePayload && typeof messagePayload === 'object') {
|
||||
msg.payload = messagePayload;
|
||||
}
|
||||
};
|
||||
|
||||
export function useChat() {
|
||||
@@ -124,6 +129,27 @@ export function useChat() {
|
||||
return text.replace(/\\n/g, '\n');
|
||||
};
|
||||
|
||||
const formatStreamError = (message: unknown) => {
|
||||
if (typeof message === 'string') return message;
|
||||
if (message && typeof message === 'object') {
|
||||
const record = message as Record<string, unknown>;
|
||||
const nested = record.error;
|
||||
if (typeof nested === 'string') return nested;
|
||||
if (nested && typeof nested === 'object') {
|
||||
const nestedRecord = nested as Record<string, unknown>;
|
||||
if (typeof nestedRecord.message === 'string') return nestedRecord.message;
|
||||
}
|
||||
if (typeof record.message === 'string') return record.message;
|
||||
if (typeof record.code === 'string') return record.code;
|
||||
try {
|
||||
return JSON.stringify(message);
|
||||
} catch {
|
||||
return 'Unknown error';
|
||||
}
|
||||
}
|
||||
return String(message ?? 'Unknown error');
|
||||
};
|
||||
|
||||
const sendMessage = async (
|
||||
query: string,
|
||||
agentId: number,
|
||||
@@ -269,6 +295,13 @@ export function useChat() {
|
||||
const currentBotMsg = runMessages[botMsgIndex];
|
||||
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
||||
}
|
||||
if (botMsgIndex !== null) {
|
||||
const runId = Number(data.run_id);
|
||||
if (Number.isFinite(runId) && runId > 0) {
|
||||
const currentBotMsg = runMessages[botMsgIndex];
|
||||
if (currentBotMsg) currentBotMsg.run_id = runId;
|
||||
}
|
||||
}
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
@@ -286,7 +319,7 @@ export function useChat() {
|
||||
} else if (eventName === 'error') {
|
||||
const botMsg = ensureBotMessage();
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += `\n[Error: ${data.message}]`;
|
||||
botMsg.content += `\n[Error: ${formatStreamError(data.message)}]`;
|
||||
run.status = 'error';
|
||||
if (messages.value === runMessages) isThinking.value = false;
|
||||
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
|
||||
@@ -287,6 +287,7 @@ export function useChatPage() {
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
|
||||
prepareToolRunProgressBeforeSend: toolRun.prepareToolRunProgressBeforeSend,
|
||||
msg,
|
||||
t,
|
||||
copiedIndex,
|
||||
|
||||
@@ -1,15 +1,33 @@
|
||||
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
|
||||
import { getToolRunProgress, type ToolRunProgress } from '@/api/toolRunProgress';
|
||||
import { getToolRunProgress, type ToolRunProgress, type ToolRunProgressMatchSource } from '@/api/toolRunProgress';
|
||||
import { buildLogProgressUrl } from '../utils/toolRunProgressConfig';
|
||||
|
||||
export interface ToolRunProgressConfig {
|
||||
type?: string;
|
||||
title?: string;
|
||||
poll_interval_seconds?: number;
|
||||
active_url?: string;
|
||||
/** 按 chat_log_id 关联批次的轮询地址 */
|
||||
log_progress_url?: string;
|
||||
/** @deprecated 使用 log_progress_url */
|
||||
session_progress_url?: string;
|
||||
detail_url_template?: string;
|
||||
schedule_task_id?: number | string | null;
|
||||
task_id?: number | string | null;
|
||||
chat_log_id?: number | string | null;
|
||||
/** 已知批次 ID 时走 detail 轮询 */
|
||||
run_id?: number | string | null;
|
||||
/** for-session 空结果最大重试次数 */
|
||||
empty_poll_max?: number;
|
||||
/** 等待 run_id 写出前的轮询窗口(秒) */
|
||||
pending_seconds?: number;
|
||||
lock_input_when_running?: boolean;
|
||||
lock_message?: string;
|
||||
session_id?: string;
|
||||
}
|
||||
|
||||
export interface UseToolRunProgressOptions {
|
||||
allowEmptySessionPolls?: Ref<boolean>;
|
||||
}
|
||||
|
||||
const clampPollMs = (seconds: unknown) => {
|
||||
@@ -18,13 +36,35 @@ const clampPollMs = (seconds: unknown) => {
|
||||
return Math.max(1, Math.min(safe, 30)) * 1000;
|
||||
};
|
||||
|
||||
export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>) {
|
||||
const TERMINAL_STATUSES = new Set(['success', 'partial_failed', 'failed', 'cancelled', 'canceled']);
|
||||
|
||||
const isTerminalStatus = (status?: string | null) => TERMINAL_STATUSES.has(String(status || '').toLowerCase());
|
||||
|
||||
/**
|
||||
* 轮询任务进度:有 run_id 时走 detail;或走 for-log / active。
|
||||
*/
|
||||
export function useToolRunProgress(
|
||||
configRef: Ref<ToolRunProgressConfig | null>,
|
||||
options: UseToolRunProgressOptions = {},
|
||||
) {
|
||||
const run = ref<ToolRunProgress | null>(null);
|
||||
const matchSource = ref<ToolRunProgressMatchSource | null>(null);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
let timer: number | undefined;
|
||||
let emptySessionPolls = 0;
|
||||
let pollSessionKey = '';
|
||||
let hasFetchedOnce = false;
|
||||
let resolvedRunId: string | null = null;
|
||||
|
||||
const enabled = computed(() => {
|
||||
const cfg = configRef.value;
|
||||
if (!cfg) return false;
|
||||
if (cfg.session_progress_url) return true;
|
||||
if (cfg.run_id && cfg.detail_url_template) return true;
|
||||
return !!cfg.active_url;
|
||||
});
|
||||
|
||||
const enabled = computed(() => !!configRef.value?.active_url || (!!configRef.value?.detail_url_template && !!configRef.value?.run_id));
|
||||
const isRunning = computed(() => run.value?.status === 'running');
|
||||
const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value);
|
||||
const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成');
|
||||
@@ -38,53 +78,184 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
|
||||
|
||||
const scheduleNext = () => {
|
||||
clearTimer();
|
||||
if (!enabled.value) return;
|
||||
if (!enabled.value || error.value) return;
|
||||
const interval = clampPollMs(configRef.value?.poll_interval_seconds);
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, interval);
|
||||
};
|
||||
|
||||
const resolveProgressUrl = (cfg: ToolRunProgressConfig) => {
|
||||
const runId = String(cfg.run_id || '').trim();
|
||||
if (runId && cfg.detail_url_template) {
|
||||
return cfg.detail_url_template.replace('{run_id}', encodeURIComponent(runId));
|
||||
const resolveDetailUrl = (cfg: ToolRunProgressConfig, runId: number | string) => {
|
||||
const template = String(cfg.detail_url_template || '').trim();
|
||||
if (!template) return '';
|
||||
return template.replace('{run_id}', encodeURIComponent(String(runId)));
|
||||
};
|
||||
|
||||
const fetchProgressUrl = async (url: string, silent: boolean) => {
|
||||
if (!silent) loading.value = true;
|
||||
try {
|
||||
const payload = await getToolRunProgress(url);
|
||||
error.value = '';
|
||||
matchSource.value = payload.match_source ?? null;
|
||||
return payload.run ?? null;
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : '任务进度查询失败';
|
||||
error.value = message;
|
||||
matchSource.value = null;
|
||||
clearTimer();
|
||||
return null;
|
||||
} finally {
|
||||
if (!silent) loading.value = false;
|
||||
hasFetchedOnce = true;
|
||||
}
|
||||
return cfg.active_url || '';
|
||||
};
|
||||
|
||||
const refreshByDetail = async (cfg: ToolRunProgressConfig, runId: string, silent: boolean) => {
|
||||
if (!runId || !cfg.detail_url_template) return null;
|
||||
const detailUrl = resolveDetailUrl(cfg, runId);
|
||||
if (!detailUrl) return null;
|
||||
return fetchProgressUrl(detailUrl, silent);
|
||||
};
|
||||
|
||||
const refreshBySession = async (cfg: ToolRunProgressConfig, silent: boolean) => {
|
||||
const sessionUrl = String(cfg.session_progress_url || '').trim();
|
||||
if (sessionUrl) {
|
||||
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 refresh = async () => {
|
||||
const cfg = configRef.value;
|
||||
const url = cfg ? resolveProgressUrl(cfg) : '';
|
||||
if (!url) {
|
||||
if (!cfg) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
resolvedRunId = null;
|
||||
error.value = '';
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
try {
|
||||
const payload = await getToolRunProgress(url);
|
||||
run.value = payload.run;
|
||||
error.value = '';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || '任务进度查询失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
|
||||
if (error.value) {
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const allowEmpty = options.allowEmptySessionPolls?.value ?? false;
|
||||
const silent = hasFetchedOnce || !!run.value || allowEmpty;
|
||||
const explicitRunId = String(cfg.run_id || resolvedRunId || '').trim();
|
||||
const hasSessionUrl = !!String(cfg.session_progress_url || cfg.session_id || '').trim();
|
||||
|
||||
if (hasSessionUrl) {
|
||||
const sessionRun = await refreshBySession(cfg, silent);
|
||||
if (sessionRun) {
|
||||
run.value = sessionRun;
|
||||
resolvedRunId = String(sessionRun.run_id);
|
||||
} else if (!allowEmpty || error.value) {
|
||||
run.value = null;
|
||||
if (!allowEmpty) {
|
||||
matchSource.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const emptyPollMax = Number(cfg.empty_poll_max) > 0 ? Number(cfg.empty_poll_max) : 30;
|
||||
if (!run.value && allowEmpty && !error.value) {
|
||||
emptySessionPolls += 1;
|
||||
if (emptySessionPolls < emptyPollMax) {
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (explicitRunId && cfg.detail_url_template) {
|
||||
const detailRun = await refreshByDetail(cfg, explicitRunId, silent);
|
||||
if (detailRun) {
|
||||
run.value = detailRun;
|
||||
}
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
return;
|
||||
}
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeUrl = String(cfg.active_url || '').trim();
|
||||
if (!activeUrl) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeRun = await fetchProgressUrl(activeUrl, silent);
|
||||
if (activeRun) {
|
||||
run.value = activeRun;
|
||||
} else if (!allowEmpty || error.value) {
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
}
|
||||
|
||||
if (run.value?.status === 'running') {
|
||||
emptySessionPolls = 0;
|
||||
scheduleNext();
|
||||
} else {
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
if (run.value && isTerminalStatus(run.value.status)) {
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
return;
|
||||
}
|
||||
|
||||
emptySessionPolls = 0;
|
||||
clearTimer();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => JSON.stringify(configRef.value || {}),
|
||||
() => {
|
||||
const cfg = configRef.value;
|
||||
return cfg
|
||||
? `${cfg.session_progress_url || ''}|${cfg.active_url || ''}|${cfg.schedule_task_id ?? cfg.task_id ?? ''}|${cfg.session_id || ''}|${cfg.run_id || ''}`
|
||||
: '';
|
||||
},
|
||||
(nextKey) => {
|
||||
if (nextKey === pollSessionKey) return;
|
||||
pollSessionKey = nextKey;
|
||||
run.value = null;
|
||||
matchSource.value = null;
|
||||
resolvedRunId = null;
|
||||
error.value = '';
|
||||
emptySessionPolls = 0;
|
||||
hasFetchedOnce = false;
|
||||
clearTimer();
|
||||
if (enabled.value) void refresh();
|
||||
},
|
||||
@@ -95,6 +266,7 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
|
||||
|
||||
return {
|
||||
run,
|
||||
matchSource,
|
||||
loading,
|
||||
error,
|
||||
isRunning,
|
||||
|
||||
@@ -39,6 +39,7 @@ export interface ChatPageSendContext {
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
refreshToolRunProgressAfterSend: () => Promise<void>;
|
||||
prepareToolRunProgressBeforeSend: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
copiedIndex: Ref<number | null>;
|
||||
@@ -88,6 +89,7 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.clearAttachments();
|
||||
|
||||
await ctx.prepareToolRunProgressBeforeSend();
|
||||
await ctx.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
await ctx.refreshToolRunProgressAfterSend();
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
/**
|
||||
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等按消息 run_id 展示进度卡片)。
|
||||
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。
|
||||
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
|
||||
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定。
|
||||
*/
|
||||
import { computed, nextTick } from 'vue';
|
||||
import { useToolRunProgress, type ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
import type { ToolRunProgress } from '@/api/toolRunProgress';
|
||||
import { getToolRunProgress } from '@/api/toolRunProgress';
|
||||
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
assistantMessageHasError,
|
||||
collectAssistantRunIds,
|
||||
getRunIdFromMessage,
|
||||
isRunningToolRunStatus,
|
||||
resolveScheduleTaskId,
|
||||
resolveMessageAnchorKey,
|
||||
} from '../utils/toolRunProgressConfig';
|
||||
|
||||
export interface ChatPageToolRunContext {
|
||||
currentAgent: Ref<{ extra_config?: Record<string, unknown> } | null>;
|
||||
currentAgent: Ref<{ id?: number; extra_config?: Record<string, unknown> } | null>;
|
||||
conversationId: Ref<string | null>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
}
|
||||
|
||||
const extractToolRunIdFromContent = (content: unknown): number | null => {
|
||||
const text = String(content || '');
|
||||
const match = text.match(/(?:检核批次 ID|当前检核批次 ID|运行 ID|run_id|run id)\s*[::]\s*(\d+)/i);
|
||||
return match?.[1] ? Number(match[1]) : null;
|
||||
};
|
||||
|
||||
export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
|
||||
const activeToolRunId = computed(() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const msg = ctx.messages.value[i];
|
||||
if (msg?.role !== 'assistant') continue;
|
||||
const runId = extractToolRunIdFromContent(msg.content);
|
||||
if (runId) return runId;
|
||||
}
|
||||
return null;
|
||||
const runsById = ref<Record<number, ToolRunProgress>>({});
|
||||
const runErrors = ref<Record<number, string>>({});
|
||||
const pollingRunIds = ref<number[]>([]);
|
||||
let pollTimer: number | undefined;
|
||||
|
||||
const rawToolRunConfig = computed(() => {
|
||||
const extra = ctx.currentAgent.value?.extra_config || {};
|
||||
const raw = extra.tool_run_progress;
|
||||
return raw && typeof raw === 'object' ? (raw as ToolRunProgressConfig) : null;
|
||||
});
|
||||
|
||||
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
|
||||
@@ -35,55 +42,190 @@ export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
|
||||
? extra.capabilities.map((item: unknown) => String(item))
|
||||
: [];
|
||||
if (!capabilities.includes('tool_run_progress')) return null;
|
||||
const raw = extra.tool_run_progress;
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const cfg = raw as ToolRunProgressConfig;
|
||||
const cid = String(ctx.conversationId.value || '').trim();
|
||||
const runId = activeToolRunId.value;
|
||||
if (runId && cfg.detail_url_template) {
|
||||
return {
|
||||
...cfg,
|
||||
run_id: runId,
|
||||
};
|
||||
}
|
||||
if (!cid || !cfg.active_url) return null;
|
||||
const separator = cfg.active_url.includes('?') ? '&' : '?';
|
||||
const cfg = rawToolRunConfig.value;
|
||||
if (!cfg) return null;
|
||||
return {
|
||||
...cfg,
|
||||
active_url: `${cfg.active_url}${separator}conversation_id=${encodeURIComponent(cid)}`,
|
||||
run_id: null,
|
||||
schedule_task_id: resolveScheduleTaskId(cfg),
|
||||
};
|
||||
});
|
||||
|
||||
const {
|
||||
run: toolRunProgress,
|
||||
loading: toolRunProgressLoading,
|
||||
error: toolRunProgressError,
|
||||
refresh: refreshToolRunProgress,
|
||||
} = useToolRunProgress(toolRunProgressConfig);
|
||||
const boundScheduleTaskId = computed(() => resolveScheduleTaskId(rawToolRunConfig.value));
|
||||
|
||||
const clearPollTimer = () => {
|
||||
if (pollTimer !== undefined) {
|
||||
window.clearTimeout(pollTimer);
|
||||
pollTimer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
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 refreshRun = async (runId: number) => {
|
||||
const url = resolveDetailUrl(runId);
|
||||
if (!url) return;
|
||||
try {
|
||||
const payload = await getToolRunProgress(url);
|
||||
if (payload.run) {
|
||||
runsById.value = { ...runsById.value, [runId]: payload.run };
|
||||
}
|
||||
const nextErrors = { ...runErrors.value };
|
||||
delete nextErrors[runId];
|
||||
runErrors.value = nextErrors;
|
||||
} catch (e: unknown) {
|
||||
runErrors.value = {
|
||||
...runErrors.value,
|
||||
[runId]: e instanceof Error ? e.message : '任务进度查询失败',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const schedulePoll = () => {
|
||||
clearPollTimer();
|
||||
const intervalSec = Number(rawToolRunConfig.value?.poll_interval_seconds);
|
||||
const intervalMs = Math.max(1, Math.min(Number.isFinite(intervalSec) ? intervalSec : 2, 30)) * 1000;
|
||||
pollTimer = window.setTimeout(() => {
|
||||
void syncProgressState();
|
||||
}, intervalMs);
|
||||
};
|
||||
|
||||
const syncProgressState = async () => {
|
||||
clearPollTimer();
|
||||
if (!toolRunProgressConfig.value) {
|
||||
runsById.value = {};
|
||||
runErrors.value = {};
|
||||
pollingRunIds.value = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const runIds = collectAssistantRunIds(ctx.messages.value);
|
||||
pollingRunIds.value = runIds;
|
||||
if (!runIds.length) {
|
||||
runsById.value = {};
|
||||
runErrors.value = {};
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(runIds.map((runId) => refreshRun(runId)));
|
||||
|
||||
const nextRuns: Record<number, ToolRunProgress> = {};
|
||||
for (const runId of runIds) {
|
||||
const run = runsById.value[runId];
|
||||
if (run) nextRuns[runId] = run;
|
||||
}
|
||||
runsById.value = nextRuns;
|
||||
|
||||
const hasRunning = Object.values(nextRuns).some((run) => isRunningToolRunStatus(run.status));
|
||||
if (hasRunning) schedulePoll();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [ctx.currentAgent.value?.id, ctx.conversationId.value] as const,
|
||||
() => {
|
||||
runsById.value = {};
|
||||
runErrors.value = {};
|
||||
pollingRunIds.value = [];
|
||||
clearPollTimer();
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => ctx.messages.value.map((msg, index) => (
|
||||
msg?.role === 'assistant'
|
||||
? `${resolveMessageAnchorKey(msg, index)}:${getRunIdFromMessage(msg) ?? ''}`
|
||||
: ''
|
||||
)).join('|'),
|
||||
async () => {
|
||||
await nextTick();
|
||||
await syncProgressState();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const refreshToolRunProgressAfterSend = async () => {
|
||||
await nextTick();
|
||||
void refreshToolRunProgress();
|
||||
await syncProgressState();
|
||||
};
|
||||
|
||||
const toolRunProgressTitle = computed(() => toolRunProgressConfig.value?.title ?? '');
|
||||
const prepareToolRunProgressBeforeSend = async () => {
|
||||
// 按轮 bind:发送前无需 session 级快照。
|
||||
};
|
||||
|
||||
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage) => {
|
||||
const matchesBoundScheduleTask = (taskId: unknown): boolean => {
|
||||
const expected = boundScheduleTaskId.value;
|
||||
if (!expected) return true;
|
||||
const actual = Number(taskId);
|
||||
return Number.isFinite(actual) && actual === expected;
|
||||
};
|
||||
|
||||
const getMessageRunProgress = (msg: ChatMessage) => {
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return null;
|
||||
return runsById.value[runId] ?? null;
|
||||
};
|
||||
|
||||
const getMessageRunProgressError = (msg: ChatMessage) => {
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return '';
|
||||
return runErrors.value[runId] || '';
|
||||
};
|
||||
|
||||
const isMessageRunProgressLoading = (msg: ChatMessage) => {
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return false;
|
||||
return !runsById.value[runId] && !runErrors.value[runId];
|
||||
};
|
||||
|
||||
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage, _index: number) => {
|
||||
if (msg?.role !== 'assistant') return false;
|
||||
if (!(toolRunProgress.value || toolRunProgressLoading.value || toolRunProgressError.value)) return false;
|
||||
const messageRunId = extractToolRunIdFromContent(msg.content);
|
||||
const currentRunId = Number(toolRunProgress.value?.run_id || activeToolRunId.value || 0);
|
||||
return !!messageRunId && messageRunId === currentRunId;
|
||||
if (!toolRunProgressConfig.value) return false;
|
||||
if (assistantMessageHasError(msg)) return false;
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (!runId) return false;
|
||||
const run = getMessageRunProgress(msg);
|
||||
if (!run || !isRunningToolRunStatus(run.status)) return false;
|
||||
if (!matchesBoundScheduleTask(run.task_id)) return false;
|
||||
return true;
|
||||
};
|
||||
|
||||
const toolRunProgress = computed(() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const msg = ctx.messages.value[i];
|
||||
if (!msg || !shouldShowToolRunProgressAfterMessage(msg, i)) continue;
|
||||
return getMessageRunProgress(msg);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const toolRunProgressLoading = computed(() => pollingRunIds.value.length > 0 && !toolRunProgress.value);
|
||||
const toolRunProgressError = computed(() => {
|
||||
const ids = pollingRunIds.value;
|
||||
for (const runId of ids) {
|
||||
const err = runErrors.value[runId];
|
||||
if (err) return err;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
const toolRunProgressTitle = computed(() => toolRunProgressConfig.value?.title ?? '');
|
||||
const isToolRunProgressWaiting = computed(() => false);
|
||||
|
||||
return {
|
||||
toolRunProgressConfig,
|
||||
toolRunProgress,
|
||||
toolRunProgressLoading,
|
||||
toolRunProgressError,
|
||||
toolRunProgressTitle,
|
||||
isToolRunProgressWaiting,
|
||||
shouldShowToolRunProgressAfterMessage,
|
||||
getMessageRunProgress,
|
||||
getMessageRunProgressError,
|
||||
isMessageRunProgressLoading,
|
||||
prepareToolRunProgressBeforeSend,
|
||||
refreshToolRunProgressAfterSend,
|
||||
syncProgressForCurrentConversation: syncProgressState,
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,8 @@ export interface ChatMessage {
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
/** RoHS 等异步任务批次 ID(按轮问答绑定) */
|
||||
run_id?: number;
|
||||
payload?: unknown;
|
||||
local_id?: string;
|
||||
local_only?: boolean;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* features/chat/utils/toolRunProgressConfig.ts
|
||||
* 用途:解析 Agent tool_run_progress 配置;构建 for-log / detail 轮询 URL。
|
||||
* 依赖:ToolRunProgressConfig、ChatMessage。
|
||||
* 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动。
|
||||
*/
|
||||
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
export interface ResolvedToolRunProgressOptions {
|
||||
empty_poll_max: number;
|
||||
}
|
||||
|
||||
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,
|
||||
): ResolvedToolRunProgressOptions {
|
||||
const cfg = raw && typeof raw === 'object' ? raw : {};
|
||||
const emptyRaw = Number(cfg.empty_poll_max);
|
||||
|
||||
return {
|
||||
empty_poll_max: Number.isFinite(emptyRaw) && emptyRaw > 0
|
||||
? Math.min(emptyRaw, 120)
|
||||
: DEFAULT_EMPTY_POLL_MAX,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string {
|
||||
const logId = Number(msg.chat_log_id);
|
||||
if (Number.isFinite(logId) && logId > 0) return `log-${logId}`;
|
||||
const localId = String(msg.local_id || '').trim();
|
||||
if (localId) return `local-${localId}`;
|
||||
return `idx-${index}`;
|
||||
}
|
||||
|
||||
export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean {
|
||||
return String(msg?.content || '').includes('[Error:');
|
||||
}
|
||||
|
||||
export function resolveScheduleTaskId(cfg: ToolRunProgressConfig | null | undefined): number | null {
|
||||
if (!cfg) return null;
|
||||
const raw = cfg.schedule_task_id ?? cfg.task_id;
|
||||
const id = Number(raw);
|
||||
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;
|
||||
}
|
||||
|
||||
export function buildLogProgressUrl(
|
||||
baseUrl: string,
|
||||
taskId: number,
|
||||
chatLogId: number,
|
||||
): string {
|
||||
const [rawPath = baseUrl, query = ''] = baseUrl.split('?');
|
||||
const path = rawPath || baseUrl;
|
||||
const search = new URLSearchParams(query);
|
||||
search.set('task_id', String(taskId));
|
||||
search.set('chat_log_id', String(chatLogId));
|
||||
search.delete('session_id');
|
||||
search.delete('conversation_id');
|
||||
const qs = search.toString();
|
||||
return qs ? `${path}?${qs}` : path;
|
||||
}
|
||||
|
||||
export function getRunIdFromMessage(msg: ChatMessage | null | undefined): number | null {
|
||||
const runId = Number(msg?.run_id);
|
||||
return Number.isFinite(runId) && runId > 0 ? runId : null;
|
||||
}
|
||||
|
||||
export function isRunningToolRunStatus(status?: string | null): boolean {
|
||||
return String(status || '').toLowerCase() === 'running';
|
||||
}
|
||||
|
||||
export function collectAssistantRunIds(messages: ChatMessage[]): number[] {
|
||||
const ids = new Set<number>();
|
||||
for (const msg of messages) {
|
||||
if (msg?.role !== 'assistant') continue;
|
||||
const runId = getRunIdFromMessage(msg);
|
||||
if (runId) ids.add(runId);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
@@ -600,6 +600,8 @@
|
||||
"owner": "Owner",
|
||||
"lastRun": "Last run",
|
||||
"nextRun": "Next run",
|
||||
"nextRunDisabled": "Disabled",
|
||||
"nextRunPending": "Not computed (save or restart schedule)",
|
||||
"noSelection": "No schedule selected",
|
||||
"selectedHint": "Selected schedule · Last run {time}",
|
||||
"runBatches": "Run batches",
|
||||
@@ -664,7 +666,8 @@
|
||||
"noAgents": "No agents available",
|
||||
"agentDisabled": "Disabled",
|
||||
"cronTitle": "Run schedule",
|
||||
"cronHint": "Configure calendar and time to auto-generate Cron, or switch to advanced mode.",
|
||||
"cronHint": "Configure calendar and time to auto-generate Cron, or switch to advanced mode. Cron times use the current schedule timezone.",
|
||||
"cronTimezoneHint": "Cron times use {tz}; displayed times follow your browser locale.",
|
||||
"cronLabel": "Cron: ",
|
||||
"editorVisual": "Visual",
|
||||
"editorAdvanced": "Advanced Cron",
|
||||
@@ -687,6 +690,8 @@
|
||||
"advancedCronInput": "Cron expression",
|
||||
"advancedCronHint": "Standard 5-field cron: minute hour day month weekday",
|
||||
"cronInvalid": "Invalid Cron configuration. Check calendar and time settings.",
|
||||
"cronRiskyHint": "This expression runs every minute during the listed hours. For 12:00 and 17:00 only, use minute 0, e.g. 0 12,17 * * *",
|
||||
"twiceDaily": "Daily at 12:00 and 17:00",
|
||||
"everyMinutes": "Every N minutes",
|
||||
"hourly": "Hourly",
|
||||
"daily": "Daily",
|
||||
|
||||
@@ -561,7 +561,8 @@
|
||||
"schedule": {
|
||||
"form": {
|
||||
"cronTitle": "ตั้งค่าเวลารัน",
|
||||
"cronHint": "กำหนดปฏิทินและเวลาเพื่อสร้าง Cron อัตโนมัติ หรือสลับไปโหมดขั้นสูง",
|
||||
"cronHint": "กำหนดปฏิทินและเวลาเพื่อสร้าง Cron อัตโนมัติ หรือสลับไปโหมดขั้นสูง Cron ใช้เขตเวลาของตารางเวลาปัจจุบัน",
|
||||
"cronTimezoneHint": "Cron ใช้เขตเวลา {tz} เวลาที่แสดงตามโซนเวลาของเบราว์เซอร์",
|
||||
"cronLabel": "Cron: ",
|
||||
"editorVisual": "กราฟิก",
|
||||
"editorAdvanced": "Cron ขั้นสูง",
|
||||
@@ -592,6 +593,8 @@
|
||||
"minute": "นาที",
|
||||
"cronPreview": "ตัวอย่าง Cron",
|
||||
"nextRun": "รันครั้งถัดไป",
|
||||
"cronRiskyHint": "นิพจน์นี้จะรันทุกนาทีในชั่วโมงที่ระบุ หากต้องการ 12:00 และ 17:00 ให้ใช้นาที 0 เช่น 0 12,17 * * *",
|
||||
"twiceDaily": "ทุกวัน 12:00 และ 17:00",
|
||||
"kbSyncEnabled": "ซิงค์ Excel ผลลัพธ์ไปยังคลังความรู้",
|
||||
"kbSyncHint": "เมื่อรันสำเร็จหรือสำเร็จบางส่วน ระบบจะเพิ่ม Excel ที่สร้างขึ้นไปยังกลุ่มคลังความรู้ที่เลือก",
|
||||
"kbGroup": "กลุ่มคลังความรู้",
|
||||
|
||||
@@ -580,6 +580,8 @@
|
||||
"owner": "所有者",
|
||||
"lastRun": "最近执行",
|
||||
"nextRun": "下次执行",
|
||||
"nextRunDisabled": "停用中",
|
||||
"nextRunPending": "未计算(请保存或重新启动)",
|
||||
"noSelection": "未选择排程",
|
||||
"selectedHint": "当前选中排程 · 最近执行 {time}",
|
||||
"runBatches": "执行批次",
|
||||
@@ -644,7 +646,8 @@
|
||||
"noAgents": "暂无可用 Agent",
|
||||
"agentDisabled": "不启用",
|
||||
"cronTitle": "运行时间设置",
|
||||
"cronHint": "通过日历与时刻配置自动生成 Cron,也可切换高级模式手输。",
|
||||
"cronHint": "通过日历与时刻配置自动生成 Cron,也可切换高级模式手输。Cron 时刻按当前排程时区解读。",
|
||||
"cronTimezoneHint": "Cron 时刻按 {tz} 解读,界面显示为本地时间。",
|
||||
"cronLabel": "Cron:",
|
||||
"editorVisual": "图形化",
|
||||
"editorAdvanced": "高级 Cron",
|
||||
@@ -667,6 +670,8 @@
|
||||
"advancedCronInput": "Cron 表达式",
|
||||
"advancedCronHint": "5 段标准 Cron:分 时 日 月 周",
|
||||
"cronInvalid": "Cron 配置无效,请检查日历选择与时刻设置。",
|
||||
"cronRiskyHint": "当前表达式会在 12、17 点内每分钟执行。若需每天 12:00 和 17:00 各执行一次,请将分钟改为 0,例如:0 12,17 * * *",
|
||||
"twiceDaily": "每天 12:00 和 17:00",
|
||||
"everyMinutes": "每隔分钟",
|
||||
"hourly": "每小时",
|
||||
"daily": "每天",
|
||||
|
||||
@@ -561,7 +561,8 @@
|
||||
"schedule": {
|
||||
"form": {
|
||||
"cronTitle": "執行時間設定",
|
||||
"cronHint": "透過日曆與時刻配置自動產生 Cron,也可切換進階模式手動輸入。",
|
||||
"cronHint": "透過日曆與時刻配置自動產生 Cron,也可切換進階模式手動輸入。Cron 時刻按目前排程時區解讀。",
|
||||
"cronTimezoneHint": "Cron 時刻按 {tz} 解讀,介面顯示為本地時間。",
|
||||
"cronLabel": "Cron:",
|
||||
"editorVisual": "圖形化",
|
||||
"editorAdvanced": "進階 Cron",
|
||||
@@ -592,6 +593,8 @@
|
||||
"minute": "分鐘",
|
||||
"cronPreview": "Cron 預覽",
|
||||
"nextRun": "下次執行",
|
||||
"cronRiskyHint": "目前表達式會在指定小時內每分鐘執行。若需每天 12:00 和 17:00 各執行一次,請將分鐘改為 0,例如:0 12,17 * * *",
|
||||
"twiceDaily": "每天 12:00 和 17:00",
|
||||
"kbSyncEnabled": "同步結果 Excel 至知識庫",
|
||||
"kbSyncHint": "排程成功或部分成功後,會把生成的 Excel 加入所選知識庫分組。",
|
||||
"kbGroup": "知識庫分組",
|
||||
|
||||
@@ -10,6 +10,7 @@ export interface ScheduleTask {
|
||||
owner_user_id: number;
|
||||
owner_username?: string | null;
|
||||
cron_expr: string;
|
||||
schedule_timezone?: string | null;
|
||||
wait_seconds: number;
|
||||
dify_agent_id?: number | null;
|
||||
platform_api_path?: string | null;
|
||||
|
||||
Reference in new issue
Block a user