import { effectScope, ref } from 'vue' import { flushPromises } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' import { submitKeyframeVision, useKeyframeVision } from '@/features/production/keyframe-vision' import type { KeyframeValidationHistoryItem } from '@/features/production/quality.types' /** 使用隔离候选和会话状态模拟正式 HTTP。 */ const shotId = 'vision-shot' const assetId = 'vision-candidate' const taskId = 'vision-task' const executionId = 'vision-run' let scope = effectScope() afterEach(() => { scope.stop() scope = effectScope() sessionStorage.clear() }) /** * 模拟正式历史中的公开任务证据。 * @param status 服务保存的状态 * @param output 公开结果 * @returns 审核历史 */ function history(status: string, output: Record = {}): KeyframeValidationHistoryItem { return { id: taskId, executionId, status, output, error: null, startedAt: null, finishedAt: null, createdAt: '2026-11-06', steps: [ { name: 'general', status: 'completed', providerRequestId: 'request-1', usage: { totalTokens: 42 } }, { name: 'gaze', status: 'received' } ] } } /** * 返回一个 HTTP Mock 响应。 * @param data 公开数据 * @param status HTTP 状态 * @returns 可交给 fetch 的响应 */ function response(data: unknown, status = 200) { return new Response(JSON.stringify({ data }), { status }) } /** 从新页面创建观察者,不触发任何 POST。 */ function observe() { return scope.run(() => useKeyframeVision(ref(JSON.stringify([shotId, assetId]))))! } describe('正式首帧 Vision 的费用与恢复边界', () => { it('202 只受理一次,刷新后从历史恢复分步状态与执行记录', async () => { const fetcher = vi.fn().mockImplementation(async (url, options) => { if (options?.method === 'POST') return response( { shotId, keyframeId: assetId, validationTaskId: taskId, executionId, status: 'pending' }, 202 ) if (String(url).endsWith('/validations')) return response([history('running')]) return response({ id: executionId, status: 'running' }) }) vi.stubGlobal('fetch', fetcher) expect(await submitKeyframeVision(shotId, assetId, ['门牌'], [])).toBeNull() const vision = observe() await flushPromises() expect(vision.state.value.active?.steps?.[0]?.usage?.totalTokens).toBe(42) expect(vision.execution.data.value?.id).toBe(executionId) expect(vision.blocked.value).toBe(true) await expect(submitKeyframeVision(shotId, assetId, ['门牌'], [history('running')])).rejects.toThrow('待核查') expect(fetcher.mock.calls.filter(([, options]) => options?.method === 'POST')).toHaveLength(1) }) it('200 复用真实结论,包括未通过的已完成结果', async () => { const fetcher = vi.fn().mockResolvedValue( response({ shotId, keyframeId: assetId, validationTaskId: taskId, passed: false, issues: [], summary: '视线未通过', subjects: [], subjectCountConsistent: true, unauthorizedText: { detected: false, texts: [] } }) ) vi.stubGlobal('fetch', fetcher) expect(await submitKeyframeVision(shotId, assetId, [], [])).toMatchObject({ passed: false }) expect(fetcher).toHaveBeenCalledTimes(1) }) it('断线保留原提交并只读找回任务;未知费用不自动重试', async () => { const fetcher = vi.fn().mockImplementation(async (url, options) => { if (options?.method === 'POST') throw new TypeError('HTTP 断线') if (String(url).endsWith('/validations')) return response([history('failed', { recoveryRequired: true })]) return response({ id: executionId, status: 'failed' }) }) vi.stubGlobal('fetch', fetcher) await expect(submitKeyframeVision(shotId, assetId, [], [])).rejects.toThrow('暂时无法连接服务') const vision = observe() await flushPromises() expect(vision.state.value.unknown?.id).toBe(taskId) expect(vision.blocked.value).toBe(true) await expect( submitKeyframeVision(shotId, assetId, [], [history('failed', { recoveryRequired: true })]) ).rejects.toThrow('已有审核或费用待核查') expect(fetcher.mock.calls.filter(([, options]) => options?.method === 'POST')).toHaveLength(1) }) it('有正式可继续结论时使用原文字显式提交,保留已完成步骤', async () => { let accepted = 0 const saved = history('failed', { recoveryRequired: false, resumeAvailable: true }) const fetcher = vi.fn().mockImplementation(async (_url, options) => { if (options?.method === 'POST') { accepted++ return response( { shotId, keyframeId: assetId, validationTaskId: taskId, executionId: accepted === 1 ? executionId : 'resume-execution', status: 'pending' }, 202 ) } return response([saved]) }) vi.stubGlobal('fetch', fetcher) await submitKeyframeVision(shotId, assetId, ['旧门牌'], []) const vision = observe() await flushPromises() expect(vision.resumeTexts.value).toEqual(['旧门牌']) expect(vision.state.value.resumable?.steps?.map(item => item.status)).toEqual(['completed', 'received']) await expect(submitKeyframeVision(shotId, assetId, ['新门牌'], [saved])).rejects.toThrow('原审核参数') expect(accepted).toBe(1) await submitKeyframeVision(shotId, assetId, ['旧门牌'], [saved]) expect(accepted).toBe(2) expect( fetcher.mock.calls .filter(([, options]) => options?.method === 'POST') .map(([, options]) => JSON.parse(String(options?.body))) ).toEqual([{ allowedTexts: ['旧门牌'] }, { allowedTexts: ['旧门牌'] }]) }) it('409 活动审核只观察原编号,不能把当前表单参数当作原参数', async () => { const fetcher = vi.fn().mockImplementation(async (url, options) => { if (options?.method === 'POST') return new Response( JSON.stringify({ message: 'KEYFRAME_VALIDATION_ACTIVE', details: { code: 'KEYFRAME_VALIDATION_ACTIVE', taskId, executionId } }), { status: 409 } ) if (String(url).endsWith('/validations')) return response([history('running')]) return response({ id: executionId, status: 'running' }) }) vi.stubGlobal('fetch', fetcher) expect(await submitKeyframeVision(shotId, assetId, ['新文字'], [])).toBeNull() const vision = observe() await flushPromises() expect(vision.execution.data.value?.id).toBe(executionId) expect(vision.resumeTexts.value).toBeNull() expect(vision.blocked.value).toBe(true) }) })