feat(short-drama-agent-front): 接入联合修订与图片费用审计

This commit is contained in:
GJ committed 2026-11-16 17:20:18 +08:00
1 parent 87427d9d43
commit f6edc4eb70
52 files changed
+5060 -516

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>联合摄影与图片费用 · 隔离验收</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./review-billing.ts"></script>
</body>
</html>
+456
View File
@@ -0,0 +1,456 @@
import { createApp, defineComponent, h, ref } from 'vue'
import { NButton, NConfigProvider, NGlobalStyle, NMessageProvider, dateZhCN, zhCN } from 'naive-ui'
import ActionMessageProvider from '../../src/components/ui/ActionMessageProvider.vue'
import { useTheme } from '../../src/composables/useTheme'
import ShotDerivedReview from '../../src/features/storyboard/components/ShotDerivedReview.vue'
import ProjectSettingsDialog from '../../src/features/generation-config/components/ProjectSettingsDialog.vue'
import KeyframeDialog from '../../src/features/production/components/KeyframeDialog.vue'
import { jointReviewFixture } from '../fixtures/joint-review'
import { imageAuditFixture } from '../fixtures/image-billing-audit'
import { additionalImageFixture } from '../fixtures/image-additional'
import { imagePreviewFixture } from '../fixtures/image-preview'
import { billingCatalog, billingProfile } from '../fixtures/billing'
import type {
ImageBillingEvidenceInput,
ImageBillingReviewInput
} from '../../src/features/image-authorization/billing-audit.types'
import type { ImageAdditionalAuthorizationInput } from '../../src/features/image-authorization/types'
import '../../src/styles/styles.css'
import '../../src/styles/admin.css'
/** 隔离数据只存在本页面,未知接口403,无任何正式项目或模型连接。 */
const joint = jointReviewFixture('mock-joint-project')
/** 可选环境验收仅修改内存草案;完整源集正文保留原始换行。 */
const environmentMode = new URLSearchParams(location.search).has('environment')
/** 模拟正式项目详情公开的本集身份和全文,不使用摘要。 */
const environmentEpisode = {
id: 'mock-source-episode',
projectId: 'mock-joint-project',
episode: 1,
title: '当前源集',
content: '第一行\r\n午后,维修间透入日光。\n天气未指定。'
}
if (environmentMode) {
joint.saved.draft.visualState.environment = {
timeOfDay: '午后',
weather: '',
atmosphere: '自然日光',
transientState: ''
}
}
/** 原unknown与账单始终保留的隔离费用账本。 */
const images = additionalImageFixture()
images.additionalAuthorizations = []
/** 原图片审计身份与费用父请求一致,所有原件必须由测试操作者填写。 */
const audit = imageAuditFixture('billing-project', 'original-image-request')
audit.identity.candidateId = 'original-image'
audit.reservedMicros = images.requests[0]!.input.reservedMicros
/** 只统计模拟同步操作,不是真实模型调用。 */
const writes = ref(0)
/** 隔离模型请求计数,已成功后同计划不再增加。 */
const mockGenerations = ref(0)
/** 精确保存当前页面发出的请求,帮助验收无隐式生成。 */
const calls: Array<{ path: string; method: string; body: unknown }> = []
/** 模拟并发仅作用于下一次正式联合采用,不改变预检。 */
let neighborConflict = false
/** 下一次采用时模拟本集正文版本变化,预检仍可通过。 */
let environmentConflict = false
/** 模拟审计409后保留表单。 */
let auditConflict = false
/** 只读结果是否已有完整同计划候选。 */
let hasImage = false
/**
* 返回隔离的正式接口响应形状。
* @param data 当前模拟数据
* @returns 不连接网络的响应
*/
function ok(data: unknown) {
return new Response(JSON.stringify({ data }), { headers: { 'Content-Type': 'application/json' } })
}
/**
* 全请求隔离处理,任何未声明路由都拒绝,不回退真实fetch。
* @param input 原请求地址
* @param init 原请求参数
* @returns 正式接口形状的Mock响应
*/
window.fetch = async (input, init) => {
const path = String(input),
method = init?.method ?? 'GET',
body = init?.body ? JSON.parse(String(init.body)) : undefined
calls.push({ path, method, body })
if (method === 'POST' || method === 'PUT') writes.value++
if (path === '/api/projects/mock-joint-project')
return ok({ id: 'mock-joint-project', episodes: [environmentEpisode] })
if (path.endsWith('/generation-models')) return ok(billingCatalog)
if (path.endsWith('/creative-profile')) return ok(billingProfile)
if (path.endsWith('/resolve')) return ok({ provider: 'openai-image', model: 'gpt-image-2.5-flare', options: {} })
if (path.includes('/keyframe-review-draft')) {
if (method === 'PUT') {
if (body.expectedRevision !== joint.saved.revision)
return new Response(JSON.stringify({ message: '草案版本已变化' }), { status: 409 })
joint.saved.draft = body.draft
joint.saved.providerInput = body.providerInput ?? null
joint.saved.expectedCurrentFormalSourceFingerprint = body.expectedCurrentFormalSourceFingerprint
joint.saved.revision++
joint.saved.status = 'current'
}
return ok(joint.saved)
}
if (path.endsWith('/storyboard-quality-confirmation'))
return ok({ ...joint.approval.approval, valid: true, confirmation: joint.approval.record })
if (path.endsWith('/storyboard-quality-confirmation/preflight'))
return ok({
current: { ...joint.approval.approval, valid: true, confirmation: joint.approval.record },
quality: joint.approval.quality
})
if (path.includes('/storyboard-directions?')) return ok(joint.directions)
if (path.includes('/storyboard-visual-states?')) return ok(joint.visuals)
if (path.includes('/keyframe-spec')) return ok(joint.keyframe)
if (path.includes('/generation-spec'))
return ok({ shotId: joint.shot.shotId, projectId: 'mock-joint-project', subjects: [] })
if (path.endsWith('/storyboard-derived-reviews/confirm')) {
if (body.shots[0]?.jointRevision) {
if (!body.preview && environmentConflict) {
environmentConflict = false
environmentEpisode.content += '\n另一位编辑已更新源正文。'
}
if (body.shots[0].jointRevision.changes.some((row: { target: string }) => row.target === 'environment')) {
const source = body.shots[0].jointRevision.environmentSource
const digest = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode(environmentEpisode.content)
)
const fingerprint = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(
''
)
if (
!source ||
source.episodeId !== environmentEpisode.id ||
source.expectedContentFingerprint !== fingerprint ||
!environmentEpisode.content.includes(source.quote)
)
return new Response(
JSON.stringify({
message: 'JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: 本集原文已变化,请重新核对。'
}),
{ status: 409 }
)
}
if (!body.preview && neighborConflict) {
neighborConflict = false
return new Response(
JSON.stringify({ message: 'JOINT_REVISION_NEIGHBOR_STALE: 相邻镜头已经更新,请重新读取。' }),
{ status: 409 }
)
}
if (!body.preview) {
const draft = body.shots[0].draft
joint.saved.status = 'stale'
joint.directions.beats[0]!.shots[0]!.direction = {
...draft.direction,
rawJson: JSON.stringify({
jointRevisionHistory: [
{
originalDirection: joint.shot.direction,
changes: body.shots[0].jointRevision.changes,
environmentSource: body.shots[0].jointRevision.environmentSource,
reviewer: body.reviewer
}
]
})
}
joint.visuals.beats[0]!.shots[0]!.visualState = {
timeOfDay: draft.visualState.environment.timeOfDay,
weather: draft.visualState.environment.weather,
atmosphere: draft.visualState.environment.atmosphere,
environmentTransientState: draft.visualState.environment.transientState,
continuityNote: draft.visualState.continuityNote,
subjects: draft.visualState.subjects.map((subject: Record<string, string>) => ({
...subject,
subjectId: 'mock-subject',
subjectFormId: subject.formId
}))
}
}
return ok({
projectId: 'mock-joint-project',
preview: body.preview,
changed: !body.preview,
reused: false,
requestFingerprint: 'f'.repeat(64),
shots: [{ shotId: joint.shot.shotId, directionId: 'mock-direction', visualStateId: 'mock-visual' }]
})
}
return ok({ shots: [{ shotId: joint.shot.shotId }] })
}
if (path.includes('/keyframe/preview')) {
const image = {
...imagePreviewFixture(),
provider: body.provider ?? 'openai-image',
model: 'gpt-image-2.5-flare',
shotId: path.includes('/audit-shot/') ? 'audit-shot' : joint.shot.shotId
}
return body.draft
? ok({
...image,
draftFingerprint: 'a'.repeat(64),
productionReady: false,
productionGate: { ready: false, reason: '隔离项目尚未完整生产' },
currentDerivedFingerprint: 'c'.repeat(64),
adjacentDerivedVersions: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }],
sceneSources: []
})
: ok(image)
}
if (path.endsWith('/image-authorizations/preview'))
return ok({
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: {
projectId: 'billing-project',
targetId: 'audit-shot',
scope: 'keyframe',
sourceFingerprint: 'c'.repeat(64)
},
planFingerprint: 'b'.repeat(64),
authorization: images
})
if (path.endsWith('/image-authorizations') && method === 'GET') return ok(images)
if (path.endsWith('/image-authorizations') && method === 'POST') {
if (body.mode === 'additional') {
const previous = images.additionalAuthorizations!.find(
row => row.input.idempotencyKey === body.idempotencyKey
)
if (previous) return ok({ authorizationId: previous.id, status: previous.status })
const approvalInput = body as ImageAdditionalAuthorizationInput
const permit = {
id: `mock-permit-${images.additionalAuthorizations!.length + 1}`,
status: 'approved',
input: { ...approvalInput, parentInputFingerprint: 'd'.repeat(64) },
usedRequests: 0,
remainingRequests: approvalInput.maxRequests
}
images.additionalAuthorizations!.push(permit)
return ok({ authorizationId: permit.id, status: permit.status, parentAuthorizationId: 'grant' })
}
return ok({ authorizationId: 'mock-standing', status: 'approved' })
}
if (path.endsWith('/revoke')) {
const id = path.split('/').at(-2)!,
row =
images.authorizations.find(item => item.id === id) ??
images.additionalAuthorizations!.find(item => item.id === id)
if (row) row.status = 'revoked'
return ok({ authorizationId: id, status: 'revoked' })
}
if (path.endsWith('/audit')) return ok(audit)
if (path.endsWith('/audit/evidence')) {
const previous = audit.history.evidence.find(row => JSON.stringify(row.body) === JSON.stringify(body))
const row = previous ?? {
id: `mock-evidence-${audit.history.evidence.length + 1}`,
requestId: audit.requestId,
taskFingerprint: audit.taskFingerprint,
body: body as ImageBillingEvidenceInput,
digest: '1'.repeat(64)
}
if (!previous) audit.history.evidence.push(row)
audit.evidenceSetFingerprint = '2'.repeat(64)
audit.released = false
audit.billingBlocked = true
audit.status = 'unreviewed'
return ok({ ...audit, evidenceId: row.id, reused: !!previous })
}
if (path.endsWith('/audit/reviews')) {
if (auditConflict) {
auditConflict = false
audit.reviewFingerprint = '3'.repeat(64)
return new Response(
JSON.stringify({
code: 'IMAGE_BILLING_AUDIT_REVIEW_CONFLICT',
message: '另一项隔离复核已先完成,请重新核对。'
}),
{ status: 409 }
)
}
const review = body as ImageBillingReviewInput
audit.history.reviews.push({
id: `mock-review-${audit.history.reviews.length + 1}`,
requestId: audit.requestId,
taskFingerprint: audit.taskFingerprint,
body: review,
digest: '4'.repeat(64),
revision: audit.history.reviews.length + 1
})
audit.released = review.decision === 'release_future_charges'
audit.status = audit.released ? 'released' : 'blocked'
audit.billingBlocked = !audit.released
audit.reviewedAmountMicros = audit.released ? 1 : null
images.billingBlocked = audit.billingBlocked
images.blockingRequestIds = audit.billingBlocked ? ['original-image-request'] : []
images.requests[0]!.billingAudit = {
status: audit.status,
released: audit.released,
reviewId: audit.released ? 'mock-review' : null,
reviewedAmountMicros: audit.reviewedAmountMicros
}
return ok({ ...audit, reused: false })
}
if (/\/audit-shot\/keyframe(?:\?|$)/.test(path)) {
if (!hasImage) {
const permit = images.additionalAuthorizations!.find(row => row.id === body.additionalAuthorizationId)
if (
!permit ||
permit.status !== 'approved' ||
!permit.remainingRequests ||
body.provider !== 'openai-image'
)
return new Response(
JSON.stringify({
code: 'IMAGE_ADDITIONAL_AUTHORIZATION_INVALID',
message: '缺少当前精确计划人工许可'
}),
{ status: 409 }
)
permit.usedRequests++
permit.remainingRequests--
mockGenerations.value++
hasImage = true
const grant = images.authorizations.find(row => row.id === images.requests[0]!.input.authorizationId)
if (grant) {
grant.usedRequests++
grant.remainingRequests = Math.max(0, grant.remainingRequests - 1)
grant.accountedMicros += images.requests[0]!.input.reservedMicros
grant.remainingMicros = Math.max(0, grant.input.budgetMicros - grant.accountedMicros)
}
images.requests.push({
...structuredClone(images.requests[0]!),
id: 'mock-image-completed',
status: 'completed',
input: { ...images.requests[0]!.input, additionalAuthorizationId: permit.id },
output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'mock-existing-result' } }
})
}
return ok({
id: 'mock-existing-candidate',
shotId: 'audit-shot',
status: 'completed',
recoveryRequired: false,
providerInputFingerprint: 'a'.repeat(64)
})
}
return new Response(JSON.stringify({ message: '隔离页面拒绝未声明接口;不会连接正式服务。' }), { status: 403 })
}
/** 原组件与原全屏抽屉组成的本地验收页,不进入正式构建入口。 */
const Preview = defineComponent({
setup() {
const theme = useTheme(),
settings = ref(false),
keyframe = ref(false)
return () =>
h(
NConfigProvider,
{ theme: theme.theme.value, themeOverrides: theme.overrides.value, locale: zhCN, dateLocale: dateZhCN },
{
default: () =>
h(
NMessageProvider,
{},
{
default: () =>
h(
ActionMessageProvider,
{},
{
default: () => [
h(NGlobalStyle),
h('main', { style: 'height:100dvh;overflow:auto;padding:24px' }, [
h(
'h1',
{ style: 'font-size:22px;margin-bottom:12px' },
'联合摄影与图片费用 · Mock隔离验收'
),
h(
'p',
{ style: 'margin-bottom:20px' },
'全部接口已拦截,测试材料仅保存在内存,不连接正式项目或真实模型。'
),
h(
'div',
{
style: 'display:flex;flex-wrap:wrap;gap:12px;margin-bottom:20px'
},
[
h(
NButton,
{ onClick: () => (settings.value = true) },
() => '项目图片授权与原请求'
),
h(
NButton,
{ onClick: () => (keyframe.value = true) },
() => '原首帧生成入口'
),
h(
NButton,
{ onClick: () => (neighborConflict = true) },
() => '模拟采用时邻镜变化'
),
h(
NButton,
{ onClick: () => (auditConflict = true) },
() => '模拟一次费用复核冲突'
),
h(
NButton,
{ onClick: () => (environmentConflict = true) },
() => '模拟采用时原文变化'
)
]
),
h(ShotDerivedReview, {
projectId: 'mock-joint-project',
episodeNo: 1,
shot: joint.shot,
shots: joint.shots,
disabled: false
}),
h(
'p',
{ role: 'status', style: 'margin-top:20px' },
`模拟同步操作 ${writes.value} 次 · 模拟图片请求 ${mockGenerations.value} 次 · 真实模型请求 0 次`
)
]),
h(ProjectSettingsDialog, {
projectId: 'billing-project',
disabled: false,
initialTab: 'image-authorization',
open: settings.value,
'onUpdate:open': value => (settings.value = value)
}),
h(KeyframeDialog, {
projectId: 'billing-project',
shotId: 'audit-shot',
shotTitle: '仅供Mock的原镜头',
disabled: true,
additionalAllowed: true,
open: keyframe.value,
'onUpdate:open': value => (keyframe.value = value),
reuseExisting: async () => hasImage,
submitGeneration: async input => {
const result = await fetch(
'/api/storyboard-shots/audit-shot/keyframe?projectId=billing-project',
{ method: 'POST', body: JSON.stringify(input) }
)
return { accepted: result.ok }
}
})
]
}
)
}
)
}
)
}
})
createApp(Preview).mount('#app')
@@ -0,0 +1,302 @@
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NCheckbox, NInput, NInputNumber, NSelect } from 'naive-ui'
import { additionalImageFixture } from '../../fixtures/image-additional'
import { additionalImageEligibility, imageChargeEligibility } from '@/features/image-authorization/model'
import { billingErrorText } from '@/lib/billing-errors'
import { imageAuthorizationApi } from '@/features/image-authorization/api'
import ImageAuthorizationSettings from '@/features/image-authorization/ImageAuthorizationSettings.vue'
import KeyframeDialog from '@/features/production/components/KeyframeDialog.vue'
import { billingCatalog, billingProfile } from '../../fixtures/billing'
import { imageRequestNotice, runGuardedImageRequest } from '@/features/subject-images/image-request-guard'
/** 释放弹层、查询和单次请求标记。 */
const wrappers: VueWrapper[] = []
afterEach(() => {
wrappers.splice(0).forEach(wrapper => wrapper.unmount())
sessionStorage.clear()
})
/**
* 创建正式包装结构的隔离响应。
* @param data Mock原数据
* @returns 独立响应
*/
function response(data: unknown) {
return new Response(JSON.stringify({ data }))
}
/**
* 以原精确范围核对人工许可。
* @param list 当前隔离费用投影
* @returns 当前范围资格
*/
function eligibility(list: ReturnType<typeof additionalImageFixture>) {
return additionalImageEligibility(
list,
'additional-permit',
'billing-project',
'audit-shot',
'gpt-image-2.5-flare',
'c'.repeat(64),
'b'.repeat(64)
)
}
describe('人工追加不解除原unknown与费用', () => {
it('默认unknown阻断;许可仅放行本精确计划,并显示已用和剩余次数', () => {
const list = additionalImageFixture()
expect(
imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed
).toBe(false)
expect(eligibility(list).allowed).toBe(true)
expect(eligibility(list).message).toContain('剩余 2 次')
expect(list.requests[0]!.status).toBe('unknown')
expect(list.requests[0]!.output?.actualBilledMicros).toBeNull()
expect(list.billingBlocked).toBe(true)
})
it.each([
'revoked',
'exhausted',
'budget',
'expired',
'project',
'shot',
'model',
'source',
'plan',
'inflight',
'another-unknown'
])('拒绝撤销/用尽/跨范围/未核清并发:%s', scenario => {
const list = additionalImageFixture(),
permit = list.additionalAuthorizations![0]!,
parent = list.requests[0]!,
grant = list.authorizations[0]!
if (scenario === 'revoked') permit.status = 'revoked'
if (scenario === 'exhausted') permit.remainingRequests = 0
if (scenario === 'budget') grant.remainingMicros = 1
if (scenario === 'expired') grant.expired = true
if (scenario === 'project') parent.input.projectId = 'other-project'
if (scenario === 'shot') parent.input.targetId = 'other-shot'
if (scenario === 'model') parent.input.model = 'other-model'
if (scenario === 'source') parent.input.sourceFingerprint = 'e'.repeat(64)
if (scenario === 'plan') parent.input.planFingerprint = 'f'.repeat(64)
if (scenario === 'inflight') parent.status = 'running'
if (scenario === 'another-unknown') {
list.requests.push({ ...structuredClone(parent), id: 'unapproved-request' })
list.blockingRequestIds.push('unapproved-request')
}
expect(eligibility(list).allowed).toBe(false)
})
it('完整同计划结果优先免费复用,许可撤销或剩余次数不能触发继续收费', () => {
const list = additionalImageFixture()
const completed = {
...structuredClone(list.requests[0]!),
id: 'returned-request',
status: 'completed',
output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'test-saved-result' } }
}
list.requests.push(completed)
list.additionalAuthorizations![0]!.status = 'revoked'
const result = imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64), {
id: 'additional-permit',
projectId: 'billing-project',
sourceFingerprint: 'c'.repeat(64)
})
expect(result).toMatchObject({ allowed: true, reusable: true })
expect(list.billingBlocked).toBe(true)
})
it('费用核清但没有结果的原unknown精确计划仍不能普通重发', () => {
const list = additionalImageFixture()
list.billingBlocked = false
list.blockingRequestIds = []
expect(
imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed
).toBe(false)
})
it('原网络连接与真实Provider额度错误分开,底层原因不伪装为额度不足', () => {
expect(
billingErrorText('OPENAI_IMAGE_REQUEST_UNKNOWN', {
failureType: 'timeout_unknown',
transportMode: 'proxy',
causeCode: 'UND_ERR_CONNECT_TIMEOUT'
})
).toContain('底层连接超时')
expect(
billingErrorText('OPENAI_IMAGE_PROVIDER_ERROR', {
failureType: 'billing_quota_exceeded',
transportMode: 'proxy',
causeCode: 'UND_ERR_CONNECT_TIMEOUT'
})
).toContain('计费配额不足')
expect(
billingErrorText('OPENAI_IMAGE_PROVIDER_ERROR', {
failureType: 'billing_quota_exceeded',
transportMode: 'proxy',
causeCode: 'UND_ERR_CONNECT_TIMEOUT'
})
).not.toContain('底层连接超时')
})
})
describe('原授权设置与首帧入口追加交互', () => {
it('用户逐项接受风险才登记additional,不提交新金额/模型/目标;撤销仍用原接口', async () => {
const list = additionalImageFixture(),
fetcher = vi.fn<typeof fetch>(async (url, init) => {
if (String(url).endsWith('/generation-models')) return response(billingCatalog)
if (init?.method === 'POST')
return response({ authorizationId: 'additional-created', status: 'approved' })
return response(list)
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(ImageAuthorizationSettings, { props: { projectId: 'billing-project', disabled: false } })
wrappers.push(wrapper)
await flushPromises()
await wrapper
.findAll('.n-collapse-item__header-main')
.find(item => item.text() === '原生成请求与费用状态')!
.trigger('click')
await flushPromises()
await wrapper
.findAll('button')
.find(button => button.text() === '人工有限追加')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('原精确计划人工有限追加')
expect(
wrapper
.findAllComponents(NInputNumber)
.find(input => input.attributes('aria-label') === '人工追加次数')!
.props('value')
).toBeNull()
await wrapper.vm.save()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(0)
wrapper
.findAllComponents(NInputNumber)
.find(input => input.attributes('aria-label') === '人工追加次数')!
.vm.$emit('update:value', 2)
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '追加批准人')!
.vm.$emit('update:value', '测试明确批准人')
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '追加批准说明')!
.vm.$emit('update:value', '接受原未知费用,仅追加此精确计划两次')
wrapper
.findAllComponents(NCheckbox)
.find(input => input.text().includes('我接受原请求'))!
.vm.$emit('update:checked', true)
await flushPromises()
await wrapper.vm.save()
const call = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(JSON.parse(String(call[1]?.body))).toEqual({
mode: 'additional',
idempotencyKey: expect.any(String),
parentRequestId: 'original-image-request',
maxRequests: 2,
acknowledgeUnknownPriorBilling: true,
approvedBy: '测试明确批准人',
approvalNote: '接受原未知费用,仅追加此精确计划两次'
})
expect(list.requests[0]!.status).toBe('unknown')
await imageAuthorizationApi.revoke('billing-project', 'additional-created', {
revokedBy: '测试操作者',
reason: '关闭剩余次数'
})
expect(fetcher.mock.calls.at(-1)?.[0]).toBe(
'/api/projects/billing-project/image-authorizations/additional-created/revoke'
)
expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/primary|\/vision/.test(String(url)))).toBe(
false
)
})
it('首帧必须主动选许可并重新预览,仅提交一次;原本地unknown标记不清除', async () => {
const list = additionalImageFixture(),
submit = vi.fn<() => Promise<{ accepted: boolean }>>().mockResolvedValue({ accepted: true })
const fetcher = vi.fn<typeof fetch>(async url => {
const path = String(url)
if (path.endsWith('/generation-models')) return response(billingCatalog)
if (path.endsWith('/creative-profile')) return response(billingProfile)
if (path.endsWith('/resolve'))
return response({ provider: 'openai-image', model: 'gpt-image-2.5-flare', options: {} })
if (path.endsWith('/image-authorizations')) return response(list)
if (path.endsWith('/image-authorizations/preview'))
return response({
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: {
projectId: 'billing-project',
targetId: 'audit-shot',
scope: 'keyframe',
sourceFingerprint: 'c'.repeat(64)
},
planFingerprint: 'b'.repeat(64),
authorization: list
})
if (path.endsWith('/keyframe/preview')) {
return response({
shotId: 'audit-shot',
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
providerPrompt: 'Mock首帧输入',
previewFingerprint: 'a'.repeat(64),
referenceImages: [],
generationConfig: {}
})
}
throw new Error('未模拟 ' + path)
})
vi.stubGlobal('fetch', fetcher)
await expect(
runGuardedImageRequest('keyframe:audit-shot', async () => {
throw new Error('原连接结果未知')
})
).rejects.toThrow('原连接结果未知')
const wrapper = mount(KeyframeDialog, {
attachTo: document.body,
props: {
open: true,
projectId: 'billing-project',
shotId: 'audit-shot',
shotTitle: '隔离镜头',
disabled: true,
additionalAllowed: true,
submitGeneration: submit
}
})
wrappers.push(wrapper)
await flushPromises()
const selection = wrapper
.findAllComponents(NSelect)
.find(select => select.attributes('aria-label') === '本次人工追加许可')!
expect(selection.props('value')).toBeNull()
selection.vm.$emit('update:value', 'additional-permit')
await flushPromises()
const preview = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
button => button.textContent?.trim() === '预览实际生成输入'
)!
preview.click()
await flushPromises()
const confirm = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
button => button.textContent?.trim() === '确认生成首帧'
)!
expect(
JSON.parse(String(fetcher.mock.calls.find(([url]) => String(url).endsWith('/keyframe/preview'))![1]?.body))
).not.toHaveProperty('additionalAuthorizationId')
expect(confirm.disabled).toBe(false)
confirm.click()
await flushPromises()
confirm.click()
await flushPromises()
expect(submit).toHaveBeenCalledTimes(1)
expect(submit).toHaveBeenCalledWith(
expect.objectContaining({
provider: 'openai-image',
additionalAuthorizationId: 'additional-permit',
expectedPreviewFingerprint: 'a'.repeat(64),
setPrimary: false
})
)
expect(imageRequestNotice('keyframe:audit-shot')).toContain('待核对')
expect(list.requests[0]!.status).toBe('unknown')
})
})
@@ -0,0 +1,246 @@
import { defineComponent, h } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useImageBillingAudit } from '@/features/image-authorization/useImageBillingAudit'
import { imageBillingAuditApi } from '@/features/image-authorization/billing-audit-api'
import {
imageBillingAmountMicros,
imageBillingEvidenceIssues,
imageBillingReleaseIssues
} from '@/features/image-authorization/billing-audit'
import { imageAuditFixture, imageAuditFacts } from '../../fixtures/image-billing-audit'
import type {
ImageBillingEvidenceInput,
ImageBillingReviewInput
} from '@/features/image-authorization/billing-audit.types'
/** 释放查询,避免迟到请求串到其它用例。 */
const wrappers: VueWrapper[] = []
afterEach(() => wrappers.splice(0).forEach(wrapper => wrapper.unmount()))
/**
* 返回正式包装结构的隔离响应。
* @param data Mock业务值
* @returns 独立响应
*/
function response(data: unknown) {
return new Response(JSON.stringify({ data }))
}
describe('图片原请求费用事实与正式API', () => {
it.each([
{ amount: null, micros: null },
{ amount: 0, micros: 0 },
{ amount: 0.000001, micros: 1 },
{ amount: 1.000001, micros: 1000001 },
{ amount: 0.0000001, micros: null },
{ amount: -1, micros: null },
{ amount: 10000000000, micros: null }
])('微美元精确换算,不把unknown显示成0:$amount', ({ amount, micros }) =>
expect(imageBillingAmountMicros(amount)).toBe(micros)
)
it('本地和LangSmith编号、弱证据和原成功事实冲突不能用于核清', () => {
const view = imageAuditFixture(),
facts = imageAuditFacts()
facts.providerRequestId = view.requestId
expect(imageBillingEvidenceIssues(facts, view)).toContain(
'本地任务、请求或 LangSmith 编号不能作为供应方请求号。'
)
facts.providerRequestId = 'test-trace'
facts.artifacts.push({
id: 'trace',
kind: 'langsmith',
recordId: 'test-trace',
sha256: '3'.repeat(64),
reference: 'Mock观察'
})
expect(imageBillingEvidenceIssues(facts, view)).toContain(
'本地任务、请求或 LangSmith 编号不能作为供应方请求号。'
)
facts.providerRequestId = 'test-provider-request'
facts.execution.outcome = 'unknown'
expect(imageBillingReleaseIssues({ ...facts, identity: view.identity }, view).join(' ')).toContain('仍未确认')
facts.execution.outcome = 'failed'
view.hasOriginalReceipt = true
expect(imageBillingReleaseIssues({ ...facts, identity: view.identity }, view)).toContain(
'外部声明与原成功回执冲突。'
)
})
it('原项目、原应用请求和原完整身份通过正式图片路径提交,不混用视频或当前新镜头', async () => {
const view = imageAuditFixture('p/1', 'r/1'),
fetcher = vi.fn<typeof fetch>().mockImplementation(async () => response(view))
vi.stubGlobal('fetch', fetcher)
await imageBillingAuditApi.get('p/1', 'r/1')
const body: ImageBillingEvidenceInput = {
expectedTaskFingerprint: view.taskFingerprint,
operator: '测试登记人',
evidence: { ...imageAuditFacts(), identity: view.identity }
}
await imageBillingAuditApi.evidence('p/1', 'r/1', body)
expect(fetcher.mock.calls.map(([url]) => url)).toEqual([
'/api/projects/p%2F1/image-requests/r%2F1/audit',
'/api/projects/p%2F1/image-requests/r%2F1/audit/evidence'
])
expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual(body)
expect(body.evidence.identity).toBe(view.identity)
})
})
/**
* 主动登记一组隔离材料,绝不自动选择复核或解除。
* @param form 真实审计表单
*/
async function register(form: ReturnType<typeof useImageBillingAudit>) {
form.operator.value = '测试登记人'
form.facts.value = imageAuditFacts()
form.confirmed.value = true
await form.submit()
await flushPromises()
}
describe('图片证据登记与独立复核编排', () => {
/**
* 挂载真实Hook,所有写入只进入内存投影。
* @param projectId 隔离项目
* @returns 表单、Mock控制和只读状态
*/
async function harness(projectId = 'image-audit-flow') {
const view = imageAuditFixture(projectId)
let conflictNext = false
const changed = vi.fn<() => void>()
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url)
if (init?.method !== 'POST')
return response({
...view,
projectId: path.includes('/other-project/') ? 'other-project' : view.projectId,
identity: {
...view.identity,
projectId: path.includes('/other-project/') ? 'other-project' : view.projectId
}
})
const body = JSON.parse(String(init.body))
if (path.endsWith('/evidence')) {
view.history.evidence.push({
id: 'registered-evidence',
requestId: view.requestId,
taskFingerprint: view.taskFingerprint,
digest: '3'.repeat(64),
body: body as ImageBillingEvidenceInput
})
view.evidenceSetFingerprint = '4'.repeat(64)
return response({ ...view, evidenceId: 'registered-evidence', reused: false })
}
if (conflictNext) {
conflictNext = false
view.reviewFingerprint = '5'.repeat(64)
return new Response(
JSON.stringify({ code: 'IMAGE_BILLING_AUDIT_REVIEW_CONFLICT', message: '另一项复核已先完成' }),
{ status: 409 }
)
}
view.history.reviews.push({
id: 'reviewed-evidence',
requestId: view.requestId,
taskFingerprint: view.taskFingerprint,
digest: '6'.repeat(64),
revision: view.history.reviews.length + 1,
body: body as ImageBillingReviewInput
})
view.status = body.decision === 'release_future_charges' ? 'released' : 'blocked'
view.released = view.status === 'released'
view.billingBlocked = !view.released
view.reviewedAmountMicros = view.released ? 1 : null
return response({ ...view, reviewId: 'reviewed-evidence', reused: false })
})
vi.stubGlobal('fetch', fetcher)
let form!: ReturnType<typeof useImageBillingAudit>
const wrapper = mount(
defineComponent({
props: { projectId: { type: String, required: true } },
setup(props) {
form = useImageBillingAudit(
{
get projectId() {
return props.projectId
},
requestId: 'unknown-image'
},
changed
)
return () => h('div')
}
}),
{ props: { projectId } }
)
wrappers.push(wrapper)
await flushPromises()
return {
form,
fetcher,
view,
changed,
wrapper,
conflict: () => {
conflictNext = true
}
}
}
it('登记不解锁;用户另行选择和复核才核清,原unknown/null/预留仍保留', async () => {
const { form, fetcher, view, changed } = await harness()
expect(fetcher).toHaveBeenCalledTimes(1)
expect(form.facts.value.billing.amount).toBeNull()
await register(form)
expect(view.billingBlocked).toBe(true)
expect(view.originalRequestStatus).toBe('unknown')
expect(form.action.value).toBe('evidence')
expect(form.confirmed.value).toBe(false)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
form.action.value = 'review'
form.evidenceId.value = 'registered-evidence'
form.decision.value = 'release_future_charges'
form.reviewer.value = '测试独立复核人'
form.reason.value = 'Mock原件与唯一请求已经核对'
form.confirmationSha256.value = '7'.repeat(64)
form.confirmed.value = true
expect(form.canSubmit.value).toBe(true)
await form.submit()
await flushPromises()
expect(view.billingBlocked).toBe(false)
expect(view.originalRequestStatus).toBe('unknown')
expect(view.originalActualBilledMicros).toBeNull()
expect(view.reservedMicros).toBe(1000000)
expect(changed).toHaveBeenCalledTimes(2)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2)
expect(fetcher.mock.calls.every(([url]) => String(url).includes('/image-requests/'))).toBe(true)
await form.refresh()
await form.submit()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2)
})
it('409刷新正式GET并保留表单、撤销确认,不自动重复提交', async () => {
const setup = await harness('image-conflict')
await register(setup.form)
const form = setup.form
form.action.value = 'review'
form.evidenceId.value = 'registered-evidence'
form.reviewer.value = '测试复核人'
form.reason.value = '保留此前已填理由'
form.confirmationSha256.value = '8'.repeat(64)
form.confirmed.value = true
setup.conflict()
await form.submit()
expect(form.reason.value).toBe('保留此前已填理由')
expect(form.confirmationSha256.value).toBe('8'.repeat(64))
expect(form.confirmed.value).toBe(false)
expect(form.query.data.value?.reviewFingerprint).toBe('5'.repeat(64))
expect(setup.view.history.reviews).toHaveLength(0)
await form.submit()
expect(setup.fetcher.mock.calls.filter(([url]) => String(url).endsWith('/reviews'))).toHaveLength(1)
await setup.wrapper.setProps({ projectId: 'other-project' })
await flushPromises()
expect(form.operator.value).toBe('')
expect(form.reason.value).toBe('')
expect(form.confirmationSha256.value).toBe('')
expect(form.evidenceId.value).toBe('')
expect(form.facts.value.artifacts).toEqual([])
})
})
@@ -0,0 +1,40 @@
import { defineComponent, h } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import { expect, it, vi } from 'vitest'
import BeatShotDirectory from '@/features/storyboard/components/BeatShotDirectory.vue'
import { designedShot } from '@/features/storyboard/testing/fixtures'
it('定位嵌套镜头时避让所属段落标题,首行镜号不被吸顶标题遮挡', async () => {
const wrapper = mount(
defineComponent({
props: { activeId: { type: String, required: true } },
setup: props => () =>
h('div', { class: 'n-scrollbar-container' }, [
h(BeatShotDirectory, {
shots: [designedShot('first'), { ...designedShot('next'), beatNo: 2 }],
activeId: props.activeId,
itemClass: 'shot-link'
})
])
}),
{ props: { activeId: 'first' } }
)
try {
await flushPromises()
const viewport = wrapper.get<HTMLElement>('.n-scrollbar-container').element
const selected = wrapper.findAll<HTMLElement>('.directory-item')[1]!.element
const heading = selected.closest('[role="group"]')!.querySelector('h4')!
Object.defineProperty(heading, 'offsetHeight', { configurable: true, value: 38 })
vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 100, 240, 400))
vi.spyOn(selected, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 180, 240, 88))
viewport.scrollTop = 80
/** 记录目录自身滚动目标,断言标题避让距离。 */
const scrollTo = vi.fn<(options: ScrollToOptions) => void>()
Object.defineProperty(viewport, 'scrollTo', { configurable: true, value: scrollTo })
await wrapper.setProps({ activeId: 'next' })
await flushPromises()
expect(scrollTo).toHaveBeenLastCalledWith({ top: 122, behavior: 'smooth' })
} finally {
wrapper.unmount()
}
})
@@ -0,0 +1,381 @@
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NCheckbox, NInput } from 'naive-ui'
import JointDraftReviewPanel from '@/features/storyboard/components/JointDraftReviewPanel.vue'
import { jointDraftDifferences } from '@/features/storyboard/joint-review'
import { visualStateTimeSections, visualStateTimeIssueLabel } from '@/features/storyboard/visual-state-time'
import { imagePreviewFixture } from '../../fixtures/image-preview'
import { createHash } from 'node:crypto'
import { jointReviewFixture } from '../../fixtures/joint-review'
/** 每个镜头用例隔离项目锁。 */
let serial = 0
/** 释放查询和免费请求。 */
const wrappers: VueWrapper[] = []
afterEach(() => wrappers.splice(0).forEach(wrapper => wrapper.unmount()))
/**
* 正式包装的独立Mock响应。
* @param data 原契约数据
* @returns 独立响应
*/
function response(data: unknown) {
return new Response(JSON.stringify({ data }))
}
describe('联合采用完整差异与时间展示', () => {
it('完整列出摄影、主体及四项环境差异,身份与主体集合仍禁止修改', () => {
const fixture = jointReviewFixture(),
draft = structuredClone(fixture.saved.draft)
let differences = jointDraftDifferences(fixture.formal, draft)
expect(differences).toHaveLength(4)
expect(differences.every(item => item.allowed)).toBe(true)
expect(differences.map(item => item.change?.target)).toEqual([
'direction',
'direction',
'visualState',
'subject'
])
draft.visualState.environment.weather = ''
draft.visualState.subjects[0]!.formId = '不能偷偷换形态'
differences = jointDraftDifferences(fixture.formal, draft)
expect(differences.find(item => item.label === '环境 · 天气')).toMatchObject({
allowed: true,
change: { target: 'environment', field: 'weather', before: '小雨', after: '' }
})
expect(differences.filter(item => !item.allowed).map(item => item.label)).toContain('@CH0001 · 形态身份')
draft.visualState.subjects.push({ ...draft.visualState.subjects[0]!, subjectRef: '@CH9999' })
expect(
jointDraftDifferences(fixture.formal, draft).some(item => !item.allowed && item.label.includes('主体集合'))
).toBe(true)
})
it('只按正式四个时间标记排版,旧文字和原问题不被重写或判通过', () => {
const note = jointReviewFixture().saved.draft.visualState.continuityNote
expect(visualStateTimeSections(note).map(section => section.kind)).toEqual([
'input',
'planned',
'continuity',
'video'
])
expect(visualStateTimeSections('角色已经持物,后续动作尚待拍摄。')).toEqual([
{ kind: 'legacy', title: '原衔接说明(未分段)', text: '角色已经持物,后续动作尚待拍摄。' }
])
expect(visualStateTimeIssueLabel({ code: 'VISUAL_STATE_START_CONFLICT', severity: 'error' })).toBe(
'开拍状态冲突'
)
expect(visualStateTimeIssueLabel({ code: 'VISUAL_STATE_TIME_NEEDS_REVIEW', severity: 'needs_review' })).toBe(
'时间语义待人工核对'
)
expect(
visualStateTimeIssueLabel({ code: 'VISUAL_STATE_VIDEO_END_UNSUPPORTED', severity: 'needs_review' })
).toBe('真实视频末态缺少证据')
expect(visualStateTimeIssueLabel({ code: 'other', severity: 'needs_review' })).toBe('需要人工核对')
})
})
/**
* 点击真实组件当前显示的指定操作。
* @param wrapper 实际表单
* @param label 可见按钮名称
*/
async function click(wrapper: VueWrapper, label: string) {
const button = wrapper.findAll('button').find(item => item.text() === label)!
expect(button.attributes('disabled')).toBeUndefined()
await button.trigger('click')
await flushPromises()
}
/**
* 明确填写实际审核人及剪辑依据。
* @param wrapper 实际表单
*/
async function author(wrapper: VueWrapper) {
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '联合修订依据')!
.vm.$emit('update:value', '本次仅调整当前开拍状态,保留原动作和相邻观察轴。')
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '联合审核人')!
.vm.$emit('update:value', '测试联合审核人')
await flushPromises()
}
describe('原摄影抽屉内的联合流程', () => {
/**
* 挂载真实联合模式,成功/冲突均只写隔离投影。
* @param conflict 是否模拟相邻版本冲突
* @param reused 是否模拟幂等采用
* @param environment 是否包含有据环境修订
* @returns 组件、模拟请求及正式来源
*/
async function editor(conflict = false, reused = false, environment = false) {
const projectId = `joint-flow-${++serial}`,
fixture = jointReviewFixture(projectId)
/** 正式项目详情中的本集身份与原始正文,摘要不能代替正文哈希。 */
const episode = {
id: 'source-episode',
projectId,
episode: 1,
title: '当前源集',
content: '第一行\r\n午后,维修间透入日光。\n天气未指定。'
}
if (environment) {
fixture.saved.draft.visualState.environment.timeOfDay = '午后'
fixture.saved.draft.visualState.environment.weather = ''
fixture.saved.draft.visualState.environment.atmosphere = '自然日光'
fixture.saved.draft.visualState.environment.transientState = ''
}
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url)
if (path === `/api/projects/${projectId}`) return response({ id: projectId, episodes: [episode] })
if (path.includes('/keyframe-review-draft')) {
if (init?.method === 'PUT') {
const body = JSON.parse(String(init.body))
fixture.saved.draft = body.draft
fixture.saved.revision++
fixture.saved.providerInput = body.providerInput
fixture.saved.expectedCurrentFormalSourceFingerprint = body.expectedCurrentFormalSourceFingerprint
}
return response(fixture.saved)
}
if (path.endsWith('/storyboard-quality-confirmation'))
return response({ ...fixture.approval.approval, valid: true, confirmation: fixture.approval.record })
if (path.includes('/storyboard-directions?')) return response(fixture.directions)
if (path.includes('/storyboard-visual-states?')) return response(fixture.visuals)
if (path.includes('/keyframe-spec')) return response(fixture.keyframe)
if (path.includes('/keyframe/preview')) {
const body = JSON.parse(String(init?.body))
if (!body.draft) return response({ ...imagePreviewFixture(), shotId: fixture.shot.shotId })
return response({
...imagePreviewFixture(),
shotId: fixture.shot.shotId,
draftFingerprint: 'a'.repeat(64),
currentDerivedFingerprint: 'c'.repeat(64),
adjacentDerivedVersions: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }],
productionReady: false,
productionGate: { ready: false, reason: '项目未完成' },
sceneSources: []
})
}
if (path.endsWith('/storyboard-derived-reviews/confirm')) {
const body = JSON.parse(String(init?.body))
if (conflict) {
if (environment) episode.content += '\n源正文已被其他人修改。'
return new Response(
JSON.stringify({
message: environment
? 'JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: 本集原文已变化。'
: 'JOINT_REVISION_NEIGHBOR_STALE: 紧邻镜头已更新,请重读。'
}),
{ status: 409 }
)
}
if (!body.preview) fixture.saved.status = 'stale'
return response({
projectId,
preview: body.preview,
changed: !body.preview && !reused,
reused: !body.preview && reused,
requestFingerprint: 'f'.repeat(64),
shots: [
{ shotId: fixture.shot.shotId, directionId: 'direction-formal', visualStateId: 'visual-formal' }
]
})
}
throw new Error(`未模拟 ${init?.method ?? 'GET'} ${path}`)
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(JointDraftReviewPanel, {
props: { projectId, episodeNo: 1, shot: fixture.shot, shots: fixture.shots, disabled: false }
})
wrappers.push(wrapper)
await flushPromises()
return { wrapper, fixture, fetcher, episode }
}
it.each([false, true])('保存、画面预览、联合免费预检和采用分开,幂等回执=%s', async reused => {
const { wrapper, fetcher, fixture } = await editor(false, reused)
expect(wrapper.text()).toContain('完整字段差异(4 项)')
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '联合摄影意图')!
.vm.$emit('update:value', '明确修改后保存的摄影意图')
await flushPromises()
await wrapper.vm.save()
await flushPromises()
expect(wrapper.emitted('changed')).toBeUndefined()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1)
await click(wrapper, '免费核对草案画面输入')
expect(wrapper.text()).toContain('相邻镜头依据')
await author(wrapper)
await click(wrapper, '免费预检联合采用')
expect(wrapper.vm.canAdopt).toBe(false)
wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
expect(wrapper.vm.canAdopt).toBe(true)
await wrapper.vm.adopt()
await flushPromises()
const confirms = fetcher.mock.calls.filter(([url]) =>
String(url).endsWith('/storyboard-derived-reviews/confirm')
)
expect(confirms).toHaveLength(2)
const first = JSON.parse(String(confirms[0]![1]?.body)),
second = JSON.parse(String(confirms[1]![1]?.body))
expect(second).toEqual({ ...first, preview: false })
expect(first.shots[0].jointRevision).toMatchObject({
expectedDraftRevision: 8,
expectedDerivedFingerprint: 'c'.repeat(64),
expectedNeighbors: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }]
})
expect(first.shots[0].jointRevision.changes).toHaveLength(4)
expect(first.shots[0].jointRevision).not.toHaveProperty('environmentSource')
expect(first.shots[0].expectedCurrentFormalSourceFingerprint).toBe(fixture.keyframe.formalSourceFingerprint)
expect(first.shots[0].draft).not.toHaveProperty('subjectStateRevision')
expect(wrapper.emitted('changed')).toHaveLength(1)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1)
expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/vision|\/primary/.test(String(url)))).toBe(
false
)
expect(wrapper.text()).toContain('原草案和历史保留')
})
it('邻镜变化409保留原稿并重读,不自动采用或改为当前新版本', async () => {
const { wrapper, fetcher } = await editor(true)
await click(wrapper, '免费核对草案画面输入')
await author(wrapper)
await click(wrapper, '免费预检联合采用')
expect(wrapper.vm.canAdopt).toBe(false)
expect(wrapper.text()).toContain('当前输入已保留')
expect(
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '联合摄影意图')!
.props('value')
).toBe('保留正式动作的开拍意图')
const confirms = fetcher.mock.calls.filter(([url]) =>
String(url).endsWith('/storyboard-derived-reviews/confirm')
)
expect(confirms).toHaveLength(1)
expect(JSON.parse(String(confirms[0]![1]?.body)).preview).toBe(true)
expect(wrapper.emitted('changed')).toBeUndefined()
})
it('内容改变撤销原预检,不自动套用重新读取的草案', async () => {
const { wrapper, fetcher, fixture } = await editor()
await click(wrapper, '免费核对草案画面输入')
await author(wrapper)
await click(wrapper, '免费预检联合采用')
wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '摄影构图')!
.vm.$emit('update:value', '重新编辑,旧确认失效')
await flushPromises()
expect(wrapper.vm.canAdopt).toBe(false)
fixture.saved.draft.visualState.environment.weather = '不能暗改天气'
await click(wrapper, '重新读取正式来源与草案')
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
).toHaveLength(1)
})
it('环境差异须逐字本集证据,冻结原字节全文SHA;保存和预检不自动采用', async () => {
const { wrapper, fetcher, episode } = await editor(false, false, true)
expect(wrapper.text()).toContain('本集原文依据')
await wrapper.vm.save()
await flushPromises()
await click(wrapper, '免费核对草案画面输入')
await author(wrapper)
const preflight = () => wrapper.findAll('button').find(item => item.text() === '免费预检联合采用')!
expect(preflight().attributes('disabled')).toBeDefined()
const quote = wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '环境原文片段')!
quote.vm.$emit('update:value', '另一集才有的晴天')
await flushPromises()
expect(preflight().attributes('disabled')).toBeDefined()
quote.vm.$emit('update:value', '午后,维修间透入日光。')
await flushPromises()
await click(wrapper, '免费预检联合采用')
const confirms = () =>
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
expect(confirms()).toHaveLength(1)
const previewBody = JSON.parse(String(confirms()[0]![1]?.body))
expect(previewBody.shots[0].jointRevision.environmentSource).toEqual({
episodeId: 'source-episode',
expectedContentFingerprint: createHash('sha256').update(episode.content).digest('hex'),
quote: '午后,维修间透入日光。'
})
expect(
previewBody.shots[0].jointRevision.changes.filter((row: { target: string }) => row.target === 'environment')
).toHaveLength(4)
expect(wrapper.vm.canAdopt).toBe(false)
wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
quote.vm.$emit('update:value', '午后,维修间透入日光。\n天气未指定。')
await flushPromises()
expect(wrapper.vm.canAdopt).toBe(false)
await click(wrapper, '免费预检联合采用')
wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
await Promise.all([wrapper.vm.adopt(), wrapper.vm.adopt()])
expect(confirms()).toHaveLength(3)
const second = JSON.parse(String(confirms()[1]![1]?.body)),
adopted = JSON.parse(String(confirms()[2]![1]?.body))
expect(adopted).toEqual({ ...second, preview: false })
expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/vision|\/primary/.test(String(url)))).toBe(
false
)
})
it('环境来源409重读本集全文并保留片段和草案,不自动重试', async () => {
const { wrapper, fetcher, episode } = await editor(true, false, true)
await click(wrapper, '免费核对草案画面输入')
await author(wrapper)
const quote = wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '环境原文片段')!
quote.vm.$emit('update:value', '午后,维修间透入日光。')
await flushPromises()
await click(wrapper, '免费预检联合采用')
expect(quote.props('value')).toBe('午后,维修间透入日光。')
expect(wrapper.vm.canAdopt).toBe(false)
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
).toHaveLength(1)
expect(
fetcher.mock.calls.filter(([url]) => String(url) === `/api/projects/${episode.projectId}`).length
).toBeGreaterThanOrEqual(2)
await wrapper
.findAll('.n-collapse-item__header-main')
.find(item => item.text() === '环境修订(需本集原文)')!
.trigger('click')
await flushPromises()
expect(
wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '环境天气')!
.props('value')
).toBe('')
})
it('正式集身份或全文缺失时保留输入但不允许环境预检', async () => {
const { wrapper, episode, fetcher } = await editor(false, false, true)
await click(wrapper, '免费核对草案画面输入')
await author(wrapper)
const quote = wrapper
.findAllComponents(NInput)
.find(input => input.attributes('aria-label') === '环境原文片段')!
quote.vm.$emit('update:value', '午后,维修间透入日光。')
await flushPromises()
Reflect.deleteProperty(episode, 'content')
await click(wrapper, '刷新本集原文')
expect(wrapper.text()).toContain('缺少本集正式身份或全文')
expect(quote.props('value')).toBe('午后,维修间透入日光。')
expect(
wrapper
.findAll('button')
.find(item => item.text() === '免费预检联合采用')!
.attributes('disabled')
).toBeDefined()
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
).toHaveLength(0)
})
})
@@ -0,0 +1,117 @@
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import StoryboardPage from '@/features/storyboard/StoryboardPage.vue'
import { projectContextKey } from '@/features/projects/context'
import { testProjectContext } from '@/testing/project-context'
import { directionsResult, visualStatesResult, storyboardCheckpoint } from '@/features/storyboard/testing/fixtures'
import { preparationFixture } from '../storyboard-preparation/fixtures'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
/** 释放真实页面及任务订阅,避免迟到响应跨用例。 */
const wrappers: VueWrapper[] = []
afterEach(() => {
wrappers.splice(0).forEach(wrapper => wrapper.unmount())
localStorage.clear()
})
/**
* 还原进入页面后发现已结束历史任务的场景,不连接真实服务。
* @param projectId 当前隔离项目
* @returns 实际页面和请求记录
*/
async function page(projectId: string) {
const context = testProjectContext(projectId)
context.data.value!.checkpoints = [storyboardCheckpoint()]
const fixture = preparationFixture(projectId)
const history: WorkflowExecution = {
id: 'restored-direction-history',
projectId,
workflowName: 'storyboard-direction',
status: 'completed',
stage: 'completed',
current: 2,
total: 2,
currentResourceId: null,
metadata: { episodeNo: 1 },
error: null,
startedAt: null,
completedAt: null,
createdAt: '2026-11-16T00:00:00Z',
updatedAt: '2026-11-16T00:00:00Z',
result: {
projectId,
episodeCount: 1,
completedEpisodes: 1,
skippedEpisodes: 0,
failedEpisodes: 0,
episodes: [{ episodeNo: 1, status: 'completed', directionCount: 2, shotCount: 2 }]
}
}
localStorage.setItem(`short-drama:workflow-execution:${projectId}:storyboard-direction`, history.id)
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url)
if (init?.method && init.method !== 'GET') throw new Error('浏览页面不应产生写入')
let data: unknown
if (path.includes('/storyboard-directions?')) data = directionsResult(projectId)
else if (path.includes('/storyboard-visual-states?')) data = visualStatesResult(projectId, 1, true)
else if (path.endsWith('/storyboard-quality-confirmation'))
data = { ...fixture.approval, valid: true, confirmation: fixture.record }
else if (path.endsWith('/storyboard-quality-confirmation/preflight'))
data = {
current: { ...fixture.approval, valid: true, confirmation: fixture.record },
quality: fixture.quality
}
else if (path.endsWith('/production/entry-readiness')) data = fixture.entry
else if (path.endsWith('/storyboard/duration-audit')) data = { projectId, issues: [] }
else if (path.endsWith('/duration-budget')) data = { projectId, episodes: [] }
else if (path.includes('/workflow-executions/latest'))
data = path.includes('workflowName=storyboard-direction') ? history : null
else if (path.includes('/workflow-executions/restored-direction-history')) data = history
else throw new Error(`未模拟只读请求 ${path}`)
return Response.json({ data })
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(StoryboardPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context } }
})
wrappers.push(wrapper)
await flushPromises()
await flushPromises()
return { wrapper, fetcher }
}
describe('分镜浏览与生成配置分离', () => {
it('恢复历史回执只提示入口,不自动打开生成配置', async () => {
const { wrapper, fetcher } = await page('browse-restored-history')
expect(wrapper.find('[data-workspace-tools]').attributes('aria-expanded')).toBe('false')
expect(wrapper.find('[data-workspace-tools]').text()).toContain('有回执')
expect(document.body.querySelector('.n-drawer')).toBeNull()
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
})
it('普通目录只浏览,用户打开生成范围后才能按镜头勾选,历史回执仍可查看', async () => {
const { wrapper, fetcher } = await page('browse-range-selection')
const directory = wrapper.get('nav[aria-label="本集镜头"]')
expect(directory.findAll('[role="checkbox"]')).toHaveLength(0)
await directory.findAll('button')[1]!.trigger('click')
expect(directory.findAll('.selected')).toHaveLength(1)
await wrapper.get('[data-workspace-tools]').trigger('click')
await flushPromises()
const history = [...document.querySelectorAll<HTMLElement>('.n-collapse-item__header-main')].find(item =>
item.textContent?.includes('历史任务与回执')
)!
history.click()
await flushPromises()
expect(document.body.textContent).toContain('摄影设计任务')
const range = [...document.querySelectorAll<HTMLElement>('.n-collapse-item__header-main')].find(item =>
item.textContent?.includes('选择镜头')
)!
range.click()
await flushPromises()
const checkbox = document.querySelector<HTMLElement>('.n-drawer [aria-label="选择镜头 1.1"]')!
checkbox.click()
await flushPromises()
expect(document.body.textContent).toContain('第 1 集所选 1 镜')
expect(directory.findAll('[role="checkbox"]')).toHaveLength(0)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
})
})
+60
View File
@@ -0,0 +1,60 @@
import { imageAuthorizationsFixture } from './billing'
import type { ImageChargeRequest, ImageAuthorizationList } from '../../src/features/image-authorization/types'
/**
* 仅供Mock的unknown请求及同一精确计划的有限许可。
* @param projectId 隔离项目
* @returns 原预留与unknown始终保留的费用投影
*/
export function additionalImageFixture(projectId = 'billing-project'): ImageAuthorizationList {
const list = imageAuthorizationsFixture()
const grant = list.authorizations[0]!
const parent: ImageChargeRequest = {
id: 'original-image-request',
status: 'unknown',
input: {
projectId,
authorizationId: grant.id,
candidateId: 'original-image',
targetId: 'audit-shot',
scope: 'keyframe',
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
planFingerprint: 'b'.repeat(64),
sourceFingerprint: 'c'.repeat(64),
reservedMicros: grant.input.perRequestMicros,
request: { prompt: '仅供Mock的原精确计划' }
},
output: {
usageCostMicros: null,
actualBilledMicros: null,
error: { failureType: 'timeout_unknown', transportMode: 'proxy', causeCode: 'UND_ERR_CONNECT_TIMEOUT' }
}
}
grant.usedRequests++
grant.remainingRequests--
grant.accountedMicros += parent.input.reservedMicros
grant.remainingMicros -= parent.input.reservedMicros
list.requests.push(parent)
list.billingBlocked = true
list.originalBlockingRequestIds = [parent.id]
list.blockingRequestIds = [parent.id]
list.additionalAuthorizations = [
{
id: 'additional-permit',
status: 'approved',
input: {
mode: 'additional',
idempotencyKey: 'test-additional',
parentRequestId: parent.id,
maxRequests: 2,
acknowledgeUnknownPriorBilling: true,
approvedBy: '测试人工批准人',
approvalNote: '仅供Mock的有限风险确认',
parentInputFingerprint: 'd'.repeat(64)
},
usedRequests: 0,
remainingRequests: 2
}
]
return list
}
+72
View File
@@ -0,0 +1,72 @@
import type { BillingFacts } from '../../src/features/billing-audit/types'
import type { ImageBillingAuditView } from '../../src/features/image-authorization/billing-audit.types'
/**
* 仅供Mock的原图片请求视图,不代表真实Provider材料。
* @param projectId 隔离项目
* @param requestId 隔离原请求
* @returns 带完整原版本和空历史的审计视图
*/
export function imageAuditFixture(projectId = 'audit-project', requestId = 'unknown-image'): ImageBillingAuditView {
return {
projectId,
requestId,
identity: {
projectId,
requestId,
authorizationId: 'grant',
scope: 'keyframe',
targetId: 'audit-shot',
candidateId: 'unknown-candidate',
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
sourceFingerprint: 'c'.repeat(64),
planFingerprint: 'b'.repeat(64),
requestFingerprint: 'd'.repeat(64)
},
taskFingerprint: 'a'.repeat(64),
evidenceSetFingerprint: 'e'.repeat(64),
reviewFingerprint: 'f'.repeat(64),
originalRequestStatus: 'unknown',
reservedMicros: 1_000_000,
originalUsageCostMicros: null,
originalActualBilledMicros: null,
originalProviderRequestId: null,
hasOriginalReceipt: false,
originalBillingBlocked: true,
billingBlocked: true,
released: false,
status: 'unreviewed',
reviewId: null,
reviewedAmountMicros: null,
releaseIssues: ['缺少当前独立复核的证据'],
history: { evidence: [], reviews: [] }
}
}
/**
* 只用于隔离验收的合格材料,不能登记到正式项目。
* @returns 明确标为测试的Provider原件声明
*/
export function imageAuditFacts(): BillingFacts {
return {
correlation: 'unique',
providerRequestId: 'test-provider-request',
artifacts: [
{
id: 'exec',
kind: 'provider-execution',
recordId: 'test-provider-execution',
sha256: '1'.repeat(64),
reference: '仅供Mock验收的执行原件'
},
{
id: 'bill',
kind: 'provider-billing',
recordId: 'test-provider-bill',
sha256: '2'.repeat(64),
reference: '仅供Mock验收的账单原件'
}
],
execution: { outcome: 'failed', evidenceIds: ['exec'] },
billing: { finding: 'charged', amount: 0.000001, currency: 'USD', evidenceIds: ['bill'] }
}
}
+53
View File
@@ -0,0 +1,53 @@
import { directionsResult, visualStatesResult, designedShot } from '../../src/features/storyboard/testing/fixtures'
import { draftFromFormal } from '../../src/features/storyboard/derived-review'
import { preparationFixture } from '../features/storyboard-preparation/fixtures'
import type { KeyframeSpec } from '../../src/features/production/types'
import type { SavedKeyframeDraft } from '../../src/features/storyboard/derived-review.types'
/**
* 当前正式数据和已保存草案的隔离投影,不用于正式项目。
* @param projectId 隔离项目
* @returns 可用于Vitest/Chrome的完整原版本与有限差异
*/
export function jointReviewFixture(projectId = 'joint-review-project') {
const shot = designedShot(),
approval = preparationFixture(projectId),
directions = directionsResult(projectId),
visuals = visualStatesResult(projectId, 1, true)
const keyframe: KeyframeSpec = {
projectId,
shotId: shot.shotId,
episodeNo: 1,
beatNo: 1,
shotNo: 1,
prompt: '隔离正式开拍输入',
formalSourceFingerprint: 'e'.repeat(64),
references: []
}
const formal = draftFromFormal(shot, keyframe, approval.record.shotFingerprint)
const draft = structuredClone(formal)
draft.direction.composition = '仅用于Mock的构图调整'
draft.direction.visualIntent = '保留正式动作的开拍意图'
draft.visualState.subjects[0]!.pose = '仅用于Mock的0秒姿态'
draft.visualState.continuityNote =
'【输入事实】原主体保持开拍姿态。【规划末态】后续镜头规划,尚未执行。【连续要求】保持原观察轴。【视频末态】未知,尚无真实视频末态证据。'
const saved: SavedKeyframeDraft = {
shotId: shot.shotId,
revision: 7,
updatedAt: '2026-11-16T01:00:00Z',
status: 'current',
staleReason: null,
draft,
providerInput: { provider: 'openai-image', generationOptions: { quality: 'auto' } },
expectedCurrentFormalSourceFingerprint: keyframe.formalSourceFingerprint!
}
return {
shot,
shots: [shot, { ...designedShot('shot-db-1-2'), beatNo: 2 }],
approval,
directions,
visuals,
keyframe,
formal,
saved
}
}