166 lines
6.0 KiB
TypeScript
166 lines
6.0 KiB
TypeScript
/**
|
||
* 对话页:发送消息编排(出货/请假前置拦截 → 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('<details>')
|
||
|| 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<string>;
|
||
messages: Ref<ChatMessage[]>;
|
||
isThinking: Ref<boolean>;
|
||
currentAgentId: ComputedRef<number>;
|
||
selectedKb: Ref<string>;
|
||
isUploadingAttachments: Ref<boolean>;
|
||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||
attachments: Ref<unknown[]>;
|
||
allowsSendWithAttachmentsOnly: ComputedRef<boolean>;
|
||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||
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<void> },
|
||
) => Promise<void>;
|
||
refreshHistoryAfterSend: () => Promise<void>;
|
||
refreshConversationAfterSend?: () => Promise<void>;
|
||
tryHandleShippingAttachmentAutoFlow: (
|
||
textOrEvent: string | Event | undefined,
|
||
content: string,
|
||
trimmed: string,
|
||
) => Promise<boolean>;
|
||
tryHandleLeaveSend: (content: string) => boolean;
|
||
tryHandleShippingSend: (
|
||
textOrEvent: string | Event | undefined,
|
||
content: string,
|
||
trimmed: string,
|
||
) => Promise<boolean>;
|
||
refreshToolRunProgressAfterSend: () => Promise<void>;
|
||
prepareToolRunProgressBeforeSend: () => Promise<void>;
|
||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||
t: (key: string) => string;
|
||
copiedIndex: Ref<number | null>;
|
||
getChatContext?: () => { task_id?: string; batch_no?: string; display_query?: string };
|
||
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
|
||
}
|
||
|
||
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<string, string> | 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 };
|
||
}
|