From 9d2fa522fa6746e43a8a6ea6274bce4e2aae2b48 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Mon, 14 Sep 2026 11:06:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(chat):=20=E5=AE=8C=E5=96=84=E9=99=84?= =?UTF-8?q?=E4=BB=B6=E9=A2=84=E8=A7=88=E4=B8=8E=E8=AE=A2=E5=8D=95=E6=8F=90?= =?UTF-8?q?=E5=8F=96=E4=BA=A4=E4=BA=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 优化聊天附件上传、预览及 PDF.js 加载 - 完善订单文档画布与审核预览体验 - 优化订单提取运行状态及发送流程 - 增强会话附件接口与相关测试覆盖 - 更新 Nginx 配置、技术文档及四语言文案 --- backend/app/api/chat/sessions.py | 14 +- backend/app/api/chat/shared.py | 21 ++- backend/tests/test_chat_user_attachments.py | 77 +++++++++-- docs/features/shipping-notice/technical.md | 2 + frontend/nginx.conf | 14 ++ .../OrderProfileEditorPage.vue | 19 ++- .../OrderProfileDocumentCanvas.spec.ts | 94 ++++++++++++- .../components/OrderProfileDocumentCanvas.vue | 128 +++++++++++++----- .../features/chat/components/ChatInputBar.vue | 10 +- .../chat/components/ChatViewContent.vue | 2 + .../shipping-review/ReviewDocumentPreview.vue | 22 +-- .../features/chat/composables/useChatPage.ts | 4 + .../chat/composables/useChatShipping.ts | 3 + .../chat/page/useChatPageSend.spec.ts | 32 ++++- .../src/features/chat/page/useChatPageSend.ts | 25 ++++ .../useChatShippingSendHandler.spec.ts | 25 ++++ .../shipping/useChatShippingSendHandler.ts | 15 +- .../useShippingOrderExtractionRuns.spec.ts | 49 ++++++- .../useShippingOrderExtractionRuns.ts | 111 ++++++++------- .../chat/utils/attachmentCard.utils.ts | 3 + frontend/src/locales/en/chat.json | 1 + frontend/src/locales/en/errors.json | 1 + frontend/src/locales/th/chat.json | 1 + frontend/src/locales/th/errors.json | 1 + frontend/src/locales/zh-CN/chat.json | 1 + frontend/src/locales/zh-CN/errors.json | 1 + frontend/src/locales/zh-TW/chat.json | 1 + frontend/src/locales/zh-TW/errors.json | 1 + frontend/src/shared/utils/pdfjs.ts | 46 +++++++ 29 files changed, 584 insertions(+), 140 deletions(-) create mode 100644 frontend/src/shared/utils/pdfjs.ts diff --git a/backend/app/api/chat/sessions.py b/backend/app/api/chat/sessions.py index a46ab083..4e359b22 100644 --- a/backend/app/api/chat/sessions.py +++ b/backend/app/api/chat/sessions.py @@ -2,8 +2,8 @@ api/chat/sessions.py 用途:处理聊天会话、历史消息与本地结构化消息路由。 -依赖:chat.shared、chat.core、ChatSession、ChatLog。 -逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。 +依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。 +逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。 """ from __future__ import annotations @@ -246,7 +246,8 @@ def save_local_message(): 保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。 核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡; - 结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。 + 结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题; + user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。 """ user = getattr(g, 'current_user', None) agent = getattr(g, 'current_agent', None) @@ -286,6 +287,13 @@ def save_local_message(): if user_query and _looks_like_review_auto_title(session.title or ''): session.title = _session_title_from_text(user_query) + # [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截 + if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload: + payload = { + **payload, + 'user_attachments': _normalize_user_attachments(payload.get('user_attachments')), + } + # 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录 # 这样能保证前端表单状态(例如已确认)被持久化 local_id = payload.get('formId') if payload and isinstance(payload, dict) else None diff --git a/backend/app/api/chat/shared.py b/backend/app/api/chat/shared.py index faf3c128..f3baf80a 100644 --- a/backend/app/api/chat/shared.py +++ b/backend/app/api/chat/shared.py @@ -43,7 +43,7 @@ from app.core.errors import ( SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice' # 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。 -CHAT_USER_ATTACHMENT_LIMIT = 20 +CHAT_USER_ATTACHMENT_LIMIT = 200 CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024 CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'} CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'} @@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]: """ 校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。 - 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。 + 核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举; + 列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。 Args: - value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。 + value: 前端 user_attachments 原始值;必须为列表。 Returns: 可安全写入 JSON 的附件快照列表;非法项目被忽略。 + + Raises: + ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。 """ if not isinstance(value, list): return [] + if len(value) > CHAT_USER_ATTACHMENT_LIMIT: + raise ValidationError( + f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})', + code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED', + details={ + 'limit': CHAT_USER_ATTACHMENT_LIMIT, + 'count': len(value), + }, + ) normalized: list[dict] = [] - for item in value[:CHAT_USER_ATTACHMENT_LIMIT]: + for item in value: if not isinstance(item, dict): continue raw_name = str(item.get('name') or '') diff --git a/backend/tests/test_chat_user_attachments.py b/backend/tests/test_chat_user_attachments.py index 90bbda70..3f00834e 100644 --- a/backend/tests/test_chat_user_attachments.py +++ b/backend/tests/test_chat_user_attachments.py @@ -1,16 +1,19 @@ """ backend/tests/test_chat_user_attachments.py -用途:验证聊天附件快照的后端白名单清洗与归属安全合并。 -依赖:chat API 附件辅助函数、pytest monkeypatch。 -逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。 +用途:验证聊天附件快照的后端白名单清洗、超限显式失败与归属安全合并。 +依赖:chat API 附件辅助函数、pytest、ValidationError。 +逻辑:覆盖敏感字段过滤、数量上限显式失败、无效项丢弃、无 ChatLog ID 不写入和有效终态合并。 """ +import pytest + from app.api.chat import ( CHAT_USER_ATTACHMENT_LIMIT, _merge_user_attachments_from_terminal_event, _normalize_user_attachments, ) +from app.core.errors import ValidationError def test_normalize_user_attachments_keeps_only_display_whitelist(): @@ -34,7 +37,7 @@ def test_normalize_user_attachments_keeps_only_display_whitelist(): }] -def test_normalize_user_attachments_limits_items_and_drops_invalid_values(): +def test_normalize_user_attachments_keeps_all_items_at_limit(): valid = { 'name': 'file.pdf', 'size': 1, @@ -42,16 +45,66 @@ def test_normalize_user_attachments_limits_items_and_drops_invalid_values(): 'type': 'document', 'source': 'local', } - items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)] - items[0] = {**valid, 'type': 'executable'} - items[1] = {**valid, 'source': 'unknown'} - items[2] = {**valid, 'size': -1, 'extension': '../pdf'} - + items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(CHAT_USER_ATTACHMENT_LIMIT)] normalized = _normalize_user_attachments(items) + assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT + assert normalized[0]['name'] == 'file-0.pdf' + assert normalized[-1]['name'] == f'file-{CHAT_USER_ATTACHMENT_LIMIT - 1}.pdf' - assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2 - assert 'size' not in normalized[0] - assert 'extension' not in normalized[0] + +def test_normalize_user_attachments_keeps_more_than_legacy_twenty(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(21)] + normalized = _normalize_user_attachments(items) + assert len(normalized) == 21 + + +def test_normalize_user_attachments_raises_when_over_limit(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 1)] + with pytest.raises(ValidationError) as exc_info: + _normalize_user_attachments(items) + err = exc_info.value + assert err.code == 'CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED' + assert err.details.get('limit') == CHAT_USER_ATTACHMENT_LIMIT + assert err.details.get('count') == CHAT_USER_ATTACHMENT_LIMIT + 1 + + +def test_normalize_user_attachments_drops_invalid_values_without_truncating_valid_tail(): + valid = { + 'name': 'file.pdf', + 'size': 1, + 'extension': 'pdf', + 'type': 'document', + 'source': 'local', + } + items = [ + {**valid, 'type': 'executable'}, + {**valid, 'source': 'unknown'}, + ] + # 旧 [:20] 会在处理完前 20 项后丢弃尾部合法项;无 slice 后应保留 tail。 + items.extend({**valid, 'type': 'executable'} for _ in range(18)) + items.append({**valid, 'name': 'kept-tail.pdf'}) + normalized = _normalize_user_attachments(items) + assert normalized == [{ + 'name': 'kept-tail.pdf', + 'type': 'document', + 'source': 'local', + 'extension': 'pdf', + 'size': 1, + }] def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch): diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 74557b8f..513d0ec3 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2642,6 +2642,8 @@ ui_state.actions -> 前端唯一可渲染的履约动作投影 6. **重试、扩批(Run 内 selection_batch)、恢复、重新识别(同谱系)不产生新的用户可见任务**;仅当用户再次发送且无法追加时,才创建新的用户可见任务。 7. 内容全集 Hash 复用(`reused=true`)仍有效;部分重叠不合并。复用结果须投影到既有用户可见任务,并写审计。 +**对话附件展示与写入契约(2026-09-14)**:用户消息气泡中的附件数量为本次发送写入 `ChatLog.payload.user_attachments` 的**顶层提交快照**条数(一次提交的 EML/PDF 等各对应一条);下方货代进度卡的文件计数可包含 EML 展开后的 Workflow Unit,二者口径 intentionally 不同。`user_attachments` 上限 **200**,前后端均禁止静默 `[:20]` 截断;超限须显式失败(后端 `CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED`,前端发送前 warning 拦截)。进度卡出现后,对应用户气泡附件区切换为 `summaryOnly`(仅摘要、不可展开),避免与进度卡重复展示。 + #### 会话级 processing 投影(阶段 1 返回) ```text diff --git a/frontend/nginx.conf b/frontend/nginx.conf index b0442e05..f061a803 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -15,8 +15,22 @@ server { } # Vite 构建产物(/assets/ 下带 hash 文件):内容寻址,文件名一变即换新缓存,可放心长期 immutable 缓存。 + # alpine nginx 默认 mime.types 无 .mjs;缺省会落到 default_type application/octet-stream。 + # 同级 include + types 合并映射。前端另用 Blob Worker 绕过错误 MIME 的 immutable 磁盘缓存。 location /assets/ { root /usr/share/nginx/html; + include /etc/nginx/mime.types; + types { + text/javascript mjs; + } + add_header Cache-Control "public, max-age=31536000, immutable"; + } + + # 显式兜底:任意 .mjs 都按 JS 模块输出(RFC 9239: text/javascript)。 + location ~* \.mjs$ { + root /usr/share/nginx/html; + default_type text/javascript; + types { } add_header Cache-Control "public, max-age=31536000, immutable"; } diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue index 55efb327..bf4faa94 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorPage.vue @@ -613,6 +613,14 @@ const coordinateCanvasActions = computed(() => ({ page: (nextPageNo) => { void selectPage(nextPageNo); }, draw: (kind) => startDrawing(kind), })); +/** 页图 token 失效时自动重签;客户端渲染失败(如 worker MIME)不得超过预算。 */ +let previewReauthInFlight = false; +let previewAutoReauthCount = 0; +const PREVIEW_AUTO_REAUTH_LIMIT = 2; +const resetPreviewAutoReauthBudget = () => { + previewAutoReauthCount = 0; +}; + /** * 共享视觉画布模型:模板差异在此处一次性被 adapter 吸收,之后所有画布事件和 props * 均只消费 visualCanvas。datasets path、集合与拆分规则不属于视觉模型,继续留在 XFA @@ -659,7 +667,10 @@ const visualCanvas = computed(() => { warningVisible: adapterWarningVisible || canvasUnavailable.value, warningText: adapterWarningText || (canvasUnavailable.value ? t('admin.shippingOrderProfiles.workbench.canvasUnavailable') : null), - retryCanvas: () => { void loadPages(); }, + retryCanvas: () => { + resetPreviewAutoReauthBudget(); + void loadPages(); + }, reportCanvasLoadFailed: () => { canvasUnavailable.value = true; }, applyAutomarkCandidates: () => false, canRender: true, @@ -814,13 +825,13 @@ const deskCanvasReadonly = computed(() => visualCanvas.value.canvasReadonly); const deskCanvasWarningVisible = computed(() => visualCanvas.value.warningVisible); const deskCanvasWarningText = computed(() => visualCanvas.value.warningText || ''); const onDeskCanvasRetry = () => visualCanvas.value.retryCanvas(); -/** 页图 token 失效时自动重签一批预览令牌,避免翻页后只能手动点「重试画布」。 */ -let previewReauthInFlight = false; +/** 页图/原 PDF 令牌 HTTP 失效时自动重签;客户端渲染失败不得走此路径(见 DocumentCanvas)。 */ const onDeskCanvasLoadFailed = async () => { - if (previewReauthInFlight) { + if (previewReauthInFlight || previewAutoReauthCount >= PREVIEW_AUTO_REAUTH_LIMIT) { visualCanvas.value.reportCanvasLoadFailed(); return; } + previewAutoReauthCount += 1; previewReauthInFlight = true; try { await loadPages(); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts index 411d498a..becbd3fd 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.spec.ts @@ -14,11 +14,12 @@ const { getDocumentMock, getPageMock, renderMock } = vi.hoisted(() => ({ renderMock: vi.fn(), })); -vi.mock('pdfjs-dist', () => ({ - GlobalWorkerOptions: {}, - getDocument: (...args: unknown[]) => getDocumentMock(...args), +vi.mock('@/shared/utils/pdfjs', () => ({ + loadPdfJs: async () => ({ + GlobalWorkerOptions: {}, + getDocument: (...args: unknown[]) => getDocumentMock(...args), + }), })); -vi.mock('pdfjs-dist/build/pdf.worker.min.mjs?url', () => ({ default: '/pdf.worker.min.mjs' })); vi.mock('@/shared/utils/auth', () => ({ getAuthHeaders: () => ({ Authorization: 'Bearer test' }) })); describe('OrderProfileDocumentCanvas PDF preview', () => { @@ -274,4 +275,89 @@ describe('OrderProfileDocumentCanvas PDF preview', () => { // 使用 PDF.js 原始像素而不是 CSS 缩放后的大小,保证回读与用户框选区域一致。 expect(drawImage).toHaveBeenCalledWith(source, 60, 160, 181, 240, 0, 0, 181, 240); }); + + it('keeps pdfCanvas mounted under pdfPreview error overlay and does not reauth on render failure', async () => { + getDocumentMock.mockReturnValue({ + promise: Promise.resolve({ + numPages: 1, + getPage: vi.fn(async () => { + throw new Error('PDF canvas is unavailable'); + }), + }), + }); + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'single-use-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { + plugins: [createI18n({ + legacy: false, + locale: 'zh-CN', + messages: { + 'zh-CN': { + admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } }, + }, + }, + })], + }, + }); + await flushPromises(); + await flushPromises(); + + // 关键断言:原 PDF 路径失败不得卸掉 canvas,否则重试/reauth 后 render 仍读到 null。 + expect(wrapper.find('canvas.pdf-page').exists()).toBe(true); + expect(wrapper.find('.canvas-error-overlay').exists()).toBe(true); + expect(wrapper.emitted('loadFailed')).toBeUndefined(); + }); + + it('reuses in-memory PDF bytes for the same single-use preview token', async () => { + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'single-use-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { plugins: [createI18n({ legacy: false, locale: 'zh', messages: { zh: {} } })] }, + }); + await flushPromises(); + await flushPromises(); + expect(fetch).toHaveBeenCalledTimes(1); + + // 改 grant 依赖重入 watch,但 pdfPreview token 不变;必须走内存缓存,否则 getdel 二次 GET=404。 + await wrapper.setProps({ + grant: { page_no: 1, preview_token: 'png-ignored' }, + pdfPreview: { preview_token: 'single-use-token' }, + }); + await flushPromises(); + await flushPromises(); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it('emits loadFailed only for preview-token HTTP failures', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 }))); + const wrapper = mount(OrderProfileDocumentCanvas, { + props: { + profileId: 71, + pdfPreview: { preview_token: 'dead-token' }, + regions: [], pageNo: 1, pageCount: 1, + }, + global: { + plugins: [createI18n({ + legacy: false, + locale: 'zh-CN', + messages: { + 'zh-CN': { + admin: { shippingOrderProfiles: { workbench: { canvasUnavailable: '受控 PDF 画布暂不可用', retryCanvas: '重试' } } }, + }, + }, + })], + }, + }); + await flushPromises(); + await flushPromises(); + expect(wrapper.emitted('loadFailed')).toHaveLength(1); + expect(wrapper.find('canvas.pdf-page').exists()).toBe(true); + }); }); diff --git a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue index df98dbcd..9ab029c1 100644 --- a/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue +++ b/frontend/src/features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue @@ -4,6 +4,9 @@ 依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion、isUnboundOrderFieldCanvasRegion。 逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动; PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token; + 原 PDF(pdf-preview)令牌亦为 Redis getdel 单次消费:同 token 字节必须缓存,且仅 HTTP 401/403/404 + 才 emit loadFailed 触发父级 reauth;画布/渲染失败不得重签,否则会空转授权风暴; + pdfPreview 错误态用 overlay,禁止 v-if 卸掉 pdfCanvas(否则 renderPdfPage 必失败); 未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除; 选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效); 拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走; @@ -16,28 +19,11 @@ import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; import { Anchor, ArrowLeft, ArrowRight, Columns3, Copy, Eraser, MessageSquareText, Minus, Plus, Redo2, RotateCcw, Rows3, Save, TableProperties, Tag, TextCursorInput, Trash2, WandSparkles } from 'lucide-vue-next'; import { getAuthHeaders } from '@/shared/utils/auth'; +import { loadPdfJs } from '@/shared/utils/pdfjs'; import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/features/admin/types/shipping-order-document-profile.types'; import { isUnboundOrderFieldCanvasRegion } from '../orderProfileForm.utils'; import type { PDFDocumentProxy } from 'pdfjs-dist'; -type PdfJsModule = typeof import('pdfjs-dist'); -let pdfjsLoader: Promise | null = null; - -/** 动态加载 PDF.js 与 worker;坐标 PDF 与 XFA 在受控管理员画布按需共用。 */ -async function loadPdfJs(): Promise { - if (!pdfjsLoader) { - pdfjsLoader = (async () => { - const [pdfjs, workerMod] = await Promise.all([ - import('pdfjs-dist'), - import('pdfjs-dist/build/pdf.worker.min.mjs?url'), - ]); - pdfjs.GlobalWorkerOptions.workerSrc = workerMod.default; - return pdfjs; - })(); - } - return pdfjsLoader; -} - const props = defineProps<{ profileId: number | null; grant?: OrderProfilePreviewPageGrant | null; @@ -107,6 +93,12 @@ const viewport = ref(null); const zoom = ref(1); /** 按页缓存已消费 token 拉取的 PNG,翻页回访不再触发一次性 token 失效。 */ const pageImageCache = new Map(); +/** + * 原 PDF 字节缓存:pdf-preview 令牌是 Redis getdel 单次消费。 + * 同 token 的并发/重入 loadPage 若再次 GET 会 404,并误触发父级 reauth 风暴。 + */ +let cachedPdfBytes: Uint8Array | null = null; +let cachedPdfToken: string | null = null; let loadGeneration = 0; let cachedProfileId: number | null = null; const zoomPercent = computed(() => Math.round(zoom.value * 100)); @@ -123,17 +115,34 @@ const emptyStateText = computed(() => ( props.emptyHint || t('admin.shippingOrderProfiles.workbench.selectBoundPdf') )); +/** + * 等待 pdfCanvas 进入 DOM。 + * 错误态曾用 v-if 卸掉 canvas;清错后仅一次 nextTick 仍可能读到 null, + * 进而抛 "PDF canvas is unavailable",被空 catch 吃掉且 0 console error。 + */ +const ensurePdfCanvas = async (): Promise<{ canvas: HTMLCanvasElement; context: CanvasRenderingContext2D }> => { + for (let attempt = 0; attempt < 10; attempt += 1) { + await nextTick(); + const el = pdfCanvas.value; + const context = el?.getContext('2d'); + if (el && context) return { canvas: el, context }; + await new Promise((resolve) => { + if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve()); + else window.setTimeout(() => resolve(), 16); + }); + } + throw new Error('PDF canvas is unavailable'); +}; + /** * 将内存中的原 PDF 按真实页面外观流绘制到 Canvas。 * 核心逻辑:坐标 PDF 与 hybrid XFA 都用 page.render(),不生成可下载 URL。 */ const renderPdfPage = async (pdf: PDFDocumentProxy) => { - await nextTick(); - const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages); + const targetPage = Math.min(Math.max(props.pageNo, 1), pdf.numPages || 1); + if (pdf.numPages < 1) throw new Error('PDF has no pages'); const page = await pdf.getPage(targetPage); - const canvas = pdfCanvas.value; - const context = canvas?.getContext('2d'); - if (!canvas || !context) throw new Error('PDF canvas is unavailable'); + const { canvas, context } = await ensurePdfCanvas(); const viewport = page.getViewport({ scale: zoom.value }); pdfPageSize.value = { width: viewport.width, height: viewport.height }; canvas.width = Math.ceil(viewport.width); @@ -142,6 +151,12 @@ const renderPdfPage = async (pdf: PDFDocumentProxy) => { pdfRendered.value = true; }; +/** 令牌失效类 HTTP 才值得父级 reauth;画布未挂载/渲染失败重签只会空转。 */ +const isPreviewTokenHttpError = (error: unknown): boolean => { + if (!(error instanceof Error)) return false; + return /^HTTP (401|403|404)\b/.test(error.message); +}; + /** * 回收某次会话内全部页图 blob;切换样本 Profile 或卸载时调用。 */ @@ -149,6 +164,8 @@ const clearPageImageCache = () => { for (const url of pageImageCache.values()) URL.revokeObjectURL(url); pageImageCache.clear(); inflightPageLoads.clear(); + cachedPdfBytes = null; + cachedPdfToken = null; }; /** 同一页的并发拉取共用一个 Promise,成功后必入缓存(即使请求已过期)。 */ @@ -206,13 +223,21 @@ const loadPage = async () => { || `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`; if (props.pdfPreview) { imageUrl.value = ''; - const response = await fetch( - `${previewPath}?preview_token=${encodeURIComponent(props.pdfPreview.preview_token)}`, - { headers: getAuthHeaders(), cache: 'no-store' }, - ); - if (!response.ok) throw new Error(`HTTP ${response.status}`); + const token = props.pdfPreview.preview_token; + let bytes: Uint8Array; + if (cachedPdfToken === token && cachedPdfBytes) { + bytes = cachedPdfBytes; + } else { + const response = await fetch( + `${previewPath}?preview_token=${encodeURIComponent(token)}`, + { headers: getAuthHeaders(), cache: 'no-store' }, + ); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + bytes = new Uint8Array(await response.arrayBuffer()); + cachedPdfBytes = bytes; + cachedPdfToken = token; + } const pdfjs = await loadPdfJs(); - const bytes = new Uint8Array(await response.arrayBuffer()); pdfDocument = await pdfjs.getDocument({ data: bytes, enableXfa: true }).promise; if (generation !== loadGeneration) return; emit('pageCount', pdfDocument.numPages); @@ -224,7 +249,7 @@ const loadPage = async () => { const blobUrl = await fetchPageImage(previewPath, grant); if (generation !== loadGeneration) return; imageUrl.value = blobUrl; - } catch { + } catch (error) { if (generation !== loadGeneration) return; const fallback = props.grant ? pageImageCache.get(String(props.grant.page_no)) : null; if (fallback) { @@ -234,7 +259,10 @@ const loadPage = async () => { } imageUrl.value = ''; internalLoadError.value = t('admin.shippingOrderProfiles.workbench.canvasUnavailable'); - emit('loadFailed'); + // 仅令牌 HTTP 失效才通知父级重签;画布未挂载/PDF.js 渲染失败重签只会烧掉单次 token。 + if (isPreviewTokenHttpError(error) || (props.grant && error instanceof Error && /^HTTP \d+/.test(error.message))) { + emit('loadFailed'); + } } finally { if (generation === loadGeneration) loading.value = false; } @@ -442,10 +470,20 @@ defineExpose({ watch(() => [props.grant?.page_no, props.grant?.preview_token, props.pdfPreview?.preview_token], () => { void loadPage(); }, { immediate: true }); watch(() => props.pageNo, async (value) => { pageInput.value = value; - if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument); + if (!(props.pdfPreview && pdfDocument)) return; + try { + await renderPdfPage(pdfDocument); + } catch { + /* 翻页时画布可能短暂卸载;下一次 load/retry 会恢复 */ + } }); watch(zoom, async () => { - if (props.pdfPreview && pdfDocument) await renderPdfPage(pdfDocument); + if (!(props.pdfPreview && pdfDocument)) return; + try { + await renderPdfPage(pdfDocument); + } catch { + /* 缩放同翻页:避免未捕获 Promise 干扰控制台 */ + } }); onBeforeUnmount(() => { endMove(); @@ -494,7 +532,8 @@ onBeforeUnmount(() => {
{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}
- + @@ -635,7 +680,20 @@ onBeforeUnmount(() => { cursor: pointer; } .canvas-retry:hover { border-color: #60a5fa; background: #26364f; } -.canvas-work-area { display: flex; min-height: 0; flex: 1; gap: .6rem; } +.canvas-work-area { position: relative; display: flex; min-height: 0; flex: 1; gap: .6rem; } +.canvas-error-overlay { + position: absolute; + inset: 0; + z-index: 8; + display: grid; + place-content: center; + gap: .75rem; + background: rgb(15 23 42 / .82); + color: #fecaca; + font-size: .875rem; + text-align: center; + padding: 1rem; +} .canvas-work-area.readonly { gap: 0; } .canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; } .canvas-viewport.panning { cursor: grab; } diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index c9f44a90..a1e4384f 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -4,6 +4,7 @@ * 依赖:lucide 图标、附件完整性判断工具。 * 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。 * 同时支持采购合同双文件输入控件:底部左区放附件/合同等工具,右区语音与发送并排;采购合同审查用专用上传按钮,不展示通用回形针附件入口。 + * 货代订单抽取提交中(isOrderExtractionSubmitting)时发送钮展示 Loader,免责声明区提示提交中。 */