/** * 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。 */ import { computed } from 'vue'; import { BusinessError } from '@/shared/api/client'; import { copyTextToClipboard } from '@/shared/utils/clipboard'; 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; isThinking: Ref; currentAgentId: ComputedRef; selectedKb: Ref; isUploadingAttachments: Ref; attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>; attachments: Ref; allowsSendWithAttachmentsOnly: ComputedRef; buildFileSpecsForSend: () => Promise; clearAttachments: () => void; sendMessage: ( content: string, agentId: number, kb: string, files: ChatUploadFileSpec[], context?: { task_id?: string; batch_no?: string; display_query?: string }, hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise }, ) => 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; refreshToolRunProgressAfterSend: () => Promise; prepareToolRunProgressBeforeSend: () => Promise; msg: { warning: (text: string) => void; info: (text: string) => void }; t: (key: string) => string; copiedIndex: Ref; getChatContext?: () => { task_id?: string; batch_no?: string; display_query?: string }; onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise; } export function createChatPageSendApi(ctx: ChatPageSendContext) { const canSendMessage = computed(() => { 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; }); 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.isUploadingAttachments.value || (ctx.isThinking.value && !allowSendWhileThinking)) { return; } if (ctx.tryHandleLeaveSend(content)) { return; } if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) { return; } let files: ChatUploadFileSpec[] = []; if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) { try { files = await ctx.buildFileSpecsForSend(); } 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(`附件处理失败:${message}${suffix}`); return; } } if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.clearAttachments(); await ctx.prepareToolRunProgressBeforeSend(); await ctx.sendMessage( content, ctx.currentAgentId.value, ctx.selectedKb.value, files, ctx.getChatContext?.(), { onAssistantMessageFinished: ctx.onAssistantMessageFinished }, ); 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 }; }