diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index bf44edfd..f473086c 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -67,6 +67,19 @@ def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_b } +def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool: + """ + 判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。 + + 核心逻辑: + - 仅对“固资管理”Agent 生效; + - 仅当用户本轮问题可脱离上一轮上下文独立完成时触发; + - 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。 + """ + from app.services.text2sql import Text2SQLService + + return Text2SQLService._should_reset_provider_conversation(query, agent_proxy) + def _session_title_from_text(text: str) -> str: value = str(text or '').strip() if not value: @@ -1187,6 +1200,19 @@ def chat_completions(): status='running', ) external_conversation_id = session.external_conversation_id + if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy): + current_app.logger.info( + '[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s', + request_id, + session.session_id, + external_conversation_id, + query, + ) + session.external_conversation_id = None + session.updated_at = datetime.utcnow() + session.last_active_at = datetime.utcnow() + db.session.commit() + external_conversation_id = None else: session = _ensure_chat_session( user_id, diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 9534df0f..585ab618 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -63,31 +63,6 @@ def _ok(payload: dict): return ok(payload, request_id=getattr(g, 'request_id', None)) -def _notice_file_type(upload) -> str | None: - """提取上传文件 MIME type;为空时返回 None,保持响应字段稳定。""" - return str(getattr(upload, 'mimetype', '') or '').strip() or None - - -def _build_notice_file_summary( - *, - total_files: int, - accepted_files: list[dict], - rejected_files: list[dict], -) -> dict[str, object]: - """ - 构建工作台批量上传预检摘要。 - - 核心逻辑:把可建任务文件与被拒文件统一汇总到 file_summary,供前端回显和测试断言使用。 - """ - return { - 'total_files': total_files, - 'accepted_count': len(accepted_files), - 'rejected_count': len(rejected_files), - 'accepted_files': accepted_files, - 'rejected_files': rejected_files, - } - - @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): """列出当前用户可见的发货任务,可按批次与处理状态过滤。""" @@ -123,77 +98,27 @@ def workspace_create_shipping_batch_from_notices(): raise ValidationError('files is required') from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice.notice_upload import ( + build_notice_file_summary, cleanup_temp_notice_uploads, - extract_notice_text, - guess_source_type, - max_notice_chars, - save_temp_notice_upload, + intake_temp_notice_uploads, ) conversation_id = str(request.form.get('conversation_id') or '').strip() temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex) - notice_items: list[dict] = [] - accepted_files: list[dict] = [] - rejected_files: list[dict] = [] try: - for index, upload in enumerate(uploads, start=1): - raw = upload.read() or b'' - filename = upload.filename or 'notice' - source_type = guess_source_type(filename) - source_file_type = _notice_file_type(upload) - text = '' - warnings: list[str] = [] - try: - saved_path = save_temp_notice_upload(temp_request_id, index, filename, raw) - text, meta = extract_notice_text(saved_path) - warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] - except Exception as exc: - warnings = [f'notice_extract_failed:{exc}'] - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - warnings.append(f'notice_text_truncated:{limit}') - notice_items.append( - { - 'source_type': source_type, - 'source_file_name': filename, - 'source_file_type': source_file_type, - 'raw_text': text, - 'warnings': warnings, - } - ) - accepted_files.append( - { - 'filename': filename, - 'source_type': source_type, - 'source_file_type': source_file_type, - 'text_length': len(text), - 'warnings': warnings, - } - ) - continue - rejected_files.append( - { - 'filename': filename, - 'source_type': source_type, - 'source_file_type': source_file_type, - 'reason': 'empty_text', - 'message': 'notice text is empty after extraction', - 'warnings': warnings, - } - ) + accepted, rejected = intake_temp_notice_uploads(temp_request_id, uploads) finally: cleanup_temp_notice_uploads(temp_request_id) - file_summary = _build_notice_file_summary( + file_summary = build_notice_file_summary( total_files=len(uploads), - accepted_files=accepted_files, - rejected_files=rejected_files, + accepted=accepted, + rejected=rejected, ) + notice_items = [item.to_notice_item() for item in accepted] if not notice_items: raise ValidationError( 'all uploaded files failed extraction or contained no parseable text', - details={'rejected_files': rejected_files, 'file_summary': file_summary}, + details={'rejected_files': file_summary['rejected_files'], 'file_summary': file_summary}, ) payload = { @@ -327,8 +252,11 @@ def workspace_create_shipping_task_from_notice(): if not upload: raise ValidationError('file is required') from app.services.shipping_notice import tools as shipping_tools - from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload - source_type = guess_source_type(upload.filename or '') + from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type + filename = upload.filename or 'notice' + raw = upload.read() or b'' + source_file_type = notice_source_file_type(upload) + source_type = guess_source_type(filename) conversation_id = str(request.form.get('conversation_id') or '').strip() payload = {'user_id': user.id, 'source_type': source_type} if conversation_id: @@ -337,29 +265,25 @@ def workspace_create_shipping_task_from_notice(): task_id = str(created.get('task_id') or '').strip() if not task_id: raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500) - raw = upload.read() or b'' - saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw) - text, meta = extract_notice_text(saved_path) - if not text: + intake = intake_notice_attachment( + filename=filename, + raw=raw, + source_file_type=source_file_type, + storage='task', + task_no=task_id, + ) + if not intake.accepted: from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint - return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)}) - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}') - task = ShippingTask.query.filter_by(task_no=task_id).first() - if task: - task.raw_content = text - db.session.commit() + return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)}) task = ShippingTask.query.filter_by(task_no=task_id).first() if task: - task.source_file_name = str(upload.filename or '').strip() or task.source_file_name - task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type + task.raw_content = intake.text + task.source_file_name = intake.filename or task.source_file_name + task.source_file_type = intake.source_file_type or task.source_file_type db.session.commit() from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator orchestrator_started = start_task_orchestrator(task_id) - return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) + return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) @workspace_shipping_notice_bp.route('/shipping-tasks//replace-notice', methods=['POST']) def workspace_replace_shipping_task_notice(task_no: str): @@ -372,28 +296,25 @@ def workspace_replace_shipping_task_notice(task_no: str): if not upload: raise ValidationError('file is required') from app.services.shipping_notice import task_workflow - from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload - raw = upload.read() or b'' - filename = upload.filename or 'notice' - saved_path = save_task_notice_upload(task.task_no, filename, raw) - text, meta = extract_notice_text(saved_path) - warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - warnings.append(f'notice_text_truncated:{limit}') - task.source_type = guess_source_type(filename) or task.source_type + from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type + intake = intake_notice_attachment( + filename=upload.filename or 'notice', + raw=upload.read() or b'', + source_file_type=notice_source_file_type(upload), + storage='task', + task_no=task.task_no, + ) + task.source_type = intake.source_type or task.source_type result = task_workflow.replace_task_notice( task, - raw_text=text, - source_file_name=filename, - source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(), - warnings=warnings, + raw_text=intake.text, + source_file_name=intake.filename, + source_file_type=intake.source_file_type, + warnings=list(intake.warnings), ) data = result.setdefault('data', {}) if isinstance(data, dict): - data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})} + data['notice_upload'] = intake.to_notice_upload_meta() return _ok(result) @workspace_shipping_notice_bp.route('/shipping-tasks/', methods=['GET']) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 36e6f916..83ae013d 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -40,7 +40,6 @@ from app.models import ChatLog from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled from app.services.integration_api import IntegrationApiService - class DifyService: """Dify service wrapper.""" VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on") diff --git a/backend/app/services/fixed_assets_snapshot.py b/backend/app/services/fixed_assets_snapshot.py index ceac1256..a5b9270a 100644 --- a/backend/app/services/fixed_assets_snapshot.py +++ b/backend/app/services/fixed_assets_snapshot.py @@ -617,12 +617,83 @@ INSERT INTO fixed_assets ( return normalized_tokens[:5] @classmethod - def _build_where_clause(cls, query: str, user_context: dict[str, Any] | None = None) -> tuple[str, list[str]]: + def _build_generic_keyword_match_clause(cls, keyword: str) -> tuple[str, list[str]]: + """为宽泛资产关键词查询构造更严格的直连字段匹配条件。 + + AI 触发时机:当用户只输入“资讯有哪些资产”“电脑有哪些资产”这类宽泛关键词时, + 不能再把 `remark_normalized` 这类兜底字段也纳入匹配,否则容易把仅备注命中的低质量记录一起带出。 + + Args: + keyword: 已抽取的资产关键词。 + + Returns: + tuple[str, list[str]]: SQL 条件片段与对应参数。 + """ + like_keyword = f"%{keyword.upper()}%" + clause = ( + "(" + "UPPER(COALESCE(asset_name, '')) LIKE ? " + "OR UPPER(COALESCE(asset_name2, '')) LIKE ? " + "OR UPPER(COALESCE(specification, '')) LIKE ? " + "OR UPPER(COALESCE(location_name, '')) LIKE ? " + "OR UPPER(COALESCE(custodian_name, '')) LIKE ? " + "OR UPPER(COALESCE(department_name, '')) LIKE ? " + "OR UPPER(COALESCE(vendor_name, '')) LIKE ?" + ")" + ) + return clause, [like_keyword] * 7 + + @classmethod + def _generic_result_quality_guard_sql(cls) -> str: + """过滤仅命中名称但关键业务列几乎全空的低质量快照记录。 + + AI 触发时机:宽泛关键词查询会返回很多候选记录,其中一部分只有资产名称, + 其余关键字段(编号、保管人、部门、账套、供应商、状态、数量、取得日期)全部为空。 + 这类记录即使展示出来也无法支撑业务判断,应在快照层直接剔除。 + """ + informative_fields = ( + "asset_no", + "custodian_name", + "department_name", + "operating_center_code", + "vendor_name", + "asset_status", + "quantity", + "acquisition_date", + ) + checks = [f"TRIM(COALESCE({field}, '')) <> ''" for field in informative_fields] + return "(" + " OR ".join(checks) + ")" + + @classmethod + def _generic_result_quality_score_sql(cls) -> str: + """为宽泛关键词查询生成字段完整度评分,便于优先展示高质量记录。""" + informative_fields = ( + "asset_no", + "custodian_name", + "department_name", + "operating_center_code", + "vendor_name", + "asset_status", + "quantity", + "acquisition_date", + ) + return " + ".join( + f"CASE WHEN TRIM(COALESCE({field}, '')) <> '' THEN 1 ELSE 0 END" + for field in informative_fields + ) + + @classmethod + def _build_where_clause( + cls, + query: str, + user_context: dict[str, Any] | None = None, + ) -> tuple[str, list[str], dict[str, Any]]: """根据用户问句生成本地快照过滤条件。""" from app.services.text2sql import Text2SQLService clauses: list[str] = [] params: list[str] = [] + query_profile = {"uses_generic_keyword_search": False} advanced_conds = Text2SQLService._extract_advanced_asset_conditions(query) asset_code = advanced_conds.get("asset_code") or Text2SQLService._extract_asset_code(query) @@ -681,31 +752,10 @@ INSERT INTO fixed_assets ( params.append(f"%{explicit_department.upper()}%") if should_use_generic_keyword_search: - normalized_keyword = cls._normalize_search_text(asset_name) - clauses.append( - "(" - "UPPER(COALESCE(asset_name, '')) LIKE ? " - "OR UPPER(COALESCE(asset_name2, '')) LIKE ? " - "OR UPPER(COALESCE(specification, '')) LIKE ? " - "OR UPPER(COALESCE(location_name, '')) LIKE ? " - "OR UPPER(COALESCE(custodian_name, '')) LIKE ? " - "OR UPPER(COALESCE(department_name, '')) LIKE ? " - "OR UPPER(COALESCE(vendor_name, '')) LIKE ? " - "OR UPPER(COALESCE(remark_normalized, '')) LIKE ?" - ")" - ) - params.extend( - [ - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{asset_name.upper()}%", - f"%{normalized_keyword}%", - ] - ) + generic_clause, generic_params = cls._build_generic_keyword_match_clause(asset_name) + clauses.append(generic_clause) + params.extend(generic_params) + query_profile["uses_generic_keyword_search"] = True normalized_user = user_context or {} if Text2SQLService._is_self_asset_query(query): @@ -730,7 +780,7 @@ INSERT INTO fixed_assets ( params.append(f"%{token}%") where_sql = " AND ".join(clauses) if clauses else "1=1" - return where_sql, params + return where_sql, params, query_profile @classmethod def query_assets( @@ -745,7 +795,7 @@ INSERT INTO fixed_assets ( if not cls.is_snapshot_available(): return ["Error"], [("固定资产快照尚未生成,请稍后重试。",)], 0 - where_sql, params = cls._build_where_clause(query, user_context=user_context) + where_sql, params, query_profile = cls._build_where_clause(query, user_context=user_context) deduped_assets_cte = """ WITH deduped_assets AS ( SELECT * @@ -764,6 +814,24 @@ WITH deduped_assets AS ( WHERE dedupe_rn = 1 ) """.strip() + filtered_assets_cte = "" + result_source_name = "deduped_assets" + order_by_sql = "asset_no" + if query_profile.get("uses_generic_keyword_search"): + filtered_assets_cte = f""" +, filtered_assets AS ( + SELECT *, + {cls._generic_result_quality_score_sql()} AS quality_score + FROM deduped_assets + WHERE {cls._generic_result_quality_guard_sql()} +) +""".rstrip() + result_source_name = "filtered_assets" + order_by_sql = ( + "quality_score DESC, " + "CASE WHEN TRIM(COALESCE(asset_no, '')) = '' THEN 1 ELSE 0 END, " + "asset_no, asset_name" + ) visible_select = """ asset_no AS "资产编号", asset_name AS "资产名称", @@ -784,15 +852,17 @@ accounting_date AS "入账日期" """.strip() list_sql = f""" {deduped_assets_cte} +{filtered_assets_cte} SELECT {visible_select} -FROM deduped_assets +FROM {result_source_name} WHERE {where_sql} -ORDER BY asset_no +ORDER BY {order_by_sql} LIMIT ? OFFSET ? """.strip() count_sql = f""" {deduped_assets_cte} -SELECT COUNT(*) FROM deduped_assets WHERE {where_sql} +{filtered_assets_cte} +SELECT COUNT(*) FROM {result_source_name} WHERE {where_sql} """.strip() conn = sqlite3.connect(cls._latest_db_path()) diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 4bfd8b76..c573fff2 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -11,6 +11,7 @@ from app.services.shipping_notice.state_machine import ( ALL_ACTION_IDS, ALL_CHECKPOINT_IDS, CHECKPOINT_REGISTRY, + CP_INVENTORY_SOURCE_REVIEW, TaskTransition, TaskUiState, action_buttons_for_checkpoint, @@ -21,6 +22,7 @@ from app.services.shipping_notice.state_machine import ( human_options_for_checkpoint, human_options_for_task, human_options_for_task_or_checkpoint, + inventory_source_action_buttons, resolve_task_ui_state, ui_state_for_checkpoint, upload_req_options_for_task, diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py index 3c80a6b5..048f57e4 100644 --- a/backend/app/services/shipping_notice/notice_upload.py +++ b/backend/app/services/shipping_notice/notice_upload.py @@ -1,9 +1,10 @@ """ services/shipping_notice/notice_upload.py -用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。 +用途:管理发货通知附件上传、文本抽取、截断与统一接入结果模型。 依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。 -逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow;批量上传的预检临时文件也在这里统一落盘和清理。 +逻辑:workspace 单票建单、批量建单、重新上传三条入口均经 intake_notice_attachment / intake_temp_notice_uploads + 收敛抽取与失败分流;下游 extract/task_workflow 只消费 NoticeIntakeResult。 """ from __future__ import annotations @@ -11,10 +12,11 @@ from __future__ import annotations import base64 import re import shutil +from dataclasses import dataclass, field from email import policy from email.parser import BytesParser from pathlib import Path -from typing import Any +from typing import Any, Literal, Sequence from flask import current_app @@ -228,3 +230,237 @@ def max_notice_chars() -> int: except Exception: value = 0 return value if value > 0 else 200000 + + +EMPTY_TEXT_REJECT_MESSAGE = "notice text is empty after extraction" + + +@dataclass(frozen=True) +class NoticeIntakeResult: + """ + 发货通知附件统一接入结果。 + + 三条工作台入口(单票建单 / 批量建单 / 重新上传)共用本模型,避免抽取、截断与失败分流行为漂移。 + """ + + filename: str + source_type: str + source_file_type: str | None + text: str + warnings: list[str] = field(default_factory=list) + meta: dict[str, Any] = field(default_factory=dict) + status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text" + saved_path: Path | None = None + + @property + def accepted(self) -> bool: + """抽取成功且正文非空。""" + return self.status == "accepted" + + def to_notice_item(self) -> dict[str, Any]: + """批量建单 notice_items 载荷项。""" + return { + "source_type": self.source_type, + "source_file_name": self.filename, + "source_file_type": self.source_file_type, + "raw_text": self.text, + "warnings": list(self.warnings), + } + + def to_accepted_file_summary(self) -> dict[str, Any]: + """批量预检 accepted_files 摘要项。""" + return { + "filename": self.filename, + "source_type": self.source_type, + "source_file_type": self.source_file_type, + "text_length": len(self.text), + "warnings": list(self.warnings), + } + + def to_rejected_file_summary(self) -> dict[str, Any]: + """批量预检 rejected_files 摘要项。""" + return { + "filename": self.filename, + "source_type": self.source_type, + "source_file_type": self.source_file_type, + "reason": "empty_text", + "message": EMPTY_TEXT_REJECT_MESSAGE, + "warnings": list(self.warnings), + } + + def to_notice_upload_meta(self) -> dict[str, Any]: + """API data.notice_upload 响应字段。""" + payload = dict(self.meta) if isinstance(self.meta, dict) else {} + payload["filename"] = self.filename + payload["warnings"] = list(self.warnings) + return payload + + +def notice_source_file_type(upload: Any) -> str | None: + """从 Flask/Werkzeug 上传对象提取 MIME type;为空时返回 None。""" + return str(getattr(upload, "mimetype", "") or "").strip() or None + + +def truncate_notice_text(text: str, warnings: list[str] | None = None) -> tuple[str, list[str]]: + """ + 按配置上限截断发货通知正文,并追加统一 warning 标记。 + + Args: + text: 抽取后的原始正文。 + warnings: 已有 warnings,截断时会追加 notice_text_truncated 项。 + + Returns: + tuple[str, list[str]]: (截断后正文, 更新后的 warnings)。 + """ + ws = list(warnings or []) + limit = max_notice_chars() + if len(text) > limit: + text = text[:limit] + ws.append(f"notice_text_truncated:{limit}") + return text, ws + + +def intake_notice_attachment( + *, + filename: str, + raw: bytes, + source_file_type: str | None = None, + storage: Literal["task", "temp"] = "task", + task_no: str | None = None, + temp_request_id: str | None = None, + temp_index: int = 1, +) -> NoticeIntakeResult: + """ + 单份发货通知附件的统一接入:落盘 → 抽取 → 截断 → 失败分流。 + + 核心逻辑:三条工作台入口均调用本函数,保证 empty_text / extract_failed 与 warnings 语义一致。 + + Args: + filename: 原始文件名。 + raw: 文件字节流。 + source_file_type: MIME type,可为空。 + storage: task 为任务级持久化目录;temp 为批量预检临时目录。 + task_no: storage=task 时必填。 + temp_request_id: storage=temp 时必填。 + temp_index: storage=temp 时文件序号,避免同名覆盖。 + + Returns: + NoticeIntakeResult: 含 accepted / empty_text / extract_failed 状态与截断后正文。 + """ + name = str(filename or "").strip() or "notice" + source_type = guess_source_type(name) + saved_path: Path | None = None + text = "" + meta: dict[str, Any] = {} + warnings: list[str] = [] + status: Literal["accepted", "empty_text", "extract_failed"] = "empty_text" + + try: + if storage == "task": + if not task_no: + raise ValueError("task_no is required for task storage") + saved_path = save_task_notice_upload(task_no, name, raw or b"") + else: + if not temp_request_id: + raise ValueError("temp_request_id is required for temp storage") + saved_path = save_temp_notice_upload(temp_request_id, temp_index, name, raw or b"") + text, meta = extract_notice_text(saved_path) + warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else [] + except Exception as exc: + warnings = [f"notice_extract_failed:{exc}"] + status = "extract_failed" + return NoticeIntakeResult( + filename=name, + source_type=source_type, + source_file_type=source_file_type, + text="", + warnings=warnings, + meta=meta if isinstance(meta, dict) else {}, + status=status, + saved_path=saved_path, + ) + + if not str(text or "").strip(): + return NoticeIntakeResult( + filename=name, + source_type=source_type, + source_file_type=source_file_type, + text="", + warnings=warnings, + meta=meta if isinstance(meta, dict) else {}, + status="empty_text", + saved_path=saved_path, + ) + + text, warnings = truncate_notice_text(text, warnings) + return NoticeIntakeResult( + filename=name, + source_type=source_type, + source_file_type=source_file_type, + text=text, + warnings=warnings, + meta=meta if isinstance(meta, dict) else {}, + status="accepted", + saved_path=saved_path, + ) + + +def intake_temp_notice_uploads( + temp_request_id: str, + uploads: Sequence[Any], +) -> tuple[list[NoticeIntakeResult], list[NoticeIntakeResult]]: + """ + 批量建单入口:逐份附件接入并在 finally 外由调用方清理临时目录。 + + Args: + temp_request_id: 请求级临时目录 ID。 + uploads: Flask request.files 中的上传对象序列。 + + Returns: + tuple[list, list]: (accepted 结果列表, rejected 结果列表)。 + """ + accepted: list[NoticeIntakeResult] = [] + rejected: list[NoticeIntakeResult] = [] + for index, upload in enumerate(uploads, start=1): + raw = upload.read() or b"" + result = intake_notice_attachment( + filename=upload.filename or "notice", + raw=raw, + source_file_type=notice_source_file_type(upload), + storage="temp", + temp_request_id=temp_request_id, + temp_index=index, + ) + if result.accepted: + accepted.append(result) + else: + rejected.append(result) + return accepted, rejected + + +def build_notice_file_summary( + *, + total_files: int, + accepted: Sequence[NoticeIntakeResult], + rejected: Sequence[NoticeIntakeResult], +) -> dict[str, Any]: + """ + 构建批量上传预检摘要,供前端回显与测试断言。 + + Args: + total_files: 请求内附件总数。 + accepted: 接入成功的结果列表。 + rejected: 接入失败的结果列表。 + + Returns: + dict: total/accepted/rejected 计数与文件明细。 + """ + accepted_files = [item.to_accepted_file_summary() for item in accepted] + rejected_files = [item.to_rejected_file_summary() for item in rejected] + return { + "total_files": total_files, + "accepted_count": len(accepted_files), + "rejected_count": len(rejected_files), + "accepted_files": accepted_files, + "rejected_files": rejected_files, + } diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 81cae770..f10569d0 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -151,6 +151,51 @@ class Text2SQLService: "当前登录用户", "登录用户", ) + _ASSET_CONTEXT_DEPENDENT_MARKERS = ( + "这个", + "这个资产", + "该资产", + "这台", + "这个设备", + "这个人", + "这个部门", + "这些", + "上述", + "上面", + "前面", + "刚才", + "上一条", + "上一个", + "同一个", + "它", + "它的", + "其", + "他的", + "她的", + ) + _ASSET_RESET_SAFE_INTENT_MARKERS = ( + "明细", + "列表", + "统计", + "查询", + "查下", + "看下", + "看看", + "有多少", + "多少", + "多少台", + "状态", + "规格", + "型号", + "账套", + "保管人", + "保管部门", + "存放位置", + "位置", + "供应商", + "取得日期", + "入账日期", + ) _ASSET_CODE_HINT_PATTERN = re.compile( r"(?:资产编号|财产编号|资产编码|设备编号|编号|设备|资产|固资|固定资产)\s*(?:为|是|=|:|:)?\s*([A-Za-z][A-Za-z0-9_-]{4,30})", re.IGNORECASE, @@ -547,6 +592,68 @@ class Text2SQLService: or any(marker.lower() in sql_text.lower() for marker in cls._ASSET_TABLE_MARKERS) ) + @classmethod + def _is_context_dependent_asset_query(cls, query: str) -> bool: + """判断固资问句是否依赖上一轮上下文。 + + AI 触发时机:当用户说“这个资产”“上面那条”“它的状态”等省略表达时, + 不能贸然重置 provider conversation,否则会把真正依赖上下文的追问切断。 + """ + text = cls._strip_asset_query_prefix(query) + if not text: + return False + if cls._extract_asset_code(text): + return False + if cls._has_explicit_asset_scope(text) or cls._is_self_asset_query(text): + return False + if cls._extract_advanced_asset_conditions(text): + return False + if cls._extract_explicit_asset_name(text): + return False + if cls._extract_asset_name_combo_keyword(text): + return False + if cls._extract_asset_name_keyword(text): + return False + return any(marker in text for marker in cls._ASSET_CONTEXT_DEPENDENT_MARKERS) + + @classmethod + def _should_reset_provider_conversation(cls, query: str, agent=None) -> bool: + """判断固资查询是否应主动切断上游会话上下文。 + + AI 触发时机:固资管理中的多数查询本质上都是“本轮文本可独立完成”的单轮检索。 + 当上一轮返回超大结果时,继续复用 Dify 会话容易把 token 撑爆;此时应保留本地历史会话, + 但把上游 provider conversation 重置为空,让当前这轮按独立查询执行。 + + Args: + query: 用户当前输入的问题文本。 + agent: 当前会话 Agent,仅固资管理 Agent 会进入该策略。 + + Returns: + bool: True 表示当前问题可脱离旧上下文独立执行,应切断上游会话; + False 表示当前问题明显依赖上一轮上下文,或根本不是固资管理问题。 + """ + text = cls._strip_asset_query_prefix(query) + if not text or not cls._is_asset_management_agent(agent): + return False + if not cls._looks_like_asset_query(text): + return False + if cls._is_context_dependent_asset_query(text): + return False + + if cls._extract_asset_code(text): + return True + if cls._has_explicit_asset_scope(text) or cls._is_self_asset_query(text): + return True + if cls._extract_advanced_asset_conditions(text): + return True + if cls._extract_explicit_asset_name(text): + return True + if cls._extract_asset_name_combo_keyword(text): + return True + if cls._extract_asset_name_keyword(text): + return True + return any(marker in text for marker in cls._ASSET_RESET_SAFE_INTENT_MARKERS) + @staticmethod def _normalize_user_context(user) -> dict: if user is None: diff --git a/backend/tests/test_notice_intake.py b/backend/tests/test_notice_intake.py new file mode 100644 index 00000000..fc0a9b93 --- /dev/null +++ b/backend/tests/test_notice_intake.py @@ -0,0 +1,142 @@ +""" +tests/test_notice_intake.py + +用途:验证发货通知附件统一接入服务的抽取、截断与失败分流语义。 +依赖:notice_upload.intake_notice_attachment、truncate_notice_text。 +逻辑:保证单票/批量/重传三条入口共用同一 intake 结果模型,避免行为漂移。 +""" + +from __future__ import annotations + +from io import BytesIO + + +def test_truncate_notice_text_appends_warning(app): + """正文超长时应截断并追加 notice_text_truncated warning。""" + from app.services.shipping_notice.notice_upload import truncate_notice_text + + with app.app_context(): + app.config["SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS"] = 10 + text, warnings = truncate_notice_text("abcdefghijklmnop", []) + + assert text == "abcdefghij" + assert warnings == ["notice_text_truncated:10"] + + +def test_intake_notice_attachment_accepts_txt(app, tmp_path): + """任务级接入应落盘、抽取并标记 accepted。""" + from app.services.shipping_notice.notice_upload import intake_notice_attachment + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + with app.app_context(): + result = intake_notice_attachment( + filename="notice-a.txt", + raw="客户:ACME\nA001 x 10".encode("utf-8"), + source_file_type="text/plain", + storage="task", + task_no="SN-INTAKE-001", + ) + + assert result.accepted is True + assert result.status == "accepted" + assert "A001" in result.text + assert result.to_notice_item()["source_file_name"] == "notice-a.txt" + assert result.to_notice_upload_meta()["filename"] == "notice-a.txt" + assert result.saved_path is not None + assert result.saved_path.exists() + + +def test_intake_notice_attachment_empty_text_is_rejected(app, tmp_path, monkeypatch): + """抽取空文本时应标记 empty_text,供批量入口分流到 rejected_files。""" + from app.services.shipping_notice import notice_upload + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + monkeypatch.setattr( + notice_upload, + "extract_notice_text", + lambda saved_path: ("", {"warnings": ["ocr_empty"], "file_type": "pdf"}), + ) + + with app.app_context(): + result = notice_upload.intake_notice_attachment( + filename="scan.pdf", + raw=b"%PDF-1.4", + source_file_type="application/pdf", + storage="temp", + temp_request_id="req-empty", + temp_index=1, + ) + + assert result.accepted is False + assert result.status == "empty_text" + rejected = result.to_rejected_file_summary() + assert rejected["reason"] == "empty_text" + assert rejected["warnings"] == ["ocr_empty"] + + +def test_intake_temp_notice_uploads_splits_accepted_and_rejected(app, tmp_path, monkeypatch): + """批量接入应分别返回 accepted / rejected,并生成统一 file_summary。""" + from app.services.shipping_notice import notice_upload + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + + def fake_extract(saved_path): + name = str(saved_path).replace("\\", "/") + if name.endswith("/notice-a.txt"): + return "客户:ACME\nA001 x 10", {"warnings": [], "file_type": "txt"} + return "", {"warnings": ["ocr_empty"], "file_type": "pdf"} + + monkeypatch.setattr(notice_upload, "extract_notice_text", fake_extract) + + class _Upload: + def __init__(self, name: str, raw: bytes, mimetype: str): + self.filename = name + self._raw = raw + self.mimetype = mimetype + + def read(self): + return self._raw + + uploads = [ + _Upload("notice-a.txt", b"ok", "text/plain"), + _Upload("notice-b.pdf", b"%PDF-1.4", "application/pdf"), + ] + + with app.app_context(): + accepted, rejected = notice_upload.intake_temp_notice_uploads("req-batch", uploads) + summary = notice_upload.build_notice_file_summary( + total_files=len(uploads), + accepted=accepted, + rejected=rejected, + ) + + assert len(accepted) == 1 + assert len(rejected) == 1 + assert summary["accepted_count"] == 1 + assert summary["rejected_count"] == 1 + assert summary["accepted_files"][0]["filename"] == "notice-a.txt" + assert summary["rejected_files"][0]["filename"] == "notice-b.pdf" + + +def test_intake_notice_attachment_extract_failure(app, tmp_path, monkeypatch): + """抽取异常时应标记 extract_failed 并保留 notice_extract_failed warning。""" + from app.services.shipping_notice import notice_upload + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path) + monkeypatch.setattr( + notice_upload, + "extract_notice_text", + lambda saved_path: (_ for _ in ()).throw(RuntimeError("ocr down")), + ) + + with app.app_context(): + result = notice_upload.intake_notice_attachment( + filename="broken.pdf", + raw=BytesIO(b"%PDF").read(), + storage="task", + task_no="SN-INTAKE-FAIL", + ) + + assert result.accepted is False + assert result.status == "extract_failed" + assert result.warnings[0].startswith("notice_extract_failed:") diff --git a/debug-rpa-trigger-missing.md b/debug-rpa-trigger-missing.md new file mode 100644 index 00000000..150c41ab --- /dev/null +++ b/debug-rpa-trigger-missing.md @@ -0,0 +1,21 @@ +# [OPEN] debug-rpa-trigger-missing + +## 现象 +- 用户点击“重试 RPA”后,界面出现“已重新触发 RPA 库存导出。若长时间无结果,可手动重试,或上传库存 Excel。”之类提示。 +- 但用户怀疑实际并没有真正触发 RPA。 + +## 当前范围 +- 仅收集“重试 RPA”从前端点击到后端写 trigger 的运行时证据。 +- 在拿到证据前,不修改业务逻辑。 + +## 待证伪假设 +- H1:前端按钮点击后没有真正调用 `workspace-action`/`submit-decision`,只是本地 UI 文本更新了。 +- H2:前端请求已经发出,但请求参数里的 `taskNo`/`decision` 不对,导致后端没有走到 `retry_rpa` 分支。 +- H3:后端进入了 `retry_rpa` 分支,但 `write_inventory_export_trigger()` 返回空,实际没有生成 trigger 文件。 +- H4:后端确实写出了 trigger,但工作台刷新拿到的是旧状态或旧消息,造成“看起来没触发”。 +- H5:当前显示的这段文案不是本轮点击实时产生,而是旧消息残留/复用。 + +## 计划 +- 1. 先查看现有前后端运行日志,确认是否已有直接证据。 +- 2. 若证据不足,只增加最小插桩,打通“点击 -> 请求 -> 后端 decision -> trigger 写入”链路。 +- 3. 复现一次并按证据排除假设。 diff --git a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue index d9776a08..f717faba 100644 --- a/frontend/src/features/chat/components/messages/ChatMessageBubble.vue +++ b/frontend/src/features/chat/components/messages/ChatMessageBubble.vue @@ -162,17 +162,17 @@ const FIXED_ASSET_HEADER_LABELS: Record = { specification: '规格型号', account_period: '账套', operating_center_code: '账套', - custodian_person: '保管人姓名', - custodian_name: '保管人姓名', - custodian_dept: '保管部门名称', - department_name: '保管部门名称', + custodian_person: '保管人', + custodian_name: '保管人', + custodian_dept: '保管部门', + department_name: '保管部门', storage_location: '存放位置名称', location_name: '存放位置名称', asset_status: '资产状态', reserved_field: '预留残值', residual_value: '预留残值', - supplier: '供应厂商', - vendor_name: '供应厂商', + supplier: '供应商', + vendor_name: '供应商', asset_nature: '资产性质', nature: '资产性质', amount_local: '本币金额(元)', @@ -180,8 +180,8 @@ const FIXED_ASSET_HEADER_LABELS: Record = { quantity: '数量', unit: '计量单位', unit_of_measurement: '计量单位', - acquisition_date: '取得日期', - acquired_date: '取得日期', + acquisition_date: '取得时间', + acquired_date: '取得时间', accounting_date: '入账日期', recorded_date: '入账日期', created_at: '创建时间', @@ -189,6 +189,18 @@ const FIXED_ASSET_HEADER_LABELS: Record = { updated_at: '更新时间', snapshot_time: '快照时间', }; +const FIXED_ASSET_CANONICAL_COLUMNS = [ + { key: 'id', label: '序号', aliases: ['id'] }, + { key: 'asset_id', label: '资产编号', aliases: ['asset_id', 'asset_no'] }, + { key: 'asset_name', label: '资产名称', aliases: ['asset_name'] }, + { key: 'custodian_person', label: '保管人', aliases: ['custodian_person', 'custodian_name'] }, + { key: 'custodian_dept', label: '保管部门', aliases: ['custodian_dept', 'department_name'] }, + { key: 'account_period', label: '账套', aliases: ['account_period', 'operating_center_code'] }, + { key: 'supplier', label: '供应商', aliases: ['supplier', 'vendor_name'] }, + { key: 'asset_status', label: '资产状态', aliases: ['asset_status'] }, + { key: 'quantity', label: '数量', aliases: ['quantity'] }, + { key: 'acquisition_date', label: '取得时间', aliases: ['acquisition_date', 'acquired_date'] }, +] as const; const INLINE_DIALOG_PAGE_SIZE = 15; /** @@ -237,6 +249,24 @@ function localizeInlineTableHeader(header: string): string { return FIXED_ASSET_HEADER_LABELS[normalizedHeader] || header || '-'; } +/** + * 将固定资产时间字段统一裁剪为“年月日”。 + * 核心逻辑:优先提取 `YYYY-MM-DD` 或 `YYYY/MM/DD` 形式;若无法识别标准日期,则保留原始值避免误改内容。 + * @param value - 原始时间文本。 + * @returns 仅保留年月日的展示值。 + */ +function formatInlineDateOnly(value: string): string { + const normalized = String(value ?? '').trim(); + if (!normalized) return ''; + const dateMatch = normalized.match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/); + if (!dateMatch) return normalized; + const year = dateMatch[1] || ''; + const month = dateMatch[2] || ''; + const day = dateMatch[3] || ''; + if (!year || !month || !day) return normalized; + return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`; +} + /** * 统一表格中的空值展示。 * 核心逻辑:对空串、短横线、null/none 等占位值统一显示“无”,但保留数字 0 与正常文本。 @@ -262,6 +292,19 @@ function findInlineTableHeaderIndex(headers: string[], aliases: string[]): numbe return headers.findIndex((header) => normalizedAliases.includes(String(header || '').trim().toLowerCase())); } +/** + * 判断当前 CSV 是否为固定资产明细导出结构。 + * 核心逻辑:按业务关键列做命中检测,只有命中固定资产列集时才收敛为指定 10 列,避免影响其他 Agent 的 CSV 预览。 + * @param headers - CSV 原始表头。 + * @returns 是否按固定资产明细规则处理。 + */ +function isFixedAssetInlineTable(headers: string[]): boolean { + return FIXED_ASSET_CANONICAL_COLUMNS + .filter((column) => column.key !== 'id') + .filter((column) => findInlineTableHeaderIndex(headers, [...column.aliases]) >= 0) + .length >= 5; +} + /** * 将用户输入与单元格内容统一成可搜索的文本。 * 核心逻辑:统一 trim + lowerCase,避免筛选时受大小写和首尾空白干扰。 @@ -288,9 +331,37 @@ function serializeCsvRows(rows: string[][]): string { }).join(',')).join('\r\n'); } +/** + * 按固定资产业务要求抽取并重排列顺序。 + * 核心逻辑:只输出指定的 10 个业务字段;若某列缺失则补“无”,并把取得时间统一裁剪为年月日。 + * @param rawHeaders - CSV 原始表头。 + * @param dataRows - 原始数据行。 + * @returns 规范化后的表头与数据行。 + */ +function buildFixedAssetInlineTable(rawHeaders: string[], dataRows: string[][]): InlinePreviewTable { + const headers = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.label); + const canonicalHeaders = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.key); + const allRows = dataRows.map((row, rowIndex) => FIXED_ASSET_CANONICAL_COLUMNS.map((column) => { + if (column.key === 'id') return String(rowIndex + 1); + const columnIndex = findInlineTableHeaderIndex(rawHeaders, [...column.aliases]); + const rawValue = columnIndex >= 0 ? row[columnIndex] ?? '' : ''; + const normalizedValue = column.key === 'acquisition_date' + ? formatInlineDateOnly(rawValue) + : rawValue; + return normalizeInlineTableCell(normalizedValue); + })); + return { + rawHeaders: canonicalHeaders, + headers, + allRows, + totalRows: dataRows.length, + isCsv: true, + }; +} + /** * 将 CSV 文本转成结构化表格,供聊天文件弹窗展示全部数据。 - * 核心逻辑:首行先做中文列名转换;若存在 id 列则重写为从 1 递增的序号,确保弹窗与下载文件显示一致。 + * 核心逻辑:固定资产明细优先收敛为指定业务列与日期格式;其他 CSV 保持原表头映射,避免误伤通用附件预览。 * @param file - 当前预览文件。 * @returns 表头、完整数据行和总行数。 */ @@ -313,6 +384,9 @@ function buildInlinePreviewTable(file: InlineDownloadFile): InlinePreviewTable { const headerLine = lines[0] || ''; const rawHeaders = parseCsvLine(headerLine); const dataRows = lines.slice(1).map((line) => parseCsvLine(line)); + if (isFixedAssetInlineTable(rawHeaders)) { + return buildFixedAssetInlineTable(rawHeaders, dataRows); + } const idColumnIndex = rawHeaders.findIndex((header) => String(header || '').trim().toLowerCase() === 'id'); const headers = rawHeaders.map((header) => localizeInlineTableHeader(header)); const allRows = dataRows.map((row, rowIndex) => rawHeaders.map((_, columnIndex) => { diff --git a/frontend/src/features/chat/composables/useChat.ts b/frontend/src/features/chat/composables/useChat.ts index 21d86ebc..0f53a422 100644 --- a/frontend/src/features/chat/composables/useChat.ts +++ b/frontend/src/features/chat/composables/useChat.ts @@ -246,6 +246,22 @@ export function useChat() { ); }; + /** + * 判断当前消息列表里是否已经出现“用户可感知为完成态”的上一轮回答。 + * + * 说明: + * - 固资管理的第一轮大结果常常已经把完整表格和分析展示出来,但 SSE 终态还会晚 1~2 秒; + * - 若这时用户继续提问,不应再把发送动作死锁在 `isThinking=true` 上。 + */ + const hasVisibleCompletedAssistantReply = (items: ChatMessage[]) => { + for (let i = items.length - 1; i >= 0; i -= 1) { + const message = items[i]; + if (message?.role !== 'assistant') continue; + return looksLikeCompletedAssistantReply(String(message.content || '')); + } + return false; + }; + /** * 对“已看到完整报告但流未结束”的情况做兜底收尾。 * @@ -330,6 +346,41 @@ export function useChat() { return String(message ?? 'Unknown error'); }; + /** + * 从 workflow_finished 失败事件中提取用户可读错误。 + * + * 说明: + * - Dify Chatflow 失败时常以 `workflow_finished + data.status=failed` 返回,HTTP 仍是 200; + * - 若这里只按“终态成功”处理,页面会出现“没有任何响应”; + * - 因此需要优先从 top-level / nested data / error 对象里抽取失败文案。 + */ + const extractWorkflowFailureMessage = (data: Record) => { + if (String(data.event || '') !== 'workflow_finished') return ''; + const workflowData = data.data && typeof data.data === 'object' + ? data.data as Record + : {}; + const isFailed = String(workflowData.status || '').toLowerCase() === 'failed'; + if (!isFailed) return ''; + const candidates = [ + data.message, + data.description, + data.error, + workflowData.message, + workflowData.description, + workflowData.error, + workflowData.errmsg, + ]; + for (const candidate of candidates) { + const normalized = formatStreamError(candidate).trim(); + if (!normalized || normalized === 'Unknown error') continue; + if (/maximum context length|input_tokens/i.test(normalized)) { + return '当前会话上下文过长,模型无法继续回答。请新建对话后重新查询该资产编号。'; + } + return normalized; + } + return '工作流执行失败,请稍后重试'; + }; + const streamErrorLabels = (): StreamErrorLabels => ({ networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'), partialInterrupted: t('chat.streamError.partialInterrupted'), @@ -350,7 +401,12 @@ export function useChat() { ) => { const displayQuery = String(context?.display_query || query || '').trim(); clearLikelyCompletedStreamTimer(); - cancelActiveStream(); + const shouldDetachPreviousStream = Boolean(activeStreamController.value) && hasVisibleCompletedAssistantReply(messages.value); + if (shouldDetachPreviousStream) { + detachActiveStreamFromView(); + } else { + cancelActiveStream(); + } const controller = new AbortController(); activeStreamController.value = controller; const runViewId = viewId.value; @@ -478,8 +534,13 @@ export function useChat() { if (currentBotMsg) applyEventMetadata(currentBotMsg, data); } } else if (eventName === 'message_end' || eventName === 'workflow_finished') { + const workflowFailureMessage = extractWorkflowFailureMessage(data); hasTerminalEvent = true; ignoreFurtherStreamEvents = true; + // [STEP 2] 一旦拿到终态事件,当前轮回答在用户视角已经结束; + // 这里立刻把旧流从活动视图脱离,允许用户继续提问,同时让底层连接在后台自然读到 EOF, + // 避免下一次 sendMessage 先 abort 旧请求,导致网络面板残留 ERR_ABORTED。 + detachActiveStreamFromView(); const relay = (data.hxops_relay || {}) as Record; if (relay.total_relay_ms != null) { // eslint-disable-next-line no-console @@ -487,9 +548,14 @@ export function useChat() { `[chat-perf] hxops relay first_chunk=${String(relay.first_chunk_ms ?? '')}ms total=${String(relay.total_relay_ms ?? '')}ms`, ); } - run.status = 'done'; + run.status = workflowFailureMessage ? 'error' : 'done'; clearLikelyCompletedStreamTimer(); if (messages.value === runMessages) isThinking.value = false; + if (workflowFailureMessage) { + const botMsg = ensureBotMessage(); + if (!botMsg) continue; + applyStreamErrorToMessage(botMsg, workflowFailureMessage, streamErrorLabels()); + } if (typeof data.answer === 'string' && data.answer.length > 0) { const botMsg = ensureBotMessage(); if (!botMsg) continue; @@ -523,6 +589,9 @@ export function useChat() { } else if (eventName === 'error') { const botMsg = ensureBotMessage(); if (!botMsg) continue; + // [STEP 2] SSE error 对用户来说也是当前轮终态,脱离活动视图后可继续发下一问, + // 同时保留底层连接在后台自然收尾,避免后续交互误触 abort。 + detachActiveStreamFromView(); applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels()); run.status = 'error'; clearLikelyCompletedStreamTimer(); diff --git a/frontend/src/features/chat/page/useChatPageSend.ts b/frontend/src/features/chat/page/useChatPageSend.ts index 4fe56d16..ebe8f2aa 100644 --- a/frontend/src/features/chat/page/useChatPageSend.ts +++ b/frontend/src/features/chat/page/useChatPageSend.ts @@ -8,6 +8,29 @@ import type { ChatMessage } from '../types/chat.types'; import type { ChatUploadFileSpec } from '../types/shipping.types'; import type { ComputedRef, Ref } from 'vue'; +const looksLikeCompletedAssistantReply = (content: string) => { + if (!content) return false; + return ( + content.includes('
') + || content.includes('**查询结果如下:**') + || content.includes('**错误详情**') + || content.includes('[FILE_START]') + || content.includes('【💡 数据概述】') + || content.includes('【📊 数据预览】') + || content.includes('【📈 数据分析汇总报告】') + || content.includes('系统为您从数据库中检索到共计') + ); +}; + +const canContinueSendWhileThinking = (messages: ChatMessage[]) => { + for (let i = messages.length - 1; i >= 0; i -= 1) { + const message = messages[i]; + if (message?.role !== 'assistant') continue; + return looksLikeCompletedAssistantReply(String(message.content || '')); + } + return false; +}; + export interface ChatPageSendContext { input: Ref; messages: Ref; @@ -52,8 +75,9 @@ export interface ChatPageSendContext { export function createChatPageSendApi(ctx: ChatPageSendContext) { const canSendMessage = computed(() => { - if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false; - if (ctx.input.value.trim()) return true; + const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value); + if (ctx.isUploadingAttachments.value) return false; + if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking; if (ctx.allowsSendWithAttachmentsOnly.value) return true; return false; }); @@ -61,10 +85,11 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) { const handleSend = async (textOrEvent?: string | Event) => { const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value; const trimmed = content.trim(); + const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value); if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) { return; } - if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) { + if (!trimmed || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) { return; } if (ctx.tryHandleLeaveSend(content)) { diff --git a/frontend/src/features/kb/views/KbWorkspaceView.vue b/frontend/src/features/kb/views/KbWorkspaceView.vue index 32ece3e9..44050380 100644 --- a/frontend/src/features/kb/views/KbWorkspaceView.vue +++ b/frontend/src/features/kb/views/KbWorkspaceView.vue @@ -3,7 +3,8 @@ * features/kb/views/KbWorkspaceView.vue * 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。 */ -import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Settings, Trash2, Upload } from 'lucide-vue-next'; +import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Settings, SquareCheck, Trash2, Upload } from 'lucide-vue-next'; +import PaginationBar from '@/shared/components/PaginationBar.vue'; import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue'; import { useKbWorkspace } from '../composables/useKbWorkspace'; @@ -45,14 +46,6 @@ const kb = useKbWorkspace({ embedded: props.embedded });
-
- -
-
- - - -
-
-
-
- -
-
- {{ kb.t('kbWorkspace.documents.selectedCount', { selected: kb.selectedDocuments.length, total: kb.filteredDocuments.length }) }} - {{ kb.t('kbWorkspace.documents.showingRange', { start: kb.pagedDocumentRange.start, end: kb.pagedDocumentRange.end }) }} +
+ +
+ + +
+ +
+
+ +
@@ -403,121 +374,111 @@ const kb = useKbWorkspace({ embedded: props.embedded }); ? 'border-brand-200 bg-brand-50/50 border-brand-200' : 'border-default'" > -
-
- -
- - -
- {{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }} - {{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }} +
+
+
+ +
+ - {{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }} +
+ {{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }} + {{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }} + +
+
+ {{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }} +
+
+ +
+ + + + +
+
+ +
+ + {{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }} + +
- {{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }} + {{ badge.label }}:{{ badge.value }}
- -
-
- {{ badge.label }}:{{ badge.value }} -
-
- -
- - - - -
-
-
- {{ kb.t('kbWorkspace.documents.pageInfo', { page: kb.documentListPage, totalPages: kb.filteredDocumentTotalPages, total: kb.filteredDocuments.length }) }} -
-
- - -
-
+ v-model:page="kb.documentListPage" + v-model:page-size="kb.documentListPageSize" + :total="kb.filteredDocuments.length" + :pages="kb.filteredDocumentTotalPages" + :page-size-options="[...kb.DOCUMENT_PAGE_SIZE_OPTIONS]" + />
diff --git a/frontend/src/locales/en/kb.json b/frontend/src/locales/en/kb.json index 28bc6997..5a844013 100644 --- a/frontend/src/locales/en/kb.json +++ b/frontend/src/locales/en/kb.json @@ -1,4 +1,4 @@ -{ +{ "kbDifySettings": { "title": "Dify Settings", "subtitle": "Manage Dify connection and default sync parameters for the knowledge base module.", @@ -168,8 +168,8 @@ "infoTip": "Basic document entries in this group. Uploading files creates documents and starts cleaning automatically.", "uploadPath": "Upload path", "uploadFile": "Upload file", - "batchClean": "Clean data", - "batchCleanCount": "Clean data ({count})", + "batchClean": "Batch clean", + "batchCleanCount": "Batch clean ({count})", "batchSync": "Batch sync", "batchSyncCount": "Batch sync ({count})", "batchDelete": "Batch delete", @@ -390,3 +390,4 @@ } } } + diff --git a/frontend/src/locales/th/kb.json b/frontend/src/locales/th/kb.json index 039e0247..56e191fa 100644 --- a/frontend/src/locales/th/kb.json +++ b/frontend/src/locales/th/kb.json @@ -1,4 +1,4 @@ -{ +{ "kbDifySettings": { "title": "ตั้งค่า Dify", "subtitle": "จัดการการเชื่อมต่อ Dify และค่าซิงค์เริ่มต้นของโมดูลคลังความรู้", @@ -168,8 +168,8 @@ "infoTip": "รายการเอกสารพื้นฐานในกลุ่มนี้ การอัปโหลดไฟล์จะสร้างเอกสารและเริ่มทำความสะอาดอัตโนมัติ", "uploadPath": "อัปโหลดจาก path", "uploadFile": "อัปโหลดไฟล์", - "batchClean": "ทำความสะอาดข้อมูล", - "batchCleanCount": "ทำความสะอาดข้อมูล ({count})", + "batchClean": "ทำความสะอาดเป็นชุด", + "batchCleanCount": "ทำความสะอาดเป็นชุด ({count})", "batchSync": "ซิงค์เป็นชุด", "batchSyncCount": "ซิงค์เป็นชุด ({count})", "batchDelete": "ลบเป็นชุด", @@ -390,3 +390,4 @@ } } } + diff --git a/frontend/src/locales/zh-CN/kb.json b/frontend/src/locales/zh-CN/kb.json index b32daae8..8e553639 100644 --- a/frontend/src/locales/zh-CN/kb.json +++ b/frontend/src/locales/zh-CN/kb.json @@ -1,4 +1,4 @@ -{ +{ "kbDifySettings": { "title": "Dify 设置", "subtitle": "管理知识库模块使用的 Dify 连接和默认同步参数。", @@ -168,8 +168,8 @@ "infoTip": "当前分组下的基础文档条目,上传文件后将自动创建文档并开始清洗流程。", "uploadPath": "上传路径", "uploadFile": "上传文件", - "batchClean": "清洗数据", - "batchCleanCount": "清洗数据({count})", + "batchClean": "批量清洗", + "batchCleanCount": "批量清洗({count})", "batchSync": "批量同步", "batchSyncCount": "批量同步({count})", "batchDelete": "批量删除", @@ -390,3 +390,4 @@ } } } + diff --git a/frontend/src/locales/zh-TW/kb.json b/frontend/src/locales/zh-TW/kb.json index 383fa075..4b47b053 100644 --- a/frontend/src/locales/zh-TW/kb.json +++ b/frontend/src/locales/zh-TW/kb.json @@ -1,4 +1,4 @@ -{ +{ "kbDifySettings": { "title": "Dify 設定", "subtitle": "管理知識庫模組使用的 Dify 連線和預設同步參數。", @@ -168,8 +168,8 @@ "infoTip": "當前分組下的基礎文檔條目,上傳文件後將自動創建文檔並開始清洗流程。", "uploadPath": "上傳路徑", "uploadFile": "上傳文件", - "batchClean": "清洗數據", - "batchCleanCount": "清洗數據({count})", + "batchClean": "批量清洗", + "batchCleanCount": "批量清洗({count})", "batchSync": "批量同步", "batchSyncCount": "批量同步({count})", "batchDelete": "批量刪除", @@ -390,3 +390,4 @@ } } } +