/** * features/chat/page/useChatPageSend.ts * 用途:编排聊天消息发送、业务前置拦截、复制与重新生成。 * 依赖:统一 BusinessError、剪贴板工具、Chat 消息与附件参数类型。 * 逻辑:附件上传成功后调用 Dify SSE;仅在消息发送成功后清空附件,失败时保留供重试。 * 兼容:依次处理货代附件、采购合同、请假与货代文本前置拦截。 * 货代路径另受 hasBlockingNoticeIntake / isOrderExtractionSubmitting 约束 canSendMessage。 */ import { computed } from 'vue'; import { BusinessError } from '@/shared/api/client'; import { copyTextToClipboard } from '@/shared/utils/clipboard'; import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types'; import type { SendMessageLifecycleHooks } from '../composables/useChat'; import type { ChatUploadFileSpec } from '../types/shipping.types'; import type { ChatMessageSendResult } from '../types/chat-turn.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; isThinking: Ref; currentAgentId: ComputedRef; selectedKb: Ref; isUploadingAttachments: Ref; attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>; attachments: Ref; allowsSendWithAttachmentsOnly: ComputedRef; buildFileSpecsForSend: () => Promise; createMessageAttachmentSnapshots: () => ChatMessageAttachment[]; clearAttachments: () => void; sendMessage: ( content: string, agentId: number, kb: string, files: ChatUploadFileSpec[], context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ) => Promise; refreshHistoryAfterSend: () => Promise; refreshConversationAfterSend?: () => Promise; tryHandleShippingAttachmentAutoFlow: ( textOrEvent: string | Event | undefined, content: string, trimmed: string, ) => Promise; tryHandleLeaveSend: (content: string) => boolean; tryHandleShippingSend: ( textOrEvent: string | Event | undefined, content: string, trimmed: string, ) => Promise; tryHandleProcurementContractSend: ( textOrEvent: string | Event | undefined, content: string, trimmed: string, ) => Promise; refreshToolRunProgressAfterSend: () => Promise; prepareToolRunProgressBeforeSend: () => Promise; msg: { warning: (text: string) => void; info: (text: string) => void }; t: (key: string, values?: Record) => string; copiedIndex: Ref; getChatContext?: () => { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }; onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise; /** 货代 Intake 仍在上传/解析时返回 true,用于早禁用发送。 */ hasBlockingNoticeIntake?: () => boolean; /** 订单抽取统一提交进行中;为 true 时禁用发送并展示 Loader。 */ isOrderExtractionSubmitting?: Ref; } /** * 组装聊天页发送 API:canSendMessage / handleSend / 复制 / 重新生成。 * 核心逻辑:货代 blocking/submitting 优先禁用;附件失败保留、成功后清空。 * @param ctx - 页面发送所需的响应式状态与业务钩子。 * @returns 发送相关计算属性与方法。 */ export function createChatPageSendApi(ctx: ChatPageSendContext) { /** * 是否允许点击发送。 * 核心逻辑:上传中、订单抽取提交中、或 Intake 阻塞解析时一律 false;其余沿用输入/附件/thinking 规则。 */ const canSendMessage = computed(() => { if (ctx.isOrderExtractionSubmitting?.value) return false; if (ctx.hasBlockingNoticeIntake?.()) return false; const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value); if (ctx.isUploadingAttachments.value) return false; if (ctx.input.value.trim()) return !ctx.isThinking.value || allowSendWhileThinking; if ( ctx.attachments.value.length > 0 && ctx.attachmentPolicy.value.anyEnabled && (!ctx.isThinking.value || allowSendWhileThinking) ) return true; if (ctx.allowsSendWithAttachmentsOnly.value) return true; return false; }); /** * 处理发送:依次尝试货代附件自动流、采购合同、请假、货代文本,否则走通用 SSE。 * @param textOrEvent - 可选字符串覆盖输入框内容,或来自 UI 事件。 */ const handleSend = async (textOrEvent?: string | Event) => { const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value; const trimmed = content.trim(); const hasAttachments = ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0; const allowSendWhileThinking = canContinueSendWhileThinking(ctx.messages.value); // [STEP 0] 提交中禁止重复触发(含 Enter);Intake 阻塞仍交给货代 handler 提示,不在此静默吞掉。 if (ctx.isOrderExtractionSubmitting?.value) { return; } if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) { return; } if (await ctx.tryHandleProcurementContractSend(textOrEvent, content, trimmed)) { return; } if ((!trimmed && !hasAttachments) || ctx.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) { return; } if (ctx.tryHandleLeaveSend(content)) { return; } if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) { return; } let files: ChatUploadFileSpec[] = []; let messageAttachments: ChatMessageAttachment[] = []; if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) { try { files = await ctx.buildFileSpecsForSend(); messageAttachments = ctx.createMessageAttachmentSnapshots(); } catch (e: unknown) { let suffix = ''; if (e instanceof BusinessError) { const headers = e.details?.headers as Record | undefined; const requestId = headers?.['x-request-id'] || headers?.['x-requestid'] || headers?.['request-id'] || headers?.['trace-id'] || headers?.['cf-ray']; if (requestId) suffix = `(rid=${requestId})`; } const message = e instanceof Error ? e.message : 'unknown error'; ctx.msg.warning(ctx.t('chat.attachmentsUi.processFailed', { message, suffix })); return; } } const shouldClearInput = typeof textOrEvent !== 'string'; if (shouldClearInput) ctx.input.value = ''; const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt'); const sendContext = { ...(ctx.getChatContext?.() || {}), ...(!trimmed && messageAttachments.length > 0 ? { display_query: '' } : {}), }; await ctx.prepareToolRunProgressBeforeSend(); const sent = await ctx.sendMessage( requestContent, ctx.currentAgentId.value, ctx.selectedKb.value, files, Object.keys(sendContext).length > 0 ? sendContext : undefined, { userAttachments: messageAttachments, onAssistantMessageFinished: ctx.onAssistantMessageFinished, }, ); // Keep the legacy boolean result compatible while callers migrate to ChatMessageSendResult. const accepted = (sent as unknown) === true || Boolean(sent.accepted); if (!accepted) { if (shouldClearInput) ctx.input.value = content; return; } ctx.clearAttachments(); await ctx.refreshHistoryAfterSend(); await ctx.refreshConversationAfterSend?.(); await ctx.refreshToolRunProgressAfterSend(); }; const copyToClipboard = async (message: { role?: string; content?: string }, index: number) => { const text = String(message?.content ?? '').trim(); if (!text) { ctx.msg.warning(ctx.t('chat.actions.copyEmpty')); return; } const ok = await copyTextToClipboard(text); if (ok) { ctx.copiedIndex.value = index; setTimeout(() => { ctx.copiedIndex.value = null; }, 2000); return; } ctx.msg.warning(ctx.t('chat.actions.copyFailed')); }; const regenerate = () => { const lastUserMsg = [...ctx.messages.value].reverse().find((m) => m.role === 'user'); if (lastUserMsg) { void handleSend(lastUserMsg.content); } }; return { canSendMessage, handleSend, copyToClipboard, regenerate }; }