feat(rohs-check): 新增 RoHS 对话轮次注册与检核批次绑定功能

This commit is contained in:
hugo committed 2026-06-15 16:30:17 +08:00
1 parent 9cba517bff
commit fa0cdee8df
20 files changed
+1050 -201

No files matched your search

+9
View File
@@ -1186,6 +1186,15 @@ def chat_completions():
dify_inputs = build_shipping_dify_chat_inputs()
elif is_rohs_check_chat_agent(agent_proxy):
hxops_turn_id = uuid.uuid4().hex
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
register_rohs_chat_turn(
turn_id=hxops_turn_id,
session_id=session.session_id,
user_id=user_proxy.id,
agent_id=agent_proxy.id,
query=query,
)
dify_inputs = build_rohs_dify_chat_inputs(
hxops_session_id=session.session_id,
hxops_turn_id=hxops_turn_id,
+15 -3
View File
@@ -889,12 +889,24 @@ def submit_document_clean(document_id: int):
raise ValidationError('当前文档暂无可清洗版本')
latest_clean_job = _latest_job_for_version(version.id, 'clean')
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
if latest_clean_job and latest_clean_job.status == 'running':
payload = _serialize_job(latest_clean_job)
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
payload['queue_result'] = 'already_running'
payload['message'] = latest_clean_job.message or '清洗任务正在执行中'
return jsonify(payload), 202
if latest_clean_job and latest_clean_job.status == 'queued':
from app.services.knowledge_cleaning.tasks import run_clean_job
_ok, _message = run_clean_job(latest_clean_job.id)
db.session.expire_all()
refreshed = db.session.get(KbJob, latest_clean_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': latest_clean_job.id}
payload['accepted'] = True
payload['queue_result'] = 'inline_on_manual'
payload['message'] = (refreshed.message if refreshed else None) or _message or '清洗任务已执行'
status_code = 200 if refreshed and refreshed.status == 'success' else 202
return jsonify(payload), status_code
version.status = 'uploaded'
version.error_message = None
+50 -7
View File
@@ -233,11 +233,58 @@ def list_rohs_tasks():
return jsonify({"ok": True, "tasks": tasks})
def _normalize_rohs_bind_payload(data: dict | None) -> dict:
"""
规范化启动检核 Body 中的绑定字段,兼容 Chatflow 漏传 hxops_session_id 的场景。
核心逻辑:若 hxops_session_id 为空但 conversation_id 实为 HXOPS session_id,则自动补齐。
"""
payload = dict(data or {})
session_id = str(payload.get("hxops_session_id") or "").strip()
if session_id:
return payload
conversation_id = str(payload.get("conversation_id") or "").strip()
if not conversation_id:
return payload
from app.models import ChatSession
session = ChatSession.query.filter_by(session_id=conversation_id).first()
if session:
payload["hxops_session_id"] = conversation_id
return payload
def _prepare_rohs_bind_payload(data: dict | None) -> dict:
"""
合并规范化与 turn 注册表推断,得到可用于 ChatLog 绑定的启动检核 Body。
核心逻辑:Dify HTTP 漏传 hxops_turn_id / hxops_session_id 时,从 HXOPS 侧登记轮次补齐。
"""
from app.services.rohs_check_tools.chat_turn_registry import infer_bind_context_for_run_request
payload = _normalize_rohs_bind_payload(data)
inferred = infer_bind_context_for_run_request(payload)
if inferred:
payload = {**payload, **inferred}
return payload
def _record_rohs_run_bind(run: ScheduleRun, data: dict) -> None:
"""写入 ScheduleRun 绑定上下文,并同步 turn 注册表。"""
from app.services.rohs_check_tools.chat_log_run_binding import merge_chat_log_bind_context
from app.services.rohs_check_tools.chat_turn_registry import attach_run_to_turn
merge_chat_log_bind_context(run, data)
turn_id = str(data.get("hxops_turn_id") or "").strip()
if turn_id:
attach_run_to_turn(turn_id, int(run.id))
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_rohs_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
perf_started = time.perf_counter()
data = request.get_json(silent=True) or {}
data = _prepare_rohs_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
@@ -252,9 +299,7 @@ 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)
_record_rohs_run_bind(existing, data)
db.session.commit()
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
@@ -288,9 +333,7 @@ def run_rohs_check():
)
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)
_record_rohs_run_bind(run, data)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
@@ -16,6 +16,12 @@ from flask import current_app
from app import db
from app.models import ChatLog, ScheduleRun
from app.services.rohs_check_tools.chat_turn_registry import (
attach_run_to_turn,
infer_bind_context_for_run_request,
resolve_run_id_by_session_query,
resolve_run_id_by_turn,
)
from app.services.rohs_check_tools.task_resolver import is_rohs_check_schedule_task
@@ -92,6 +98,9 @@ def resolve_run_id_for_chat_log(
rohs_rows = [row for row in rows if is_rohs_check_schedule_task(row.task)]
if turn_key:
registry_run_id = resolve_run_id_by_turn(turn_key)
if registry_run_id:
return registry_run_id
for run in rohs_rows:
req = _req(run)
bind_turn = str(req.get("bind_turn_id") or req.get("hxops_turn_id") or "").strip()
@@ -131,6 +140,10 @@ def resolve_run_id_for_chat_log(
if bind_at and bind_at >= cutoff and run.status == "running":
return int(run.id)
registry_run_id = resolve_run_id_by_session_query(session_key, query_key)
if registry_run_id:
return registry_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",
@@ -0,0 +1,225 @@
"""
services/rohs_check_tools/chat_turn_registry.py
用途:RoHS 对话轮次与检核批次的内存注册表(HXOPS 侧登记 turn,不依赖 Dify HTTP 传参)。
依赖:threading、datetime。
逻辑:chat.py 发消息时 register;run API 推断绑定并 attach_run;message_end 按 turn_id 解析 run_id。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from threading import Lock
from typing import Any
_REGISTRY_TTL = timedelta(hours=2)
_MAX_ENTRIES = 500
def _normalize_text(text: str | None) -> str:
"""折叠空白,便于 query / user_message 对齐。"""
return re.sub(r"\s+", " ", str(text or "").strip())
@dataclass
class RohsChatTurn:
"""单轮 RoHS 对话的绑定上下文。"""
turn_id: str
session_id: str
user_id: int
agent_id: int
query: str
created_at: datetime
run_id: int | None = None
_lock = Lock()
_turns_by_id: dict[str, RohsChatTurn] = {}
def _prune_locked(now: datetime | None = None) -> None:
"""清理过期或超量的轮次记录。"""
current = now or datetime.utcnow()
cutoff = current - _REGISTRY_TTL
expired = [key for key, item in _turns_by_id.items() if item.created_at < cutoff]
for key in expired:
_turns_by_id.pop(key, None)
if len(_turns_by_id) <= _MAX_ENTRIES:
return
ordered = sorted(_turns_by_id.items(), key=lambda pair: pair[1].created_at)
overflow = len(_turns_by_id) - _MAX_ENTRIES
for key, _ in ordered[:overflow]:
_turns_by_id.pop(key, None)
def register_rohs_chat_turn(
*,
turn_id: str,
session_id: str,
user_id: int,
agent_id: int,
query: str,
) -> None:
"""
登记本轮 RoHS 对话上下文(chat API 在调用 Dify 前执行)。
Args:
turn_id: 本轮唯一标识(hxops_turn_id)。
session_id: ChatSession.session_id。
user_id: 当前用户 ID。
agent_id: 当前 Agent ID。
query: 用户输入原文。
"""
turn_key = str(turn_id or "").strip()
session_key = str(session_id or "").strip()
if not turn_key or not session_key:
return
item = RohsChatTurn(
turn_id=turn_key,
session_id=session_key,
user_id=int(user_id),
agent_id=int(agent_id),
query=str(query or ""),
created_at=datetime.utcnow(),
)
with _lock:
_turns_by_id[turn_key] = item
_prune_locked()
def attach_run_to_turn(turn_id: str, run_id: int) -> bool:
"""
将检核批次 ID 关联到已登记轮次。
Returns:
是否成功关联。
"""
turn_key = str(turn_id or "").strip()
if not turn_key or run_id <= 0:
return False
with _lock:
item = _turns_by_id.get(turn_key)
if not item:
return False
item.run_id = int(run_id)
return True
def resolve_run_id_by_turn(turn_id: str | None) -> int | None:
"""按 turn_id 读取已关联的检核批次 ID。"""
turn_key = str(turn_id or "").strip()
if not turn_key:
return None
with _lock:
item = _turns_by_id.get(turn_key)
if not item or not item.run_id or item.run_id <= 0:
return None
return int(item.run_id)
def infer_bind_context_for_run_request(data: dict[str, Any] | None) -> dict[str, str]:
"""
为启动检核 HTTP Body 推断缺失的 hxops_session_id / hxops_turn_id。
核心逻辑:Dify HTTP 常漏传绑定字段时,用近期未绑定轮次 + query 模糊匹配补齐。
Args:
data: 启动检核请求 Body。
Returns:
可合并进 Body 的绑定字段 dict(可能为空)。
"""
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()
if session_id and turn_id:
return {}
user_message = _normalize_text(payload.get("user_message"))
now = datetime.utcnow()
recent_cutoff = now - timedelta(minutes=15)
with _lock:
_prune_locked(now)
candidates = [
item for item in _turns_by_id.values()
if item.created_at >= recent_cutoff
]
if turn_id and not session_id:
matched = next((item for item in candidates if item.turn_id == turn_id), None)
if matched:
return {"hxops_session_id": matched.session_id, "hxops_turn_id": matched.turn_id}
if session_id and not turn_id:
scoped = [item for item in candidates if item.session_id == session_id]
if user_message:
exact = next(
(item for item in scoped if _normalize_text(item.query) == user_message),
None,
)
if exact:
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
unbound = [item for item in scoped if not item.run_id]
if len(unbound) == 1:
item = unbound[0]
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
if not session_id and not turn_id:
if user_message:
exact = next(
(item for item in candidates if _normalize_text(item.query) == user_message and not item.run_id),
None,
)
if exact:
return {"hxops_session_id": exact.session_id, "hxops_turn_id": exact.turn_id}
unbound = [item for item in candidates if not item.run_id]
if len(unbound) == 1:
item = unbound[0]
return {"hxops_session_id": item.session_id, "hxops_turn_id": item.turn_id}
return {}
def resolve_run_id_by_session_query(
session_id: str | None,
query: str | None,
) -> int | None:
"""按 session_id + query 从注册表读取已关联 run_id。"""
session_key = str(session_id or "").strip()
query_key = _normalize_text(query)
if not session_key:
return None
now = datetime.utcnow()
recent_cutoff = now - timedelta(minutes=15)
with _lock:
candidates = [
item for item in _turns_by_id.values()
if item.session_id == session_key and item.created_at >= recent_cutoff and item.run_id
]
if query_key:
exact = next((item for item in candidates if _normalize_text(item.query) == query_key), None)
if exact and exact.run_id:
return int(exact.run_id)
if len(candidates) == 1 and candidates[0].run_id:
return int(candidates[0].run_id)
return None
def clear_registry_for_tests() -> None:
"""测试专用:清空注册表。"""
with _lock:
_turns_by_id.clear()
__all__ = [
"attach_run_to_turn",
"clear_registry_for_tests",
"infer_bind_context_for_run_request",
"register_rohs_chat_turn",
"resolve_run_id_by_session_query",
"resolve_run_id_by_turn",
]
@@ -69,26 +69,39 @@ def resolve_default_rohs_schedule_task_id() -> int | None:
def enrich_tool_run_progress_extra(extra_config: dict | None) -> dict:
"""
为 RoHS Agent 的 extra_config 补全 tool_run_progress.schedule_task_id(若缺失)。
为 RoHS Agent 的 extra_config 补全 tool_run_progress 能力与默认轮询配置。
核心逻辑:RoHS 对话 Agent 自动挂载 tool_run_progress 能力,避免漏配 capabilities 导致进度卡片不显示。
Returns:
新的 extra_config 副本;无变更时返回原 dict 浅拷贝。
新的 extra_config 副本。
"""
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 = dict(tool_cfg) if isinstance(tool_cfg, dict) else {
"type": "rohs_check",
"title": "RoHS 文件检核",
"poll_interval_seconds": 2,
"lock_input_when_running": True,
}
merged.setdefault("log_progress_url", "/api/workspace/rohs-check/runs/for-log")
merged.setdefault("detail_url_template", "/api/workspace/rohs-check/runs/{run_id}")
merged.setdefault("poll_interval_seconds", 2)
merged.setdefault("title", "RoHS 文件检核")
merged.setdefault("type", "rohs_check")
merged.setdefault("lock_input_when_running", True)
if not resolve_schedule_task_id_from_mapping(tool_cfg):
if not resolve_schedule_task_id_from_mapping(merged):
task_id = resolve_default_rohs_schedule_task_id()
if task_id:
merged["schedule_task_id"] = task_id
extra["tool_run_progress"] = merged
capabilities = list(extra.get("capabilities") or [])
if "tool_run_progress" not in capabilities:
capabilities.append("tool_run_progress")
extra["capabilities"] = capabilities
return extra
@@ -0,0 +1,58 @@
"""
backend/edkb_system/skills/excel_bridge.py
用途:Windows 环境下通过 Excel COM 将 .xls 转为 .xlsx。
依赖:pywin32(仅 Windows 且已安装 Microsoft Excel 时可用)。
逻辑:由 loader_excel._convert_xls_to_xlsx 在 soffice 失败后按需调用。
"""
from __future__ import annotations
from pathlib import Path
def convert_with_excel(path: Path, output: Path) -> Path:
"""
使用 Microsoft Excel COM 将源表格另存为 .xlsx。
核心逻辑:启动 Excel.Application → Open → SaveAs(xlsx) → Quit。
Args:
path: 源 .xls 文件路径。
output: 目标 .xlsx 路径。
Returns:
成功写入的 output 路径。
Raises:
RuntimeError: 非 Windows、缺少 pywin32/Excel,或转换未产出目标文件。
"""
import os
if os.name != "nt":
raise RuntimeError("Excel COM conversion is only available on Windows")
try:
import win32com.client
except ImportError as exc:
raise RuntimeError("Excel COM conversion requires pywin32 on Windows") from exc
source = str(path.resolve())
target = str(output.resolve())
output.parent.mkdir(parents=True, exist_ok=True)
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
excel.DisplayAlerts = False
workbook = None
try:
workbook = excel.Workbooks.Open(source)
# 51 = xlOpenXMLWorkbook (.xlsx)
workbook.SaveAs(target, FileFormat=51)
finally:
if workbook is not None:
workbook.Close(SaveChanges=False)
excel.Quit()
if not output.exists():
raise RuntimeError(f"Excel COM did not produce output file: {output}")
return output
+3 -2
View File
@@ -7,13 +7,13 @@ backend/edkb_system/skills/loader_excel.py
"""
from __future__ import annotations
import os
from pathlib import Path
from openpyxl import load_workbook, Workbook
from edkb_system.contracts import Context
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
from edkb_system.skills.excel_bridge import convert_with_excel
def _convert_xls_to_xlsx_python(path: Path, output: Path) -> Path:
@@ -64,6 +64,8 @@ def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
# 2. Windows 环境下尝试 Excel COM
if os.name == "nt":
try:
from edkb_system.skills.excel_bridge import convert_with_excel
return convert_with_excel(path, output)
except Exception as exc:
errors.append(f"Excel COM conversion failed: {exc}")
@@ -93,7 +95,6 @@ def _trim_trailing_empty(vals: list[str]) -> list[str]:
def run(input_data: dict, context: Context) -> list[dict]:
import os
file_path = Path(input_data["file_path"])
work_dir = Path(input_data["work_dir"])
if file_path.suffix.lower() == ".xls":
+87
View File
@@ -8,6 +8,15 @@ from app.models import ChatLog, ChatSession, ScheduleRun, ScheduleTask, User
from app.services.rohs_check import RoHSCheckService
@pytest.fixture(autouse=True)
def _clear_rohs_turn_registry():
from app.services.rohs_check_tools.chat_turn_registry import clear_registry_for_tests
clear_registry_for_tests()
yield
clear_registry_for_tests()
@pytest.fixture(autouse=True)
def _stub_minio(monkeypatch):
minio_module = types.ModuleType('minio')
@@ -1157,3 +1166,81 @@ def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path
assert clean_calls == [clean_job_id]
assert sync_calls
assert run.kb_sync_status in ('success', 'ready', 'syncing')
def test_rohs_turn_registry_binds_run_without_http_turn_id(app, client, monkeypatch):
"""Dify HTTP 仅传 task_id + user_message 时,仍应通过 turn 注册表回写 run_id。"""
class _Thread:
def __init__(self, *, target, daemon, name):
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
admin_id = admin.id
from app.services.rohs_check_tools.chat_turn_registry import register_rohs_chat_turn
from app.services.rohs_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
register_rohs_chat_turn(
turn_id='turn-registry-001',
session_id='sess-registry-001',
user_id=1,
agent_id=1,
query='立即执行 RoHS 检核',
)
res = client.post(
'/api/rohs-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'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') == 'sess-registry-001'
assert req.get('bind_turn_id') == 'turn-registry-001'
assert resolve_run_id_for_chat_log(turn_id='turn-registry-001') == run_id
assert resolve_run_id_for_chat_log(
session_id='sess-registry-001',
query='立即执行 RoHS 检核',
) == run_id
chat_log_id = None
from app.services.dify import DifyService
result = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-registry-001'},
event_name='message_end',
request_id='req-bind-test',
user_id=admin_id,
agent=type('AgentProxy', (), {'id': 1, 'name': 'RoHS文件检核助手'})(),
session_id='sess-registry-001',
hxops_turn_id='turn-registry-001',
normalized_conversation_id='sess-registry-001',
query='立即执行 RoHS 检核',
answer_text='检核已启动',
latency=10,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = result.get('chat_log_id')
assert chat_log_id
log = db.session.get(ChatLog, chat_log_id)
assert log.run_id == run_id
@@ -5,6 +5,7 @@
*/
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
import { useSchedulesAdminContext } from '../composables/schedules.context';
import ScheduleCronDesigner from './ScheduleCronDesigner.vue';
const admin = useSchedulesAdminContext();
</script>
@@ -344,103 +345,10 @@ const admin = useSchedulesAdminContext();
></textarea>
</div>
<div class="rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-3">
<h4 class="text-base font-bold text-primary">{{ $t('admin.schedule.form.cronTitle') }}</h4>
<p class="text-sm text-muted">{{ $t('admin.schedule.form.cronHint') }}</p>
</div>
<div
class="segment-control segment-control--cols-4 segment-control--sm"
role="radiogroup"
:aria-label="$t('admin.schedule.form.cronTitle')"
>
<button
type="button"
role="radio"
:aria-checked="admin.scheduleCronDesigner.mode === 'every_minutes'"
class="segment-item"
:class="admin.scheduleCronDesigner.mode === 'every_minutes' ? 'segment-item--active' : ''"
@click="admin.scheduleCronDesigner.mode = 'every_minutes'"
>
{{ $t('admin.schedule.form.everyMinutes') }}
</button>
<button
type="button"
role="radio"
:aria-checked="admin.scheduleCronDesigner.mode === 'hourly'"
class="segment-item"
:class="admin.scheduleCronDesigner.mode === 'hourly' ? 'segment-item--active' : ''"
@click="admin.scheduleCronDesigner.mode = 'hourly'"
>
{{ $t('admin.schedule.form.hourly') }}
</button>
<button
type="button"
role="radio"
:aria-checked="admin.scheduleCronDesigner.mode === 'daily'"
class="segment-item"
:class="admin.scheduleCronDesigner.mode === 'daily' ? 'segment-item--active' : ''"
@click="admin.scheduleCronDesigner.mode = 'daily'"
>
{{ $t('admin.schedule.form.daily') }}
</button>
<button
type="button"
role="radio"
:aria-checked="admin.scheduleCronDesigner.mode === 'weekly'"
class="segment-item"
:class="admin.scheduleCronDesigner.mode === 'weekly' ? 'segment-item--active' : ''"
@click="admin.scheduleCronDesigner.mode = 'weekly'"
>
{{ $t('admin.schedule.form.weekly') }}
</button>
</div>
<div class="mt-4 grid grid-cols-1 gap-3 md:grid-cols-3">
<template v-if="admin.scheduleCronDesigner.mode === 'every_minutes'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minuteInterval') }}</label>
<input v-model.number="admin.scheduleCronDesigner.every_minutes" type="number" min="1" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else-if="admin.scheduleCronDesigner.mode === 'hourly'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minuteOfHour') }}</label>
<input v-model.number="admin.scheduleCronDesigner.hourly_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else-if="admin.scheduleCronDesigner.mode === 'daily'">
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.hour') }}</label>
<input v-model.number="admin.scheduleCronDesigner.daily_hour" type="number" min="0" max="23" class="input-field !text-sm !leading-5" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minute') }}</label>
<input v-model.number="admin.scheduleCronDesigner.daily_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
<template v-else>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.weekday') }}</label>
<select v-model.number="admin.scheduleCronDesigner.weekly_day" class="input-field !text-sm !leading-5">
<option v-for="d in admin.weeklyDayOptions" :key="d.value" :value="d.value">{{ d.label }}</option>
</select>
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.hour') }}</label>
<input v-model.number="admin.scheduleCronDesigner.weekly_hour" type="number" min="0" max="23" class="input-field !text-sm !leading-5" />
</div>
<div>
<label class="mb-1 block text-xs font-semibold text-muted uppercase">{{ $t('admin.schedule.form.minute') }}</label>
<input v-model.number="admin.scheduleCronDesigner.weekly_minute" type="number" min="0" max="59" class="input-field !text-sm !leading-5" />
</div>
</template>
</div>
<div class="mt-4 rounded-xl border border-dashed border-default bg-surface-soft px-4 py-3 text-xs text-secondary">
{{ $t('admin.schedule.form.cronPreview') }}:<span class="font-mono text-primary">{{ admin.scheduleCronPreview }}</span>
<span v-if="admin.scheduleNextRunPreview" class="ml-4">{{ $t('admin.schedule.form.nextRun') }}:<span class="font-medium text-primary">{{ admin.formatDateTime(admin.scheduleNextRunPreview.toISOString()) }}</span></span>
</div>
</div>
<ScheduleCronDesigner
:designer="admin.cronDesigner"
:format-date-time="admin.formatDateTime"
/>
<div class="input-field px-3 py-2.5">
<div class="flex flex-col gap-2 md:flex-row md:items-center">
@@ -522,7 +430,7 @@ const admin = useSchedulesAdminContext();
<button
type="button"
class="btn-primary inline-flex items-center gap-2 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="admin.scheduleCreateSaving || !admin.scheduleCreateForm.name || !admin.scheduleCreateForm.owner_user_id"
:disabled="admin.scheduleCreateSaving || !admin.scheduleCreateForm.name || !admin.scheduleCreateForm.owner_user_id || !admin.cronDesigner.isValid"
@click="admin.createSchedule"
>
<Plus class="h-4 w-4 shrink-0" />
@@ -7,7 +7,6 @@ import type { ScheduleRun, ScheduleTask, TestScheduleRunResult } from '@/feature
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import type { KbGroup } from '@/features/kb/api/kb.api';
import {
createDefaultCronDesigner,
createDefaultScheduleCreateForm,
createDefaultScheduleSqlEditForm,
} from '../../types/schedule-admin.types';
@@ -79,7 +78,6 @@ export function createScheduleAdminState() {
const scheduleEditingId = ref<number | null>(null);
const scheduleCreateForm = ref(createDefaultScheduleCreateForm());
const scheduleConfigCollapsed = ref(true);
const scheduleCronDesigner = ref(createDefaultCronDesigner());
const expandedScheduleRunId = ref<number | null>(null);
@@ -132,7 +130,6 @@ export function createScheduleAdminState() {
scheduleEditingId,
scheduleCreateForm,
scheduleConfigCollapsed,
scheduleCronDesigner,
expandedScheduleRunId,
showTestRunDialog,
testRunSchedule,
@@ -2,7 +2,7 @@
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminForm.ts
* 创建/编辑弹窗:Cron 设计器、负责人/通知人、SQL 配置与提交。
*/
import { computed, watch } from 'vue';
import { computed, markRaw, watch } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import {
createAdminSchedule,
@@ -14,16 +14,11 @@ import {
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import { useMessage } from '@/shared/composables/useMessage';
import {
createDefaultCronDesigner,
createDefaultScheduleCreateForm,
createDefaultScheduleSqlEditForm,
} from '../../types/schedule-admin.types';
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
import {
buildCronExprFromDesigner,
computeNextRunPreview,
parseCronExprToDesigner,
} from '../../utils/schedule-cron.utils';
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminLookups } from './useScheduleAdminLookups';
import type { ScheduleAdminList } from './useScheduleAdminList';
@@ -37,6 +32,8 @@ export function useScheduleAdminForm(
t: ComposerTranslation,
) {
const msg = useMessage();
/** markRaw 避免 SchedulesPage reactive() 深度代理破坏内部 Ref */
const cronDesigner = markRaw(useScheduleCronDesigner());
const {
users,
showScheduleCreateModal,
@@ -44,7 +41,6 @@ export function useScheduleAdminForm(
scheduleEditingId,
scheduleCreateForm,
scheduleConfigCollapsed,
scheduleCronDesigner,
scheduleSqlEditForm,
scheduleTestLoading,
scheduleTestResult,
@@ -57,19 +53,6 @@ export function useScheduleAdminForm(
let scheduleNotifyCloseTimer: ReturnType<typeof setTimeout> | null = null;
let scheduleOwnerCloseTimer: ReturnType<typeof setTimeout> | null = null;
const weeklyDayOptions = computed(() => [
{ value: 1, label: t('admin.schedule.weekday.mon') },
{ value: 2, label: t('admin.schedule.weekday.tue') },
{ value: 3, label: t('admin.schedule.weekday.wed') },
{ value: 4, label: t('admin.schedule.weekday.thu') },
{ value: 5, label: t('admin.schedule.weekday.fri') },
{ value: 6, label: t('admin.schedule.weekday.sat') },
{ value: 0, label: t('admin.schedule.weekday.sun') },
]);
const scheduleCronPreview = computed(() => buildCronExprFromDesigner(scheduleCronDesigner.value));
const scheduleNextRunPreview = computed(() => computeNextRunPreview(scheduleCronPreview.value));
const formatUserOptionLabel = (u: AdminUserRow) =>
`${u.real_name || u.username}${u.employee_id ? `(${u.employee_id})` : ''}`;
@@ -112,7 +95,7 @@ export function useScheduleAdminForm(
scheduleNotifyDropdownOpen.value = false;
scheduleOwnerQuery.value = '';
scheduleOwnerDropdownOpen.value = false;
scheduleCronDesigner.value = createDefaultCronDesigner();
cronDesigner.reset();
};
const openScheduleCreateModal = async () => {
@@ -180,7 +163,7 @@ export function useScheduleAdminForm(
}
scheduleTestResult.value = null;
scheduleCronDesigner.value = parseCronExprToDesigner(task.cron_expr);
cronDesigner.loadFromExpr(task.cron_expr);
syncScheduleOwnerQuery();
showScheduleCreateModal.value = true;
};
@@ -264,6 +247,10 @@ export function useScheduleAdminForm(
const createSchedule = async () => {
if (!scheduleCreateForm.value.name || !scheduleCreateForm.value.owner_user_id) return;
if (!cronDesigner.isValid.value) {
msg.error(t('admin.schedule.form.cronInvalid'));
return;
}
const dst = scheduleCreateForm.value.data_source_type;
const hasAgent = !!scheduleCreateForm.value.dify_agent_id;
@@ -305,7 +292,7 @@ export function useScheduleAdminForm(
name: scheduleCreateForm.value.name,
schedule_type: 'platform_app',
owner_user_id: scheduleCreateForm.value.owner_user_id,
cron_expr: scheduleCronPreview.value,
cron_expr: cronDesigner.cronExpr.value,
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 : [],
@@ -337,9 +324,7 @@ export function useScheduleAdminForm(
};
return {
weeklyDayOptions,
scheduleCronPreview,
scheduleNextRunPreview,
cronDesigner,
filteredNotifyUsers,
filteredOwnerUsers,
openScheduleCreateModal,
@@ -17,8 +17,6 @@ import {
Send,
X,
} from 'lucide-vue-next';
import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import type { PendingAttachment } from '../types/shipping.types';
export interface ChatInputAttachmentPolicy {
@@ -11,7 +11,7 @@ import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue';
import type { ChatMessage } from '../types/chat.types';
import type { ToolRunProgress } from '@/api/toolRunProgress';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
const {
messages,
@@ -1,6 +1,7 @@
import { computed, onBeforeUnmount, ref, type Ref, watch } from 'vue';
import { buildLogProgressUrl } from '../utils/toolRunProgressConfig';
import { getToolRunProgress, type ToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressMatchSource } from '../types/tool-run-progress.types';
export interface ToolRunProgressConfig {
type?: string;
@@ -1,231 +1,685 @@
/**
* 对话页:Agent tool_run_progress 能力轮询(RoHS 等异步任务进度卡片)。
* 依赖:useToolRunProgress、toolRunProgressConfig、ChatMessage。
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定。
* 逻辑:按助手消息 ChatLog.run_id 展示进度,每轮问答独立绑定;无 run_id 时不展示进度卡片。
*/
import { computed, nextTick, ref, watch } from 'vue';
import type { ToolRunProgress } from '@/api/toolRunProgress';
import { getToolRunProgress } from '@/api/toolRunProgress';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
import { getToolRunProgress } from '../api/toolRunProgress.api';
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
import {
assistantMessageHasError,
collectAssistantRunIds,
buildLogProgressUrl,
collectAssistantProgressTargets,
getChatLogIdFromMessage,
getRunIdFromMessage,
isRunningToolRunStatus,
resolveLogProgressBaseUrl,
resolveScheduleTaskId,
resolveMessageAnchorKey,
} from '../utils/toolRunProgressConfig';
export interface ChatPageToolRunContext {
currentAgent: Ref<{ id?: number; extra_config?: Record<string, unknown> } | null>;
conversationId: Ref<string | null>;
messages: Ref<ChatMessage[]>;
}
export function useChatPageToolRun(ctx: ChatPageToolRunContext) {
const runsById = ref<Record<number, ToolRunProgress>>({});
const runErrors = ref<Record<number, string>>({});
const chatLogRunMap = ref<Record<number, number>>({});
const chatLogErrors = ref<Record<number, string>>({});
const pollingRunIds = ref<number[]>([]);
const pollingChatLogIds = 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>(() => {
const extra = ctx.currentAgent.value?.extra_config || {};
const capabilities = Array.isArray(extra.capabilities)
? extra.capabilities.map((item: unknown) => String(item))
: [];
if (!capabilities.includes('tool_run_progress')) return null;
const cfg = rawToolRunConfig.value;
if (!cfg) return null;
return {
...cfg,
schedule_task_id: resolveScheduleTaskId(cfg),
};
});
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 resolveForLogUrl = (chatLogId: number) => {
const taskId = boundScheduleTaskId.value;
if (!taskId) return '';
const base = resolveLogProgressBaseUrl(rawToolRunConfig.value || {});
return buildLogProgressUrl(base, taskId, chatLogId);
};
/**
* 解析消息对应的检核批次 ID(消息 run_id 优先,其次 for-log 映射)。
*/
const resolveMessageRunId = (msg: ChatMessage): number | null => {
const direct = getRunIdFromMessage(msg);
if (direct) return direct;
const chatLogId = getChatLogIdFromMessage(msg);
if (!chatLogId) return null;
const mapped = chatLogRunMap.value[chatLogId];
return mapped && mapped > 0 ? mapped : null;
};
const storeRunPayload = (run: ToolRunProgress, chatLogId?: number | null) => {
const runId = Number(run.run_id);
if (!Number.isFinite(runId) || runId <= 0) return;
runsById.value = { ...runsById.value, [runId]: run };
const nextErrors = { ...runErrors.value };
delete nextErrors[runId];
runErrors.value = nextErrors;
if (chatLogId && chatLogId > 0) {
chatLogRunMap.value = { ...chatLogRunMap.value, [chatLogId]: runId };
const nextChatLogErrors = { ...chatLogErrors.value };
delete nextChatLogErrors[chatLogId];
chatLogErrors.value = nextChatLogErrors;
}
};
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 };
storeRunPayload(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 : '任务进度查询失败',
};
}
};
/**
* 按 chat_log_id 走 for-log 解析批次;成功时回写消息 run_id 供后续 detail 轮询。
*/
const refreshRunByChatLog = async (chatLogId: number, messageIndex: number) => {
const url = resolveForLogUrl(chatLogId);
if (!url) return;
try {
const payload = await getToolRunProgress(url);
if (payload.run) {
storeRunPayload(payload.run, chatLogId);
const msg = ctx.messages.value[messageIndex];
if (msg && !getRunIdFromMessage(msg)) {
msg.run_id = Number(payload.run.run_id);
}
}
const nextErrors = { ...chatLogErrors.value };
delete nextErrors[chatLogId];
chatLogErrors.value = nextErrors;
} catch (e: unknown) {
chatLogErrors.value = {
...chatLogErrors.value,
[chatLogId]: 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 = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
pollingRunIds.value = [];
pollingChatLogIds.value = [];
return;
}
const runIds = collectAssistantRunIds(ctx.messages.value);
const targets = collectAssistantProgressTargets(ctx.messages.value);
const runIds = [...new Set(targets.map((item) => item.runId).filter((id): id is number => !!id))];
const chatLogIds = [...new Set(
targets
.filter((item) => !item.runId && item.chatLogId)
.map((item) => item.chatLogId as number),
)];
pollingRunIds.value = runIds;
if (!runIds.length) {
pollingChatLogIds.value = chatLogIds;
if (!targets.length) {
runsById.value = {};
runErrors.value = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
return;
}
await Promise.all(runIds.map((runId) => refreshRun(runId)));
await Promise.all([
...runIds.map((runId) => refreshRun(runId)),
...targets
.filter((item) => !item.runId && item.chatLogId)
.map((item) => refreshRunByChatLog(item.chatLogId as number, item.messageIndex)),
]);
const activeRunIds = new Set<number>();
for (const target of targets) {
const runId = resolveMessageRunId(target.message);
if (runId) activeRunIds.add(runId);
}
const nextRuns: Record<number, ToolRunProgress> = {};
for (const runId of runIds) {
for (const runId of activeRunIds) {
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();
() => [ctx.currentAgent.value?.id, ctx.conversationId.value] as const,
() => {
runsById.value = {};
runErrors.value = {};
chatLogRunMap.value = {};
chatLogErrors.value = {};
pollingRunIds.value = [];
pollingChatLogIds.value = [];
clearPollTimer();
},
{ immediate: true },
);
watch(
() => ctx.messages.value.map((msg, index) => (
msg?.role === 'assistant'
? `${resolveMessageAnchorKey(msg, index)}:${getRunIdFromMessage(msg) ?? ''}:${getChatLogIdFromMessage(msg) ?? ''}`
: ''
)).join('|'),
async () => {
await nextTick();
await syncProgressState();
},
{ immediate: true },
);
const refreshToolRunProgressAfterSend = async () => {
await nextTick();
await syncProgressState();
};
const prepareToolRunProgressBeforeSend = async () => {
// 按轮 bind:发送前无需 session 级快照。
};
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);
const runId = resolveMessageRunId(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 runId = resolveMessageRunId(msg);
if (runId && runErrors.value[runId]) return runErrors.value[runId];
const chatLogId = getChatLogIdFromMessage(msg);
if (chatLogId && chatLogErrors.value[chatLogId]) return chatLogErrors.value[chatLogId];
return '';
};
const isMessageRunProgressLoading = (msg: ChatMessage) => {
const runId = getRunIdFromMessage(msg);
const runId = resolveMessageRunId(msg);
if (!runId) return false;
return !runsById.value[runId] && !runErrors.value[runId];
};
/**
* 判断是否在该助手消息后展示进度卡片。
* 核心逻辑:已解析到 run_id 时展示;执行中、已完成、加载中或查询报错均保留卡片,无 run_id 不展示。
*/
const shouldShowToolRunProgressAfterMessage = (msg: ChatMessage, _index: number) => {
if (msg?.role !== 'assistant') return false;
if (!toolRunProgressConfig.value) return false;
if (assistantMessageHasError(msg)) return false;
const runId = getRunIdFromMessage(msg);
const runId = resolveMessageRunId(msg);
if (!runId) return false;
const error = getMessageRunProgressError(msg);
if (error) return true;
const loading = isMessageRunProgressLoading(msg);
if (loading) return true;
const run = getMessageRunProgress(msg);
if (!run || !isRunningToolRunStatus(run.status)) return false;
if (!matchesBoundScheduleTask(run.task_id)) return false;
return true;
if (!run) return false;
return matchesBoundScheduleTask(run.task_id);
};
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 toolRunProgressLoading = computed(() => {
if (toolRunProgress.value) return false;
return pollingRunIds.value.length > 0 || pollingChatLogIds.value.length > 0;
});
const toolRunProgressError = computed(() => {
for (const runId of pollingRunIds.value) {
const err = runErrors.value[runId];
if (err) return err;
}
for (const chatLogId of pollingChatLogIds.value) {
const err = chatLogErrors.value[chatLogId];
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,
};
}
@@ -2,7 +2,7 @@
* features/chat/utils/toolRunProgressConfig.ts
* 用途:解析 Agent tool_run_progress 配置;构建 for-log / detail 轮询 URL。
* 依赖:ToolRunProgressConfig、ChatMessage。
* 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动。
* 逻辑:进度卡片由 ChatLog.run_id(按轮问答)驱动;执行中与已完成批次均展示。
*/
import type { ToolRunProgressConfig } from '../composables/useToolRunProgress';
import type { ChatMessage } from '../types/chat.types';
@@ -77,6 +77,16 @@ export function isRunningToolRunStatus(status?: string | null): boolean {
return String(status || '').toLowerCase() === 'running';
}
const TERMINAL_TOOL_RUN_STATUSES = new Set(['success', 'partial_failed', 'failed', 'cancelled', 'canceled']);
/**
* 判断检核批次是否已进入终态(成功/失败/取消等)。
* 核心逻辑:与 useToolRunProgress 轮询终止条件保持一致,供进度卡片展示判断复用。
*/
export function isTerminalToolRunStatus(status?: string | null): boolean {
return TERMINAL_TOOL_RUN_STATUSES.has(String(status || '').toLowerCase());
}
export function collectAssistantRunIds(messages: ChatMessage[]): number[] {
const ids = new Set<number>();
for (const msg of messages) {
@@ -86,3 +96,32 @@ export function collectAssistantRunIds(messages: ChatMessage[]): number[] {
}
return [...ids];
}
export interface AssistantProgressTarget {
message: ChatMessage;
messageIndex: number;
runId: number | null;
chatLogId: number | null;
}
/**
* 收集助手消息上的进度轮询目标:优先 run_id,否则用 chat_log_id 走 for-log 兜底。
* 核心逻辑:run_id 未从 SSE 回写时,仍可通过 chat_log_id 解析已绑定的检核批次。
*/
export function collectAssistantProgressTargets(messages: ChatMessage[]): AssistantProgressTarget[] {
const targets: AssistantProgressTarget[] = [];
messages.forEach((msg, messageIndex) => {
if (msg?.role !== 'assistant') return;
const runId = getRunIdFromMessage(msg);
const chatLogIdRaw = Number(msg.chat_log_id);
const chatLogId = Number.isFinite(chatLogIdRaw) && chatLogIdRaw > 0 ? chatLogIdRaw : null;
if (!runId && !chatLogId) return;
targets.push({ message: msg, messageIndex, runId, chatLogId });
});
return targets;
}
export function getChatLogIdFromMessage(msg: ChatMessage | null | undefined): number | null {
const chatLogId = Number(msg?.chat_log_id);
return Number.isFinite(chatLogId) && chatLogId > 0 ? chatLogId : null;
}
@@ -106,7 +106,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
return workflow.upload.code !== 'success';
}
if (filter === 'clean') {
return ['pending', 'running', 'failed'].includes(workflow.clean.code);
return ['pending', 'queued', 'running', 'failed'].includes(workflow.clean.code);
}
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
};
@@ -172,7 +172,7 @@ export function useKbWorkspaceComputed(state: KbWorkspaceState) {
selectedDocuments.value.filter((doc) => {
if (!doc.latest_version) return false;
const workflow = resolveWorkflowState(doc);
return ['failed', 'pending', 'idle'].includes(workflow.clean.code);
return ['failed', 'pending', 'queued', 'idle'].includes(workflow.clean.code);
}),
);
@@ -11,7 +11,7 @@ export type KbFeedbackType = 'success' | 'error' | '';
/** 上传 → 清洗 → 同步 各阶段展示状态 */
export type WorkflowStageState = {
code: 'pending' | 'running' | 'success' | 'failed' | 'idle';
code: 'pending' | 'queued' | 'running' | 'success' | 'failed' | 'idle';
label: string;
className: string;
errorMessage?: string | null;
@@ -101,11 +101,17 @@ export const getDocumentWorkflowState = (
};
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
cleanStage = { code: 'success', label: t('kbWorkspace.status.done'), className: getStatusBadgeClass('success') };
} else if (['running', 'queued'].includes(String(cleanJob?.status || '').toLowerCase()) || latestStatus === 'processing') {
} else if (String(cleanJob?.status || '').toLowerCase() === 'queued') {
cleanStage = {
code: 'queued',
label: t('kbWorkspace.status.queued'),
className: getStatusBadgeClass('queued'),
};
} else if (String(cleanJob?.status || '').toLowerCase() === 'running' || latestStatus === 'processing') {
cleanStage = {
code: 'running',
label: latestStatus === 'processing' ? t('kbWorkspace.status.cleaning') : t('kbWorkspace.status.pendingClean'),
className: getStatusBadgeClass(latestStatus === 'processing' ? 'processing' : 'uploaded'),
label: t('kbWorkspace.status.cleaning'),
className: getStatusBadgeClass('processing'),
};
} else if (latestStatus === 'uploaded') {
cleanStage = { code: 'pending', label: t('kbWorkspace.status.pendingClean'), className: getStatusBadgeClass('uploaded') };