feat(shipping-notice): 增加发货通知建单幂等性支持及内容哈希校验
This commit is contained in:
1 parent
0a9bd6415d
commit
143e054d86
39 files changed
+1750
-80
No files matched your search
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingNoticeBatchIdempotency.spec.ts
|
||||
* 用途:验证前端文件集合指纹与后端 compute_notice_items_content_fingerprint 对齐。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
|
||||
describe('shippingNoticeBatchIdempotency', () => {
|
||||
it('treats duplicate files as one content set', async () => {
|
||||
const content = 'same-notice-content';
|
||||
const single = new File([content], 'a.txt', { type: 'text/plain' });
|
||||
const duplicatePair = [
|
||||
new File([content], 'a.txt', { type: 'text/plain' }),
|
||||
new File([content], 'b.txt', { type: 'text/plain' }),
|
||||
];
|
||||
|
||||
const singleFp = await computeNoticeFilesContentFingerprint([single]);
|
||||
const duplicateFp = await computeNoticeFilesContentFingerprint(duplicatePair);
|
||||
|
||||
expect(singleFp).toBeTruthy();
|
||||
expect(duplicateFp).toBe(singleFp);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingNoticeBatchIdempotency.ts
|
||||
* 用途:发货通知建批幂等键与文件集合指纹计算。
|
||||
* 依赖:浏览器 Web Crypto API。
|
||||
* 逻辑:useChatShippingUploadHandler 在重试时绑定「幂等键 + 文件指纹」,文件变化时生成新键。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 将 File 列表转为与后端 notice_items 对齐的内容指纹(排序哈希后二次 SHA-256)。
|
||||
*/
|
||||
export async function computeNoticeFilesContentFingerprint(files: File[]): Promise<string> {
|
||||
const hashes: string[] = [];
|
||||
for (const file of files) {
|
||||
if (!file) continue;
|
||||
const buffer = await file.arrayBuffer();
|
||||
const digest = await crypto.subtle.digest('SHA-256', buffer);
|
||||
const hex = Array.from(new Uint8Array(digest))
|
||||
.map((byte) => byte.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
hashes.push(hex.toLowerCase());
|
||||
}
|
||||
const uniqueHashes = [...new Set(hashes)].sort();
|
||||
if (!uniqueHashes.length) return '';
|
||||
const joined = uniqueHashes.join('|');
|
||||
const encoded = new TextEncoder().encode(joined);
|
||||
const fingerprintDigest = await crypto.subtle.digest('SHA-256', encoded);
|
||||
return Array.from(new Uint8Array(fingerprintDigest))
|
||||
.map((byte) => byte.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
.toLowerCase();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingTurnActions.spec.ts
|
||||
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildShippingCreateBatchTurn } from './shippingTurnActions';
|
||||
|
||||
describe('shippingTurnActions', () => {
|
||||
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
|
||||
const files = [
|
||||
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
|
||||
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
|
||||
];
|
||||
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
|
||||
|
||||
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
|
||||
expect(turn.payload.conversation_id).toBe('conv-001');
|
||||
expect(turn.payload.file_count).toBe(2);
|
||||
expect(turn.payload.idempotency_key).toBe('idem-key-001');
|
||||
expect(turn.files).toEqual(files);
|
||||
});
|
||||
});
|
||||
@@ -78,6 +78,7 @@ export function buildShippingSubmitDecisionTurn(
|
||||
export function buildShippingCreateBatchTurn(
|
||||
files: File[],
|
||||
conversationId?: string | null,
|
||||
idempotencyKey?: string,
|
||||
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
|
||||
const count = files.length;
|
||||
const displayText = count === 1
|
||||
@@ -89,6 +90,7 @@ export function buildShippingCreateBatchTurn(
|
||||
payload: {
|
||||
conversation_id: conversationId || undefined,
|
||||
file_count: count,
|
||||
idempotency_key: idempotencyKey,
|
||||
},
|
||||
files,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingSendHandler.spec.ts
|
||||
* 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingSendHandlers, type ShippingSendHandlerContext } from './useChatShippingSendHandler';
|
||||
|
||||
const isShippingNoticeBatchSubmitting = vi.hoisted(() => vi.fn(() => false));
|
||||
|
||||
vi.mock('./useChatShippingUploadHandler', () => ({
|
||||
isShippingNoticeBatchSubmitting,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingSendHandlerContext> = {},
|
||||
): ShippingSendHandlerContext => ({
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
isThinking: ref(false),
|
||||
isUploadingAttachments: ref(false),
|
||||
messages: ref([]),
|
||||
conversationId: ref('conv-send'),
|
||||
history: ref([]),
|
||||
input: ref(''),
|
||||
attachments: ref([{ kind: 'local', file: new File(['notice'], 'notice.txt', { type: 'text/plain' }) }]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
currentAgentId: computed(() => 1),
|
||||
selectedKb: ref(''),
|
||||
attachmentPolicy: computed(() => ({ anyEnabled: true })),
|
||||
getActiveShippingTaskId: () => '',
|
||||
lastAssistantMessageContent: () => '',
|
||||
lastAssistantShippingActions: () => [],
|
||||
sendMessage: vi.fn(async () => undefined),
|
||||
buildFileSpecsForSend: vi.fn(async () => []),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
openShippingInventoryPicker: vi.fn(() => true),
|
||||
executeShippingDecision: vi.fn(async () => true),
|
||||
executeShippingManualUpload: vi.fn(async () => true),
|
||||
handleShippingMenuAction: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadFile: vi.fn(async () => undefined),
|
||||
handleShippingAutoUploadNoticeBatch: vi.fn(async () => undefined),
|
||||
isShippingNoticeBatchSubmitting: () => isShippingNoticeBatchSubmitting(),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
isShippingShortageQueryIntent: () => false,
|
||||
queryShippingShortageDetails: vi.fn(async () => true),
|
||||
msg: { warning: vi.fn(), info: vi.fn() },
|
||||
t: (key: string) => key,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingSendHandler', () => {
|
||||
beforeEach(() => {
|
||||
isShippingNoticeBatchSubmitting.mockReset();
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(false);
|
||||
});
|
||||
|
||||
it('consumes send while notice batch is submitting and does not call sendMessage', async () => {
|
||||
isShippingNoticeBatchSubmitting.mockReturnValue(true);
|
||||
const ctx = createContext();
|
||||
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
|
||||
|
||||
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
|
||||
|
||||
expect(consumed).toBe(true);
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
|
||||
});
|
||||
});
|
||||
@@ -61,6 +61,7 @@ export interface ShippingSendHandlerContext {
|
||||
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||||
isShippingNoticeBatchSubmitting?: () => boolean;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
@@ -189,6 +190,10 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
|
||||
if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false;
|
||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||
if (ctx.isShippingNoticeBatchSubmitting?.()) {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting'));
|
||||
return true;
|
||||
}
|
||||
const requestedAutoFlow = ctx.shippingAutoFlowRequested.value;
|
||||
ctx.shippingAutoFlowRequested.value = false;
|
||||
const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
onNoticeBatchConversationChanging,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
|
||||
@@ -15,10 +18,21 @@ const { createWorkspaceShippingTask } = vi.hoisted(() => ({
|
||||
createWorkspaceShippingTask: vi.fn(),
|
||||
}));
|
||||
|
||||
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
|
||||
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
|
||||
const content = await files[0]?.text();
|
||||
return `fp-${content || 'empty'}`;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
createWorkspaceShippingTask,
|
||||
}));
|
||||
|
||||
vi.mock('./shippingNoticeBatchIdempotency', () => ({
|
||||
computeNoticeFilesContentFingerprint,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingUploadHandlerContext> = {},
|
||||
): ShippingUploadHandlerContext => ({
|
||||
@@ -50,6 +64,12 @@ const createContext = (
|
||||
describe('useChatShippingUploadHandler', () => {
|
||||
beforeEach(() => {
|
||||
createWorkspaceShippingTask.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockReset();
|
||||
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
|
||||
const content = await files[0]?.text();
|
||||
return `fp-${content || 'empty'}`;
|
||||
});
|
||||
resetShippingNoticeBatchSubmitStateForTests();
|
||||
});
|
||||
|
||||
it('opens inventory picker for explicit taskId instead of current active task', () => {
|
||||
@@ -103,6 +123,186 @@ describe('useChatShippingUploadHandler', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
return true;
|
||||
});
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
const first = handleShippingAutoUploadNoticeBatch([file]);
|
||||
const second = handleShippingAutoUploadNoticeBatch([file]);
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(startChatTurn).toHaveBeenCalledTimes(1);
|
||||
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
|
||||
expect(payload?.idempotency_key).toBeTruthy();
|
||||
});
|
||||
|
||||
it('reuses idempotency key on retry and generates new key after success', async () => {
|
||||
let attempt = 0;
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
attempt += 1;
|
||||
return attempt >= 2;
|
||||
});
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBe(secondKey);
|
||||
expect(thirdKey).not.toBe(secondKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when files change after a failed attempt', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
|
||||
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([firstFile]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
await handleShippingAutoUploadNoticeBatch([secondFile]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
|
||||
const conversationId = ref<string | null>(null);
|
||||
const startChatTurn = vi.fn(async () => {
|
||||
conversationId.value = 'conv-server-new';
|
||||
return false;
|
||||
});
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when switching from new chat to historical session', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref<string | null>(null);
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
onNoticeBatchConversationChanging('conv-history', '');
|
||||
conversationId.value = 'conv-history';
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref('conv-a');
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
clearPendingNoticeBatchRetry();
|
||||
conversationId.value = null;
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
|
||||
const startChatTurn = vi.fn(async () => false);
|
||||
const conversationId = ref('conv-a');
|
||||
const ctx = createContext({
|
||||
conversationId,
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
onNoticeBatchConversationChanging('conv-b', 'conv-a');
|
||||
conversationId.value = 'conv-b';
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
|
||||
|
||||
expect(firstKey).toBeTruthy();
|
||||
expect(secondKey).toBeTruthy();
|
||||
expect(secondKey).not.toBe(firstKey);
|
||||
});
|
||||
|
||||
it('releases submit lock when fingerprint computation fails', async () => {
|
||||
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
|
||||
const startChatTurn = vi.fn(async () => true);
|
||||
const ctx = createContext({
|
||||
getActiveShippingTaskId: () => '',
|
||||
startChatTurn,
|
||||
});
|
||||
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
|
||||
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
|
||||
|
||||
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
|
||||
expect(startChatTurn).not.toHaveBeenCalled();
|
||||
expect(isShippingNoticeBatchSubmitting()).toBe(false);
|
||||
|
||||
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
|
||||
await handleShippingAutoUploadNoticeBatch([file]);
|
||||
expect(startChatTurn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not open notice picker when both explicit taskId and active task are missing', () => {
|
||||
const noticeClick = vi.fn();
|
||||
const warning = vi.fn();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/useChatShippingUploadHandler.ts
|
||||
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
|
||||
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
|
||||
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE。
|
||||
* 逻辑:发货通知建批/库存上传/单票覆盖均经 startChatTurn + multipart SSE;待重试幂等键绑定 conversation_id。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
@@ -11,12 +11,91 @@ import {
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingCreateBatchTurn, buildShippingReplaceNoticeTurn, buildShippingUploadInventoryTurn } from './shippingTurnActions';
|
||||
import { computeNoticeFilesContentFingerprint } from './shippingNoticeBatchIdempotency';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
let noticeBatchSubmitting = false;
|
||||
|
||||
interface PendingNoticeBatchRetryState {
|
||||
conversationId: string;
|
||||
idempotencyKey: string;
|
||||
fileFingerprint: string;
|
||||
}
|
||||
|
||||
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
|
||||
|
||||
function normalizeConversationId(conversationId: string | null | undefined): string {
|
||||
return String(conversationId || '').trim();
|
||||
}
|
||||
|
||||
function clearPendingNoticeBatchRetryState(): void {
|
||||
pendingNoticeBatchRetry = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
|
||||
*/
|
||||
export function clearPendingNoticeBatchRetry(): void {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断待重试状态是否应绑定到当前会话。
|
||||
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
|
||||
*/
|
||||
function reconcilePendingNoticeBatchConversation(
|
||||
pending: PendingNoticeBatchRetryState,
|
||||
conversationKey: string,
|
||||
): void {
|
||||
const pendingKey = pending.conversationId;
|
||||
if (pendingKey === conversationKey) {
|
||||
return;
|
||||
}
|
||||
if (!pendingKey && conversationKey) {
|
||||
pending.conversationId = conversationKey;
|
||||
return;
|
||||
}
|
||||
if (pendingKey && !conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
return;
|
||||
}
|
||||
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
|
||||
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
|
||||
*/
|
||||
export function onNoticeBatchConversationChanging(
|
||||
nextId: string,
|
||||
prevId?: string | null,
|
||||
): void {
|
||||
const next = normalizeConversationId(nextId);
|
||||
const prev = normalizeConversationId(prevId);
|
||||
if (next !== prev) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
|
||||
*/
|
||||
export function isShippingNoticeBatchSubmitting(): boolean {
|
||||
return noticeBatchSubmitting;
|
||||
}
|
||||
|
||||
/** 单测重置模块级建批提交状态。 */
|
||||
export function resetShippingNoticeBatchSubmitStateForTests(): void {
|
||||
noticeBatchSubmitting = false;
|
||||
clearPendingNoticeBatchRetry();
|
||||
}
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
conversationId: Ref<string | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
@@ -135,25 +214,58 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
};
|
||||
|
||||
const runNoticeBatchChatTurn = async (files: File[]) => {
|
||||
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
files: turn.files,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
if (noticeBatchSubmitting) {
|
||||
return true;
|
||||
}
|
||||
noticeBatchSubmitting = true;
|
||||
try {
|
||||
const conversationKey = normalizeConversationId(ctx.conversationId.value);
|
||||
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
|
||||
if (pendingNoticeBatchRetry) {
|
||||
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
|
||||
}
|
||||
if (
|
||||
pendingNoticeBatchRetry
|
||||
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
|
||||
) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
if (!pendingNoticeBatchRetry) {
|
||||
pendingNoticeBatchRetry = {
|
||||
conversationId: conversationKey,
|
||||
idempotencyKey: crypto.randomUUID(),
|
||||
fileFingerprint,
|
||||
};
|
||||
} else {
|
||||
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
|
||||
}
|
||||
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
|
||||
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
|
||||
const ok = await ctx.startChatTurn({
|
||||
agentId: ctx.currentAgentId.value,
|
||||
inputType: 'upload_followup',
|
||||
displayText: turn.displayText,
|
||||
actionType: turn.actionType,
|
||||
payload: turn.payload,
|
||||
files: turn.files,
|
||||
hooks: {
|
||||
onAssistantMessageFinished: async (assistantMsg) => {
|
||||
syncBatchContextFromTurnMessage(assistantMsg);
|
||||
void ctx.refreshShippingActions();
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!ok) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
});
|
||||
if (ok) {
|
||||
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
|
||||
clearPendingNoticeBatchRetryState();
|
||||
}
|
||||
} else {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
|
||||
}
|
||||
return ok;
|
||||
} finally {
|
||||
noticeBatchSubmitting = false;
|
||||
}
|
||||
return ok;
|
||||
};
|
||||
|
||||
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
|
||||
@@ -317,5 +429,6 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
handleShippingInventorySelected,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
isShippingNoticeBatchSubmitting,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user