feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -14,12 +14,16 @@ const api = vi.hoisted(() => ({
|
||||
createRun: vi.fn(),
|
||||
getRun: vi.fn(),
|
||||
listRuns: vi.fn(),
|
||||
markSeen: vi.fn(),
|
||||
retryRun: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
createWorkspaceShippingOrderExtractionRun: api.createRun,
|
||||
getWorkspaceShippingOrderExtractionRun: api.getRun,
|
||||
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
|
||||
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
|
||||
retryWorkspaceShippingOrderExtractionRun: api.retryRun,
|
||||
}));
|
||||
|
||||
const run = (patch: Partial<ShippingOrderExtractionRun>): ShippingOrderExtractionRun => ({
|
||||
@@ -50,6 +54,7 @@ const createHarness = () => {
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
loadHistory: vi.fn(async () => undefined),
|
||||
onConversationResolved: vi.fn(async () => undefined),
|
||||
onRetryError: vi.fn(),
|
||||
t: (key: string) => key,
|
||||
};
|
||||
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
|
||||
@@ -127,16 +132,110 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('retries a failed Run in place and resumes polling without creating a new user message', async () => {
|
||||
const failed = run({ run_no: 'SNER-RETRY', status: 'failed', phase: 'failed', error: { message: 'bad workflow' } });
|
||||
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
||||
api.listRuns.mockResolvedValue({ items: [failed] });
|
||||
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
await expect(harness.runs.retryRun('SNER-RETRY')).resolves.toBe(true);
|
||||
|
||||
expect(api.retryRun).toHaveBeenCalledWith('SNER-RETRY');
|
||||
expect(harness.options.refreshNoticeIntakeStatuses).toHaveBeenCalledTimes(1);
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('extracting');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-RETRY');
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('reports a retry API error and leaves the failed state available for another retry', async () => {
|
||||
api.retryRun.mockRejectedValue(new Error('retry unavailable'));
|
||||
const harness = createHarness();
|
||||
|
||||
await expect(harness.runs.retryRun('SNER-FAILED')).resolves.toBe(false);
|
||||
|
||||
expect(harness.options.onRetryError).toHaveBeenCalledWith('retry unavailable');
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('maps queued/running to indeterminate extracting state', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({ status: 'running', phase: 'calling_provider' }))).toMatchObject({
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'running',
|
||||
phase: 'calling_provider',
|
||||
progress: {
|
||||
version: 3,
|
||||
current_stage_code: 'document_processing',
|
||||
health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
},
|
||||
}))).toMatchObject({
|
||||
status: 'extracting', terminal: false, phase: 'llm_extraction',
|
||||
current_stage_code: 'document_processing', health: 'normal',
|
||||
last_activity_at: '2026-07-21T03:24:51Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('persists a changed progress projection even when Run status and result are unchanged', async () => {
|
||||
vi.useFakeTimers();
|
||||
const first = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 1, current_stage_code: 'workflow_accepted' },
|
||||
});
|
||||
const second = run({
|
||||
run_no: 'SNER-PROGRESS',
|
||||
status: 'running',
|
||||
progress: { version: 2, current_stage_code: 'order_recognition' },
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [first] });
|
||||
api.getRun.mockResolvedValueOnce(second);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.current_stage_code).toBe('order_recognition');
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('merges duplicate local cards for one Run when a terminal update arrives', async () => {
|
||||
vi.useFakeTimers();
|
||||
const active = run({ run_no: 'SNER-DUPLICATE', status: 'running' });
|
||||
const failed = run({
|
||||
run_no: 'SNER-DUPLICATE', status: 'failed', phase: 'failed', error: { message: 'provider unavailable' },
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [active] });
|
||||
api.getRun.mockResolvedValue(failed);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
harness.messages.value.push({
|
||||
role: 'assistant', type: 'text', content: '', local_id: 'legacy-duplicate', local_only: true,
|
||||
shipping_order_extraction_state: mapOrderExtractionRunToMessageState(active),
|
||||
payload: { formId: 'legacy-state-card', order_extraction_run_no: 'SNER-DUPLICATE' },
|
||||
});
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
|
||||
const cards = harness.messages.value.filter((item) => item.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.status).toBe('failed');
|
||||
harness.runs.stopPolling();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('maps completed result counters without guessing from text', () => {
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'completed',
|
||||
@@ -152,6 +251,19 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
}))).toMatchObject({ status: 'partially_completed', pending_count: 3, terminal: true });
|
||||
expect(mapOrderExtractionRunToMessageState(run({
|
||||
status: 'failed', error: { code: 'X', message: 'provider failed' },
|
||||
}))).toMatchObject({ status: 'failed', message: 'provider failed', terminal: true });
|
||||
}))).toMatchObject({ status: 'failed', message: '', terminal: true });
|
||||
});
|
||||
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [terminal] });
|
||||
api.markSeen.mockResolvedValue({ seen: true });
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.markSeen).toHaveBeenCalledWith('SNER-SEEN');
|
||||
expect(harness.options.loadHistory).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
createWorkspaceShippingOrderExtractionRun,
|
||||
getWorkspaceShippingOrderExtractionRun,
|
||||
listWorkspaceShippingOrderExtractionRuns,
|
||||
markWorkspaceShippingOrderExtractionRunSeen,
|
||||
retryWorkspaceShippingOrderExtractionRun,
|
||||
} from '../api/shipping.api';
|
||||
import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionState } from '../types/chat.types';
|
||||
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
|
||||
@@ -25,6 +27,7 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
onRetryError: (message: string) => void;
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
@@ -39,7 +42,8 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
return {
|
||||
status: failed ? 'failed' : partial ? 'partially_completed' : completed ? 'completed' : 'extracting',
|
||||
phase: failed ? 'failed' : run.status === 'result_persisted' ? 'result_persisted' : 'llm_extraction',
|
||||
message: failed ? String(run.error?.message || '') : '',
|
||||
// Provider/网络错误正文仅供管理员诊断,用户卡片统一展示可操作的业务提示。
|
||||
message: '',
|
||||
created_count: Number(result.created_count || 0),
|
||||
opened_existing_count: Number(result.opened_existing_count || 0),
|
||||
pending_count: Number(result.pending_count || 0),
|
||||
@@ -47,6 +51,10 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
created_with_missing_fields_count: Number(result.created_with_missing_fields_count || 0),
|
||||
batch_no: result.batch_no || null,
|
||||
terminal: failed || partial || completed,
|
||||
current_stage_code: run.progress?.current_stage_code || null,
|
||||
health: run.progress?.health || 'normal',
|
||||
last_activity_at: run.progress?.last_activity_at || null,
|
||||
started_at: run.started_at || run.created_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -77,10 +85,19 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const upsertRunMessage = async (run: ShippingOrderExtractionRun): Promise<ChatMessage> => {
|
||||
const formId = `shipping-order-extraction-run:${run.run_no}`;
|
||||
const state = mapOrderExtractionRunToMessageState(run);
|
||||
let message = options.messages.value.find((item) => {
|
||||
const stateCards = options.messages.value.filter((item) => {
|
||||
if (item.role !== 'assistant') return false;
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.formId === formId || payload.order_extraction_run_no === run.run_no;
|
||||
});
|
||||
let message = stateCards.find((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.formId === formId;
|
||||
});
|
||||
}) || stateCards[0];
|
||||
if (stateCards.length > 1) {
|
||||
// 网络恢复或历史合并可能重复注入同一 Run 的旧卡;Run 编号是唯一业务锚点,只保留一张原位更新。
|
||||
options.messages.value = options.messages.value.filter((item) => item === message || !stateCards.includes(item));
|
||||
}
|
||||
if (!message) {
|
||||
message = {
|
||||
role: 'assistant',
|
||||
@@ -97,7 +114,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
order_extraction_run_no: run.run_no,
|
||||
shipping_order_extraction_state: state,
|
||||
};
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error });
|
||||
const signature = JSON.stringify({ status: run.status, phase: run.phase, result: run.result, error: run.error, progress: run.progress });
|
||||
if (persistedSignatures.get(run.run_no) !== signature) {
|
||||
const persisted = await options.saveLocalMessageToBackend(message);
|
||||
if (persisted) persistedSignatures.set(run.run_no, signature);
|
||||
@@ -105,6 +122,25 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return message;
|
||||
};
|
||||
|
||||
/**
|
||||
* 终态卡已投影到当前会话后才确认已查看,避免侧栏或历史预加载错误清除提醒。
|
||||
* 确认失败不影响状态卡、轮询或业务 Run,下一次进入会话会继续尝试。
|
||||
*/
|
||||
const acknowledgeTerminalRunWhenVisible = async (run: ShippingOrderExtractionRun): Promise<void> => {
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status) || run.conversation_id !== options.conversationId.value) return;
|
||||
const stateCardVisible = options.messages.value.some((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
return payload.order_extraction_run_no === run.run_no && item.shipping_order_extraction_state?.terminal;
|
||||
});
|
||||
if (!stateCardVisible) return;
|
||||
try {
|
||||
await markWorkspaceShippingOrderExtractionRunSeen(run.run_no);
|
||||
await options.loadHistory();
|
||||
} catch {
|
||||
// 待查看状态仍由服务端保留,后续成功加载同一终态卡时再次确认。
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Run 终态后容错刷新领域事实;单个视图失败不得阻断其他事实和聊天历史恢复。
|
||||
* @returns 所有可独立执行的刷新均已尝试完成。
|
||||
@@ -152,6 +188,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
pollFailureCount = 0;
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
if (generation !== pollGeneration || activeRunNo !== runNo) return;
|
||||
if (!ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
stopPolling();
|
||||
@@ -211,6 +248,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
options.messages.value.push(userMessage);
|
||||
await options.saveLocalMessageToBackend(userMessage, query);
|
||||
await upsertRunMessage(run);
|
||||
await acknowledgeTerminalRunWhenVisible(run);
|
||||
await options.onConversationResolved(run.conversation_id);
|
||||
if (ACTIVE_RUN_STATUSES.has(run.status)) {
|
||||
beginPolling(run.run_no, 1000);
|
||||
@@ -220,6 +258,26 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return true;
|
||||
};
|
||||
|
||||
/** 复用原 Run 的冻结附件重新识别,并恢复同一状态卡的轮询。 */
|
||||
const retryRun = async (runNo: string): Promise<boolean> => {
|
||||
const normalizedRunNo = String(runNo || '').trim();
|
||||
if (!normalizedRunNo) return false;
|
||||
try {
|
||||
stopPolling();
|
||||
const response = await retryWorkspaceShippingOrderExtractionRun(normalizedRunNo);
|
||||
await upsertRunMessage(response.run);
|
||||
await acknowledgeTerminalRunWhenVisible(response.run);
|
||||
await Promise.allSettled([options.refreshNoticeIntakeStatuses()]);
|
||||
if (ACTIVE_RUN_STATUSES.has(response.run.status)) {
|
||||
beginPolling(response.run.run_no, 1000);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
options.onRetryError(error instanceof Error ? error.message : options.t('chat.shippingOrderExtractionRetryFailed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run;活动 Run 继续轮询,终态只恢复状态卡。 */
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
stopPolling();
|
||||
@@ -231,6 +289,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
await upsertRunMessage(latest);
|
||||
await acknowledgeTerminalRunWhenVisible(latest);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(latest.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
@@ -241,5 +300,5 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
};
|
||||
|
||||
onBeforeUnmount(stopPolling);
|
||||
return { startRun, restoreForConversation, stopPolling, getActiveRunNo: () => activeRunNo };
|
||||
return { startRun, retryRun, restoreForConversation, stopPolling, getActiveRunNo: () => activeRunNo };
|
||||
}
|
||||
Reference in new issue
Block a user