feat(short-drama-agent-front): 接入首帧授权与连续性审核

This commit is contained in:
GJ committed 2026-11-07 12:23:19 +08:00
1 parent dbf97e6f98
commit 518b630a46
35 files changed
+3070 -97

No files matched your search

@@ -0,0 +1,146 @@
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { NInput } from 'naive-ui'
import { afterEach, describe, expect, it, vi } from 'vitest'
import ContinuityReviewDrawer from '@/features/production/components/ContinuityReviewDrawer.vue'
import GeometryObservationEditor from '@/features/production/components/GeometryObservationEditor.vue'
import { createContinuityMock, continuityShots, fingerprint } from '../../fixtures/continuity'
import type { GeometryFrameObservation } from '@/features/production/continuity.types'
/** 挂载实际表单逻辑,布局和 Teleport 在本地 Chrome 独立验证。 */
let wrapper: VueWrapper
/**
* 从当前隔离页面点击真实按钮。
* @param label 完整按钮名称
*/
async function click(label: string) {
const button = wrapper.findAll('button').find(item => item.text() === label)
expect(button, `应存在按钮 ${label}`).toBeDefined()
await button!.trigger('click')
await flushPromises()
}
afterEach(() => {
wrapper?.unmount()
localStorage.clear()
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('连续性审核真实组件流程', () => {
it('完成观察才能保存本次指纹,编辑后需重新诊断,历史失效保留原结论', async () => {
const mock = createContinuityMock()
vi.stubGlobal('fetch', mock.fetcher)
wrapper = mount(ContinuityReviewDrawer, {
props: { open: true, projectId: 'mock-project', shots: continuityShots, disabled: false },
global: {
stubs: {
AppDrawer: { template: '<div><slot/><slot name="footer"/></div>' },
AssetImage: true,
LayoutSupplementPanel: true
}
}
})
await flushPromises()
expect(mock.calls.every(item => item.method === 'GET')).toBe(true)
await click('免费读取当前证据')
expect(wrapper.text()).toContain('证据不足')
expect(wrapper.text()).toContain('开门、关门属于即时状态')
const inputs = wrapper.findAllComponents(NInput)
inputs.find(item => item.props('placeholder') === '固定地标一')!.vm.$emit('update:value', '窗')
inputs.find(item => item.props('placeholder') === '固定地标二')!.vm.$emit('update:value', '门')
for (const [i, editor] of wrapper.findAllComponents(GeometryObservationEditor).entries()) {
const frame: GeometryFrameObservation = {
shotId: 's' + (i + 1),
view: 'same_side',
landmarkOrder: 'as_layout',
evidence: '画面同侧地标可辨',
features: [{ key: '铰链', side: 'left', evidence: '铰链连接可辨' }]
}
editor.vm.$emit('update:modelValue', frame)
}
await flushPromises()
await click('免费诊断人工观察')
expect(wrapper.text()).toContain('诊断结果:通过')
wrapper
.findAllComponents(NInput)
.find(item => item.props('placeholder') === '填写真实审核人')!
.vm.$emit('update:value', '测试审核人')
await flushPromises()
await click('保存本次连续性审核')
const writes = mock.calls.filter(item => item.url.endsWith('/continuity/reviews'))
expect(writes).toHaveLength(1)
expect((writes[0]!.body.observation as { expectedFingerprint: string }).expectedFingerprint).toBe(fingerprint)
expect(wrapper.text()).toContain('原审核结论:通过')
mock.state.stale = true
await click('读取')
expect(wrapper.text()).toContain('当前状态:已失效')
expect(wrapper.text()).toContain('原审核结论:通过')
wrapper.findAllComponents(GeometryObservationEditor)[0]!.vm.$emit('update:modelValue', {
shotId: 's1',
view: 'unknown',
landmarkOrder: 'unknown',
evidence: '编辑了观察',
features: []
})
await flushPromises()
const save = wrapper.findAll('button').find(item => item.text() === '保存本次连续性审核')!
expect(save.attributes('disabled')).toBeDefined()
expect(mock.calls.filter(item => item.method === 'PUT')).toHaveLength(0)
})
it('三镜相同来源问题合并范围,仍保留逐镜来源状态', async () => {
const mock = createContinuityMock()
mock.state.stale = true
vi.stubGlobal('fetch', mock.fetcher)
wrapper = mount(ContinuityReviewDrawer, {
props: { open: true, projectId: 'mock-project', shots: continuityShots, disabled: false },
global: {
stubs: {
AppDrawer: { template: '<div><slot/><slot name="footer"/></div>' },
AssetImage: true,
LayoutSupplementPanel: true
}
}
})
await flushPromises()
await click('免费读取当前证据')
expect(wrapper.text()).toContain('镜头 1.1、1.2、1.3:布局来源已变化')
expect(wrapper.text().match(/镜头 1.1、1.2、1.3:布局来源已变化/g)).toHaveLength(1)
})
it('预览参数变化废弃待审结果,版本冲突不重发正式确认', async () => {
const mock = createContinuityMock()
vi.stubGlobal('fetch', mock.fetcher)
wrapper = mount(ContinuityReviewDrawer, {
props: { open: true, projectId: 'mock-project', shots: continuityShots, disabled: false },
global: { stubs: { AppDrawer: { template: '<div><slot/><slot name="footer"/></div>' }, AssetImage: true } }
})
await flushPromises()
const inputs = wrapper.findAllComponents(NInput)
inputs
.find(item => item.props('placeholder') === '待审结构约束,例如固定连接位置与活动方向')!
.vm.$emit('update:value', '固定门轴')
inputs
.find(item => item.props('placeholder') === '填写人工观察或设计依据')!
.vm.$emit('update:value', '人工依据')
await flushPromises()
await click('免费预览结构约束')
expect(wrapper.text()).toContain('需要确认布局并重新确认母版')
inputs
.find(item => item.props('placeholder') === '待审结构约束,例如固定连接位置与活动方向')!
.vm.$emit('update:value', '修改后的门轴')
await flushPromises()
expect(wrapper.text()).not.toContain('确认正式布局')
await click('免费预览结构约束')
wrapper
.findAllComponents(NInput)
.find(item => item.props('placeholder') === '填写真实确认人')!
.vm.$emit('update:value', 'goujun')
await flushPromises()
await wrapper.find('[role="checkbox"]').trigger('click')
mock.state.conflict = true
await click('确认正式布局')
const writes = mock.calls.filter(item => item.method === 'PUT')
expect(writes).toHaveLength(1)
expect(writes[0]!.body.confirmedBy).toBe('goujun')
expect(writes[0]!.body.expectedVersion).toBe(fingerprint)
expect(wrapper.text()).not.toContain('确认正式布局')
expect(wrapper.emitted('changed')).toHaveLength(1)
})
})
@@ -0,0 +1,67 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { continuityApi, continuitySelectionValid, validObservation } from '@/features/production/continuity'
import { layoutApi } from '@/features/production/layout-api'
/** 隔离正式 HTTP 契约,所有请求由 Mock 接收。 */
const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ data: {} })))
afterEach(() => vi.unstubAllGlobals())
describe('固定几何诊断与正式保存契约', () => {
it('只接受正式顺序连续的两到三镜,不跨间隔或重复', () => {
expect(continuitySelectionValid(['a', 'b'], ['a', 'b', 'c', 'd'])).toBe(true)
expect(continuitySelectionValid(['a', 'c'], ['a', 'b', 'c', 'd'])).toBe(false)
expect(continuitySelectionValid(['b', 'a'], ['a', 'b', 'c'])).toBe(false)
expect(continuitySelectionValid(['a', 'a'], ['a', 'b'])).toBe(false)
})
it('诊断、保存指纹及历史回读使用同项目的正式接口', async () => {
vi.stubGlobal('fetch', fetcher)
const observation = {
expectedFingerprint: 'a'.repeat(64),
landmarks: ['窗', '门'] as [string, string],
frames: ['s1', 's2'].map(shotId => ({
shotId,
view: 'same_side' as const,
landmarkOrder: 'as_layout' as const,
evidence: '当前图可见',
features: [{ key: '铰链', side: 'left' as const, evidence: '连接处可见' }]
}))
}
const input = { shotIds: ['s1', 's2'], sceneFormId: 'form', observation }
await continuityApi.diagnose('p', input)
await continuityApi.save('p', { ...input, reviewer: '审核人' })
await continuityApi.review('p', 'review')
expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([
'/api/projects/p/storyboard-keyframes/continuity/diagnosis',
'/api/projects/p/storyboard-keyframes/continuity/reviews',
'/api/projects/p/storyboard-keyframes/continuity/reviews/review'
])
expect(JSON.parse(fetcher.mock.calls[1]![1]!.body as string).observation.expectedFingerprint).toBe(
'a'.repeat(64)
)
expect(validObservation(observation, ['s1', 's2'])).toBe(true)
expect(validObservation({ ...observation, landmarks: ['窗', '窗'] }, ['s1', 's2'])).toBe(false)
})
it('布局预览不混入摄影草案,正式确认使用原返回参数和真实确认人', async () => {
vi.stubGlobal('fetch', fetcher)
const supplement = {
layoutId: 'layout',
expectedVersion: 'b'.repeat(64),
sceneSubjectId: 'scene',
instruction: '远窗侧固定铰链',
evidence: '人工确认'
}
await layoutApi.preview('p', 's', supplement)
expect(JSON.parse(fetcher.mock.calls.at(-1)![1]!.body as string)).toEqual({ layoutSupplement: supplement })
const confirmation = {
name: '布局',
sceneSubjectIds: ['scene'],
constraints: [],
evidence: '人工确认',
expectedVersion: 'b'.repeat(64)
}
await layoutApi.confirm('p', confirmation, 'goujun')
expect(JSON.parse(fetcher.mock.calls.at(-1)![1]!.body as string)).toEqual({
...confirmation,
confirmedBy: 'goujun'
})
})
})
@@ -83,3 +83,28 @@ describe('首帧质量正式后端契约', () => {
expect(fetcher.mock.calls[0]![1]?.signal).toBeInstanceOf(AbortSignal)
})
})
// 同步复用回执也必须依据真实质量状态,不能只看 HTTP 200 或 passed 字段。
describe('同步首帧质量展示门禁', () => {
it('来源失效、待核查或存在硬错误时不显示通过,原回执保持不变', async () => {
const { keyframeValidationPassed } = await import('@/features/production/quality')
const result = {
passed: true,
summary: '历史通过',
subjects: [],
subjectCountConsistent: true,
unauthorizedText: { detected: false, texts: [] },
issues: []
}
expect(keyframeValidationPassed(result)).toBe(true)
expect(keyframeValidationPassed({ ...result, qualityDecision: 'stale' })).toBe(false)
expect(keyframeValidationPassed({ ...result, recoveryRequired: true })).toBe(false)
expect(
keyframeValidationPassed({
...result,
issues: [{ type: 'physical', severity: 'error', description: '结构冲突' }]
})
).toBe(false)
expect(result.passed).toBe(true)
})
})
@@ -0,0 +1,113 @@
import { defineComponent, ref } from 'vue'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { NInput, NCheckbox } from 'naive-ui'
import { afterEach, describe, expect, it, vi } from 'vitest'
import KeyframeValidationHistory from '@/features/production/components/KeyframeValidationHistory.vue'
import KeyframeExecutionStatus from '@/features/production/components/KeyframeExecutionStatus.vue'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
/** 隔离当前弹窗与会话,所有 HTTP 均由 Mock 接收。 */
let wrapper: VueWrapper
/** 复用实际历史组件公开的底栏操作,不绕过提交守卫。 */
const HistoryHarness = defineComponent({
components: { KeyframeValidationHistory, NCheckbox },
setup() {
const history = ref<InstanceType<typeof KeyframeValidationHistory> | null>(null)
return { history }
},
template:
'<KeyframeValidationHistory ref="history" project-id="auth-ui" shot-id="s" keyframe-id="k" initial-open/><NCheckbox v-if="history?.authorizationAvailable" :checked="history.authorizationAcknowledged" @update:checked="history.setAuthorizationAcknowledged($event)"/><button v-if="history?.authorizationAvailable" :disabled="!history.authorizationReady" @click="history.submitAuthorization()">授权提交</button>'
})
afterEach(() => {
wrapper?.unmount()
localStorage.clear()
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('独立授权底栏与当前审核结论', () => {
it('人工终止保留原状态和费用,显式填写、勾选后仅提交一个授权字段,409 刷新历史', async () => {
let reads = 0
const fetcher = vi.fn<typeof fetch>(async (input, init) => {
const path = String(input)
if (init?.method === 'POST')
return new Response(
JSON.stringify({ message: '授权无效', code: 'KEYFRAME_VALIDATION_AUTHORIZATION_INVALID' }),
{ status: 409 }
)
if (path.includes('/validations')) {
reads++
return new Response(
JSON.stringify({
data: [
{
id: 'terminated-task',
status: 'running',
output: null,
error: null,
createdAt: '2026-11-07',
legacyTermination: {
auditId: 'audit',
terminatedAt: '2026-11-07',
billingFinding: 'unresolved',
requiresNewAuthorization: true
}
}
]
})
)
}
return new Response(
JSON.stringify({
data: {
validationTaskId: 'terminated-task',
qualityDecision: 'passed',
effectiveQualityStatus: 'passed',
manualReviewAvailable: true,
historicalGazePreview: []
}
})
)
})
vi.stubGlobal('fetch', fetcher)
wrapper = mount(HistoryHarness)
await flushPromises()
expect(wrapper.text()).toContain('原任务状态:执行中')
expect(wrapper.text()).toContain('费用结论:待核查')
expect(wrapper.text()).toContain('已终止,无有效结论')
expect(wrapper.text()).not.toContain('人工接受')
expect(wrapper.find('button:last-child').attributes('disabled')).toBeDefined()
wrapper.findComponent(NInput).vm.$emit('update:value', 'independent-grant')
await flushPromises()
wrapper.findComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
await wrapper.find('button:last-child').trigger('click')
await flushPromises()
const posts = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')
expect(posts).toHaveLength(1)
expect(JSON.parse(String(posts[0]![1]?.body))).toEqual({ legacyVisionAuthorizationId: 'independent-grant' })
expect(reads).toBeGreaterThan(1)
expect(wrapper.find('button:last-child').attributes('disabled')).toBeDefined()
})
it('执行完成但质量未通过使用中性状态,缺少质量结论不报通过', () => {
const record = {
id: 'run',
projectId: 'p',
workflowName: 'shot-keyframe-validation',
status: 'completed',
stage: 'completed',
current: 2,
total: 2,
updatedAt: '2026-11-07',
currentResourceId: null,
metadata: null,
error: null,
startedAt: null,
completedAt: '2026-11-07',
createdAt: '2026-11-07',
result: { passed: false, qualityDecision: 'failed' }
} as WorkflowExecution
wrapper = mount(KeyframeExecutionStatus, { props: { execution: record, loading: false } })
expect(wrapper.text()).toContain('执行完成,质量未通过')
expect(wrapper.classes().join(' ')).not.toContain('success')
})
})
@@ -0,0 +1,119 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { visionState, submitKeyframeVision, physicalRetryTarget } from '@/features/production/keyframe-vision'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import type { KeyframeValidationHistoryItem } from '@/features/production/quality.types'
/** 创建隔离的历史任务,不调用任何模型。 */
const record = (extra: Partial<KeyframeValidationHistoryItem> = {}): KeyframeValidationHistoryItem => ({
id: 'original-task',
status: 'running',
output: null,
error: null,
startedAt: null,
finishedAt: null,
createdAt: '2026-11-07',
...extra
})
afterEach(() => {
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('历史终止和独立单步授权', () => {
it('终止记录保持原状态,但不再作为活动任务,不允许普通重新审核', async () => {
const terminated = record({
legacyTermination: {
auditId: 'audit',
terminatedAt: '2026-11-07',
billingFinding: 'unresolved',
requiresNewAuthorization: true
}
})
expect(visionState([terminated]).active).toBeUndefined()
expect(visionState([terminated]).terminated?.id).toBe('original-task')
await expect(submitKeyframeVision('s', 'k', [], [terminated], 'p')).rejects.toThrow('授权')
})
it('独立授权只发送授权编号,不混入文字或继续参数', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
new Response(
JSON.stringify({
data: {
shotId: 's',
keyframeId: 'k',
validationTaskId: 'new-task',
executionId: 'new-run',
status: 'pending'
}
}),
{ status: 202 }
)
)
vi.stubGlobal('fetch', fetcher)
const terminated = record({
legacyTermination: {
auditId: 'audit',
terminatedAt: '2026-11-07',
billingFinding: 'unresolved',
requiresNewAuthorization: true
}
})
await expect(
submitKeyframeVision('s', 'k', { legacyVisionAuthorizationId: 'grant' }, [terminated], 'p')
).resolves.toBeNull()
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({ legacyVisionAuthorizationId: 'grant' })
expect(String(fetcher.mock.calls[0]![0])).toContain('projectId=p')
})
it('仅 General 已完成且 Physical 失败并有计量的原任务可进入单步授权', () => {
const failed = record({
status: 'failed',
requestFingerprint: 'a'.repeat(64),
recoveryRequired: true,
steps: [
{ name: 'general', status: 'completed', issues: [] },
{ name: 'physical', status: 'failed', usage: { totalTokens: 40 } }
]
})
expect(physicalRetryTarget([failed])?.id).toBe('original-task')
expect(physicalRetryTarget([{ ...failed, steps: [{ name: 'general', status: 'failed' }] }])).toBeUndefined()
})
it('物理专项三项同时发送,可处理费用已记录的失败任务', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
new Response(
JSON.stringify({
data: {
shotId: 's2',
keyframeId: 'k2',
validationTaskId: 'original-task',
executionId: 'physical-run',
status: 'pending'
}
}),
{ status: 202 }
)
)
vi.stubGlobal('fetch', fetcher)
const failed = record({
status: 'failed',
requestFingerprint: 'a'.repeat(64),
recoveryRequired: true,
steps: [
{ name: 'general', status: 'completed', issues: [] },
{ name: 'physical', status: 'failed', usage: { totalTokens: 40 } }
]
})
const input = {
resumeValidationTaskId: failed.id,
expectedRequestFingerprint: failed.requestFingerprint!,
physicalRetryAuthorizationId: 'physical-grant'
}
await expect(submitKeyframeVision('s2', 'k2', input, [failed], 'p')).resolves.toBeNull()
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual(input)
})
it('GET 和 SSE 传递相同项目范围,旧调用省略范围仍兼容', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: {} })))
vi.stubGlobal('fetch', fetcher)
await workflowExecutionApi.get('run', undefined, 'project')
expect(String(fetcher.mock.calls[0]![0])).toContain('projectId=project')
expect(workflowExecutionApi.executionEventsUrl('run', 'project')).toContain('projectId=project')
expect(workflowExecutionApi.executionEventsUrl('run')).not.toContain('?')
})
})
@@ -0,0 +1,180 @@
import { effectScope, ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useKeyframeVision, visionState } from '@/features/production/keyframe-vision'
import type { KeyframeValidationHistoryItem } from '@/features/production/quality.types'
/** 仅模拟公开历史,不连接真实执行和 Provider。 */
function task(executionId = 'shared-run', status = 'running'): KeyframeValidationHistoryItem {
return {
id: 'same-task',
executionId,
status,
output: null,
error: null,
startedAt: null,
finishedAt: null,
createdAt: '2026-11-07'
}
}
/** 带项目归属的真实形状执行片段。 */
function execution(projectId: string, id = 'shared-run', status = 'running') {
return {
id,
projectId,
workflowName: 'shot-keyframe-validation',
status,
stage: 'validating',
current: 0,
total: 2,
updatedAt: '2026-11-07T00:00:00Z'
}
}
/** 记录所有事件连接,以模拟迟到事件及断线。 */
class Source extends EventTarget {
/** 测试创建的连接。 */ static instances: Source[] = []
/** 断线不提交新审核。 */ close = vi.fn<() => void>()
/**
* 保存实际订阅地址。
* @param url 同项目执行事件路径
*/
constructor(public url: string) {
super()
Source.instances.push(this)
}
}
let scope = effectScope()
afterEach(() => {
scope.stop()
scope = effectScope()
Source.instances = []
localStorage.clear()
sessionStorage.clear()
vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('审核 GET 与 SSE 项目隔离', () => {
it('同执行编号切项目也关闭旧 SSE,旧 404 和迟到事件不污染新项目', async () => {
let resolveOld!: (response: Response) => void
const fetcher = vi.fn<typeof fetch>(async input => {
const url = new URL(String(input), 'http://localhost')
const p = url.searchParams.get('projectId')!
if (url.pathname.endsWith('/validations')) return new Response(JSON.stringify({ data: [task()] }))
if (p === 'scope-old')
return new Promise<Response>(resolve => {
resolveOld = resolve
})
return new Response(JSON.stringify({ data: execution(p) }))
})
vi.stubGlobal('fetch', fetcher)
vi.stubGlobal('EventSource', Source)
const key = ref(JSON.stringify(['s', 'k', 'scope-old']))
const vision = scope.run(() => useKeyframeVision(key))!
await flushPromises()
const old = Source.instances[0]!
expect(old.url).toContain('projectId=scope-old')
key.value = JSON.stringify(['s', 'k', 'scope-new'])
await flushPromises()
expect(old.close).toHaveBeenCalled()
expect(Source.instances.at(-1)!.url).toContain('projectId=scope-new')
resolveOld(new Response(JSON.stringify({ message: '项目不匹配' }), { status: 404 }))
old.dispatchEvent(
new MessageEvent('message', { data: JSON.stringify(execution('scope-old', 'shared-run', 'failed')) })
)
await flushPromises()
expect(vision.execution.data.value?.projectId).toBe('scope-new')
expect(vision.execution.error.value).toBe('')
})
it('SSE 断开后只读轮询恢复,绝不自动 POST', async () => {
vi.useFakeTimers()
const fetcher = vi.fn<typeof fetch>(
async input =>
new Response(
JSON.stringify({
data: String(input).includes('/validations') ? [task()] : execution('poll-project')
})
)
)
vi.stubGlobal('fetch', fetcher)
vi.stubGlobal('EventSource', Source)
scope.run(() => useKeyframeVision(ref(JSON.stringify(['s', 'k', 'poll-project']))))!
await flushPromises()
const source = Source.instances[0]!
source.dispatchEvent(new Event('error'))
await vi.advanceTimersByTimeAsync(2600)
await flushPromises()
expect(source.close).toHaveBeenCalled()
expect(
fetcher.mock.calls.filter(([url]) => String(url).includes('/workflow-executions/')).length
).toBeGreaterThan(1)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('刷新时服务已有更新执行,不保留旧提交的未知费用锁', async () => {
const key = JSON.stringify(['s', 'k', 'external-new-run'])
sessionStorage.setItem(
'keyframe-vision:' + key,
JSON.stringify({
before: 'same-task',
beforeExecutionId: 'before-run',
taskId: 'same-task',
executionId: 'previous-run'
})
)
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(
async input =>
new Response(
JSON.stringify({
data: String(input).includes('/validations')
? [task('current-run', 'completed')]
: execution('external-new-run', 'current-run', 'completed')
})
)
)
)
const vision = scope.run(() => useKeyframeVision(ref(key)))!
await flushPromises()
expect(vision.uncertain.value).toBe(false)
expect(vision.execution.data.value?.id).toBe('current-run')
})
it('同任务出现新执行时切换观察编号,旧执行失败不覆盖新执行', async () => {
let records = [task('old-execution', 'failed')]
const fetcher = vi.fn<typeof fetch>(
async input =>
new Response(
JSON.stringify({
data: String(input).includes('/validations')
? records
: execution(
'multi',
String(input).includes('new-execution') ? 'new-execution' : 'old-execution',
String(input).includes('new-execution') ? 'running' : 'failed'
)
})
)
)
vi.stubGlobal('fetch', fetcher)
vi.stubGlobal('EventSource', Source)
const vision = scope.run(() => useKeyframeVision(ref(JSON.stringify(['s', 'k', 'multi']))))!
await flushPromises()
const old = Source.instances[0]!
records = [task('new-execution', 'running')]
await vision.history.refresh()
await flushPromises()
old.dispatchEvent(
new MessageEvent('message', { data: JSON.stringify(execution('multi', 'old-execution', 'failed')) })
)
expect(vision.execution.data.value?.id).toBe('new-execution')
expect(vision.state.value.active?.id).toBe('same-task')
expect(vision.observedExecutions.value.map(item => item.executionId)).toEqual([
'old-execution',
'new-execution'
])
const state = visionState([
task('new-execution', 'completed'),
{ ...task('old-execution', 'failed'), id: 'older-task', recoveryRequired: true }
])
expect(state.unknown).toBeUndefined()
})
})
+1 -1
View File
@@ -171,7 +171,7 @@ describe('WorkflowExecution 前端契约', () => {
const scope = effectScope()
const tracker = scope.run(() => useWorkflowExecution(ref('project-1'), 'video-quality'))!
await flushPromises()
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/workflow-executions/execution-1')
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/workflow-executions/execution-1?projectId=project-1')
expect(tracker.query.data.value?.stage).toBe('validating')
tracker.dismiss()
expect(localStorage.getItem('short-drama:workflow-execution:project-1:video-quality')).toBe('execution-1')
+7 -4
View File
@@ -150,7 +150,8 @@ function stubFetch(fetcher: Mock<typeof fetch>) {
warningCount: 0,
issues: []
})
if (path.includes('/workflow-executions/')) return jsonResponse(executions.get(path.split('/').at(-1)!))
if (path.includes('/workflow-executions/'))
return jsonResponse(executions.get(path.split('?')[0]!.split('/').at(-1)!))
const response = await implementation(url, init)
const workflowName = path.endsWith('/storyboard-directions/generate')
? 'storyboard-direction'
@@ -1943,9 +1944,11 @@ describe('工作台页面交互', () => {
for (const route of ['storyboard-directions', 'storyboard-visual-states'])
expect(fetcher.mock.calls.filter(([url]) => String(url).includes('/' + route + '?'))).toHaveLength(2)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(2)
expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe(
true
)
expect(
fetcher.mock.calls.some(
([url]) => String(url) === `/api/workflow-executions/page-execution-1?projectId=${fixture.id}`
)
).toBe(true)
})
it('后台终态部分失败不显示全成功,默认补齐与显式覆盖参数独立', async () => {
+214
View File
@@ -0,0 +1,214 @@
import type { ContinuityDiagnosis, ContinuityInput, ContinuityReview } from '@/features/production/continuity.types'
import type { DesignedShot } from '@/features/storyboard/types'
import type { LayoutConfirmation } from '@/features/production/layout-api'
/** 隔离测试使用的固定正式来源版本。 */
export const fingerprint = 'a'.repeat(64)
/** 隔离图组的摄影设计。 */
export const direction = {
shotSize: 'wide',
cameraAngle: 'eye-level',
cameraMovement: 'static',
composition: '窗在左、门在右,结构位置清晰。',
cameraPosition: '同侧观察面',
lensIntent: 'wide',
depthOfField: 'deep',
visualIntent: '固定结构对照'
}
/** 三镜正式顺序,专用于免费 Mock 验收。 */
export const continuityShots: DesignedShot[] = ['s1', 's2', 's3'].map((shotId, i) => ({
shotId,
shotNo: i + 1,
beatNo: 1,
title: `隔离测试镜头 ${i + 1}`,
description: '固定结构测试画面',
visualFocus: '固定结构',
direction,
visualState: null
}))
/** 与正式确认入口相同的完整参数。 */
export const confirmation: LayoutConfirmation = {
name: '测试空间',
sceneSubjectIds: ['scene'],
constraints: [{ kind: 'attachment', description: '固定连接位置', subjectIds: ['scene'], source: 'art-direction' }],
evidence: '隔离人工依据',
expectedVersion: fingerprint
}
/**
* 创建与本次输入绑定的正式诊断形状。
* @param input 免费诊断请求
* @param imageUrl 隔离图片地址
* @returns 当前图组与观察结论
*/
export function diagnosisFixture(input: ContinuityInput, imageUrl = '/storage/test-frame.png'): ContinuityDiagnosis {
return {
projectId: 'mock-project',
sceneFormId: input.sceneFormId,
fingerprint,
layout: {
id: 'layout',
name: '测试空间',
version: fingerprint,
evidence: '隔离人工依据',
constraints: confirmation.constraints
},
observation: input.observation ?? null,
status: input.observation ? 'passed' : 'insufficient_evidence',
issues: input.observation
? []
: [{ code: 'observations_missing', shotIds: input.shotIds, message: '待人工观察固定地标和局部结构' }],
frames: input.shotIds.map((shotId, i) => ({
shotId,
episodeNo: 1,
beatNo: 1,
shotNo: i + 1,
direction,
scene: {
subjectId: 'scene',
subjectRef: '@SC001',
formId: 'scene-form',
position: '同一空间',
transientState: i === 0 ? '门关闭' : '门打开'
},
primaryId: 'primary-' + shotId,
imageUrl,
status: 'passed',
formalSourceFingerprint: fingerprint,
providerInputFingerprint: fingerprint,
layoutReferences: []
}))
}
}
/**
* 创建可改变来源版本的纯 Mock 服务;未定义请求一律拒绝,不访问真实服务。
* @param imageUrl 隔离测试图片
* @returns Mock fetch、调用记录及可切换状态
*/
export function createContinuityMock(imageUrl = '/storage/test-frame.png') {
const calls: Array<{ url: string; method: string; body: Record<string, unknown> }> = []
const state = { stale: false, version: fingerprint, review: null as ContinuityReview | null, conflict: false }
/**
* 拦截全部请求,保证测试不产生真实 API 写入。
* @param input 请求地址
* @param init 请求参数
* @returns 隔离的正式响应
*/
const fetcher: typeof fetch = async (input, init) => {
const url = new URL(String(input), 'http://localhost')
const path = url.pathname
const method = init?.method ?? 'GET'
const body = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
calls.push({ url: String(input), method, body })
let data: unknown
let status = 200
if (path.endsWith('/generation-spec')) {
const shotId = path.split('/')[3]!
data = {
projectId: 'mock-project',
shotId,
episodeNo: 1,
beatNo: 1,
shotNo: Number(shotId.slice(1)),
title: '隔离测试镜头',
direction,
subjects: [
{
subjectId: 'scene',
subjectRef: '@SC001',
subjectName: '测试场景',
subjectFormId: 'scene-form',
subjectFormName: '日间',
module: 'scene'
}
]
}
} else if (path.endsWith('/keyframes')) {
const shotId = path.split('/')[3]!
data = [{ id: 'primary-' + shotId, shotId, isPrimary: true, status: 'completed', imageUrl }]
} else if (path.endsWith('/shared-spatial-layouts')) {
if (method === 'PUT') {
if (state.conflict)
return new Response(JSON.stringify({ message: '空间布局版本已变化,请重新审核' }), { status: 409 })
state.version = 'b'.repeat(64)
state.stale = true
data = { ...body, id: 'layout', version: state.version }
} else data = [{ id: 'layout', name: '测试空间', version: state.version, sceneSubjectIds: ['scene'] }]
} else if (path.endsWith('/masters'))
data = [
{
id: 'master',
subjectFormId: null,
viewDescription: '测试全局观察面',
imageUrl,
status: 'confirmed',
spatialLayoutVersion: fingerprint
}
]
else if (path.endsWith('/images'))
data = [{ id: 'scene-primary', subjectFormId: 'scene-form', isPrimary: true, imageUrl }]
else if (path.endsWith('/validate/preview'))
data = {
sourceCurrent: !state.stale,
sourceStaleReason: state.stale ? '布局来源已变化,需要重新核对' : null
}
else if (path.endsWith('/continuity/diagnosis')) {
data = diagnosisFixture(body as unknown as ContinuityInput, imageUrl)
if (state.stale)
data = {
...(data as ContinuityDiagnosis),
status: 'stale',
fingerprint: null,
layout: null,
observation: null,
issues: (body.shotIds as string[]).map(shotId => ({
code: 'stale',
shotIds: [shotId],
message: '布局来源已变化'
})),
frames: (data as ContinuityDiagnosis).frames.map(frame => ({
...frame,
status: 'stale',
reason: '布局来源已变化'
}))
}
} else if (path.endsWith('/continuity/reviews') && method === 'POST') {
if (state.conflict)
return new Response(JSON.stringify({ message: '来源已变化', code: 'CONTINUITY_REVIEW_STALE' }), {
status: 409
})
state.review ??= {
reviewId: 'mock-review',
reviewer: String(body.reviewer),
reviewedAt: '2026-11-07T00:00:00Z',
status: 'passed',
invalidation: null,
diagnosis: diagnosisFixture(body as unknown as ContinuityInput, imageUrl)
}
data = state.review
} else if (path.includes('/continuity/reviews/')) {
data = state.review
? {
...state.review,
...(state.stale
? { status: 'stale', invalidation: { code: 'evidence_changed', issues: [] } }
: {})
}
: null
} else if (path.endsWith('/keyframe/preview'))
data = {
shotId: path.split('/')[3],
providerPrompt: '固定结构约束:门轴在远窗侧。',
draftFingerprint: 'd'.repeat(64),
layoutConfirmation: confirmation,
productionReady: false,
requiresLayoutConfirmation: true,
requiresMasterReconfirmation: true
}
else {
data = null
status = 404
}
return new Response(JSON.stringify({ data }), { status })
}
return { fetcher, calls, state }
}
+3 -1
View File
@@ -258,7 +258,9 @@ describe('后端 API 契约', () => {
.slice(1)
.every(
([url, init]) =>
url === '/api/workflow-executions/http-breakdown-execution' && init?.method === 'GET'
url ===
'/api/workflow-executions/http-breakdown-execution?projectId=http-breakdown-project' &&
init?.method === 'GET'
)
).toBe(true)
} finally {