feat(short-drama-agent-front): 接入摄影审核与首帧制作

This commit is contained in:
GJ committed 2026-11-06 17:10:52 +08:00
1 parent 3503926d62
commit 751106985e
32 files changed
+1970 -153

No files matched your search

@@ -0,0 +1,174 @@
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<string, unknown> = {}): 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<typeof fetch>().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<typeof fetch>().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<typeof fetch>().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<typeof fetch>().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<typeof fetch>().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)
})
})
+58 -16
View File
@@ -70,6 +70,15 @@ function recoveryButton(label: string) {
return [...document.querySelectorAll('button')].find(item => item.textContent?.trim() === label)!
}
/**
* 在实际弹窗中定位当前可操作的按钮。
* @param label 完整按钮文字
* @returns 对应按钮
*/
function dialogButton(label: string) {
return [...document.querySelectorAll<HTMLButtonElement>('button')].find(item => item.textContent?.trim() === label)
}
describe('精简公开资产回归', () => {
it('无内部字段的视频可播放,晋升使用后端权限,会话通过不能授权', async () => {
const projectId = 'public-video-contract'
@@ -298,24 +307,35 @@ describe('精简公开资产回归', () => {
const projectId = 'keyframe-promotion-contract'
const primary = keyframeFixture()
const candidate = keyframeFixture({ id: 'keyframe-2', isPrimary: false })
let persistedQuality = 'unknown'
const primaryRequests: string[] = []
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(
async url =>
new Response(
JSON.stringify({
data: String(url).endsWith('/generation-models')
? imageCatalog
: String(url).endsWith('/creative-profile')
? generationProfile(projectId)
: String(url).endsWith('/keyframes')
? [primary, candidate]
: []
})
)
)
vi.fn<typeof fetch>().mockImplementation(async (url, options) => {
if (options?.method === 'PUT') {
primaryRequests.push(String(url))
return new Response(JSON.stringify({ data: { ...candidate, isPrimary: true } }))
}
return new Response(
JSON.stringify({
data: String(url).endsWith('/generation-models')
? imageCatalog
: String(url).endsWith('/creative-profile')
? generationProfile(projectId)
: String(url).endsWith('/keyframes')
? [primary, candidate]
: String(url).endsWith('/quality-review')
? {
effectiveQualityStatus: String(url).includes(candidate.id)
? persistedQuality
: 'passed'
}
: []
})
)
})
)
const wrapper = mount(ShotProductionAssets, {
let wrapper = mount(ShotProductionAssets, {
attachTo: document.body,
props: { projectId, shot, disabled: false }
})
@@ -365,7 +385,29 @@ describe('精简公开资产回归', () => {
expect(sessionKeyframePassed(projectId, shot.shotId, candidate.id)).toBe(true)
expect(
[...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))
).toBe(true)
).toBe(false)
wrapper.unmount()
persistedQuality = 'passed'
wrapper = mount(ShotProductionAssets, {
attachTo: document.body,
props: { projectId, shot, disabled: false }
})
await flushPromises()
await wrapper
.findAll('button')
.find(item => item.text().includes('管理候选'))!
.trigger('click')
await flushPromises()
const promote = dialogButton('设为主首帧')
expect(promote).toBeDefined()
promote?.click()
await flushPromises()
dialogButton('确认切换')?.click()
await flushPromises()
expect(primaryRequests).toEqual([
'/api/storyboard-shots/' + shot.shotId + '/keyframes/' + candidate.id + '/primary'
])
} finally {
wrapper.unmount()
}
+6 -1
View File
@@ -30,6 +30,7 @@ afterEach(() => {
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
sessionStorage.clear()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
@@ -162,6 +163,10 @@ function server() {
error: null
}
else if (path.endsWith('/checkpoints')) data = []
else if (path.endsWith('/production/entry-readiness')) data = { ready: true }
else if (path.endsWith('/validations')) data = []
else if (path.endsWith('/quality-review'))
data = { effectiveQualityStatus: 'unknown', qualityDecision: 'unknown', historicalGazePreview: [] }
else if (path.includes('/readiness')) data = readiness
else if (path.endsWith('/keyframes')) data = [keyframe]
else if (path.endsWith('/videos')) data = [video]
@@ -450,7 +455,7 @@ describe('质量面板渐进展示', () => {
expect(validationButton().disabled).toBe(true)
expect(document.body.textContent).toContain('更多参数与模型限制')
expect(document.querySelector('[aria-label="额外允许的画面文字"]')).not.toBeNull()
expect(data.fetcher).not.toHaveBeenCalled()
expect(data.posts()).toHaveLength(0)
wrapper.findAllComponents(NCheckbox).at(-1)!.vm.$emit('update:checked', true)
await flushPromises()
expect(validationButton().disabled).toBe(false)
+2 -2
View File
@@ -487,7 +487,7 @@ describe('剧本完成前的下游访问限制', () => {
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/subject-identity"]`).exists()).toBe(false)
})
it('部分身份未齐备时可以逐项准备形态资料,但不能提前进入镜头设计或生产', async () => {
it('部分身份未齐备时允许核对已准备分镜,项目制作仍受限', async () => {
const id = 'partial-asset-preparation'
const state = readiness(id)
state.identity = { ready: false, reason: '还有角色尚未确认选角' }
@@ -499,7 +499,7 @@ describe('剧本完成前的下游访问限制', () => {
const { mounted } = await openProject(`/projects/${id}/subject-images`)
expect(mounted).toHaveBeenCalledExactlyOnceWith('subject-images')
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/subject-images"]`).exists()).toBe(true)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/storyboard"]`).exists()).toBe(false)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/storyboard"]`).exists()).toBe(true)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/production"]`).exists()).toBe(false)
})
@@ -0,0 +1,144 @@
import { describe, expect, it, vi } from 'vitest'
import { derivedReviewApi } from '@/features/storyboard/derived-review-api'
import { draftFromFormal } from '@/features/storyboard/derived-review'
import { subjectImagesApi } from '@/features/subject-images/api'
import type { DesignedShot } from '@/features/storyboard/types'
import type { KeyframeSpec } from '@/features/production/types'
/** 已保存的正式镜头样本,保留空间、动作和形态值。 */
const shot: DesignedShot = {
shotId: 'shot/1',
beatNo: 1,
shotNo: 1,
title: '开门',
description: '角色站在门边',
visualFocus: '手',
direction: {
shotSize: 'wide',
cameraAngle: 'eye_level',
cameraMovement: 'static',
composition: '门在右侧',
cameraPosition: '室内',
lensIntent: 'wide',
depthOfField: 'deep',
visualIntent: '空间关系'
},
visualState: {
timeOfDay: '午后',
weather: '',
atmosphere: '',
environmentTransientState: '日光',
continuityNote: '保持视角',
subjects: [
{
subjectId: 'scene',
subjectRef: '@SC0001',
subjectFormId: 'scene-form',
formName: '客厅',
expression: '',
pose: '',
gaze: '',
position: '画面右侧',
transientState: ''
}
]
}
}
/** 正式来源及已确认的场景几何。 */
const keyframe: KeyframeSpec = {
formalSourceFingerprint: 'a'.repeat(64),
projectId: 'p/1',
shotId: shot.shotId,
episodeNo: 1,
beatNo: 1,
shotNo: 1,
prompt: '正式描述',
references: [
{
subjectId: 'scene',
subjectRef: '@SC0001',
module: 'scene',
role: 'layout-master',
imageId: 'master-1',
imageUrl: '/storage/master.png',
spatialLayoutVersion: 'geometry-1'
}
]
}
describe('摄影草案与规格复用的正式契约', () => {
it('受控修订只变更摄影字段,采用原预览和正式来源', async () => {
const fingerprint = 'b'.repeat(64)
const draft = draftFromFormal(shot, keyframe, fingerprint)
const original = structuredClone(draft)
draft.direction.composition = '保留原场景并移动构图'
draft.direction.cameraPosition = '室内右侧'
expect(draft.visualState).toEqual(original.visualState)
expect(draft.sceneSources).toEqual([
{ subjectRef: '@SC0001', imageId: 'master-1', spatialLayoutVersion: 'geometry-1' }
])
const mock = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
new Response(
JSON.stringify({ data: { draftFingerprint: 'draft-fingerprint', productionReady: false } })
)
)
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { shots: [{ shotId: shot.shotId }] } })))
vi.stubGlobal('fetch', mock)
const params = { provider: 'seedream', generationOptions: { size: '2048x2048' } }
const preview = await derivedReviewApi.preview(shot.shotId, draft, params)
expect(preview.productionReady).toBe(false)
expect(mock).toHaveBeenCalledTimes(1)
await derivedReviewApi.confirm('p/1', '人工', [
{
...params,
shotId: shot.shotId,
draft,
expectedDraftFingerprint: preview.draftFingerprint,
expectedCurrentFormalSourceFingerprint: keyframe.formalSourceFingerprint
}
])
expect(mock.mock.calls.map(([url]) => url)).toEqual([
'/api/storyboard-shots/shot%2F1/keyframe/preview',
'/api/projects/p%2F1/storyboard-derived-reviews/confirm'
])
expect(JSON.parse(String(mock.mock.calls[1]![1]?.body)).shots[0]).toMatchObject({
...params,
draft,
expectedCurrentFormalSourceFingerprint: keyframe.formalSourceFingerprint,
expectedDraftFingerprint: 'draft-fingerprint'
})
})
it('场景沿用保留其它状态,只将选定的正式前镜证据交给免费预览', async () => {
const draft = draftFromFormal(shot, keyframe, 'b'.repeat(64))
draft.sceneStateCarryForward = { previousShotId: 'previous', subjectRef: '@SC0001' }
draft.visualState.subjects[0]!.transientState = '门半开'
const mock = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response(JSON.stringify({ data: { productionReady: false } })))
vi.stubGlobal('fetch', mock)
await derivedReviewApi.preview(shot.shotId, draft, {})
expect(JSON.parse(String(mock.mock.calls[0]![1]?.body)).draft).toMatchObject({
sceneStateCarryForward: draft.sceneStateCarryForward,
visualState: {
subjects: [{ formId: 'scene-form', transientState: '门半开' }],
environment: { transientState: '日光' }
}
})
expect(shot.visualState?.subjects[0]?.transientState).toBe('')
expect(mock).toHaveBeenCalledTimes(1)
})
it('道具复用冲突只发送一次 reuseOnly,不回退文字模型', async () => {
const mock = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response(JSON.stringify({ message: '没有等价规格' }), { status: 409 }))
vi.stubGlobal('fetch', mock)
await expect(subjectImagesApi.prepareStructure('form/1', true)).rejects.toMatchObject({ status: 409 })
expect(mock).toHaveBeenCalledTimes(1)
expect(mock.mock.calls[0]![0]).toBe('/api/subject-forms/form%2F1/prop-structure-spec/generate')
expect(JSON.parse(String(mock.mock.calls[0]![1]?.body))).toEqual({ reuseOnly: true })
})
})
+4 -4
View File
@@ -112,7 +112,7 @@ function stubFetch(fetcher: Mock<typeof fetch>) {
let executionCount = 0
fetcher.mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/storyboard/quality-confirmation')) {
if (path.endsWith('/storyboard-quality-confirmation')) {
const current = preparationFixture(fixture.id)
return jsonResponse({ ...current.approval, valid: true, confirmation: current.record })
}
@@ -1955,7 +1955,7 @@ describe('工作台页面交互', () => {
fetcher.mock.calls.filter(
([url, init]) =>
(!init?.method || init.method === 'GET') &&
!String(url).endsWith('/storyboard/quality-confirmation')
!String(url).endsWith('/storyboard-quality-confirmation')
)
).toHaveLength(12)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(2)
@@ -2055,10 +2055,10 @@ describe('工作台页面交互', () => {
expect(wrapper!.text()).not.toContain('第1集镜头1')
/** 切换剧集只增加当前集查询,项目时长预算只在挂载时读取一次。 */
expect(
fetcher.mock.calls.filter(([url]) => !String(url).endsWith('/storyboard/quality-confirmation'))
fetcher.mock.calls.filter(([url]) => !String(url).endsWith('/storyboard-quality-confirmation'))
).toHaveLength(6)
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard/quality-confirmation'))
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-quality-confirmation'))
).toHaveLength(1)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(1)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)