refactor(frontend): 重构前端第二版

This commit is contained in:
sophie committed 2026-06-11 13:47:06 +08:00
1 parent 2631f78b00
commit 4b562cfa82
205 files changed
+15399 -12015

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
/** 对话页编排子模块 barrel */
export * from './useChatPageUser';
export * from './useChatPageLocalMessage';
export * from './useChatPageDialogs';
export * from './useChatPageVoice';
export * from './useChatPageMarkdown';
export * from './useChatPageConversation';
export * from './useChatPageSend';
export * from './useChatPageHandlerBundles';
@@ -0,0 +1,80 @@
/**
* 对话页:加载历史会话、新建对话、切换 Agent 时重置状态。
*/
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import { listChatMessages } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface ChatPageConversationContext {
deps: { t: (key: string) => string; msg: { warning: (text: string) => void } };
route: RouteLocationNormalizedLoaded;
router: Router;
currentAgentId: ComputedRef<number>;
conversationId: Ref<string | null>;
activeRunId: Ref<number | null>;
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
createNewChatView: () => void;
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
onConversationLoadedEmpty: () => Promise<void>;
onConversationLoadFailed: () => Promise<void>;
isShippingNoticeAgent: ComputedRef<boolean>;
shippingTaskIdFromQuery: ComputedRef<string>;
clearHistory: () => void;
clearAttachments: () => void;
input: Ref<string>;
resetCurrentAgent: () => void;
copiedIndex: Ref<number | null>;
resetPeripheralState: () => void;
filePreviewVisible: Ref<boolean>;
previewFile: Ref<unknown>;
}
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
const loadConversation = async (id: string, options?: { force?: boolean }) => {
const force = options?.force ?? false;
if (!force && ctx.conversationId.value === id && !ctx.activeRunId.value && ctx.messages.value.length > 0) {
return;
}
const prevConversationId = ctx.conversationId.value;
try {
ctx.onConversationIdChanging(id, prevConversationId);
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
if (!loaded?.length) {
ctx.deps.msg.warning(ctx.deps.t('chat.historyEmpty'));
await ctx.onConversationLoadedEmpty();
return;
}
} catch (e) {
console.error('Failed to load conversation', e);
await ctx.onConversationLoadFailed();
if (ctx.isShippingNoticeAgent.value && ctx.shippingTaskIdFromQuery.value && !ctx.isThinking.value) {
return;
}
ctx.deps.msg.warning(ctx.deps.t('chat.historyLoadFailed'));
}
};
const startNewChat = () => {
ctx.createNewChatView();
void ctx.router.replace({ path: ctx.route.path, query: {} });
};
const resetChatStateForAgentChange = () => {
ctx.createNewChatView();
ctx.clearHistory();
ctx.clearAttachments();
ctx.input.value = '';
ctx.resetCurrentAgent();
ctx.copiedIndex.value = null;
ctx.resetPeripheralState();
ctx.filePreviewVisible.value = false;
ctx.previewFile.value = null;
};
return { loadConversation, startNewChat, resetChatStateForAgentChange };
}
@@ -0,0 +1,69 @@
/**
* 对话页:删除确认弹窗、消息反馈弹窗状态。
*/
import { computed, ref } from 'vue';
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void,
) => {
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
await pendingDeleteAction();
closeDeleteConfirmDialog();
};
const showGeneralFeedbackDialog = ref(false);
const activeFeedbackMessageIndex = ref<number | null>(null);
const handleOpenFeedback = (index: number) => {
activeFeedbackMessageIndex.value = index;
showGeneralFeedbackDialog.value = true;
};
const currentGeneralFeedbackChatLogId = computed(() => {
if (activeFeedbackMessageIndex.value !== null) {
const msgItem = messages.value[activeFeedbackMessageIndex.value];
const id = Number(msgItem?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
for (let i = messages.value.length - 1; i >= 0; i--) {
const msgItem = messages.value[i];
if (msgItem?.role === 'assistant') {
const id = Number(msgItem?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
}
return null;
});
return {
showDeleteConfirmDialog,
deleteConfirmMessage,
openDeleteConfirmDialog,
closeDeleteConfirmDialog,
handleDeleteConfirm,
showGeneralFeedbackDialog,
activeFeedbackMessageIndex,
handleOpenFeedback,
currentGeneralFeedbackChatLogId,
};
}
@@ -0,0 +1,73 @@
/**
* 对话页:子组件 inject 用的 handlers 对象打包(请假表单、出货映射、消息气泡)。
*/
import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from '../components/messages/ShippingInventoryMappingMessage.vue';
import type { useChatLeave } from '../composables/useChatLeave';
import type { useChatShipping } from '../composables/useChatShipping';
import type { Ref } from 'vue';
type LeaveHandlerSource = Pick<
ReturnType<typeof useChatLeave>,
| 'getLeaveFormPayload'
| 'getLeaveConfirmationPayload'
| 'getLeaveResultPayload'
| 'getLeaveAgentDisplayValue'
| 'getLeaveTypeLabel'
| 'formatDurationLabel'
| 'formatYesNoLabel'
| 'syncLeaveDuration'
| 'openLeaveAgentDialog'
| 'openOALeaveRequestDirectly'
| 'openOARequestDirectly'
| 'submitLeaveForm'
| 'editLeaveConfirmation'
| 'confirmLeaveSubmission'
>;
type ShippingHandlerSource = Pick<
ReturnType<typeof useChatShipping>,
| 'getShippingInventoryMappingPayload'
| 'normalizeShippingHeaderForDisplay'
| 'hasShippingInventorySampleRows'
| 'getShippingInventorySampleRowText'
| 'reuploadShippingInventoryFromMappingForm'
| 'applyShippingInventoryMappingForm'
>;
/** 请假消息块 handlers(LeaveMessageBlock) */
export function createLeaveMessageHandlers(leave: LeaveHandlerSource): LeaveMessageHandlers {
return {
getLeaveFormPayload: leave.getLeaveFormPayload,
getLeaveConfirmationPayload: leave.getLeaveConfirmationPayload,
getLeaveResultPayload: leave.getLeaveResultPayload,
getLeaveAgentDisplayValue: leave.getLeaveAgentDisplayValue,
getLeaveTypeLabel: leave.getLeaveTypeLabel,
formatDurationLabel: leave.formatDurationLabel,
formatYesNoLabel: leave.formatYesNoLabel,
syncLeaveDuration: leave.syncLeaveDuration,
openLeaveAgentDialog: leave.openLeaveAgentDialog,
openOALeaveRequestDirectly: leave.openOALeaveRequestDirectly,
openOARequestDirectly: leave.openOARequestDirectly,
submitLeaveForm: leave.submitLeaveForm,
editLeaveConfirmation: leave.editLeaveConfirmation,
confirmLeaveSubmission: leave.confirmLeaveSubmission,
};
}
/** 出货库存映射块 handlers(ShippingInventoryMappingMessage) */
export function createShippingMappingHandlers(shipping: ShippingHandlerSource): ShippingMappingHandlers {
return {
getPayload: shipping.getShippingInventoryMappingPayload,
normalizeHeader: shipping.normalizeShippingHeaderForDisplay,
hasSampleRows: shipping.hasShippingInventorySampleRows,
getSampleRowText: shipping.getShippingInventorySampleRowText,
reupload: shipping.reuploadShippingInventoryFromMappingForm,
apply: shipping.applyShippingInventoryMappingForm,
};
}
/** 隐藏 file input ref 包裹,避免 template 自动解包 Ref */
export function createShippingPickerRefHolder(pickerRef: Ref<HTMLInputElement | null>) {
return { pickerRef };
}
@@ -0,0 +1,43 @@
/**
* 对话页:本地消息落库(请假/出货等不经过 SSE 的消息)。
*/
import { saveLocalChatMessage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface ChatPageLocalMessageContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
}
export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext) {
let localMessageCounter = 0;
const newLocalMessageId = (prefix: string) => {
localMessageCounter += 1;
return `${prefix}-${Date.now()}-${localMessageCounter}`;
};
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = '') => {
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
type: localMsg.type,
content: localMsg.content,
payload: localMsg.payload,
query: userQuery,
agent_id: ctx.currentAgentId.value,
});
if (!ctx.conversationId.value && data.conversation_id) {
ctx.conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
localMsg.chat_log_id = data.chat_log_id;
}
} catch (e) {
console.error('Failed to save local message', e);
}
};
return { newLocalMessageId, saveLocalMessageToBackend };
}
@@ -0,0 +1,111 @@
/**
* 对话页:Markdown 渲染、消息可见性判断、PLM/请假链接点击。
*/
import { computed } from 'vue';
import { marked } from 'marked';
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
import type { ChatMessage, SourceFileLink } from '../types/chat.types';
import type { Ref } from 'vue';
marked.setOptions({ gfm: true, breaks: true });
export interface ChatPageMarkdownContext {
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
prepareMarkdownDisplayText: (text: string) => string;
handleLeaveMarkdownClick: (event: MouseEvent) => void;
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
openPreview: (file: SourceFileLink) => Promise<void>;
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
shouldExpandSourceDetails: (msgItem: Record<string, unknown>) => boolean;
getSourceTitle: ChatMessageBubbleHandlers['getSourceTitle'];
getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta'];
getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief'];
getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload'];
canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview'];
getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary'];
openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog'];
shippingActionButtonClass: ChatMessageBubbleHandlers['shippingActionButtonClass'];
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
}
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
if (msgItem?.role === 'user') return true;
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
const content = (msgItem?.content || '').trim();
if (content) return true;
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
if (ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>).length > 0) return true;
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
};
const shouldShowThinkingBubble = computed(() => {
if (!ctx.isThinking.value) return false;
let lastUserIndex = -1;
for (let i = ctx.messages.value.length - 1; i >= 0; i--) {
if (ctx.messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return true;
return !ctx.messages.value
.slice(lastUserIndex + 1)
.some((msgItem) => msgItem?.role === 'assistant' && shouldRenderMessage(msgItem));
});
const handleChatMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
const preview = ctx.parsePlmPreviewLink(anchor?.getAttribute('href') || '');
if (preview) {
event.preventDefault();
void ctx.openPreview(preview);
return;
}
ctx.handleLeaveMarkdownClick(event);
};
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = ctx.prepareMarkdownDisplayText(text);
try {
const rendered = marked.parse(displayText);
const html = typeof rendered === 'string' ? rendered : displayText;
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
));
} catch {
return displayText;
}
};
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
canOpenQueryPreview: ctx.canOpenQueryPreview,
getQueryPreviewSummary: ctx.getQueryPreviewSummary,
openQueryPreviewDialog: ctx.openQueryPreviewDialog,
shippingActionButtonClass: ctx.shippingActionButtonClass,
onShippingActionClick: ctx.onShippingActionClick,
getDisplayRetrieverResources: (msgItem) => ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>),
getSourceLinks: (resources) => ctx.getSourceLinks(resources),
shouldExpandSourceDetails: (msgItem) => ctx.shouldExpandSourceDetails(msgItem as unknown as Record<string, unknown>),
getSourceTitle: ctx.getSourceTitle,
getSourceMeta: ctx.getSourceMeta,
getSourceBrief: ctx.getSourceBrief,
openPreview: ctx.openPreview,
};
return {
shouldRenderMessage,
shouldShowThinkingBubble,
messageBubbleHandlers,
renderMarkdown,
handleChatMarkdownClick,
};
}
@@ -0,0 +1,119 @@
/**
* 对话页:发送消息编排(出货/请假前置拦截 → 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';
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[],
) => Promise<void>;
refreshHistoryAfterSend: () => 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>;
msg: { warning: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
}
export function createChatPageSendApi(ctx: ChatPageSendContext) {
const canSendMessage = computed(() => {
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
if (ctx.input.value.trim()) return true;
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();
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
return;
}
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) 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.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
await ctx.refreshHistoryAfterSend();
};
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 };
}
@@ -0,0 +1,51 @@
/**
* 对话页:当前登录用户展示名、工号与登出/管理入口。
*/
import { computed, ref } from 'vue';
import type { Router } from 'vue-router';
import { getStoredAuthUser, logoutAuth } from '@/shared/utils/auth';
export function useChatPageUser(router: Router) {
const currentUser = ref(getStoredAuthUser());
const currentUserDisplayName = computed(() => {
const realName = currentUser.value?.real_name?.trim();
if (realName) return realName;
const aliasName = (currentUser.value as { name?: string; wecom_name?: string } | null)?.name?.trim?.()
|| (currentUser.value as { wecom_name?: string } | null)?.wecom_name?.trim?.();
if (aliasName) return aliasName;
const username = currentUser.value?.username?.trim();
if (username && !/^\d+$/.test(username)) return username;
return '当前用户';
});
const currentUserEmployeeId = computed(() => {
const employeeId = currentUser.value?.employee_id?.trim();
if (employeeId) return employeeId;
const username = currentUser.value?.username?.trim();
return username || '-';
});
const onAuthLogout = () => {
currentUser.value = null;
};
const handleLogout = () => {
logoutAuth();
onAuthLogout();
router.push('/');
};
const goToAdmin = () => {
router.push('/admin');
};
return {
currentUser,
currentUserDisplayName,
currentUserEmployeeId,
onAuthLogout,
handleLogout,
goToAdmin,
};
}
@@ -0,0 +1,56 @@
/**
* 对话页:语音输入(当前功能开关关闭,保留占位与思考态取消录音)。
*/
import { watch } from 'vue';
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '@/shared/composables/useAudioTranscription';
import type { Ref } from 'vue';
const VOICE_INPUT_ENABLED = false;
export interface ChatPageVoiceContext {
input: Ref<string>;
isThinking: Ref<boolean>;
msg: { info: (text: string) => void; warning: (text: string) => void };
t: (key: string) => string;
}
export function useChatPageVoice(ctx: ChatPageVoiceContext) {
const {
isRecording: isVoiceRecording,
isTranscribing: isVoiceTranscribing,
toggle: toggleVoiceInput,
cancel: cancelVoiceInput,
} = useAudioTranscription({
onResult: (text) => {
ctx.input.value = text;
},
onError: (key) => {
ctx.msg.warning(ctx.t(key));
},
});
const handleVoiceFeatureClick = () => {
if (!VOICE_INPUT_ENABLED) {
ctx.msg.info(ctx.t('chat.devComingSoon'));
return;
}
if (ctx.isThinking.value || isVoiceTranscribing.value) return;
const unavailable = getVoiceUnavailableErrorKey();
if (unavailable) {
ctx.msg.warning(ctx.t(unavailable));
return;
}
toggleVoiceInput(ctx.input.value);
};
watch(ctx.isThinking, (thinking) => {
if (thinking) cancelVoiceInput();
});
return {
isVoiceRecording,
isVoiceTranscribing,
handleVoiceFeatureClick,
cancelVoiceInput,
};
}