feat(rohs-check): 增强 RoHS 检核工具进度展示,新增判定统计与当前步骤信息

This commit is contained in:
hugo committed 2026-06-11 11:47:07 +08:00
1 parent b82f31af8f
commit ee39270069
9 files changed
+349 -11

No files matched your search

+2
View File
@@ -13,6 +13,7 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text from sqlalchemy import text
from app import db from app import db
from app.api.workspace_rohs_check import serialize_rohs_judgement
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask from app.models import ScheduleRun, ScheduleTask
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
@@ -165,6 +166,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
"success_count": payload["success_count"], "success_count": payload["success_count"],
"failed_count": payload["failed_count"], "failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"], "skipped_count": payload["skipped_count"],
"judgement": serialize_rohs_judgement(payload),
"started_at": payload.get("started_at"), "started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"), "finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"), "duration_ms": payload.get("duration_ms"),
+41 -2
View File
@@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from flask import Blueprint, jsonify from flask import Blueprint, jsonify, request
from app.auth_jwt import get_current_user from app.auth_jwt import get_current_user
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
@@ -31,6 +31,35 @@ def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS) return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def serialize_rohs_judgement(payload: dict) -> dict:
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
return {
"qualified_count": int(judgement.get("qualified_count") or 0),
"unqualified_count": int(judgement.get("unqualified_count") or 0),
"manual_count": int(judgement.get("manual_count") or 0),
"dify_error_count": int(judgement.get("dify_error_count") or 0),
"invalid_result_count": int(judgement.get("invalid_result_count") or 0),
}
def serialize_current_step(payload: dict) -> dict | None:
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
current_step = response_summary.get("current_step") if isinstance(response_summary.get("current_step"), dict) else None
if not current_step:
return None
return {
"step": str(current_step.get("step") or ""),
"label": str(current_step.get("label") or current_step.get("step") or ""),
"row_id": current_step.get("row_id"),
"started_at": current_step.get("started_at"),
"processed_count": int(current_step.get("processed_count") or 0),
"success_count": int(current_step.get("success_count") or 0),
"failed_count": int(current_step.get("failed_count") or 0),
"skipped_count": int(current_step.get("skipped_count") or 0),
}
def _serialize_progress_run(run: ScheduleRun) -> dict: def _serialize_progress_run(run: ScheduleRun) -> dict:
payload = serialize_run(run) payload = serialize_run(run)
total = int(payload.get("total_count") or 0) total = int(payload.get("total_count") or 0)
@@ -51,6 +80,8 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"success_count": success, "success_count": success,
"failed_count": failed, "failed_count": failed,
"skipped_count": skipped, "skipped_count": skipped,
"judgement": serialize_rohs_judgement(payload),
"current_step": serialize_current_step(payload),
"progress_percent": percent, "progress_percent": percent,
"started_at": payload.get("started_at"), "started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"), "finished_at": payload.get("finished_at"),
@@ -75,13 +106,21 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"]) @workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
def workspace_rohs_active_run(): def workspace_rohs_active_run():
_require_user() _require_user()
conversation_id = str(request.args.get("conversation_id") or "").strip()
rows = ( rows = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id) ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running") .filter(ScheduleRun.status == "running")
.order_by(ScheduleRun.id.desc()) .order_by(ScheduleRun.id.desc())
.all() .all()
) )
run = next((row for row in rows if _is_rohs_check_task(row.task)), None) 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}) return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
@@ -339,11 +339,13 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
run.failed_count = failed_count run.failed_count = failed_count
run.skipped_count = skipped_count run.skipped_count = skipped_count
run.step_logs = step_logs if step_logs else None run.step_logs = step_logs if step_logs else None
run.response_summary_json = { response_summary = dict(run.response_summary_json or {})
response_summary.update({
"errors": errors[:20], "errors": errors[:20],
"schedule_type": task.schedule_type, "schedule_type": task.schedule_type,
"platform_api_path": task.platform_api_path, "platform_api_path": task.platform_api_path,
} })
run.response_summary_json = response_summary
run.error_message = "; ".join(errors[:3]) if errors else None run.error_message = "; ".join(errors[:3]) if errors else None
run.excel_file_data = file_data run.excel_file_data = file_data
run.excel_file_name = file_name run.excel_file_name = file_name
+78 -2
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from datetime import datetime from datetime import datetime
from typing import Any, Callable from typing import Any, Callable
from flask import current_app from flask import current_app, has_app_context
from app.services.rohs_check import RoHSCheckService from app.services.rohs_check import RoHSCheckService
@@ -16,13 +16,31 @@ except Exception: # pragma: no cover
def _connect(conn_str: str): def _connect(conn_str: str):
if pyodbc is None: if pyodbc is None:
raise RuntimeError("pyodbc is not installed") raise RuntimeError("pyodbc is not installed")
return pyodbc.connect(conn_str, timeout=15) return pyodbc.connect(conn_str, timeout=_sql_timeout_seconds())
def _sql_timeout_seconds() -> int:
if not has_app_context():
return 15
try:
value = int(current_app.config.get("SRM_SQLSERVER_TIMEOUT", 15) or 15)
except Exception:
value = 15
return max(1, value)
def _apply_cursor_timeout(cursor) -> None:
try:
cursor.timeout = _sql_timeout_seconds()
except Exception:
pass
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]: def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
conn = _connect(conn_str) conn = _connect(conn_str)
try: try:
cur = conn.cursor() cur = conn.cursor()
_apply_cursor_timeout(cur)
if params: if params:
cur.execute(sql, params) cur.execute(sql, params)
else: else:
@@ -38,6 +56,7 @@ def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
conn = _connect(conn_str) conn = _connect(conn_str)
try: try:
cur = conn.cursor() cur = conn.cursor()
_apply_cursor_timeout(cur)
cur.execute(sql, params) cur.execute(sql, params)
conn.commit() conn.commit()
finally: finally:
@@ -111,6 +130,16 @@ def _make_step(
return entry return entry
def _step_label(step: str) -> str:
return {
"fetch_srm": "查询待检数据",
"pre_dify": "查询成分明细",
"call_dify": "调用 Dify 判定",
"writeback_srm": "写回 SRM",
"completed": "处理完成",
}.get(step, step)
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str: def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
if len(s) <= max_len: if len(s) <= max_len:
return s return s
@@ -158,6 +187,14 @@ def _run_check_job_loop(
success_count = 0 success_count = 0
failed_count = 0 failed_count = 0
skipped_count = 0 skipped_count = 0
judgement_stats = {
"qualified_count": 0,
"unqualified_count": 0,
"manual_count": 0,
"dify_error_count": 0,
"invalid_result_count": 0,
}
current_step: dict[str, Any] | None = None
all_errors: list[str] = [] all_errors: list[str] = []
def _save_progress(total: int | None = None) -> None: def _save_progress(total: int | None = None) -> None:
@@ -175,13 +212,33 @@ def _run_check_job_loop(
progress_run.success_count = success_count progress_run.success_count = success_count
progress_run.failed_count = failed_count progress_run.failed_count = failed_count
progress_run.skipped_count = skipped_count progress_run.skipped_count = skipped_count
summary = dict(progress_run.response_summary_json or {})
summary["rohs_judgement"] = dict(judgement_stats)
if current_step:
summary["current_step"] = dict(current_step)
progress_run.response_summary_json = summary
db.session.commit() db.session.commit()
except Exception as progress_exc: except Exception as progress_exc:
if current_app: if current_app:
current_app.logger.warning("[%s] save progress failed run_id=%s error=%s", log_prefix, run_id, progress_exc) current_app.logger.warning("[%s] save progress failed run_id=%s error=%s", log_prefix, run_id, progress_exc)
def _set_current_step(step: str, row_id: str | None = None, total: int | None = None) -> None:
nonlocal current_step
current_step = {
"step": step,
"label": _step_label(step),
"row_id": row_id,
"started_at": _ts(),
"processed_count": success_count + failed_count + skipped_count,
"success_count": success_count,
"failed_count": failed_count,
"skipped_count": skipped_count,
}
_save_progress(total=total)
t0 = _ts() t0 = _ts()
try: try:
_set_current_step("fetch_srm")
rows = fetch_fn(conn_str) rows = fetch_fn(conn_str)
if max_rows > 0: if max_rows > 0:
rows = rows[:max_rows] rows = rows[:max_rows]
@@ -221,6 +278,7 @@ def _run_check_job_loop(
if pre_dify_fn: if pre_dify_fn:
t_pre = _ts() t_pre = _ts()
try: try:
_set_current_step("pre_dify", row_id_value)
pre_result = pre_dify_fn(conn_str, item, row_id_value) pre_result = pre_dify_fn(conn_str, item, row_id_value)
except Exception as pre_exc: except Exception as pre_exc:
pre_result = { pre_result = {
@@ -257,6 +315,7 @@ def _run_check_job_loop(
dify_inputs["system_prompt"] = prompt dify_inputs["system_prompt"] = prompt
t_dify = _ts() t_dify = _ts()
try: try:
_set_current_step("call_dify", row_id_value)
dify_res = RoHSCheckService.evaluate( dify_res = RoHSCheckService.evaluate(
agent=agent, agent=agent,
run_no=run_no, run_no=run_no,
@@ -280,6 +339,19 @@ def _run_check_job_loop(
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {}) dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
dify_ok = True dify_ok = True
if dify_result == "合格":
judgement_stats["qualified_count"] += 1
elif dify_result == "不合格":
judgement_stats["unqualified_count"] += 1
else:
judgement_stats["manual_count"] += 1
if dify_error:
judgement_stats["dify_error_count"] += 1
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
judgement_stats["invalid_result_count"] += 1
if current_app: if current_app:
current_app.logger.info( current_app.logger.info(
@@ -304,11 +376,13 @@ def _run_check_job_loop(
dify_result = "人工判定" dify_result = "人工判定"
dify_message = "未配置 Agent ID,跳过 Dify" dify_message = "未配置 Agent ID,跳过 Dify"
dify_ok = True dify_ok = True
judgement_stats["manual_count"] += 1
wb_sql = writeback_sql wb_sql = writeback_sql
wb_params = (run_no, dify_result, dify_message, str(row_id_value)) wb_params = (run_no, dify_result, dify_message, str(row_id_value))
t_wb = _ts() t_wb = _ts()
try: try:
_set_current_step("writeback_srm", row_id_value)
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message) writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={ step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
"sql": _truncate_str(wb_sql, 500), "sql": _truncate_str(wb_sql, 500),
@@ -352,6 +426,7 @@ def _run_check_job_loop(
all_errors.append(str(exc)) all_errors.append(str(exc))
t_wb2 = _ts() t_wb2 = _ts()
try: try:
_set_current_step("writeback_srm", row_id_value)
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message) writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"})) step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
item["writeback_srm"] = True item["writeback_srm"] = True
@@ -366,5 +441,6 @@ def _run_check_job_loop(
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW: if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW] step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
_set_current_step("completed")
total_count = success_count + failed_count + skipped_count total_count = success_count + failed_count + skipped_count
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
+139
View File
@@ -108,6 +108,105 @@ def test_rohs_service_normalizes_invalid_result():
assert payload['workflow_run_id'] == 'wf-1' assert payload['workflow_run_id'] == 'wf-1'
def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
from app.services.schedule.srm_service import _run_check_job_loop
class _Agent:
id = 1
dify_api_key = 'secret'
def _evaluate(**kwargs):
return {
'dify_result': '人工判定',
'dify_message': 'Dify执行失败:workflow timeout',
'workflow_run_id': 'wf-failed',
'error': 'workflow timeout',
}
writebacks = []
monkeypatch.setattr('app.services.schedule.srm_service.RoHSCheckService.evaluate', _evaluate)
with app.app_context():
admin = _mk_admin()
db.session.flush()
task = _mk_check_task(admin.id)
run = ScheduleRun(run_no='RUN-JUDGEMENT-SPLIT', schedule_task_id=task.id, status='running', trigger_type='manual')
db.session.add(run)
db.session.commit()
run_id = run.id
total, success, failed, skipped, details, errors, step_logs = _run_check_job_loop(
conn_str='',
run_no='RUN-1',
agent=_Agent(),
user='tester',
wait_seconds=5,
run_id=run_id,
fetch_fn=lambda _conn: [{'id': 'R1'}],
build_record_fn=lambda _conn, item, row_id: ('record text', None),
writeback_fn=lambda _conn, **kwargs: writebacks.append(kwargs),
row_id_key='id',
log_prefix='row',
)
db.session.refresh(run)
judgement = (run.response_summary_json or {}).get('rohs_judgement') or {}
assert total == 1
assert success == 1
assert failed == 0
assert skipped == 0
assert writebacks
assert details[0]['writeback_srm'] is True
assert errors == []
assert judgement['manual_count'] == 1
assert judgement['dify_error_count'] == 1
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch):
from app.services.schedule import srm_service
observed = {'connect_timeout': None, 'cursor_timeout': None}
class _Cursor:
description = [('id',)]
def __setattr__(self, name, value):
if name == 'timeout':
observed['cursor_timeout'] = value
object.__setattr__(self, name, value)
def execute(self, *_args):
return None
def fetchall(self):
return [(1,)]
class _Conn:
def cursor(self):
return _Cursor()
def commit(self):
return None
def close(self):
return None
class _Pyodbc:
@staticmethod
def connect(_conn_str, timeout):
observed['connect_timeout'] = timeout
return _Conn()
monkeypatch.setattr(srm_service, 'pyodbc', _Pyodbc)
with app.app_context():
app.config['SRM_SQLSERVER_TIMEOUT'] = 7
srm_service._execute_writeback('conn', 'update table set col=?', ('x',))
assert observed == {'connect_timeout': 7, 'cursor_timeout': 7}
def test_rohs_tool_requires_auth(app, client): def test_rohs_tool_requires_auth(app, client):
with app.app_context(): with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret' app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -274,6 +373,18 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
success_count=3, success_count=3,
failed_count=1, failed_count=1,
skipped_count=1, skipped_count=1,
response_summary_json={
'current_step': {
'step': 'writeback_srm',
'label': '写回 SRM',
'row_id': 'ROW-16',
'started_at': '2026-06-11T10:00:00',
'processed_count': 4,
'success_count': 3,
'failed_count': 1,
'skipped_count': 0,
},
},
) )
db.session.add(run) db.session.add(run)
db.session.commit() db.session.commit()
@@ -285,6 +396,34 @@ def test_workspace_rohs_active_run_returns_progress(app, client):
assert data['run']['run_no'] == 'RUN-ROHS-ACTIVE' assert data['run']['run_no'] == 'RUN-ROHS-ACTIVE'
assert data['run']['processed_count'] == 5 assert data['run']['processed_count'] == 5
assert data['run']['progress_percent'] == 50 assert data['run']['progress_percent'] == 50
assert data['run']['current_step']['step'] == 'writeback_srm'
assert data['run']['current_step']['row_id'] == 'ROW-16'
def test_workspace_rohs_active_run_filters_by_conversation_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-ACTIVE-CONV',
schedule_task_id=task.id,
status='running',
trigger_type='dify_chatflow',
total_count=10,
success_count=2,
api_request_json={'conversation_id': 'conv-a'},
)
db.session.add(run)
db.session.commit()
miss = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
assert miss.status_code == 200
assert miss.get_json()['run'] is None
hit = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
assert hit.status_code == 200
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
def test_workspace_rohs_active_run_returns_null_when_idle(app, client): def test_workspace_rohs_active_run_returns_null_when_idle(app, client):
+17
View File
@@ -12,6 +12,23 @@ export interface ToolRunProgress {
success_count: number; success_count: number;
failed_count: number; failed_count: number;
skipped_count: number; skipped_count: number;
current_step?: {
step?: string;
label?: string;
row_id?: string | number | null;
started_at?: string | null;
processed_count?: number;
success_count?: number;
failed_count?: number;
skipped_count?: number;
} | null;
judgement?: {
qualified_count?: number;
unqualified_count?: number;
manual_count?: number;
dify_error_count?: number;
invalid_result_count?: number;
};
progress_percent: number; progress_percent: number;
started_at?: string | null; started_at?: string | null;
finished_at?: string | null; finished_at?: string | null;
@@ -23,10 +23,29 @@ const statusLabel = (status?: string) => {
const formatTime = (value?: string | null) => { const formatTime = (value?: string | null) => {
if (!value) return '-'; if (!value) return '-';
return String(value).replace('T', ' ').slice(0, 19); const date = new Date(String(value));
if (Number.isNaN(date.getTime())) return String(value).replace('T', ' ').slice(0, 19);
const pad = (num: number) => String(num).padStart(2, '0');
return [
date.getFullYear(),
pad(date.getMonth() + 1),
pad(date.getDate()),
].join('-') + ' ' + [
pad(date.getHours()),
pad(date.getMinutes()),
pad(date.getSeconds()),
].join(':');
}; };
const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent || 0), 100)); const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent || 0), 100));
const judgementTotal = () => {
const judgement = props.run?.judgement;
if (!judgement) return 0;
return Number(judgement.qualified_count || 0)
+ Number(judgement.unqualified_count || 0)
+ Number(judgement.manual_count || 0);
};
</script> </script>
<template> <template>
@@ -48,6 +67,11 @@ const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent ||
<template v-else-if="loading">正在查询任务进度...</template> <template v-else-if="loading">正在查询任务进度...</template>
<template v-else>{{ error }}</template> <template v-else>{{ error }}</template>
</p> </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 }}
<span v-if="run.current_step.row_id"> · 当前记录:{{ run.current_step.row_id }}</span>
<span v-if="run.current_step.started_at"> · 阶段开始:{{ formatTime(run.current_step.started_at) }}</span>
</p>
</div> </div>
<a <a
v-if="run?.excel?.download_url" v-if="run?.excel?.download_url"
@@ -95,6 +119,32 @@ const percent = () => Math.max(0, Math.min(Number(props.run?.progress_percent ||
</div> </div>
</div> </div>
<div v-if="judgementTotal() > 0" class="rounded-xl bg-white/70 px-3 py-3">
<div class="mb-2 text-xs font-semibold text-slate-600">判定口径</div>
<div class="grid grid-cols-2 gap-2 md:grid-cols-5">
<div class="rounded-lg bg-emerald-50/80 px-3 py-2">
<div class="text-xs text-slate-500">合格</div>
<div class="text-lg font-bold text-emerald-700">{{ run.judgement?.qualified_count || 0 }}</div>
</div>
<div class="rounded-lg bg-rose-50/80 px-3 py-2">
<div class="text-xs text-slate-500">不合格</div>
<div class="text-lg font-bold text-rose-700">{{ run.judgement?.unqualified_count || 0 }}</div>
</div>
<div class="rounded-lg bg-amber-50/80 px-3 py-2">
<div class="text-xs text-slate-500">人工判定</div>
<div class="text-lg font-bold text-amber-700">{{ run.judgement?.manual_count || 0 }}</div>
</div>
<div class="rounded-lg bg-orange-50/80 px-3 py-2">
<div class="text-xs text-slate-500">Dify 异常</div>
<div class="text-lg font-bold text-orange-700">{{ run.judgement?.dify_error_count || 0 }}</div>
</div>
<div class="rounded-lg bg-slate-50/80 px-3 py-2">
<div class="text-xs text-slate-500">返回异常</div>
<div class="text-lg font-bold text-slate-700">{{ run.judgement?.invalid_result_count || 0 }}</div>
</div>
</div>
</div>
<div v-if="run.knowledge_base?.sync_status || run.error_message" class="rounded-xl bg-white/70 px-3 py-2 text-xs text-slate-600"> <div v-if="run.knowledge_base?.sync_status || run.error_message" class="rounded-xl bg-white/70 px-3 py-2 text-xs text-slate-600">
<div v-if="run.knowledge_base?.sync_status">知识库同步:{{ run.knowledge_base.sync_status }}</div> <div v-if="run.knowledge_base?.sync_status">知识库同步:{{ run.knowledge_base.sync_status }}</div>
<div v-if="run.knowledge_base?.error_message" class="text-amber-700">同步错误:{{ run.knowledge_base.error_message }}</div> <div v-if="run.knowledge_base?.error_message" class="text-amber-700">同步错误:{{ run.knowledge_base.error_message }}</div>
@@ -11,8 +11,6 @@ export interface ToolRunProgressConfig {
lock_message?: string; lock_message?: string;
} }
const TERMINAL_STATUSES = new Set(['success', 'partial_failed', 'failed', 'cancelled', 'canceled']);
const clampPollMs = (seconds: unknown) => { const clampPollMs = (seconds: unknown) => {
const raw = Number(seconds); const raw = Number(seconds);
const safe = Number.isFinite(raw) ? raw : 2; const safe = Number.isFinite(raw) ? raw : 2;
@@ -65,7 +63,7 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
loading.value = false; loading.value = false;
} }
if (!run.value || run.value.status === 'running' || !TERMINAL_STATUSES.has(run.value.status)) { if (run.value?.status === 'running') {
scheduleNext(); scheduleNext();
} else { } else {
clearTimer(); clearTimer();
+16 -1
View File
@@ -466,7 +466,14 @@ const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
if (!capabilities.includes('tool_run_progress')) return null; if (!capabilities.includes('tool_run_progress')) return null;
const raw = extra.tool_run_progress; const raw = extra.tool_run_progress;
if (!raw || typeof raw !== 'object') return null; if (!raw || typeof raw !== 'object') return null;
return raw as ToolRunProgressConfig; const cfg = raw as ToolRunProgressConfig;
const cid = String(conversationId.value || '').trim();
if (!cid || !cfg.active_url) return null;
const separator = cfg.active_url.includes('?') ? '&' : '?';
return {
...cfg,
active_url: `${cfg.active_url}${separator}conversation_id=${encodeURIComponent(cid)}`,
};
}); });
const { const {
run: toolRunProgress, run: toolRunProgress,
@@ -474,8 +481,14 @@ const {
error: toolRunProgressError, error: toolRunProgressError,
shouldLockInput: toolRunShouldLockInput, shouldLockInput: toolRunShouldLockInput,
lockMessage: toolRunLockMessage, lockMessage: toolRunLockMessage,
refresh: refreshToolRunProgress,
} = useToolRunProgress(toolRunProgressConfig); } = useToolRunProgress(toolRunProgressConfig);
const refreshToolRunProgressAfterSend = async () => {
await nextTick();
void refreshToolRunProgress();
};
type AgentSuggestedQuestionItem = { type AgentSuggestedQuestionItem = {
question: string; question: string;
group: string; group: string;
@@ -3171,6 +3184,7 @@ const handleSend = async (textOrEvent?: string | Event) => {
if (typeof textOrEvent !== 'string') input.value = ''; if (typeof textOrEvent !== 'string') input.value = '';
attachments.value = []; attachments.value = [];
await sendMessage(prompt, currentAgentId.value, selectedKb.value, files); await sendMessage(prompt, currentAgentId.value, selectedKb.value, files);
await refreshToolRunProgressAfterSend();
if (!conversationId.value && history.value.length === 0) { if (!conversationId.value && history.value.length === 0) {
await loadHistory(); await loadHistory();
} else if (conversationId.value) { } else if (conversationId.value) {
@@ -3332,6 +3346,7 @@ const handleSend = async (textOrEvent?: string | Event) => {
attachments.value = []; attachments.value = [];
await sendMessage(content, currentAgentId.value, selectedKb.value, files); await sendMessage(content, currentAgentId.value, selectedKb.value, files);
await refreshToolRunProgressAfterSend();
if (!conversationId.value && history.value.length === 0) { if (!conversationId.value && history.value.length === 0) {
await loadHistory(); await loadHistory();