import { effectScope, ref } from 'vue' import { flushPromises } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' import { useValidationExecutions } from '@/features/production/useValidationExecutions' import { qualityApi } from '@/features/production/quality-api' import type { ValidationExecutionHistory } from '@/features/production/validation-executions.types' /** 隔离范围包含完整资源路径,不能复用其他任务的游标。 */ const target = ['project', 'shot', 'keyframe', 'task'] as const /** 创建单页正式响应,旧执行保持自己的失败结果。 */ function page(ids: string[], current = 'new', cursor: string | null = null): ValidationExecutionHistory { return { projectId: target[0], shotId: target[1], keyframeId: target[2], validationTaskId: target[3], taskStatus: 'running', currentExecutionId: current, total: 3, integrity: { currentExecution: 'valid' }, nextCursor: cursor, items: ids.map(id => ({ execution: { id, projectId: target[0], workflowName: 'shot-keyframe-validation', status: id === 'new' ? 'running' : 'failed', stage: 'vision', current: 1, total: 2, currentResourceId: null, metadata: { validationTaskId: target[3], shotId: target[1], keyframeId: target[2] }, result: null, error: id === 'new' ? null : '旧执行失败', startedAt: null, completedAt: null, createdAt: '2026-11-07T00:00:00Z', updatedAt: '2026-11-07T00:00:00Z' }, isCurrent: id === current, mode: 'unknown', scheduledSteps: null, reusedSteps: null, steps: null, stepsEvidence: 'not_recorded' })) } } /** 解包模拟响应,不调用任何真实 API。 */ function response(data: unknown, status = 200) { return new Response( JSON.stringify( status === 200 ? { data } : { message: '读取失败', code: 'KEYFRAME_VALIDATION_EXECUTION_CONFLICT' } ), { status } ) } let scope = effectScope() afterEach(() => { scope.stop() scope = effectScope() localStorage.clear() vi.unstubAllGlobals() }) describe('正式首帧执行分页', () => { it('API 编码完整目标,显式传项目、limit 与原样游标', async () => { const fetcher = vi.fn().mockResolvedValue(response(page([]))) vi.stubGlobal('fetch', fetcher) await qualityApi.keyframeExecutions( 's/a', 'k/b', 't/c', { projectId: 'p/d', limit: 20, cursor: 'opaque_A-1' }, new AbortController().signal ) expect(String(fetcher.mock.calls[0]![0])).toBe( '/api/storyboard-shots/s%2Fa/keyframes/k%2Fb/validations/t%2Fc/executions?projectId=p%2Fd&limit=20&cursor=opaque_A-1' ) expect(fetcher.mock.calls[0]![1]?.method).toBe('GET') }) it('默认关闭不读取,不读本机缓存;打开后按游标加载并去重,不按 total 猜测页数', async () => { const fetcher = vi .fn() .mockImplementation(async input => response( String(input).includes('cursor=opaque') ? { ...page(['new', 'old'], 'later'), total: 9 } : page(['new'], 'new', 'opaque') ) ) vi.stubGlobal('fetch', fetcher) const key = ref('') localStorage.setItem( 'vision-executions:' + JSON.stringify(['shot', 'keyframe', 'project']), JSON.stringify([{ taskId: 'fake', executionId: 'fake' }]) ) const history = scope.run(() => useValidationExecutions(key))! await flushPromises() expect(fetcher).not.toHaveBeenCalled() key.value = JSON.stringify(target) await flushPromises() expect(history.items.value.map(item => item.execution.id)).toEqual(['new']) await Promise.all([history.loadMore(), history.loadMore()]) await flushPromises() expect(history.items.value.map(item => item.execution.id)).toEqual(['new', 'old']) expect(history.data.value?.currentExecutionId).toBe('later') expect(history.items.value.some(item => item.isCurrent)).toBe(false) expect(history.nextCursor.value).toBeNull() await history.loadMore() expect(fetcher).toHaveBeenCalledTimes(2) }) it('切项目或任务清空旧页并取消旧请求,迟到 404 不影响新范围', async () => { let resolveOld!: (value: Response) => void let oldSignal: AbortSignal | undefined const fetcher = vi.fn().mockImplementation(async (input, init) => { if (String(input).includes('/task/')) { oldSignal = init?.signal as AbortSignal return new Promise(resolve => { resolveOld = resolve }) } return response({ ...page(['new']), validationTaskId: 'other-task', items: [] }) }) vi.stubGlobal('fetch', fetcher) const key = ref(JSON.stringify(target)) const history = scope.run(() => useValidationExecutions(key))! await flushPromises() key.value = JSON.stringify(['project', 'shot', 'keyframe', 'other-task']) await flushPromises() resolveOld(response(null, 404)) await flushPromises() expect(oldSignal?.aborted).toBe(true) expect(history.data.value?.validationTaskId).toBe('other-task') expect(history.error.value).toBe('') }) it('切项目时同时更换完整资源身份,旧页回执和游标不能进入新项目', async () => { let resolveOld!: (value: Response) => void vi.stubGlobal( 'fetch', vi.fn(async input => { if (new URL(String(input), 'http://localhost').searchParams.get('projectId') === 'project') return new Promise(resolve => { resolveOld = resolve }) return response({ ...page([]), projectId: 'new-project', shotId: 'new-shot', keyframeId: 'new-keyframe', validationTaskId: 'new-task', currentExecutionId: null, integrity: { currentExecution: 'not_recorded' } }) }) ) const key = ref(JSON.stringify(target)) const history = scope.run(() => useValidationExecutions(key))! await flushPromises() key.value = JSON.stringify(['new-project', 'new-shot', 'new-keyframe', 'new-task']) await flushPromises() resolveOld(response(page(['new'], 'new', 'old-cursor'))) await flushPromises() expect(history.data.value?.projectId).toBe('new-project') expect(history.items.value).toEqual([]) expect(history.nextCursor.value).toBeNull() }) it('刷新首屏中止旧翻页,新当前指针不被旧页回填,当前不在本页也不选第一条', async () => { let resolveMore!: (value: Response) => void let refreshed = false vi.stubGlobal( 'fetch', vi.fn(async input => { if (String(input).includes('cursor=')) return new Promise(resolve => { resolveMore = resolve }) return response(refreshed ? page(['old'], 'outside') : page(['new'], 'new', 'opaque')) }) ) const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))! await flushPromises() const more = history.loadMore() await flushPromises() refreshed = true await history.refresh() resolveMore(response(page(['older']))) await more expect(history.items.value.map(item => item.execution.id)).toEqual(['old']) expect(history.items.value[0]?.isCurrent).toBe(false) expect(history.data.value?.currentExecutionId).toBe('outside') }) it.each([400, 404, 409])('翻页 %i 明确结束旧游标,不自动重试或 POST', async status => { const fetcher = vi.fn(async input => String(input).includes('cursor=') ? response(null, status) : response(page(['new'], 'new', 'opaque')) ) vi.stubGlobal('fetch', fetcher) const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))! await flushPromises() await history.loadMore() await history.loadMore() expect(history.nextCursor.value).toBeNull() expect(history.error.value).not.toBe('') expect(fetcher).toHaveBeenCalledTimes(2) expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true) expect(history.items.value).toHaveLength(status === 400 ? 1 : 0) }) it('损坏的归属和当前标记不进入列表;旧审核空列表合法', async () => { const fetcher = vi .fn() .mockResolvedValueOnce( response({ ...page(['old']), items: page(['old']).items.map(item => ({ ...item, isCurrent: true })) }) ) .mockResolvedValueOnce( response({ ...page([]), total: 0, currentExecutionId: null, integrity: { currentExecution: 'not_recorded' } }) ) vi.stubGlobal('fetch', fetcher) const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))! await flushPromises() expect(history.items.value).toEqual([]) expect(history.error.value).not.toBe('') await history.refresh() expect(history.error.value).toBe('') expect(history.data.value?.integrity.currentExecution).toBe('not_recorded') }) })