import { effectScope, ref } from 'vue' import { flushPromises } from '@vue/test-utils' import { afterEach, expect, it, vi } from 'vitest' import { useSourceReview } from '@/features/production/useSourceReview' import { sourceReviewApi, type SourceReviewPreview, type SourceVisionPlan } from '@/features/production/source-review' /** 全部请求仅使用隔离数据,不连接 Provider。 */ const hash = 'a'.repeat(64) /** 原输入和当前参考完整公开证据。 */ const input = { fingerprint: hash, sourceFingerprint: hash, provider: 'mock', model: 'mock', providerPrompt: '历史描述', generationOptions: {}, references: [ { imageNumber: 1, bindings: [ { role: 'layout-master', subjectRef: '@SC1' }, { role: 'scene-form', subjectRef: '@SC2' } ] } ] } /** 可复用隔离预检。 */ export const sourcePreview: SourceReviewPreview = { projectId: 'p', shotId: 's', keyframeId: 'k', imageUrl: '', fingerprint: hash, originalPixels: { sha256: hash }, originalInputFingerprint: hash, originalProviderInput: input, sourceChanges: {}, historicalVision: [], references: [{ imageNumber: 1, imageId: 'i', imageUrl: '' }], currentReferenceInput: input } /** 精确机器计划。 */ export const sourcePlan: SourceVisionPlan = { reviewId: 'r', reviewFingerprint: hash, originalInputFingerprint: hash, referenceInputFingerprint: hash, sourceFingerprint: hash, requestFingerprint: hash, imageSha256: hash, model: 'mock', routeFingerprint: hash, steps: ['general', 'physical'] } /** 每次隔离作用域。 */ let scope = effectScope() afterEach(() => { scope.stop() scope = effectScope() sessionStorage.clear() vi.unstubAllGlobals() }) /** * 创建只处理正式路径的 Mock。 * @param status 人工原状态 * @returns 请求记录 */ export function sourceMock(status = 'passed') { const calls: Array<{ url: string; body: Record | null }> = [] const record = { reviewId: 'r', current: true, invalidation: null, review: { expectedFingerprint: hash, reviewer: '审核人', reason: '理由', observations: [ { imageNumber: 1, finding: { identity: 'passed', structure: 'passed', spatial: 'passed', action: 'passed', continuity: 'passed' }, note: '可见' } ] }, originalResult: { status, evidenceKind: 'manual-source-observation' }, reviewStatus: status === 'insufficient_evidence' ? 'needs_review' : status } const fetcher = vi.fn(async (url, init) => { const path = String(url) const body = init?.body ? JSON.parse(String(init.body)) : null calls.push({ url: path, body }) let data: unknown if (path.includes('/source-review/preview')) data = sourcePreview else if (path.endsWith('/source-reviews')) data = { reviewId: 'r' } else if (path.endsWith('/vision/preview')) data = sourcePlan else if (path.endsWith('/vision/authorizations')) data = { authorizationId: 'auth', plan: sourcePlan } else if (path.endsWith('/source-reviews/r')) data = record else if (path.includes('/quality-review')) data = { shotId: 's', keyframeId: 'k', effectiveQualityStatus: 'stale', manualReviewAvailable: false } else if (path.includes('/validations')) data = [] else return new Response(JSON.stringify({ error: { message: '未模拟请求' } }), { status: 404 }) return new Response(JSON.stringify({ data })) }) return { calls, fetcher, record } } /** 默认未知且逐图保存,人工通过不自动批准或执行。 */ it('默认未知,逐图包含全部职责;原人工状态不覆盖', async () => { const mock = sourceMock('insufficient_evidence') vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() await form.loadPreview() expect(Object.values(form.observations.value[0]!.finding)).toEqual(Array(5).fill('unknown')) expect(form.preview.value?.currentReferenceInput.references[0]?.bindings).toHaveLength(2) form.reviewer.value = '审核人' form.reason.value = '理由' form.observations.value[0]!.note = '门轴看不清' await form.save() expect(form.record.value?.reviewStatus).toBe('needs_review') expect(form.record.value?.originalResult.status).toBe('insufficient_evidence') await form.loadPlan() expect(mock.calls.filter(c => c.url.endsWith('/vision/preview'))).toHaveLength(0) expect(mock.calls.filter(c => c.url.endsWith('/vision') || c.url.endsWith('/authorizations'))).toHaveLength(0) }) /** 批准与执行分步;变更费用撤销原授权。 */ it('真实费用材料独立批准,变更范围撤销授权,不自动收费', async () => { const mock = sourceMock() vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.readRecord() await form.loadPlan() form.approvedBy.value = '批准人' form.operator.value = '操作人' form.approvalSha256.value = hash form.estimatedMin.value = 1 form.estimatedMax.value = 2 form.approved.value = true await form.authorize() expect(form.authorizationId.value).toBe('auth') const body = mock.calls.find(c => c.url.endsWith('/authorizations'))!.body! expect(body.feeScope).toEqual({ currency: 'CNY', estimatedMin: 1, estimatedMax: 2, maxRequests: 2 }) expect(mock.calls.some(c => c.url.endsWith('/vision'))).toBe(false) form.estimatedMax.value = 3 expect(form.authorizationId.value).toBe('') }) /** 项目切换后不接收旧预检。 */ it('旧项目迟到响应被忽略', async () => { const mock = sourceMock() let finish!: (value: Response) => void vi.stubGlobal( 'fetch', vi.fn((url, init) => String(url).includes('/source-review/preview') ? new Promise(resolve => { finish = resolve }) : mock.fetcher(url, init) ) ) const key = ref(JSON.stringify(['s', 'k', 'p'])) const form = scope.run(() => useSourceReview(key))! await flushPromises() const pending = form.loadPreview() key.value = JSON.stringify(['s2', 'k2', 'p2']) finish(new Response(JSON.stringify({ data: sourcePreview }))) await pending expect(form.preview.value).toBeNull() }) /** 执行请求仅携带本次授权和明确原任务指纹。 */ it('执行和恢复使用正式路径,不能混入模型或文字参数', async () => { const fetcher = vi.fn(async () => new Response(JSON.stringify({ data: {} }))) vi.stubGlobal('fetch', fetcher) await sourceReviewApi.execute('p/a', 'r/b', { authorizationId: 'auth', resume: { resumeValidationTaskId: 'task', expectedRequestFingerprint: hash } }) expect(String(fetcher.mock.calls[0]![0])).toBe( '/api/projects/p%2Fa/storyboard-keyframes/source-reviews/r%2Fb/vision' ) expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({ authorizationId: 'auth', resume: { resumeValidationTaskId: 'task', expectedRequestFingerprint: hash } }) }) /** 并发点击仅一次送出,断线费用未知不重发。 */ it('并发和未知费用保持同一候选提交保护', async () => { const { submitSourceVision } = await import('@/features/production/keyframe-vision') const key = JSON.stringify(['source-s', 'source-k', 'source-p']) let fail!: (cause: Error) => void const send = vi.fn<() => Promise>( () => new Promise((_, reject) => { fail = reject }) ) const first = submitSourceVision(key, [], send) await expect(submitSourceVision(key, [], send)).rejects.toThrow('费用待核查') fail(new Error('断线')) await expect(first).rejects.toThrow('断线') await expect(submitSourceVision(key, [], send)).rejects.toThrow('费用待核查') expect(send).toHaveBeenCalledTimes(1) }) /** 别的主图记录只能追溯,不可签发计划。 */ it('记录与主图指纹不同不会取得机器计划', async () => { const mock = sourceMock() mock.record.review.expectedFingerprint = 'b'.repeat(64) vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.readRecord() await form.loadPlan() expect(form.record.value?.originalResult.status).toBe('passed') expect(form.targetMatched.value).toBe(false) expect(form.plan.value).toBeNull() expect(mock.calls.some(c => c.url.endsWith('/vision/preview'))).toBe(false) }) /** 完成的失败结论也是完整结果,返回后不自动再提交。 */ it('200 失败结论保持原失败且结算提交观察', async () => { const { submitSourceVision } = await import('@/features/production/keyframe-vision') const failed = { shotId: 's', keyframeId: 'k', validationTaskId: 'task', imageUrl: '', isPrimary: true, passed: false, summary: '结构未通过', subjectCountConsistent: true, subjects: [], issues: [], unauthorizedText: { detected: false, texts: [] }, qualityDecision: 'failed' as const } const send = vi.fn<() => Promise>(async () => failed) const result = await submitSourceVision(JSON.stringify(['s', 'k', 'p']), [], send) expect(result).toEqual(failed) expect(result).toHaveProperty('passed', false) expect(send).toHaveBeenCalledTimes(1) }) /** 实际组件不自动预检、批准或执行,观察控件初始未知。 */ it('抽屉使用真实表单,打开只读历史,免费预检逐项展示全部参考', async () => { const { mount } = await import('@vue/test-utils') const Drawer = (await import('@/features/production/components/SourceReviewDrawer.vue')).default const mock = sourceMock() vi.stubGlobal('fetch', mock.fetcher) const wrapper = mount(Drawer, { props: { open: true, projectId: 'p', shotId: 's', keyframeId: 'k' }, global: { stubs: { AppDrawer: { template: '
' }, AssetImage: true } } }) try { await flushPromises() expect(mock.calls.every(c => c.body === null)).toBe(true) await wrapper .findAll('button') .find(b => b.text() === '免费预检当前来源')! .trigger('click') await flushPromises() expect(wrapper.text()).toContain('未知/无法看清') expect(wrapper.text()).toContain('本次新参考与逐图观察') expect(wrapper.text()).toContain('@SC1') expect(wrapper.text()).toContain('@SC2') expect(wrapper.text()).not.toContain('登记本次费用批准') await wrapper .findAll('.n-collapse-item__header-main') .find(item => item.text() === '原图片生成记录')! .trigger('click') await flushPromises() expect(wrapper.text()).toContain('历史描述') expect(wrapper.text()).not.toContain(hash) expect(wrapper.find('pre').exists()).toBe(false) } finally { wrapper.unmount() } }) /** 非阻断只依据服务端资格开放免费计划,未知观察和机器质量保持独立。 */ it('当前非阻断来源可查看独立计划,服务端明确拒绝时关闭入口', async () => { const mock = sourceMock('non_blocking_unknown') Object.assign(mock.record, { validationEligible: true }) mock.record.review.observations[0]!.finding.structure = 'unknown' vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.readRecord() await form.loadPlan() expect(form.plan.value?.reviewId).toBe('r') expect(form.record.value?.review.observations[0]!.finding.structure).toBe('unknown') expect(mock.calls.every(call => call.body === null)).toBe(true) form.plan.value = null Object.assign(form.record.value!, { validationEligible: false, reviewStatus: 'passed' }) const before = mock.calls.length await form.loadPlan() expect(mock.calls.length).toBe(before) expect(form.plan.value).toBeNull() }) /** 当前有效记录可以复用原观察,不把未知改成通过或自动批准。 */ it('回读有效记录保留未知和原理由,未编辑无需重复保存', async () => { const mock = sourceMock('non_blocking_unknown') Object.assign(mock.record, { validationEligible: true }) mock.record.review.observations[0]!.finding.structure = 'unknown' vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.readRecord() expect(form.restored.value).toBe(true) expect(form.observations.value).toEqual(mock.record.review.observations) expect(form.observations.value[0]!.finding.structure).toBe('unknown') expect(form.reviewer.value).toBe('审核人') expect(form.reason.value).toBe('理由') expect(form.needsSave.value).toBe(false) expect(form.plan.value?.reviewId).toBe('r') expect(mock.calls.every(call => call.body === null)).toBe(true) expect(form.approved.value).toBe(false) expect(form.executeApproved.value).toBe(false) form.observations.value[0]!.note = '补充当前可见证据' expect(form.needsSave.value).toBe(true) }) it.each(['stale', 'fingerprint', 'references'] as const)('%s 的旧观察不得回填到当前表单', async kind => { const mock = sourceMock() if (kind === 'stale') mock.record.current = false if (kind === 'fingerprint') mock.record.review.expectedFingerprint = 'b'.repeat(64) if (kind === 'references') mock.record.review.observations = [] vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.readRecord() expect(form.restored.value).toBe(false) expect(form.targetMatched.value).toBe(false) expect(Object.values(form.observations.value[0]!.finding)).toEqual(Array(5).fill('unknown')) expect(form.observations.value[0]!.note).toBe('') expect(form.plan.value).toBeNull() expect(mock.calls.every(call => call.body === null)).toBe(true) }) it('显式免费预检会只读回查已有来源记录,匹配后直接恢复观察', async () => { const mock = sourceMock() vi.stubGlobal('fetch', mock.fetcher) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() form.reviewId.value = 'r' await form.loadPreview() expect(form.restored.value).toBe(true) expect(form.needsSave.value).toBe(false) expect(form.observations.value).toEqual(mock.record.review.observations) expect(mock.calls.every(call => call.body === null)).toBe(true) }) it('免费预检从原审核历史关联来源记录,无需手工输入编号', async () => { const mock = sourceMock() vi.stubGlobal('fetch', async (url: RequestInfo | URL, init?: RequestInit) => { if (String(url).includes('/validations')) return new Response( JSON.stringify({ data: [ { id: 'v', status: 'completed', output: { passed: true, sourceReviewId: 'r', evidenceKind: 'independent-source-vision' }, error: null, steps: [], startedAt: null, finishedAt: null, createdAt: '2026-11-09' } ] }) ) return mock.fetcher(url, init) }) const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))! await flushPromises() expect(form.reviewId.value).toBe('') await form.loadPreview() expect(form.reviewId.value).toBe('r') expect(form.restored.value).toBe(true) expect(form.needsSave.value).toBe(false) expect(mock.calls.every(call => call.body === null)).toBe(true) }) it('回查原记录期间切换镜头,不接收迟到观察或发起批准', async () => { const mock = sourceMock() let finish!: (value: Response) => void vi.stubGlobal('fetch', (url: RequestInfo | URL, init?: RequestInit) => String(url).endsWith('/source-reviews/r') ? new Promise(resolve => { finish = resolve }) : mock.fetcher(url, init) ) const key = ref(JSON.stringify(['s', 'k', 'p'])) const form = scope.run(() => useSourceReview(key))! await flushPromises() form.reviewId.value = 'r' const loading = form.loadPreview() await flushPromises() key.value = JSON.stringify(['s2', 'k2', 'p2']) finish(new Response(JSON.stringify({ data: mock.record }))) await loading expect(form.preview.value).toBeNull() expect(form.restored.value).toBe(false) expect(form.observations.value).toEqual([]) expect(form.reviewer.value).toBe('') expect(mock.calls.every(call => call.body === null)).toBe(true) })