refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名
This commit is contained in:
1 parent
dde25344ca
commit
46eb63f5bb
111 files changed
+3116
-1250
No files matched your search
@@ -17,6 +17,7 @@ import type {
|
||||
ShippingOrderExtractionStatus,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
export interface SendMessageLifecycleHooks {
|
||||
@@ -533,7 +534,7 @@ export function useChat() {
|
||||
>,
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => {
|
||||
): Promise<ChatMessageSendResult> => {
|
||||
const displayQuery = String(
|
||||
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
? context.display_query ?? ''
|
||||
@@ -565,10 +566,12 @@ export function useChat() {
|
||||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||
activeRunId.value = run.runId;
|
||||
|
||||
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
|
||||
const userMessageIndex = runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments)) - 1;
|
||||
let botMsgIndex: number | null = null;
|
||||
let hasAssistantContent = false;
|
||||
let hasTerminalEvent = false;
|
||||
let requestAccepted = false;
|
||||
let chatLogId: number | undefined;
|
||||
let ignoreFurtherStreamEvents = false;
|
||||
const ensureBotMessage = () => {
|
||||
if (botMsgIndex === null) {
|
||||
@@ -609,6 +612,7 @@ export function useChat() {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
|
||||
}
|
||||
requestAccepted = true;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
@@ -655,6 +659,10 @@ export function useChat() {
|
||||
}
|
||||
|
||||
const eventName = String(data.event || '');
|
||||
const eventChatLogId = Number(data.chat_log_id || 0);
|
||||
if (Number.isInteger(eventChatLogId) && eventChatLogId > 0) {
|
||||
chatLogId = eventChatLogId;
|
||||
}
|
||||
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
|
||||
continue;
|
||||
}
|
||||
@@ -791,11 +799,24 @@ export function useChat() {
|
||||
if (run.status === 'done' && botMsgIndex !== null) {
|
||||
const botMsg = runMessages[botMsgIndex];
|
||||
if (botMsg) {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
try {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
} catch (error) {
|
||||
// 助手完成后的领域刷新属于附加动作,失败不能反向改变已被服务端接受的消息结果。
|
||||
console.error('[chat] onAssistantMessageFinished failed', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!requestAccepted) {
|
||||
const removeCount = botMsgIndex === null ? 1 : Math.max(botMsgIndex - userMessageIndex + 1, 1);
|
||||
runMessages.splice(userMessageIndex, removeCount);
|
||||
}
|
||||
}
|
||||
return run.status === 'done';
|
||||
return {
|
||||
accepted: requestAccepted,
|
||||
completed: requestAccepted && run.status === 'done',
|
||||
...(chatLogId ? { chatLogId } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -20,6 +20,7 @@ const uploadChatFileMock = vi.mocked(uploadChatFile);
|
||||
function createAttachments() {
|
||||
return useChatAttachments({
|
||||
deps: {
|
||||
t: ((key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`),
|
||||
msg: { warning: vi.fn() },
|
||||
} as unknown as ChatDeps,
|
||||
currentAgentId: computed(() => 7),
|
||||
@@ -38,7 +39,7 @@ function createAttachments() {
|
||||
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
|
||||
const file = new File(['content'], name, { type: 'application/pdf' });
|
||||
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
|
||||
return api.attachments.value[0];
|
||||
return api.attachments.value.at(-1);
|
||||
}
|
||||
|
||||
describe('useChatAttachments upload states', () => {
|
||||
@@ -86,6 +87,41 @@ describe('useChatAttachments upload states', () => {
|
||||
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('explicitly retries only the selected failed attachment', async () => {
|
||||
const api = createAttachments();
|
||||
const first = selectLocalFile(api, 'first.pdf');
|
||||
const second = selectLocalFile(api, 'second.pdf');
|
||||
if (first?.kind === 'local') first.uploadStatus = 'failed';
|
||||
if (second?.kind === 'local') {
|
||||
second.uploadStatus = 'uploaded';
|
||||
second.uploadFileId = 'upload-second';
|
||||
}
|
||||
uploadChatFileMock.mockResolvedValueOnce({ id: 'upload-first-retry' });
|
||||
|
||||
await expect(api.retryAttachment(first?.id || '')).resolves.toBe(true);
|
||||
|
||||
expect(uploadChatFileMock).toHaveBeenCalledOnce();
|
||||
expect(uploadChatFileMock).toHaveBeenCalledWith(7, first && 'file' in first ? first.file : undefined);
|
||||
expect(first).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-first-retry' });
|
||||
expect(second).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-second' });
|
||||
});
|
||||
|
||||
it('keeps explicit retry failures available for another retry', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
if (attachment?.kind === 'local') attachment.uploadStatus = 'failed';
|
||||
uploadChatFileMock.mockRejectedValueOnce(new Error('still unavailable'));
|
||||
|
||||
await expect(api.retryAttachment(attachment?.id || '')).resolves.toBe(false);
|
||||
|
||||
expect(attachment).toMatchObject({
|
||||
uploadStatus: 'failed',
|
||||
uploadProgress: 0,
|
||||
errorMessage: 'still unavailable',
|
||||
});
|
||||
expect(api.attachments.value).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('reuses earlier successful files when a later file failed', async () => {
|
||||
const api = createAttachments();
|
||||
selectLocalFile(api, 'first.pdf');
|
||||
|
||||
@@ -66,7 +66,7 @@ export interface UseChatAttachmentsOptions {
|
||||
|
||||
export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const { deps, currentAgentId, currentAgent } = options;
|
||||
const { msg } = deps;
|
||||
const { msg, t } = deps;
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const isUploadingAttachments = ref(false);
|
||||
@@ -265,12 +265,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
@@ -278,23 +278,23 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
msg.warning(t('chat.attachment.localTypeDisabled', { type }));
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
msg.warning(t('chat.attachment.fileTooLarge', { limit, name: f.name }));
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({
|
||||
@@ -314,20 +314,20 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
msg.warning(t('chat.attachment.httpOnly'));
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
msg.warning(t('chat.attachment.remoteDisabled'));
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
@@ -335,23 +335,70 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
msg.warning(t('chat.attachment.remoteTypeDisabled', { type }));
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传单个普通本地附件;成功上传 ID 可被发送流程复用。
|
||||
* @param item - 必须是仍存在于输入区的本地附件
|
||||
* @returns Dify 本地文件参数
|
||||
*/
|
||||
const uploadLocalAttachment = async (
|
||||
item: Extract<PendingAttachment, { kind: 'local' }>,
|
||||
): Promise<ChatUploadFileSpec> => {
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
return { type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId };
|
||||
}
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) throw new Error(t('chat.attachment.missingUploadId'));
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
return { type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id };
|
||||
} catch (error: unknown) {
|
||||
item.uploadStatus = 'failed';
|
||||
item.uploadProgress = 0;
|
||||
item.uploadFileId = undefined;
|
||||
item.errorMessage = error instanceof Error ? error.message : t('chat.attachment.uploadFailed');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/** 用户从失败卡片显式重试单个普通附件,不触发整条消息发送。 */
|
||||
const retryAttachment = async (id: string): Promise<boolean> => {
|
||||
const target = attachments.value.find(
|
||||
(item): item is Extract<PendingAttachment, { kind: 'local' }> => item.id === id && item.kind === 'local',
|
||||
);
|
||||
if (!target || target.uploadStatus !== 'failed' || isUploadingAttachments.value) return false;
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
await uploadLocalAttachment(target);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
|
||||
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
|
||||
@@ -370,30 +417,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId });
|
||||
continue;
|
||||
}
|
||||
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
} catch (error: unknown) {
|
||||
item.uploadStatus = 'failed';
|
||||
item.uploadProgress = 0;
|
||||
item.uploadFileId = undefined;
|
||||
item.errorMessage = error instanceof Error ? error.message : 'File upload failed';
|
||||
throw error;
|
||||
}
|
||||
specs.push(await uploadLocalAttachment(item));
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
@@ -424,6 +448,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
removeAttachment,
|
||||
retryAttachment,
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from './useChat';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
@@ -98,7 +99,7 @@ export interface UseChatShippingOptions {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
|
||||
Reference in new issue
Block a user