feat(rohs-check): 新增 RoHS 检核执行进度中增加 Excel 下载功能及相关配置

This commit is contained in:
hugo committed 2026-06-11 17:35:16 +08:00
1 parent ee39270069
commit 599d492895
14 files changed
+841 -268

No files matched your search

+1 -1
View File
@@ -1218,7 +1218,7 @@ def chat_completions():
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id: if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
known_provider_conversation_id = provider_conversation_id known_provider_conversation_id = provider_conversation_id
should_touch = True should_touch = True
if event_name == 'message_end': if event_name in ('message_end', 'workflow_finished'):
known_status = 'done' known_status = 'done'
should_touch = True should_touch = True
elif event_name == 'error': elif event_name == 'error':
+1 -1
View File
@@ -255,7 +255,7 @@ def run_rohs_check():
"error_code": "check_running", "error_code": "check_running",
"message": "该检核任务正在执行中,请稍后查询结果", "message": "该检核任务正在执行中,请稍后查询结果",
"run": _serialize_tool_run(existing), "run": _serialize_tool_run(existing),
}), 409 })
run = ScheduleRun( run = ScheduleRun(
run_no=_generate_run_no(), run_no=_generate_run_no(),
+22 -2
View File
@@ -1,6 +1,8 @@
from __future__ import annotations from __future__ import annotations
from flask import Blueprint, jsonify, request from io import BytesIO
from flask import Blueprint, jsonify, request, send_file
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
@@ -90,7 +92,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"excel": { "excel": {
"file_name": payload.get("excel_file_name"), "file_name": payload.get("excel_file_name"),
"file_size": payload.get("excel_file_size"), "file_size": payload.get("excel_file_size"),
"download_url": f"/api/workspace/schedule-runs/{run.id}/excel" if payload.get("excel_file_name") else None, "download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
}, },
"knowledge_base": { "knowledge_base": {
"sync_status": payload.get("kb_sync_status"), "sync_status": payload.get("kb_sync_status"),
@@ -133,3 +135,21 @@ def workspace_rohs_run_detail(run_id: int):
if not _is_rohs_check_task(run.task): if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden") raise ForbiddenError("Forbidden")
return jsonify({"ok": True, "run": _serialize_progress_run(run)}) return jsonify({"ok": True, "run": _serialize_progress_run(run)})
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
def workspace_rohs_run_excel(run_id: int):
_require_user()
run = get_run(run_id)
if not run:
raise NotFoundError("run_not_found")
if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden")
if not run.excel_file_data:
raise NotFoundError("excel_not_found")
return send_file(
BytesIO(run.excel_file_data),
as_attachment=True,
download_name=run.excel_file_name or f"{run.run_no}.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+2
View File
@@ -90,6 +90,8 @@ class Config:
# Dify 网关配置 # Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE') DIFY_API_BASE = os.getenv('DIFY_API_BASE')
DIFY_API_KEY = os.getenv('DIFY_API_KEY') DIFY_API_KEY = os.getenv('DIFY_API_KEY')
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
# Redis 连接配置,默认使用本地 Redis + 密码 # Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL') REDIS_URL = os.getenv('REDIS_URL')
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true' FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
+161 -56
View File
@@ -27,7 +27,7 @@ import os
import time import time
import uuid import uuid
from datetime import datetime, timedelta from datetime import datetime, timedelta
from threading import Lock from threading import Lock, Thread
from typing import Any, List, Optional from typing import Any, List, Optional
import requests import requests
@@ -567,78 +567,76 @@ class DifyService:
full_answer: List[str] = [] full_answer: List[str] = []
retriever_resources: List[Any] = [] retriever_resources: List[Any] = []
attribution_parts: List[str] = [] attribution_parts: List[str] = []
chat_logged = False chat_persist_started = False
has_sent_answer = False
def persist_stream_chat(data: dict, event_name: str) -> None: def persist_stream_chat(data: dict, event_name: str) -> None:
nonlocal chat_logged persist_stream_chat_async(data, event_name)
if chat_logged:
def persist_stream_chat_async(data: dict, event_name: str) -> None:
nonlocal chat_persist_started
if chat_persist_started:
return return
chat_persist_started = True
if data.get('answer'): app_obj = current_app._get_current_object() if current_app else None
full_answer.append(data.get('answer', '')) persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
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()
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip() answer_text = ''.join(full_answer).strip()
if data.get('answer'):
answer_text = (answer_text + str(data.get('answer') or '')).strip()
if not answer_text and event_name == 'workflow_finished': if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {} wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict): if isinstance(outputs, dict):
for key in ('answer', 'text', 'result'): for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key) value = outputs.get(key)
if isinstance(value, str) and value.strip(): if isinstance(value, str) and value.strip():
answer_text = value.strip() answer_text = value.strip()
break break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
chat_logged = True
if current_app:
current_app.logger.info(
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_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,
)
max_retries = 3 max_retries = 3
for attempt in range(1, max_retries + 1): for attempt in range(1, max_retries + 1):
try: try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response: connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
if attempt == 1:
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
if current_app: if current_app:
current_app.logger.info( current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s", "[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
@@ -665,6 +663,7 @@ class DifyService:
time.sleep(attempt * 2) time.sleep(attempt * 2)
continue continue
response.raise_for_status() response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
for line in response.iter_lines(): for line in response.iter_lines():
if not line: if not line:
@@ -696,6 +695,8 @@ class DifyService:
if event == 'message': if event == 'message':
message_count += 1 message_count += 1
if data.get('answer'):
has_sent_answer = True
if first_token_at is None: if first_token_at is None:
first_token_at = time.time() first_token_at = time.time()
if current_app: if current_app:
@@ -709,20 +710,66 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data) DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'): elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event in ('message_end', 'workflow_finished') or data.get('answer'):
has_sent_answer = True
DifyService._collect_metadata(retriever_resources, attribution_parts, data) DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'workflow_finished' and not data.get('answer'):
final_answer = build_final_answer_text(data, event)
if final_answer:
data['answer'] = final_answer
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'): if event in ('message_end', 'workflow_finished'):
persist_stream_chat(data, event) persist_stream_chat(data, event)
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n" yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
if event in ('message_end', 'workflow_finished'):
break
break break
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
if current_app: if current_app:
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e) current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries: is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
if current_app:
current_app.logger.warning(
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
request_id,
attempt,
)
persist_stream_chat(
{
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
},
'message_end',
)
break
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2) time.sleep(attempt * 2)
continue continue
error_msg = json.dumps({'event': 'error', 'message': str(e)}) if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n" yield f"data: {error_msg}\n\n"
@staticmethod @staticmethod
@@ -775,6 +822,64 @@ class DifyService:
return None return None
@staticmethod
def _persist_stream_chat_record(
*,
data: dict,
event_name: str,
request_id: str | None,
user_id: int,
agent_id: int,
session_id: str | None,
normalized_conversation_id: str | None,
query: str,
answer_text: str,
latency: int,
retriever_resources: List[Any],
attribution_parts: List[str],
) -> None:
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent_id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
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",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
@staticmethod @staticmethod
def _normalize_resources(resources): def _normalize_resources(resources):
""" """
@@ -12,26 +12,38 @@
} }
], ],
"security": [ "security": [
{ "BearerAuth": [] }, {
{ "IntegrationKey": [] } "BearerAuth": []
},
{
"IntegrationKey": []
}
], ],
"paths": { "paths": {
"/api/rohs-check/tools/tasks": { "/api/rohs-check/tools/tasks": {
"get": { "get": {
"operationId": "list_rohs_tasks", "operationId": "list_rohs_tasks",
"summary": "查询 RoHS 检核任务列表", "summary": "查询 RoHS 检核任务列表",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"responses": { "responses": {
"200": { "200": {
"description": "成功", "description": "成功",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ListTasksResponse" } "schema": {
"$ref": "#/components/schemas/ListTasksResponse"
}
} }
} }
}, },
"401": { "$ref": "#/components/responses/Unauthorized" }, "401": {
"503": { "$ref": "#/components/responses/MissingAuth" } "$ref": "#/components/responses/Unauthorized"
},
"503": {
"$ref": "#/components/responses/MissingAuth"
}
} }
} }
}, },
@@ -39,35 +51,46 @@
"post": { "post": {
"operationId": "run_rohs_check", "operationId": "run_rohs_check",
"summary": "异步启动 RoHS 检核", "summary": "异步启动 RoHS 检核",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"requestBody": { "requestBody": {
"required": true, "required": true,
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/RunCheckRequest" } "schema": {
"$ref": "#/components/schemas/RunCheckRequest"
}
} }
} }
}, },
"responses": { "responses": {
"200": { "200": {
"description": "启动成功", "description": "启动成功;或已有 RoHS 检核进行中,返回 ok=false/error_code=check_running",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/RunCheckSuccessResponse" } "schema": {
"oneOf": [
{
"$ref": "#/components/schemas/RunCheckSuccessResponse"
},
{
"$ref": "#/components/schemas/CheckRunningResponse"
}
]
}
} }
} }
}, },
"409": { "400": {
"description": "RoHS 检核进行中,全局不可重复启动", "$ref": "#/components/responses/BadRequest"
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/CheckRunningResponse" }
}
}
}, },
"400": { "$ref": "#/components/responses/BadRequest" }, "401": {
"401": { "$ref": "#/components/responses/Unauthorized" }, "$ref": "#/components/responses/Unauthorized"
"404": { "$ref": "#/components/responses/TaskNotFound" } },
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
} }
} }
}, },
@@ -75,20 +98,30 @@
"get": { "get": {
"operationId": "list_rohs_runs", "operationId": "list_rohs_runs",
"summary": "查询 RoHS 检核批次列表", "summary": "查询 RoHS 检核批次列表",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"parameters": [ "parameters": [
{ {
"name": "task_id", "name": "task_id",
"in": "query", "in": "query",
"required": false, "required": false,
"schema": { "type": "integer", "example": 12 }, "schema": {
"type": "integer",
"example": 12
},
"description": "可选;指定检核任务 ID 时只返回该任务批次" "description": "可选;指定检核任务 ID 时只返回该任务批次"
}, },
{ {
"name": "limit", "name": "limit",
"in": "query", "in": "query",
"required": false, "required": false,
"schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 }, "schema": {
"type": "integer",
"minimum": 1,
"maximum": 100,
"default": 20
},
"description": "返回条数,最大 100" "description": "返回条数,最大 100"
} }
], ],
@@ -97,12 +130,18 @@
"description": "成功", "description": "成功",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ListRunsResponse" } "schema": {
"$ref": "#/components/schemas/ListRunsResponse"
}
} }
} }
}, },
"401": { "$ref": "#/components/responses/Unauthorized" }, "401": {
"404": { "$ref": "#/components/responses/TaskNotFound" } "$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/TaskNotFound"
}
} }
} }
}, },
@@ -110,13 +149,18 @@
"get": { "get": {
"operationId": "get_rohs_run", "operationId": "get_rohs_run",
"summary": "查询指定检核批次", "summary": "查询指定检核批次",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"parameters": [ "parameters": [
{ {
"name": "run_id", "name": "run_id",
"in": "path", "in": "path",
"required": true, "required": true,
"schema": { "type": "integer", "example": 88 } "schema": {
"type": "integer",
"example": 88
}
} }
], ],
"responses": { "responses": {
@@ -124,12 +168,18 @@
"description": "成功", "description": "成功",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/GetRunResponse" } "schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
} }
} }
}, },
"401": { "$ref": "#/components/responses/Unauthorized" }, "401": {
"404": { "$ref": "#/components/responses/RunNotFound" } "$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
} }
} }
}, },
@@ -137,13 +187,18 @@
"get": { "get": {
"operationId": "get_latest_rohs_run", "operationId": "get_latest_rohs_run",
"summary": "查询检核任务最近一次检核", "summary": "查询检核任务最近一次检核",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"parameters": [ "parameters": [
{ {
"name": "task_id", "name": "task_id",
"in": "path", "in": "path",
"required": true, "required": true,
"schema": { "type": "integer", "example": 12 } "schema": {
"type": "integer",
"example": 12
}
} }
], ],
"responses": { "responses": {
@@ -151,12 +206,18 @@
"description": "成功", "description": "成功",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/GetRunResponse" } "schema": {
"$ref": "#/components/schemas/GetRunResponse"
}
} }
} }
}, },
"401": { "$ref": "#/components/responses/Unauthorized" }, "401": {
"404": { "$ref": "#/components/responses/RunNotFound" } "$ref": "#/components/responses/Unauthorized"
},
"404": {
"$ref": "#/components/responses/RunNotFound"
}
} }
} }
}, },
@@ -164,21 +225,28 @@
"get": { "get": {
"operationId": "download_rohs_run_excel", "operationId": "download_rohs_run_excel",
"summary": "下载检核报告 Excel(短期签名 token)", "summary": "下载检核报告 Excel(短期签名 token)",
"tags": ["RoHS Check"], "tags": [
"RoHS Check"
],
"security": [], "security": [],
"parameters": [ "parameters": [
{ {
"name": "run_id", "name": "run_id",
"in": "path", "in": "path",
"required": true, "required": true,
"schema": { "type": "integer", "example": 88 } "schema": {
"type": "integer",
"example": 88
}
}, },
{ {
"name": "token", "name": "token",
"in": "query", "in": "query",
"required": true, "required": true,
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒", "description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
"schema": { "type": "string" } "schema": {
"type": "string"
}
} }
], ],
"responses": { "responses": {
@@ -186,11 +254,16 @@
"description": "Excel 文件流", "description": "Excel 文件流",
"content": { "content": {
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"schema": { "type": "string", "format": "binary" } "schema": {
"type": "string",
"format": "binary"
}
} }
} }
}, },
"409": { "$ref": "#/components/responses/ExcelNotReady" } "409": {
"$ref": "#/components/responses/ExcelNotReady"
}
} }
} }
} }
@@ -213,20 +286,51 @@
"TaskSummary": { "TaskSummary": {
"type": "object", "type": "object",
"properties": { "properties": {
"task_id": { "type": "integer", "example": 12 }, "task_id": {
"task_no": { "type": "string", "example": "CHK202606090001" }, "type": "integer",
"name": { "type": "string", "example": "RoHS 自动检核" }, "example": 12
"enabled": { "type": "boolean" }, },
"last_status": { "type": "string", "nullable": true, "example": "success" }, "task_no": {
"last_run_at": { "type": "string", "format": "date-time", "nullable": true }, "type": "string",
"next_run_at": { "type": "string", "format": "date-time", "nullable": true } "example": "CHK202606090001"
},
"name": {
"type": "string",
"example": "RoHS 自动检核"
},
"enabled": {
"type": "boolean"
},
"last_status": {
"type": "string",
"nullable": true,
"example": "success"
},
"last_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"next_run_at": {
"type": "string",
"format": "date-time",
"nullable": true
}
} }
}, },
"RunExcel": { "RunExcel": {
"type": "object", "type": "object",
"properties": { "properties": {
"file_name": { "type": "string", "nullable": true, "example": "RUN202606090001.xlsx" }, "file_name": {
"file_size": { "type": "integer", "nullable": true, "example": 45678 }, "type": "string",
"nullable": true,
"example": "RUN202606090001.xlsx"
},
"file_size": {
"type": "integer",
"nullable": true,
"example": 45678
},
"download_url": { "download_url": {
"type": "string", "type": "string",
"nullable": true, "nullable": true,
@@ -237,111 +341,265 @@
"RunKnowledgeBase": { "RunKnowledgeBase": {
"type": "object", "type": "object",
"properties": { "properties": {
"enabled": { "type": "boolean" }, "enabled": {
"type": "boolean"
},
"sync_status": { "sync_status": {
"type": "string", "type": "string",
"nullable": true, "nullable": true,
"enum": ["skipped", "queued", "cleaning", "syncing", "ready", "success", "failed"] "enum": [
"skipped",
"queued",
"cleaning",
"syncing",
"ready",
"success",
"failed"
]
}, },
"group_id": { "type": "integer", "nullable": true }, "group_id": {
"document_id": { "type": "integer", "nullable": true }, "type": "integer",
"document_version_id": { "type": "integer", "nullable": true }, "nullable": true
"sync_job_id": { "type": "integer", "nullable": true }, },
"error_message": { "type": "string", "nullable": true } "document_id": {
"type": "integer",
"nullable": true
},
"document_version_id": {
"type": "integer",
"nullable": true
},
"sync_job_id": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
}
} }
}, },
"RunDetail": { "RunDetail": {
"type": "object", "type": "object",
"properties": { "properties": {
"run_id": { "type": "integer", "example": 88 }, "run_id": {
"run_no": { "type": "string", "example": "RUN202606090001" }, "type": "integer",
"task_id": { "type": "integer", "example": 12 }, "example": 88
"task_name": { "type": "string", "example": "RoHS 自动检核" }, },
"run_no": {
"type": "string",
"example": "RUN202606090001"
},
"task_id": {
"type": "integer",
"example": 12
},
"task_name": {
"type": "string",
"example": "RoHS 自动检核"
},
"status": { "status": {
"type": "string", "type": "string",
"enum": ["running", "success", "partial_failed", "failed", "queued", "cancelled"] "enum": [
"running",
"success",
"partial_failed",
"failed",
"queued",
"cancelled"
]
}, },
"total_count": { "type": "integer" }, "total_count": {
"success_count": { "type": "integer" }, "type": "integer"
"failed_count": { "type": "integer" }, },
"skipped_count": { "type": "integer" }, "success_count": {
"started_at": { "type": "string", "format": "date-time", "nullable": true }, "type": "integer"
"finished_at": { "type": "string", "format": "date-time", "nullable": true }, },
"duration_ms": { "type": "integer", "nullable": true }, "failed_count": {
"error_message": { "type": "string", "nullable": true }, "type": "integer"
"excel": { "$ref": "#/components/schemas/RunExcel" }, },
"knowledge_base": { "$ref": "#/components/schemas/RunKnowledgeBase" } "skipped_count": {
"type": "integer"
},
"started_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"finished_at": {
"type": "string",
"format": "date-time",
"nullable": true
},
"duration_ms": {
"type": "integer",
"nullable": true
},
"error_message": {
"type": "string",
"nullable": true
},
"excel": {
"$ref": "#/components/schemas/RunExcel"
},
"knowledge_base": {
"$ref": "#/components/schemas/RunKnowledgeBase"
}
} }
}, },
"ListTasksResponse": { "ListTasksResponse": {
"type": "object", "type": "object",
"required": ["ok", "tasks"], "required": [
"ok",
"tasks"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": true }, "ok": {
"type": "boolean",
"example": true
},
"tasks": { "tasks": {
"type": "array", "type": "array",
"items": { "$ref": "#/components/schemas/TaskSummary" } "items": {
"$ref": "#/components/schemas/TaskSummary"
}
} }
} }
}, },
"RunCheckRequest": { "RunCheckRequest": {
"type": "object", "type": "object",
"properties": { "properties": {
"task_id": { "type": "integer", "example": 12 }, "task_id": {
"task_no": { "type": "string", "example": "CHK202606090001" }, "type": "integer",
"trigger_source": { "type": "string", "default": "dify_chatflow" }, "example": 12
"conversation_id": { "type": "string", "nullable": true },
"user_message": { "type": "string", "nullable": true }
}, },
"required": ["task_id"], "task_no": {
"type": "string",
"example": "CHK202606090001"
},
"trigger_source": {
"type": "string",
"default": "dify_chatflow"
},
"conversation_id": {
"type": "string",
"nullable": true
},
"user_message": {
"type": "string",
"nullable": true
}
},
"required": [
"task_id"
],
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程" "description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
}, },
"RunCheckSuccessResponse": { "RunCheckSuccessResponse": {
"type": "object", "type": "object",
"required": ["ok", "message", "run"], "required": [
"ok",
"message",
"run"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": true }, "ok": {
"message": { "type": "string", "example": "检核已启动" }, "type": "boolean",
"run": { "$ref": "#/components/schemas/RunDetail" } "example": true
},
"message": {
"type": "string",
"example": "检核已启动"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
} }
}, },
"CheckRunningResponse": { "CheckRunningResponse": {
"type": "object", "type": "object",
"required": ["ok", "error_code", "message", "run"], "required": [
"ok",
"error_code",
"message",
"run"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": false }, "ok": {
"error_code": { "type": "string", "example": "check_running" }, "type": "boolean",
"message": { "type": "string", "example": "该检核任务正在执行中,请稍后查询结果" }, "example": false
"run": { "$ref": "#/components/schemas/RunDetail" } },
"error_code": {
"type": "string",
"example": "check_running"
},
"message": {
"type": "string",
"example": "该检核任务正在执行中,请稍后查询结果"
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
} }
}, },
"GetRunResponse": { "GetRunResponse": {
"type": "object", "type": "object",
"required": ["ok", "run"], "required": [
"ok",
"run"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": true }, "ok": {
"run": { "$ref": "#/components/schemas/RunDetail" } "type": "boolean",
"example": true
},
"run": {
"$ref": "#/components/schemas/RunDetail"
}
} }
}, },
"ListRunsResponse": { "ListRunsResponse": {
"type": "object", "type": "object",
"required": ["ok", "runs", "count"], "required": [
"ok",
"runs",
"count"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": true }, "ok": {
"count": { "type": "integer", "example": 2 }, "type": "boolean",
"example": true
},
"count": {
"type": "integer",
"example": 2
},
"runs": { "runs": {
"type": "array", "type": "array",
"items": { "$ref": "#/components/schemas/RunDetail" } "items": {
"$ref": "#/components/schemas/RunDetail"
}
} }
} }
}, },
"ErrorResponse": { "ErrorResponse": {
"type": "object", "type": "object",
"required": ["ok", "error_code", "message"], "required": [
"ok",
"error_code",
"message"
],
"properties": { "properties": {
"ok": { "type": "boolean", "example": false }, "ok": {
"error_code": { "type": "string" }, "type": "boolean",
"message": { "type": "string" } "example": false
},
"error_code": {
"type": "string"
},
"message": {
"type": "string"
}
} }
} }
}, },
@@ -350,13 +608,23 @@
"description": "鉴权失败", "description": "鉴权失败",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": { "examples": {
"missing_auth": { "missing_auth": {
"value": { "ok": false, "error_code": "missing_auth", "message": "missing_auth" } "value": {
"ok": false,
"error_code": "missing_auth",
"message": "missing_auth"
}
}, },
"invalid_auth": { "invalid_auth": {
"value": { "ok": false, "error_code": "invalid_auth", "message": "invalid_auth" } "value": {
"ok": false,
"error_code": "invalid_auth",
"message": "invalid_auth"
}
} }
} }
} }
@@ -366,7 +634,9 @@
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY", "description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": { "example": {
"ok": false, "ok": false,
"error_code": "missing_auth", "error_code": "missing_auth",
@@ -379,7 +649,9 @@
"description": "请求参数无效", "description": "请求参数无效",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": { "example": {
"ok": false, "ok": false,
"error_code": "invalid_request", "error_code": "invalid_request",
@@ -392,7 +664,9 @@
"description": "检核任务不存在", "description": "检核任务不存在",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": { "example": {
"ok": false, "ok": false,
"error_code": "task_not_found", "error_code": "task_not_found",
@@ -405,7 +679,9 @@
"description": "检核批次不存在", "description": "检核批次不存在",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": { "example": {
"ok": false, "ok": false,
"error_code": "run_not_found", "error_code": "run_not_found",
@@ -418,7 +694,9 @@
"description": "Excel 尚未生成", "description": "Excel 尚未生成",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "$ref": "#/components/schemas/ErrorResponse" }, "schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": { "example": {
"ok": false, "ok": false,
"error_code": "excel_not_ready", "error_code": "excel_not_ready",
@@ -430,6 +708,3 @@
} }
} }
} }
+1 -1
View File
@@ -106,7 +106,7 @@ _MAX_DIFY_RESPONSE_LEN = 4000
def _ts() -> str: def _ts() -> str:
return datetime.utcnow().isoformat() return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
def _make_step( def _make_step(
+49
View File
@@ -0,0 +1,49 @@
"""Resync PostgreSQL serial sequences after manual imports or restores."""
from __future__ import annotations
import os
import sys
from dotenv import load_dotenv
from sqlalchemy import create_engine, text
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
load_dotenv(os.path.join(ROOT, ".env.shared"))
load_dotenv(os.path.join(ROOT, ".env.dev"))
load_dotenv(os.path.join(ROOT, ".env.local"), override=True)
TABLES = ("chat_logs", "schedule_runs")
def fix_sequence(conn, table: str) -> None:
max_id = conn.execute(text(f"SELECT COALESCE(MAX(id), 0) FROM {table}")).scalar()
seq = conn.execute(
text("SELECT pg_get_serial_sequence(:table, 'id')"),
{"table": table},
).scalar()
if not seq:
print(f"{table}: no serial sequence, skipped")
return
before = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
conn.execute(text("SELECT setval(:seq, :val, true)"), {"seq": seq, "val": max_id})
after = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
print(f"{table} max_id={max_id} sequence={seq}")
print(f" before: last_value={before[0]} is_called={before[1]}")
print(f" after: last_value={after[0]} is_called={after[1]}")
def main() -> int:
url = os.environ.get("DATABASE_URL")
if not url:
print("DATABASE_URL not set", file=sys.stderr)
return 1
tables = sys.argv[1:] or TABLES
engine = create_engine(url)
with engine.begin() as conn:
for table in tables:
fix_sequence(conn, table)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+30
View File
@@ -0,0 +1,30 @@
"""One-off: resync schedule_runs.id sequence after manual imports."""
from __future__ import annotations
import os
import sys
from dotenv import load_dotenv
from sqlalchemy import create_engine, text
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
load_dotenv(os.path.join(ROOT, ".env.shared"))
load_dotenv(os.path.join(ROOT, ".env.dev"))
load_dotenv(os.path.join(ROOT, ".env.local"), override=True)
url = os.environ.get("DATABASE_URL")
if not url:
print("DATABASE_URL not set", file=sys.stderr)
sys.exit(1)
engine = create_engine(url)
with engine.begin() as conn:
max_id = conn.execute(text("SELECT COALESCE(MAX(id), 0) FROM schedule_runs")).scalar()
seq = conn.execute(text("SELECT pg_get_serial_sequence('schedule_runs', 'id')")).scalar()
before = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
conn.execute(text("SELECT setval(:seq, :val, true)"), {"seq": seq, "val": max_id})
after = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
print(f"schedule_runs max_id={max_id} sequence={seq}")
print(f"before: last_value={before[0]} is_called={before[1]}")
print(f"after: last_value={after[0]} is_called={after[1]}")
+4 -2
View File
@@ -271,8 +271,9 @@ def test_rohs_tool_running_conflict(app, client):
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id}, json={'task_id': task_id},
) )
assert res.status_code == 409 assert res.status_code == 200
data = res.get_json() data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'check_running' assert data['error_code'] == 'check_running'
@@ -331,8 +332,9 @@ def test_rohs_tool_running_conflict_is_global(app, client):
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'}, headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': second_task_id}, json={'task_id': second_task_id},
) )
assert res.status_code == 409 assert res.status_code == 200
data = res.get_json() data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'check_running' assert data['error_code'] == 'check_running'
assert data['run']['run_id'] == running_id assert data['run']['run_id'] == running_id
+7 -10
View File
@@ -7,7 +7,7 @@
}, },
"servers": [ "servers": [
{ {
"url": "http://localhost:8890", "url": "http://192.168.100.192:8890",
"description": "HXOPS_TOOLS_API_BASE" "description": "HXOPS_TOOLS_API_BASE"
} }
], ],
@@ -66,22 +66,19 @@
}, },
"responses": { "responses": {
"200": { "200": {
"description": "启动成功", "description": "启动成功;或已有 RoHS 检核进行中,返回 ok=false/error_code=check_running",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "schema": {
"oneOf": [
{
"$ref": "#/components/schemas/RunCheckSuccessResponse" "$ref": "#/components/schemas/RunCheckSuccessResponse"
}
}
}
}, },
"409": { {
"description": "RoHS 检核进行中,全局不可重复启动",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CheckRunningResponse" "$ref": "#/components/schemas/CheckRunningResponse"
} }
]
}
} }
} }
}, },
@@ -1,6 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue';
import { AlertCircle, CheckCircle2, Clock3, Download, Loader2 } from 'lucide-vue-next'; import { AlertCircle, CheckCircle2, Clock3, Download, Loader2 } from 'lucide-vue-next';
import type { ToolRunProgress } from '@/api/toolRunProgress'; import type { ToolRunProgress } from '@/api/toolRunProgress';
import { getAuthHeaders } from '@/utils/auth';
const props = defineProps<{ const props = defineProps<{
run: ToolRunProgress | null; run: ToolRunProgress | null;
@@ -9,6 +11,9 @@ const props = defineProps<{
fallbackTitle?: string; fallbackTitle?: string;
}>(); }>();
const downloadingExcel = ref(false);
const downloadError = ref('');
const statusLabel = (status?: string) => { const statusLabel = (status?: string) => {
const map: Record<string, string> = { const map: Record<string, string> = {
running: '执行中', running: '执行中',
@@ -23,7 +28,10 @@ const statusLabel = (status?: string) => {
const formatTime = (value?: string | null) => { const formatTime = (value?: string | null) => {
if (!value) return '-'; if (!value) return '-';
const date = new Date(String(value)); const normalized = String(value).match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?$/)
? `${value}Z`
: String(value);
const date = new Date(normalized);
if (Number.isNaN(date.getTime())) return String(value).replace('T', ' ').slice(0, 19); if (Number.isNaN(date.getTime())) return String(value).replace('T', ' ').slice(0, 19);
const pad = (num: number) => String(num).padStart(2, '0'); const pad = (num: number) => String(num).padStart(2, '0');
return [ return [
@@ -39,12 +47,73 @@ const formatTime = (value?: string | null) => {
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 kbSyncMeta = (status?: string | null) => {
const judgement = props.run?.judgement; const value = String(status || '').toLowerCase();
if (!judgement) return 0; if (value === 'success') {
return Number(judgement.qualified_count || 0) return { label: '知识库已同步', tone: 'border-emerald-200 bg-emerald-50 text-emerald-700', icon: 'success' };
+ Number(judgement.unqualified_count || 0) }
+ Number(judgement.manual_count || 0); if (value === 'failed') {
return { label: '知识库同步失败', tone: 'border-rose-200 bg-rose-50 text-rose-700', icon: 'failed' };
}
if (['queued', 'cleaning', 'syncing'].includes(value)) {
return { label: '知识库同步中', tone: 'border-sky-200 bg-sky-50 text-sky-700', icon: 'syncing' };
}
if (value === 'skipped') {
return { label: '知识库未同步', tone: 'border-slate-200 bg-slate-50 text-slate-600', icon: 'skipped' };
}
return { label: `知识库:${status || '未知'}`, tone: 'border-slate-200 bg-slate-50 text-slate-600', icon: 'skipped' };
};
const parseDownloadFilename = (disposition: string | null, fallback: string) => {
const value = disposition || '';
const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
const raw = utf8Match?.[1] || value.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
};
const stringifyDownloadError = (payload: any, fallback: string) => {
if (!payload) return fallback;
if (typeof payload === 'string') return payload;
if (typeof payload?.message === 'string') return payload.message;
if (typeof payload?.error === 'string') return payload.error;
if (typeof payload?.error?.message === 'string') return payload.error.message;
if (typeof payload?.code === 'string') return payload.code;
return fallback;
};
const downloadExcel = async () => {
const url = props.run?.excel?.download_url;
if (!url || downloadingExcel.value) return;
downloadingExcel.value = true;
downloadError.value = '';
try {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(stringifyDownloadError(body, `下载失败:${res.status}`));
}
const blob = await res.blob();
const filename = parseDownloadFilename(
res.headers.get('content-disposition'),
props.run?.excel?.file_name || `${props.run?.run_no || 'result'}.xlsx`,
);
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(objectUrl);
} catch (e: any) {
downloadError.value = e?.message || '下载 Excel 失败';
} finally {
downloadingExcel.value = false;
}
}; };
</script> </script>
@@ -63,7 +132,10 @@ const judgementTotal = () => {
{{ run?.title || fallbackTitle || '任务进度' }} {{ run?.title || fallbackTitle || '任务进度' }}
</div> </div>
<p class="mt-1 text-xs text-slate-500"> <p class="mt-1 text-xs text-slate-500">
<template v-if="run">批次:{{ run.run_no }} · 状态:{{ statusLabel(run.status) }}</template> <template v-if="run">
批次:{{ 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-if="loading">正在查询任务进度...</template>
<template v-else>{{ error }}</template> <template v-else>{{ error }}</template>
</p> </p>
@@ -73,18 +145,38 @@ const judgementTotal = () => {
<span v-if="run.current_step.started_at"> · 阶段开始:{{ formatTime(run.current_step.started_at) }}</span> <span v-if="run.current_step.started_at"> · 阶段开始:{{ formatTime(run.current_step.started_at) }}</span>
</p> </p>
</div> </div>
<a <div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
v-if="run?.excel?.download_url" <span
:href="run.excel.download_url" v-if="run?.knowledge_base?.sync_status"
target="_blank" class="inline-flex items-center gap-1 rounded-full border px-2.5 py-1.5 text-xs font-medium"
class="inline-flex items-center gap-1 rounded-full bg-sky-600 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-sky-700" :class="kbSyncMeta(run.knowledge_base.sync_status).tone"
:title="run.knowledge_base.error_message || kbSyncMeta(run.knowledge_base.sync_status).label"
> >
<Download class="h-3.5 w-3.5" /> <CheckCircle2 v-if="kbSyncMeta(run.knowledge_base.sync_status).icon === 'success'" class="h-3.5 w-3.5" />
下载 Excel <AlertCircle v-else-if="kbSyncMeta(run.knowledge_base.sync_status).icon === 'failed'" class="h-3.5 w-3.5" />
</a> <Loader2 v-else-if="kbSyncMeta(run.knowledge_base.sync_status).icon === 'syncing'" class="h-3.5 w-3.5 animate-spin" />
<Clock3 v-else class="h-3.5 w-3.5" />
{{ kbSyncMeta(run.knowledge_base.sync_status).label }}
</span>
<button
v-if="run?.excel?.download_url"
type="button"
:disabled="downloadingExcel"
class="inline-flex items-center gap-1 rounded-full bg-sky-600 px-3 py-1.5 text-xs font-medium text-white transition hover:bg-sky-700 disabled:cursor-not-allowed disabled:opacity-60"
@click="downloadExcel"
>
<Loader2 v-if="downloadingExcel" class="h-3.5 w-3.5 animate-spin" />
<Download v-else class="h-3.5 w-3.5" />
{{ downloadingExcel ? '下载中...' : '下载 Excel' }}
</button>
</div>
</div> </div>
<div v-if="run" class="space-y-3 px-4 py-4"> <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 class="h-2.5 overflow-hidden rounded-full bg-slate-200"> <div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
<div <div
class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500" class="h-full rounded-full bg-gradient-to-r from-sky-500 to-emerald-500 transition-all duration-500"
@@ -119,36 +211,8 @@ const judgementTotal = () => {
</div> </div>
</div> </div>
<div v-if="judgementTotal() > 0" class="rounded-xl bg-white/70 px-3 py-3"> <div v-if="run.knowledge_base?.error_message" class="rounded-xl bg-amber-50 px-3 py-2 text-xs text-amber-700">
<div class="mb-2 text-xs font-semibold text-slate-600">判定口径</div> 知识库同步错误:{{ run.knowledge_base.error_message }}
<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.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.error_message" class="text-rose-700">错误信息:{{ run.error_message }}</div>
</div> </div>
</div> </div>
</section> </section>
@@ -7,6 +7,7 @@ export interface ToolRunProgressConfig {
poll_interval_seconds?: number; poll_interval_seconds?: number;
active_url?: string; active_url?: string;
detail_url_template?: string; detail_url_template?: string;
run_id?: number | string | null;
lock_input_when_running?: boolean; lock_input_when_running?: boolean;
lock_message?: string; lock_message?: string;
} }
@@ -23,7 +24,7 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
const error = ref(''); const error = ref('');
let timer: number | undefined; let timer: number | undefined;
const enabled = computed(() => !!configRef.value?.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 isRunning = computed(() => run.value?.status === 'running');
const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value); const shouldLockInput = computed(() => Boolean(configRef.value?.lock_input_when_running) && isRunning.value);
const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成'); const lockMessage = computed(() => configRef.value?.lock_message || '当前任务执行中,请等待完成');
@@ -44,9 +45,18 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
}, interval); }, 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));
}
return cfg.active_url || '';
};
const refresh = async () => { const refresh = async () => {
const cfg = configRef.value; const cfg = configRef.value;
if (!cfg?.active_url) { const url = cfg ? resolveProgressUrl(cfg) : '';
if (!url) {
run.value = null; run.value = null;
error.value = ''; error.value = '';
clearTimer(); clearTimer();
@@ -54,7 +64,7 @@ export function useToolRunProgress(configRef: Ref<ToolRunProgressConfig | null>)
} }
loading.value = true; loading.value = true;
try { try {
const payload = await getToolRunProgress(cfg.active_url); const payload = await getToolRunProgress(url);
run.value = payload.run; run.value = payload.run;
error.value = ''; error.value = '';
} catch (e: any) { } catch (e: any) {
+53 -34
View File
@@ -441,7 +441,7 @@ const handleVoiceFeatureClick = () => {
msg.info(t('chat.devComingSoon')); msg.info(t('chat.devComingSoon'));
return; return;
} }
if (isThinking.value || isVoiceTranscribing.value || toolRunShouldLockInput.value) return; if (isThinking.value || isVoiceTranscribing.value) return;
const unavailable = getVoiceUnavailableErrorKey(); const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) { if (unavailable) {
msg.warning(t(unavailable)); msg.warning(t(unavailable));
@@ -460,6 +460,30 @@ const showGeneralFeedbackDialog = ref(false);
const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']); const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
const canUseLeaveFeature = computed(() => LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim())); const canUseLeaveFeature = computed(() => LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()));
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;
};
const shouldShowToolRunProgressAfterMessage = (msg: any) => {
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;
};
const activeToolRunId = computed(() => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const msg = messages.value[i];
if (msg?.role !== 'assistant') continue;
const runId = extractToolRunIdFromContent(msg.content);
if (runId) return runId;
}
return null;
});
const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => { const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
const extra = currentAgent.value?.extra_config || {}; const extra = currentAgent.value?.extra_config || {};
const capabilities = Array.isArray(extra.capabilities) ? extra.capabilities.map((item: unknown) => String(item)) : []; const capabilities = Array.isArray(extra.capabilities) ? extra.capabilities.map((item: unknown) => String(item)) : [];
@@ -468,19 +492,25 @@ const toolRunProgressConfig = computed<ToolRunProgressConfig | null>(() => {
if (!raw || typeof raw !== 'object') return null; if (!raw || typeof raw !== 'object') return null;
const cfg = raw as ToolRunProgressConfig; const cfg = raw as ToolRunProgressConfig;
const cid = String(conversationId.value || '').trim(); const cid = String(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; if (!cid || !cfg.active_url) return null;
const separator = cfg.active_url.includes('?') ? '&' : '?'; const separator = cfg.active_url.includes('?') ? '&' : '?';
return { return {
...cfg, ...cfg,
active_url: `${cfg.active_url}${separator}conversation_id=${encodeURIComponent(cid)}`, active_url: `${cfg.active_url}${separator}conversation_id=${encodeURIComponent(cid)}`,
run_id: null,
}; };
}); });
const { const {
run: toolRunProgress, run: toolRunProgress,
loading: toolRunProgressLoading, loading: toolRunProgressLoading,
error: toolRunProgressError, error: toolRunProgressError,
shouldLockInput: toolRunShouldLockInput,
lockMessage: toolRunLockMessage,
refresh: refreshToolRunProgress, refresh: refreshToolRunProgress,
} = useToolRunProgress(toolRunProgressConfig); } = useToolRunProgress(toolRunProgressConfig);
@@ -705,7 +735,7 @@ const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false); const showAttachmentUrlPanel = ref(false);
const canSendMessage = computed(() => { const canSendMessage = computed(() => {
if (isThinking.value || isUploadingAttachments.value || toolRunShouldLockInput.value) return false; if (isThinking.value || isUploadingAttachments.value) return false;
if (input.value.trim()) return true; if (input.value.trim()) return true;
if (isShippingNoticeAgent.value && attachments.value.length > 0) return true; if (isShippingNoticeAgent.value && attachments.value.length > 0) return true;
return false; return false;
@@ -718,7 +748,7 @@ const closeAttachmentMenu = () => {
}; };
const toggleAttachmentMenu = async () => { const toggleAttachmentMenu = async () => {
if (isThinking.value || isUploadingAttachments.value || toolRunShouldLockInput.value) return; if (isThinking.value || isUploadingAttachments.value) return;
showAttachmentMenu.value = !showAttachmentMenu.value; showAttachmentMenu.value = !showAttachmentMenu.value;
if (!showAttachmentMenu.value) { if (!showAttachmentMenu.value) {
showAttachmentUrlPanel.value = false; showAttachmentUrlPanel.value = false;
@@ -727,13 +757,13 @@ const toggleAttachmentMenu = async () => {
}; };
const selectAttachmentLocal = () => { const selectAttachmentLocal = () => {
if (!attachmentPolicy.value.canLocal || toolRunShouldLockInput.value) return; if (!attachmentPolicy.value.canLocal) return;
closeAttachmentMenu(); closeAttachmentMenu();
filePickerRef.value?.click(); filePickerRef.value?.click();
}; };
const selectAttachmentUrl = async () => { const selectAttachmentUrl = async () => {
if (!attachmentPolicy.value.canRemote || toolRunShouldLockInput.value) return; if (!attachmentPolicy.value.canRemote) return;
showAttachmentMenu.value = true; showAttachmentMenu.value = true;
showAttachmentUrlPanel.value = true; showAttachmentUrlPanel.value = true;
await nextTick(); await nextTick();
@@ -3138,10 +3168,6 @@ const reuploadShippingInventoryFromMappingForm = (msgObj: any) => {
*/ */
const handleSend = async (textOrEvent?: string | Event) => { const handleSend = async (textOrEvent?: string | Event) => {
if (toolRunShouldLockInput.value) {
msg.info(toolRunLockMessage.value);
return;
}
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value; const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
const trimmed = content.trim(); const trimmed = content.trim();
if ((shippingAutoFlowRequested.value || !trimmed) && isShippingNoticeAgent.value && attachments.value.length > 0 && !isThinking.value && !isUploadingAttachments.value) { if ((shippingAutoFlowRequested.value || !trimmed) && isShippingNoticeAgent.value && attachments.value.length > 0 && !isThinking.value && !isUploadingAttachments.value) {
@@ -3613,7 +3639,6 @@ const loadConversation = async (id: string, options?: { force?: boolean }) => {
const loaded = await listChatMessages(id, currentAgentId.value); const loaded = await listChatMessages(id, currentAgentId.value);
loadConversationState(id, Array.isArray(loaded) ? loaded : []); loadConversationState(id, Array.isArray(loaded) ? loaded : []);
if (!loaded?.length) { if (!loaded?.length) {
msg.warning(t('chat.historyEmpty'));
if (isShippingNoticeAgent.value && shippingTaskIdFromQuery.value && !isThinking.value) { if (isShippingNoticeAgent.value && shippingTaskIdFromQuery.value && !isThinking.value) {
await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } }); await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
return; return;
@@ -4654,6 +4679,15 @@ const showChatRating = ref(false);
</div> </div>
</div> </div>
<ToolRunProgressCard
v-if="shouldShowToolRunProgressAfterMessage(msg)"
:run="toolRunProgress"
:loading="toolRunProgressLoading"
:error="toolRunProgressError"
:fallback-title="toolRunProgressConfig?.title"
/>
</template> </template>
<div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start"> <div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start">
@@ -4672,21 +4706,15 @@ const showChatRating = ref(false);
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6"> <footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<div class="relative mx-auto max-w-4xl"> <div class="relative mx-auto max-w-4xl">
<ToolRunProgressCard
:run="toolRunProgress"
:loading="toolRunProgressLoading"
:error="toolRunProgressError"
:fallback-title="toolRunProgressConfig?.title"
/>
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all"> <div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<textarea <textarea
v-model="input" v-model="input"
@keydown.enter.prevent="handleSend" @keydown.enter.prevent="handleSend"
rows="1" rows="1"
:placeholder="toolRunShouldLockInput ? toolRunLockMessage : isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')" :placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent" class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent"
style="min-height: 44px; max-height: 220px;" style="min-height: 44px; max-height: 220px;"
:disabled="isThinking || isVoiceTranscribing || toolRunShouldLockInput" :disabled="isThinking || isVoiceTranscribing"
spellcheck="false" spellcheck="false"
autocorrect="off" autocorrect="off"
autocapitalize="off" autocapitalize="off"
@@ -4697,7 +4725,6 @@ const showChatRating = ref(false);
type="file" type="file"
class="hidden" class="hidden"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv" accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
:disabled="toolRunShouldLockInput"
@change="handleShippingInventorySelected" @change="handleShippingInventorySelected"
/> />
@@ -4707,7 +4734,6 @@ const showChatRating = ref(false);
multiple multiple
class="hidden" class="hidden"
:accept="attachmentPolicy.accept || undefined" :accept="attachmentPolicy.accept || undefined"
:disabled="toolRunShouldLockInput"
@change="handleLocalFilesSelected" @change="handleLocalFilesSelected"
/> />
@@ -4739,19 +4765,12 @@ const showChatRating = ref(false);
</button> </button>
<span>点发送开始处理</span> <span>点发送开始处理</span>
</div> </div>
<div
v-if="toolRunShouldLockInput"
class="px-3 pb-1 text-xs font-medium text-amber-700"
>
{{ toolRunLockMessage }}
</div>
<div class="mt-2 flex items-center justify-between px-2 pb-1"> <div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<button <button
@click="handleVoiceFeatureClick" @click="handleVoiceFeatureClick"
type="button" type="button"
:disabled="isThinking || isVoiceTranscribing || toolRunShouldLockInput" :disabled="isThinking || isVoiceTranscribing"
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')" :title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50" class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="isVoiceRecording ? 'text-red-500 animate-pulse' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'" :class="isVoiceRecording ? 'text-red-500 animate-pulse' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
@@ -4763,7 +4782,7 @@ const showChatRating = ref(false);
<button <button
@click="toggleAttachmentMenu" @click="toggleAttachmentMenu"
type="button" type="button"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput" :disabled="isThinking || isUploadingAttachments"
title="附件" title="附件"
class="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50" class="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
> >
@@ -4796,14 +4815,14 @@ const showChatRating = ref(false);
<input <input
ref="attachmentUrlInputRef" ref="attachmentUrlInputRef"
v-model="attachmentUrlInput" v-model="attachmentUrlInput"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput" :disabled="isThinking || isUploadingAttachments"
placeholder="粘贴附件 URL(http/https)" placeholder="粘贴附件 URL(http/https)"
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0" class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
@keydown.enter.prevent="addRemoteUrlAttachment" @keydown.enter.prevent="addRemoteUrlAttachment"
/> />
<button <button
type="button" type="button"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput" :disabled="isThinking || isUploadingAttachments"
@click="addRemoteUrlAttachment" @click="addRemoteUrlAttachment"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50" class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="添加" title="添加"
@@ -4812,7 +4831,7 @@ const showChatRating = ref(false);
</button> </button>
<button <button
type="button" type="button"
:disabled="isThinking || isUploadingAttachments || toolRunShouldLockInput" :disabled="isThinking || isUploadingAttachments"
@click="closeAttachmentMenu" @click="closeAttachmentMenu"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50" class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="取消" title="取消"