feat(short-drama-agent-front): 接入图片持续授权与视频费用审计

This commit is contained in:
GJ committed 2026-11-13 17:59:50 +08:00
1 parent 3915566994
commit 1e9ef33d1d
39 files changed
+3442 -51

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="./billing.ts"></script>
</body>
</html>
+335
View File
@@ -0,0 +1,335 @@
import { createApp, defineComponent, h, ref } from 'vue'
import { NButton, NConfigProvider, NMessageProvider, NGlobalStyle, zhCN, dateZhCN } from 'naive-ui'
import { useTheme } from '../../src/composables/useTheme'
import AppDrawer from '../../src/components/ui/AppDrawer.vue'
import ActionMessageProvider from '../../src/components/ui/ActionMessageProvider.vue'
import ProjectSettingsDialog from '../../src/features/generation-config/components/ProjectSettingsDialog.vue'
import KeyframeDialog from '../../src/features/production/components/KeyframeDialog.vue'
import VideoAuditPanel from '../../src/features/production/components/VideoAuditPanel.vue'
import { billingCatalog, billingProfile, imageAuthorizationsFixture, videoAuditFixture } from '../fixtures/billing'
import type { ImageAuthorizationInput, ImageChargeRequest } from '../../src/features/image-authorization/types'
import type { RegisterVideoAudit, ReviewVideoAudit } from '../../src/features/production/video-audit.types'
import '../../src/styles/styles.css'
import '../../src/styles/admin.css'
/** 浏览器隔离页面的唯一请求记录,不连接真实服务。 */
const calls: Array<{ path: string; method: string; body: unknown }> = []
/** 每次场景切换都使用新的模拟项目投影。 */
let images = imageAuthorizationsFixture()
/** 模拟原历史任务,费用处置从不改变原质量。 */
let video = videoAuditFixture()
/** 仅用于明确制造一次审计并发冲突。 */
let conflictNext = false
/** 场景重挂,刷新行为只执行读取。 */
const revision = ref(0)
/** 可从 Chrome 只读核对真实组件发出的请求。 */
Object.assign(window, {
billingTest: {
calls,
get images() {
return images
},
get video() {
return video
},
get conflictNext() {
return conflictNext
},
set conflictNext(value: boolean) {
conflictNext = value
}
}
})
/** 通过 DOM 只读导出隔离请求计数,便于浏览器检查。 */
document.addEventListener('billing-probe', () => {
document.documentElement.dataset.billingProbe = JSON.stringify({ calls, images, video, conflictNext })
})
/**
* 全量拦截当前隔离页的请求,未知接口直接拒绝,无任何真实付费或业务写入。
* @param input 请求路径
* @param init 原请求参数
* @returns 隔离正式结构响应
*/
window.fetch = async (input, init) => {
const path = String(input),
method = init?.method ?? 'GET'
const body = init?.body ? JSON.parse(String(init.body)) : undefined
calls.push({ path, method, body })
let data: unknown
if (path.endsWith('/generation-models')) data = billingCatalog
else if (path.endsWith('/creative-profile')) data = billingProfile
else if (path.endsWith('/resolve')) data = { provider: 'openai-image', model: 'gpt-image-2.5-flare', options: {} }
else if (path.includes('/workflow-executions/latest')) data = null
else if (path.endsWith('/validation/preview'))
data = { history: [video.original], blockingTasks: video.audit.billingBlocked ? [video.original] : [] }
else if (path.endsWith('/keyframe/preview'))
data = {
shotId: 'audit-shot',
provider: body.provider,
model: body.provider === 'openai-image' ? 'gpt-image-2.5-flare' : 'qwen-image-3.0-pro',
providerPrompt: '仅供隔离验收的画面描述',
previewFingerprint: 'a'.repeat(64),
referenceImages: [],
generationConfig: { options: {} }
}
else if (path.endsWith('/keyframe')) data = { id: 'mock-keyframe', shotId: 'audit-shot', status: 'completed' }
else if (path.endsWith('/image-authorizations/preview'))
data = {
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),
request: {},
currency: 'USD',
billingBasis: 'provider_usage',
hardProviderCostCap: false,
authorization: images
}
else if (path.endsWith('/image-authorizations') && method === 'GET') data = images
else if (path.endsWith('/image-authorizations') && method === 'POST') {
const previous = images.authorizations.find(item => item.input.idempotencyKey === body.idempotencyKey)
if (previous) data = { authorizationId: previous.id, status: previous.status }
else {
const id = `mock-grant-${images.authorizations.length}`
images.authorizations.push({
id,
status: 'approved',
input: body as ImageAuthorizationInput,
expired: false,
usedRequests: 0,
remainingRequests: body.maxRequests,
accountedMicros: 0,
remainingMicros: body.budgetMicros,
billingBlocked: false
})
data = { authorizationId: id, status: 'approved' }
}
} else if (path.endsWith('/revoke')) {
const id = path.split('/').at(-2)!
images.authorizations.find(item => item.id === id)!.status = 'revoked'
data = { authorizationId: id, status: 'revoked' }
} else if (path.endsWith('/audit')) data = video.audit
else if (path.endsWith('/audit-task')) data = video.original
else if (path.endsWith('/audit/evidence')) {
const value = body as RegisterVideoAudit
const step = video.audit.steps[0]!
const previous = step.evidence.find(row => JSON.stringify(row.body) === JSON.stringify(value))
const event = previous ?? {
id: `mock-evidence-${step.evidence.length}`,
createdAt: new Date().toISOString(),
taskFingerprint: video.audit.taskFingerprint,
stepName: step.name,
digest: '1'.repeat(64),
body: value
}
if (!previous) {
step.evidence.push(event)
video.audit.history.evidence.push(event)
step.evidenceSetFingerprint = String(step.evidence.length + 1).repeat(64)
step.status = 'unreviewed'
video.audit.billingBlocked = true
}
data = { evidenceId: event.id, reused: !!previous, billingBlocked: true }
} else if (path.endsWith('/audit/reviews')) {
if (conflictNext) {
conflictNext = false
video.audit.steps[0]!.reviewFingerprint = '8'.repeat(64)
return new Response(JSON.stringify({ code: 'VIDEO_AUDIT_REVIEW_CONFLICT', message: '另一复核先完成' }), {
status: 409
})
}
const value = body as ReviewVideoAudit,
step = video.audit.steps[0]!
const released = value.decision === 'release_future_charges'
const event = {
id: `mock-review-${step.reviews.length}`,
createdAt: new Date().toISOString(),
taskFingerprint: video.audit.taskFingerprint,
stepName: step.name,
digest: '3'.repeat(64),
revision: step.reviews.length + 1,
body: value
}
step.reviews.push(event)
video.audit.history.reviews.push(event)
step.status = released ? 'released' : 'blocked'
video.audit.billingBlocked = !released
step.reviewFingerprint = '7'.repeat(64)
data = { reviewId: event.id, status: step.status, billingBlocked: video.audit.billingBlocked, reused: false }
} else return new Response(JSON.stringify({ message: '隔离页拒绝未声明请求' }), { status: 403 })
return new Response(JSON.stringify({ data }), { headers: { 'Content-Type': 'application/json' } })
}
/**
* 切换隔离数据,所有金额均为测试值,与正式批准无关。
* @param kind 本次测试场景
*/
function scenario(kind: string) {
images = imageAuthorizationsFixture()
video = videoAuditFixture()
const grant = images.authorizations[0]!
if (kind === 'expired') {
grant.expired = true
grant.input.expiresAt = '2000-01-01T00:00:00Z'
}
if (kind === 'insufficient') grant.remainingMicros = 1
if (kind === 'unknown' || kind === 'reusable') {
images.billingBlocked = true
images.blockingRequestIds = ['original-image-request']
const request: ImageChargeRequest = {
id: 'original-image-request',
status: kind === 'reusable' ? 'completed' : 'unknown',
input: {
projectId: 'billing-project',
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: 500_000,
request: { prompt: '隔离原请求' }
},
output: {
usageCostMicros: null,
actualBilledMicros: null,
...(kind === 'reusable'
? { result: { image: 'mock-image' } }
: { error: { failureType: 'timeout_unknown' } })
}
}
images.requests.push(request)
}
revision.value++
}
/** 使用正式抽屉和表单验收布局,顶栏仅为隔离测试控制。 */
const Preview = defineComponent({
setup() {
/** 正式项目配置抽屉。 */
const settingsOpen = ref(false)
/** 原首帧生成弹窗。 */
const keyframeOpen = ref(false)
/** 费用审计使用正式固定底栏。 */
const auditOpen = ref(false)
/** 真实审计表单公开的底栏入口。 */
const auditForm = ref<InstanceType<typeof VideoAuditPanel> | null>(null)
return () =>
h('main', { style: 'padding:24px;height:100dvh;overflow:auto' }, [
h('h1', { style: 'font-size:24px;margin-bottom:16px' }, '图片授权与视频费用审计 · Mock 隔离验收'),
h('p', { style: 'margin-bottom:16px' }, '所有请求均拦截在当前页面,不连接真实模型或正式任务。'),
h('div', { style: 'display:flex;flex-wrap:wrap;gap:12px;margin-bottom:24px' }, [
h(NButton, { onClick: () => (settingsOpen.value = true) }, () => '项目图片授权'),
h(NButton, { onClick: () => (keyframeOpen.value = true) }, () => '原首帧生成入口'),
h(NButton, { onClick: () => (auditOpen.value = true) }, () => '视频费用审计'),
...Object.entries({
active: '有效授权',
expired: '授权到期',
insufficient: '额度不足',
unknown: '未知费用',
reusable: '同计划免费复用'
}).map(([value, label]) => h(NButton, { onClick: () => scenario(value) }, () => label)),
h(
NButton,
{
onClick: () => {
conflictNext = true
}
},
() => '下一次复核冲突'
)
]),
h(ProjectSettingsDialog, {
key: 'settings' + revision.value,
projectId: 'billing-project',
disabled: false,
initialTab: 'image-authorization',
open: settingsOpen.value,
'onUpdate:open': value => (settingsOpen.value = value)
}),
h(KeyframeDialog, {
key: 'keyframe' + revision.value,
shotId: 'audit-shot',
projectId: 'billing-project',
shotTitle: '隔离首帧',
disabled: false,
open: keyframeOpen.value,
'onUpdate:open': value => (keyframeOpen.value = value),
submitGeneration: async input => {
await fetch('/api/storyboard-shots/audit-shot/keyframe', {
method: 'POST',
body: JSON.stringify(input)
})
return { accepted: true }
}
}),
h(
AppDrawer,
{
key: 'audit' + revision.value,
open: auditOpen.value,
title: '视频费用审计',
busy: auditForm.value?.saving,
'onUpdate:open': value => (auditOpen.value = value)
},
{
default: () =>
auditOpen.value
? h(VideoAuditPanel, {
ref: auditForm,
projectId: 'billing-project',
shotId: 'audit-shot',
videoId: 'audit-video'
})
: null,
footer: () => [
h(
NButton,
{ disabled: auditForm.value?.saving, onClick: () => (auditOpen.value = false) },
() => '关闭'
),
h(
NButton,
{
type: 'primary',
disabled: !auditForm.value?.canSubmit,
loading: auditForm.value?.saving,
onClick: () => auditForm.value?.submit()
},
() => auditForm.value?.submitLabel ?? '登记外部证据'
)
]
}
)
])
}
})
createApp({
setup() {
/** 隔离页复用正式主题、中文控件与状态色。 */
const theme = useTheme()
return () =>
h(
NConfigProvider,
{ theme: theme.theme.value, themeOverrides: theme.overrides.value, locale: zhCN, dateLocale: dateZhCN },
{
default: () => [
h(NGlobalStyle),
h(
NMessageProvider,
{},
{ default: () => h(ActionMessageProvider, {}, { default: () => h(Preview) }) }
)
]
}
)
}
}).mount('#app')
+7
View File
@@ -1,3 +1,4 @@
import { generationConfigApi } from '@/features/generation-config/api'
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { routerLinkStubs } from '../../fixtures/router'
import { defineComponent, h, reactive } from 'vue'
@@ -110,6 +111,12 @@ describe('统一的 Naive UI 表单校验', () => {
})
it('图片尺寸采用目录必填枚举,切换目标清空提示词和费用确认', async () => {
/** 原图片表单先解析主体覆盖,测试仅提供正式只读配置。 */
vi.spyOn(generationConfigApi, 'resolve').mockResolvedValue({
provider: creativeProfile.imageProvider,
model: creativeProfile.imageModel,
options: { ...creativeProfile.imageOptions }
})
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: {
@@ -0,0 +1,211 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { defineComponent, ref } from 'vue'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import {
usdToMicros,
formatMicros,
imageChargeEligibility,
imageRequestBlockReason
} from '@/features/image-authorization/model'
import { imageAuthorizationApi } from '@/features/image-authorization/api'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '@/features/subject-images/generation-preview'
import { ApiError, errorMessage } from '@/lib/http'
import { imageAuthorizationsFixture } from '../../fixtures/billing'
import { imagePreviewFixture } from '../../fixtures/image-preview'
/** 每个用例清理表单、费用标记及替身。 */
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
sessionStorage.clear()
vi.restoreAllMocks()
})
/**
* 挂载真实共用生成逻辑,只模拟正式读写接口。
* @returns 真实表单、用户选择与无费用生成替身
*/
function setup() {
const open = ref(true),
provider = ref('openai-image'),
project = ref('billing-project')
const list = imageAuthorizationsFixture()
vi.spyOn(imageAuthorizationApi, 'list').mockResolvedValue(list)
const authorizationPreview = vi.spyOn(imageAuthorizationApi, 'preview').mockImplementation(async () => ({
provider: provider.value,
model: 'gpt-image-2.5-flare',
context: {
projectId: project.value,
scope: 'keyframe',
targetId: 'shot',
sourceFingerprint: 'c'.repeat(64)
},
planFingerprint: 'b'.repeat(64),
request: {},
currency: 'USD',
billingBasis: 'provider_usage',
hardProviderCostCap: false,
authorization: list
}))
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({ accepted: true }))
const load = vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => ({
...imagePreviewFixture(),
provider: provider.value,
model: 'gpt-image-2.5-flare'
}))
let flow!: ReturnType<typeof useImageGenerationPreview>
wrapper = mount(
defineComponent({
setup() {
flow = useImageGenerationPreview({
open,
target: () => project.value + ':shot',
recoveryTarget: () => 'keyframe:shot',
chargeContext: () => ({
projectId: project.value,
targetId: 'shot',
scope: 'keyframe',
exactPreview: true
}),
input: () => ({ provider: provider.value, generationOptions: {} }),
disabled: () => false,
load,
generate
})
return () => null
}
})
)
return { flow, provider, project, list, generate, load, authorizationPreview }
}
describe('OpenAI 图片有限授权及收费门禁', () => {
it('美元精确转换,未知金额不显示零,拒绝过多小数与非法金额', () => {
expect(usdToMicros('0.123456')).toBe(123456)
expect(usdToMicros('5')).toBe(5_000_000)
for (const value of ['', '0', '-1', '1e2', '0.0000001', 'Infinity']) expect(usdToMicros(value)).toBeNull()
expect(formatMicros(null)).toBe('未知')
expect(formatMicros(0)).toBe('USD 0')
})
it.each(['expired', 'revoked', 'budget', 'requests', 'scope', 'model', 'target'] as const)(
'%s 不授予新收费资格',
kind => {
const list = imageAuthorizationsFixture(),
row = list.authorizations[0]!
if (kind === 'expired') {
row.expired = true
row.input.expiresAt = '2000-01-01T00:00:00Z'
}
if (kind === 'revoked') row.status = 'revoked'
if (kind === 'budget') row.remainingMicros = row.input.perRequestMicros - 1
if (kind === 'requests') row.remainingRequests = 0
if (kind === 'scope') row.input.scopes = ['identity']
if (kind === 'model') row.input.models = ['other']
if (kind === 'target') row.input.targetIds = ['other']
expect(imageChargeEligibility(list, 'keyframe', 'shot', 'gpt-image-2.5-flare').allowed).toBe(false)
}
)
it('有效持续授权无需逐图批准,仍要求原图片预览并防止双击', async () => {
const { flow, generate } = setup()
expect(flow.canSubmit.value).toBe(false)
await flow.loadPreview()
expect(flow.requiresCostConfirmation.value).toBe(false)
expect(flow.acknowledged.value).toBe(false)
expect(flow.canSubmit.value).toBe(true)
await Promise.all([flow.submit(), flow.submit()])
expect(generate).toHaveBeenCalledExactlyOnceWith({
provider: 'openai-image',
generationOptions: {},
expectedPreviewFingerprint: 'a'.repeat(64)
})
})
it('切换供应方立即撤销原预览,重新预览后必须独立确认', async () => {
const { flow, provider, generate } = setup()
await flow.loadPreview()
provider.value = 'qwen-image'
expect(flow.preview.value).toBeNull()
await flow.loadPreview()
expect(flow.requiresCostConfirmation.value).toBe(true)
await flow.submit()
expect(generate).not.toHaveBeenCalled()
flow.acknowledged.value = true
await flow.submit()
expect(generate).toHaveBeenCalledOnce()
})
it('未知费用禁止重试;完整同计划在撤销、到期及项目阻断后仍可免费复用', async () => {
const { flow, list, generate } = setup()
list.billingBlocked = true
await flow.loadPreview()
await flow.submit()
expect(generate).not.toHaveBeenCalled()
const grant = list.authorizations[0]!
grant.expired = true
grant.status = 'revoked'
list.requests.push({
id: 'old-request',
status: 'completed',
input: {
projectId: 'billing-project',
scope: 'keyframe',
targetId: 'shot',
candidateId: 'old-candidate',
authorizationId: 'grant',
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
sourceFingerprint: 'c'.repeat(64),
planFingerprint: 'b'.repeat(64),
reservedMicros: 500_000,
request: {}
},
output: { usageCostMicros: null, actualBilledMicros: null, result: { image: 'mock' } }
})
await flow.loadPreview()
expect(flow.chargeNotice.value).toContain('免费复用')
await flow.submit()
expect(generate).toHaveBeenCalledOnce()
expect(list.authorizations[0]!.usedRequests).toBe(0)
const original = list.requests[0]!
expect(imageRequestBlockReason(original)).toContain('缺少可核验的用量')
original.output!.usageCostMicros = original.input.reservedMicros + 1
expect(imageRequestBlockReason(original)).toContain('超过单次预留')
original.status = 'running'
expect(imageRequestBlockReason(original)).toContain('禁止重发')
original.status = 'unknown'
original.output!.error = { failureType: 'rate_limited' }
expect(imageRequestBlockReason(original)).toContain('限流')
})
it('并发额度拒绝后需重新读取授权,刷新及重新挂载均不重复生成', async () => {
const { flow, list, generate, project } = setup()
generate.mockResolvedValueOnce({
accepted: false,
cause: new ApiError('额度不足', 409, undefined, 'IMAGE_AUTHORIZATION_BUDGET_EXCEEDED')
} as { accepted: boolean })
await flow.loadPreview()
await flow.submit()
expect(flow.canSubmit.value).toBe(false)
list.authorizations[0]!.remainingMicros = 0
await flow.loadPreview()
await flow.submit()
project.value = 'other-project'
await flushPromises()
expect(flow.preview.value).toBeNull()
expect(generate).toHaveBeenCalledOnce()
})
it('错误区分计费配额与限流、未知回执及供应方切换', () => {
expect(
errorMessage(new ApiError('429', 502, { failureType: 'rate_limited' }, 'OPENAI_IMAGE_PROVIDER_ERROR'))
).toContain('限流')
expect(
errorMessage(
new ApiError('429', 502, { failureType: 'billing_quota_exceeded' }, 'OPENAI_IMAGE_PROVIDER_ERROR')
)
).toContain('计费配额')
expect(
errorMessage(
new ApiError('unknown', 502, { failureType: 'receipt_unknown' }, 'OPENAI_IMAGE_RECEIPT_INVALID')
)
).toContain('禁止重试')
expect(errorMessage(new ApiError('switch', 409, undefined, 'IMAGE_PROVIDER_CONFIRMATION_REQUIRED'))).toContain(
'主动选择'
)
})
})
@@ -0,0 +1,76 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { defineComponent, ref } from 'vue'
import { imageGenerationDefaults, useAssetImageDefaults } from '@/features/generation-config/image-defaults'
import { generationConfigApi } from '@/features/generation-config/api'
import { billingCatalog, billingProfile } from '../../fixtures/billing'
import { generationProfile } from '../../fixtures/generation'
/** 原配置及覆盖在独立组件生命周期中核对。 */
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
describe('OpenAI 推荐与既有配置的优先级', () => {
it('空配置采用后端推荐,现有 Qwen 选择保留,失效选择不自动跨供应方', () => {
expect(
imageGenerationDefaults(billingCatalog, { ...billingProfile, imageProvider: '', imageOptions: {} }).provider
).toBe('openai-image')
expect(imageGenerationDefaults(billingCatalog, generationProfile('p')).provider).toBe('qwen-image')
expect(
imageGenerationDefaults(billingCatalog, { ...billingProfile, imageProvider: 'disabled-provider' }).provider
).toBe('')
})
it('以主体覆盖解析初值,手动选择保留,同主体切换形态重新读取,切项目拒绝旧回填', async () => {
const project = ref('p'),
form = ref('form-a'),
open = ref(true)
const resolve = vi
.spyOn(generationConfigApi, 'resolve')
.mockResolvedValue({ provider: 'qwen-image', model: 'qwen-image-3.0-pro', options: { size: '2048*2048' } })
let state!: ReturnType<typeof useAssetImageDefaults>
wrapper = mount(
defineComponent({
setup() {
state = useAssetImageDefaults(
open,
() => ({ ...billingProfile, projectId: project.value }),
() => 'subject',
() => form.value
)
return () => null
}
})
)
await flushPromises()
expect(resolve).toHaveBeenCalledWith(
'p',
'image',
{ target: { targetType: 'asset', targetId: 'subject' } },
expect.any(AbortSignal)
)
expect(state.provider.value).toBe('qwen-image')
state.provider.value = 'manual-provider'
await flushPromises()
expect(state.provider.value).toBe('manual-provider')
form.value = 'form-b'
await flushPromises()
expect(state.provider.value).toBe('qwen-image')
expect(resolve).toHaveBeenCalledTimes(2)
let finish!: (value: Awaited<ReturnType<typeof generationConfigApi.resolve>>) => void
resolve.mockImplementationOnce(
() =>
new Promise(accept => {
finish = accept
})
)
project.value = 'old-project'
await flushPromises()
project.value = 'new-project'
await flushPromises()
finish({ provider: 'old-provider', model: 'old-model', options: {} })
await flushPromises()
expect(state.provider.value).toBe('qwen-image')
})
})
@@ -0,0 +1,115 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { NCheckbox, NDatePicker, NInput, NInputNumber, NSelect } from 'naive-ui'
import ImageAuthorizationSettings from '@/features/image-authorization/ImageAuthorizationSettings.vue'
import { imageAuthorizationApi } from '@/features/image-authorization/api'
import { generationConfigApi } from '@/features/generation-config/api'
import { ApiError } from '@/lib/http'
import { billingCatalog, imageAuthorizationsFixture } from '../../fixtures/billing'
/** 保持真实 Naive 表单生命周期独立。 */
let wrapper: VueWrapper<InstanceType<typeof ImageAuthorizationSettings>> | undefined
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
/**
* 创建隔离授权设置,捕获正式登记与撤销输入。
* @returns 请求替身及原数据
*/
async function setup() {
const list = imageAuthorizationsFixture()
vi.spyOn(generationConfigApi, 'catalog').mockResolvedValue(billingCatalog)
vi.spyOn(imageAuthorizationApi, 'list').mockResolvedValue(list)
const create = vi
.spyOn(imageAuthorizationApi, 'create')
.mockResolvedValue({ authorizationId: 'created', status: 'approved' })
const revoke = vi.spyOn(imageAuthorizationApi, 'revoke').mockImplementation(async () => {
list.authorizations[0]!.status = 'revoked'
return { authorizationId: 'grant', status: 'revoked' }
})
wrapper = mount(ImageAuthorizationSettings, { props: { projectId: 'billing-project', disabled: false } })
await flushPromises()
return { list, create, revoke }
}
/** 完整填写用户实际批准的金额、次数、时间与范围。 */
async function fill() {
const selects = wrapper!.findAllComponents(NSelect)
selects[0]!.vm.$emit('update:value', ['gpt-image-2.5-flare'])
selects[1]!.vm.$emit('update:value', ['keyframe'])
for (const [label, value] of [
['累计预算', '1.123456'],
['单次预留', '0.123456'],
['目标编号', 'shot-1,shot-2'],
['批准人', '隔离批准人'],
['批准说明', '仅隔离测试']
] as const)
wrapper!
.findAll('label.workspace-form-field')
.find(item => item.text().startsWith(label))!
.findComponent(NInput)
.vm.$emit('update:value', value)
wrapper!.findComponent(NInputNumber).vm.$emit('update:value', 3)
wrapper!.findComponent(NDatePicker).vm.$emit('update:value', Date.UTC(2099, 0, 1))
wrapper!.findComponent(NCheckbox).vm.$emit('update:checked', true)
await flushPromises()
}
describe('项目生成设置中的 OpenAI 授权管理', () => {
it('打开时金额、次数、日期、批准均为空,不能自动登记', async () => {
const { create } = await setup()
expect(
wrapper!
.findAllComponents(NInput)
.slice(0, 2)
.map(item => item.props('value'))
).toEqual(['', ''])
expect(wrapper!.findComponent(NInputNumber).props('value')).toBeNull()
expect(wrapper!.findComponent(NDatePicker).props('value')).toBeNull()
expect(wrapper!.findComponent(NCheckbox).props('checked')).toBe(false)
await wrapper!.vm.save()
expect(create).not.toHaveBeenCalled()
expect(wrapper!.text()).toContain('请完整填写')
})
it('金额转换为整数微美元且超时后使用原幂等键,不自动重提', async () => {
const { create } = await setup()
create.mockRejectedValueOnce(new ApiError('网络未知', 0))
await fill()
await wrapper!.vm.save()
expect(create).toHaveBeenCalledOnce()
expect(wrapper!.findAllComponents(NInput)[0]!.props('value')).toBe('1.123456')
await wrapper!.vm.save()
expect(create).toHaveBeenCalledTimes(2)
expect(create.mock.calls[0]![1]).toEqual(create.mock.calls[1]![1])
expect(create.mock.calls[0]![1]).toMatchObject({
mode: 'standing',
budgetMicros: 1123456,
perRequestMicros: 123456,
maxRequests: 3,
targetIds: ['shot-1', 'shot-2'],
acknowledgeVariableBilling: true,
currency: 'USD'
})
})
it('撤销需要明确操作者和原因,保留原授权与历史请求', async () => {
const { list, create, revoke } = await setup()
await wrapper!
.findAll('button')
.find(item => item.text() === '撤销此授权')!
.trigger('click')
await wrapper!.vm.save()
expect(revoke).not.toHaveBeenCalled()
const inputs = wrapper!.findAllComponents(NInput)
inputs[0]!.vm.$emit('update:value', '隔离撤销人')
inputs[1]!.vm.$emit('update:value', '停止后续领取')
await flushPromises()
await wrapper!.vm.save()
expect(revoke).toHaveBeenCalledExactlyOnceWith('billing-project', 'grant', {
revokedBy: '隔离撤销人',
reason: '停止后续领取'
})
expect(list.authorizations).toHaveLength(1)
expect(list.authorizations[0]!.status).toBe('revoked')
expect(create).not.toHaveBeenCalled()
})
})
@@ -203,6 +203,14 @@ describe('镜头生产数据契约', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
if (path === '/api/generation-models') return new Response(JSON.stringify({ data: imageCatalog }))
if (path.endsWith('/generation-config/image/resolve'))
return Response.json({
data: {
provider: 'qwen-image',
model: 'qwen-image-3.0-pro',
options: generationProfile('project-1').imageOptions
}
})
if (path === '/api/projects/project-1/creative-profile')
return new Response(JSON.stringify({ data: generationProfile('project-1') }))
const shotId = path.match(/storyboard-shots\/([^/]+)/)?.[1]
@@ -285,6 +293,8 @@ describe('镜头生产数据契约', () => {
}
})
)
if (path.endsWith('/generation-config/image/resolve'))
return Response.json({ data: { provider: 'seedream', model: 'image-model', options: {} } })
if (path.includes('/creative-profile')) return new Response(JSON.stringify({ data: null }))
return new Response(
JSON.stringify({
@@ -206,6 +206,14 @@ describe('精简公开资产回归', () => {
const path = String(url)
if (path.endsWith('/generation-models')) return Response.json({ data: imageCatalog })
if (path.endsWith('/creative-profile')) return Response.json({ data: generationProfile(projectId) })
if (path.endsWith('/generation-config/image/resolve'))
return Response.json({
data: {
provider: 'qwen-image',
model: 'qwen-image-3.0-pro',
options: generationProfile(projectId).imageOptions
}
})
if (path.endsWith('/keyframes')) return Response.json({ data: rows })
if (path.endsWith('/keyframe/preview'))
return Response.json({
@@ -0,0 +1,219 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { defineComponent } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { ApiError } from '@/lib/http'
import { useVideoAudit } from '@/features/production/useVideoAudit'
import { videoAuditApi } from '@/features/production/video-audit-api'
import { auditEvidenceIssues, auditReleaseIssues } from '@/features/production/video-audit'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import { videoAuditFixture, videoEvidenceFixture } from '../../fixtures/billing'
/** 每次释放实际组合逻辑与请求替身。 */
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
/**
* 挂载原视频审计逻辑,仅模拟同步 HTTP 边界。
* @returns 原证据、表单、接口及刷新通知
*/
async function setup() {
const { audit, original } = videoAuditFixture()
const history = vi
.spyOn(videoAuditApi, 'history')
.mockResolvedValue({ history: [original], blockingTasks: [original] })
vi.spyOn(workflowExecutionApi, 'latest').mockResolvedValue(null)
const get = vi.spyOn(videoAuditApi, 'get').mockImplementation(async () => structuredClone(audit))
const task = vi.spyOn(videoAuditApi, 'task').mockImplementation(async () => structuredClone(original))
const register = vi
.spyOn(videoAuditApi, 'register')
.mockResolvedValue({ evidenceId: 'event', billingBlocked: true, reused: false })
const review = vi
.spyOn(videoAuditApi, 'review')
.mockResolvedValue({ reviewId: 'review', status: 'released', billingBlocked: false, reused: false })
const changed = vi.fn<() => void>()
let form!: ReturnType<typeof useVideoAudit>
wrapper = mount(
defineComponent({
setup() {
form = useVideoAudit(
{ projectId: audit.projectId, shotId: audit.shotId, videoId: original.videoId! },
changed
)
return () => null
}
})
)
await flushPromises()
return { audit, original, form, get, task, register, review, changed, history }
}
/**
* 填写隔离材料,未知仍可登记,不能据此自动核清。
* @param form 原表单
*/
async function fillEvidence(form: ReturnType<typeof useVideoAudit>) {
const evidence = videoEvidenceFixture()
form.operator.value = '隔离登记人'
form.providerRequestId.value = evidence.providerRequestId!
form.correlation.value = evidence.correlation
form.artifacts.value = evidence.artifacts
form.outcome.value = evidence.execution.outcome
form.finding.value = evidence.billing.finding
form.amount.value = evidence.billing.amount
form.executionIds.value = evidence.execution.evidenceIds
form.billingIds.value = evidence.billing.evidenceIds
await flushPromises()
form.confirmed.value = true
}
describe('视频外部费用审计独立登记与人工复核', () => {
it('登记原身份、原任务版本、未知金额,不解除或修改旧质量', async () => {
const { audit, original, form, register, review, changed } = await setup()
const before = structuredClone(original)
await fillEvidence(form)
form.amount.value = null
form.finding.value = 'unknown'
await flushPromises()
form.confirmed.value = true
await Promise.all([form.submit(), form.submit()])
expect(register).toHaveBeenCalledOnce()
expect(register.mock.calls[0]![2]).toMatchObject({
expectedTaskFingerprint: audit.taskFingerprint,
evidence: {
identity: audit.steps[0]!.identity,
billing: { amount: null, finding: 'unknown', currency: 'USD' }
}
})
expect(review).not.toHaveBeenCalled()
expect(original).toEqual(before)
expect(changed).toHaveBeenCalledOnce()
expect(form.confirmed.value).toBe(false)
})
it.each(['VIDEO_AUDIT_STALE', 'VIDEO_AUDIT_REVIEW_CONFLICT', 'VIDEO_AUDIT_IDENTITY_MISMATCH'])(
'409 %s 刷新版本并保留表单,不自动重新提交',
async code => {
const { form, register, get, audit, changed } = await setup()
await fillEvidence(form)
register.mockImplementationOnce(async () => {
audit.steps[0]!.reviewFingerprint = '9'.repeat(64)
throw new ApiError('版本已变化', 409, undefined, code)
})
await form.submit()
expect(get).toHaveBeenCalledTimes(2)
expect(form.operator.value).toBe('隔离登记人')
expect(form.providerRequestId.value).toBe('mock-provider-request')
expect(form.artifacts.value).toHaveLength(2)
expect(form.confirmed.value).toBe(false)
await form.submit()
expect(register).toHaveBeenCalledOnce()
expect(changed).not.toHaveBeenCalled()
}
)
it('核清只提交三个服务端版本并刷新原资源,费用成功不改变过期/待审质量', async () => {
const { audit, original, form, review, register, get, task, changed } = await setup()
const step = audit.steps[0]!
step.evidence.push({
id: 'evidence',
taskFingerprint: audit.taskFingerprint,
stepName: step.name,
createdAt: '2026-11-13T00:00:00Z',
digest: '1'.repeat(64),
body: {
operator: '隔离登记人',
stepName: step.name,
expectedTaskFingerprint: audit.taskFingerprint,
evidence: videoEvidenceFixture()
}
})
await form.refresh()
form.action.value = 'review'
form.evidenceId.value = 'evidence'
form.reviewer.value = '隔离复核人'
form.reason.value = '核对隔离原件'
form.confirmationSha256.value = '3'.repeat(64)
await flushPromises()
expect(form.releaseIssues.value).toEqual([])
form.decision.value = 'release_future_charges'
await flushPromises()
form.confirmed.value = true
const before = structuredClone(original)
review.mockImplementationOnce(async () => {
audit.billingBlocked = false
step.status = 'released'
return { reviewId: 'review', status: 'released', billingBlocked: false, reused: false }
})
await form.submit()
expect(review).toHaveBeenCalledExactlyOnceWith(
audit.shotId,
audit.taskId,
expect.objectContaining({
expectedTaskFingerprint: audit.taskFingerprint,
expectedEvidenceSetFingerprint: step.evidenceSetFingerprint,
expectedReviewFingerprint: step.reviewFingerprint,
decision: 'release_future_charges'
})
)
expect(register).not.toHaveBeenCalled()
expect(original).toEqual(before)
expect(form.query.data.value!.original.current).toBe(false)
expect(form.query.data.value!.original.needsReview).toBe(true)
expect(form.query.data.value!.audit.billingBlocked).toBe(false)
expect(get.mock.calls.length).toBeGreaterThan(1)
expect(task.mock.calls.length).toBeGreaterThan(1)
expect(changed).toHaveBeenCalledOnce()
})
it('真实原件缺失、歧义、未知费用、币种、原 SDK 事实与本地编号均禁止核清', () => {
const { audit } = videoAuditFixture(),
step = audit.steps[0]!
for (const kind of [
'missing',
'ambiguous',
'unknown',
'currency',
'sdk',
'local',
'observability',
'not-received'
] as const) {
const evidence = videoEvidenceFixture(),
currentStep = structuredClone(step)
if (kind === 'missing') evidence.artifacts = []
if (kind === 'ambiguous') evidence.correlation = 'ambiguous'
if (kind === 'unknown') evidence.billing.amount = null
if (kind === 'currency') evidence.billing.currency = 'CNY'
if (kind === 'sdk') currentStep.hasOriginalReceipt = true
if (kind === 'local') evidence.providerRequestId = evidence.identity.requestId
if (kind === 'observability') evidence.artifacts.forEach(item => (item.kind = 'langsmith'))
if (kind === 'not-received') evidence.execution.outcome = 'not-received'
expect(auditReleaseIssues(evidence, currentStep, audit).length).toBeGreaterThan(0)
}
})
it('校验重复/缺失原件引用,允许未知声明但不会推断零费用', () => {
const evidence = videoEvidenceFixture()
evidence.artifacts[1]!.id = 'execution'
expect(auditEvidenceIssues(evidence).length).toBeGreaterThan(0)
const unknown = videoEvidenceFixture()
unknown.correlation = 'unverified'
unknown.execution.outcome = 'unknown'
unknown.billing.finding = 'unknown'
unknown.billing.amount = null
expect(auditEvidenceIssues(unknown)).toEqual([])
expect(auditReleaseIssues(unknown, videoAuditFixture().audit.steps[0]!, videoAuditFixture().audit)).not.toEqual(
[]
)
})
it('原候选过期预检失败后仍允许按原任务号回读,归属错误禁止写入', async () => {
const { form, history, get, register, review } = await setup()
history.mockRejectedValueOnce(new ApiError('旧候选已过期', 409))
await form.discovery.refresh()
expect(form.discovery.data.value!.notice).toContain('原任务编号')
get.mockImplementationOnce(async () => ({ ...videoAuditFixture().audit, projectId: 'other' }))
await form.refresh()
form.confirmed.value = true
await form.submit()
expect(register).not.toHaveBeenCalled()
expect(review).not.toHaveBeenCalled()
expect(form.query.error.value).toContain('归属')
})
})
@@ -1,3 +1,4 @@
import { generationConfigApi } from '@/features/generation-config/api'
import { approvedCharacter, imagePreviewFixture } from '../../fixtures/image-preview'
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
@@ -20,6 +21,14 @@ import { identityImageFixture } from '@/features/subject-identity/testing/fixtur
import { formFixture } from '@/features/subject-images/testing/fixtures'
import { selectControl } from '@/testing/naive'
/** 模型初值通过正式解析接口读取,保留项目已保存参数。 */
beforeEach(() => {
vi.spyOn(generationConfigApi, 'resolve').mockResolvedValue({
provider: creativeProfile.imageProvider,
model: creativeProfile.imageModel,
options: { ...creativeProfile.imageOptions }
})
})
/** 生成提交由测试替身接收,绝不调用真实模型。 */
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
let wrapper: VueWrapper | undefined
@@ -1,3 +1,4 @@
import { generationConfigApi } from '@/features/generation-config/api'
import { validationPreviewResponse } from '../../fixtures/image-preview'
import { imagePreviewFixture } from '../../fixtures/image-preview'
import { imageCatalog, generationProfile } from '../../fixtures/generation'
@@ -13,6 +14,14 @@ import { expandSections } from '@/testing/naive'
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
/** 模型初值通过正式解析接口读取,保留项目已保存参数。 */
beforeEach(() => {
vi.spyOn(generationConfigApi, 'resolve').mockResolvedValue({
provider: creativeProfile.imageProvider,
model: creativeProfile.imageModel,
options: { ...creativeProfile.imageOptions }
})
})
/** 生成提交由测试替身接收,绝不调用真实模型。 */
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
let wrapper: VueWrapper | undefined
+10 -1
View File
@@ -1,7 +1,8 @@
import { generationConfigApi } from '@/features/generation-config/api'
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { defineComponent } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { projectContextKey } from '@/features/projects/context'
import { testProjectContext } from '@/testing/project-context'
import { getOperation } from '@/features/workflows/operations'
@@ -13,6 +14,14 @@ import GenerateImageDialog from '@/features/subject-images/components/GenerateIm
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
/** 模型初值通过正式解析接口读取,保留项目已保存参数。 */
beforeEach(() => {
vi.spyOn(generationConfigApi, 'resolve').mockResolvedValue({
provider: creativeProfile.imageProvider,
model: creativeProfile.imageModel,
options: { ...creativeProfile.imageOptions }
})
})
/** 生成提交由测试替身接收,绝不调用真实模型。 */
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
let wrapper: VueWrapper | undefined
+9
View File
@@ -119,6 +119,15 @@ function stubFetch(fetcher: Mock<typeof fetch>) {
}
if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
/** 主体与首帧表单使用原配置解析接口,不创建图片候选。 */
if (path.endsWith('/generation-config/image/resolve')) {
const profile = generationProfile(fixture.id)
return jsonResponse({
provider: profile.imageProvider,
model: profile.imageModel,
options: profile.imageOptions
})
}
if (path.endsWith('/duration-budget'))
return jsonResponse({
projectId: fixture.id,
+167
View File
@@ -0,0 +1,167 @@
import type { ImageAuthorizationList } from '../../src/features/image-authorization/types'
import type {
VideoAuditEvidence,
VideoAuditView,
VideoExecutionDetail
} from '../../src/features/production/video-audit.types'
import { imageCatalog, generationProfile } from './generation'
/** 统一隔离模型目录,保留其它供应方用于切换确认。 */
export const billingCatalog = {
...imageCatalog,
defaults: { ...imageCatalog.defaults, imageProvider: 'openai-image' },
images: [
...imageCatalog.images.map(item => ({ ...item, isDefault: false })),
{
...imageCatalog.images[0]!,
provider: 'openai-image',
providerLabel: 'OpenAI',
model: 'gpt-image-2.5-flare',
modelLabel: 'GPT Image',
isDefault: true
}
]
}
/** 隔离项目保留明确的 OpenAI 配置。 */
export const billingProfile = {
...generationProfile('billing-project'),
imageProvider: 'openai-image',
imageModel: 'gpt-image-2.5-flare'
}
/**
* 创建每个用例独立的授权与余额。
* @returns 不连接真实账户的正式投影
*/
export function imageAuthorizationsFixture(): ImageAuthorizationList {
return {
authorizations: [
{
id: 'grant',
status: 'approved',
expired: false,
usedRequests: 0,
remainingRequests: 10,
accountedMicros: 0,
remainingMicros: 5_000_000,
billingBlocked: false,
input: {
idempotencyKey: 'fixture',
mode: 'standing',
provider: 'openai-image',
models: ['gpt-image-2.5-flare'],
scopes: ['identity', 'form', 'keyframe', 'layout'],
currency: 'USD',
budgetMicros: 5_000_000,
perRequestMicros: 500_000,
maxRequests: 10,
expiresAt: '2099-01-01T00:00:00Z',
acknowledgeVariableBilling: true,
approvedBy: '隔离批准人',
approvalNote: '仅供 Mock 测试'
}
}
],
requests: [],
billingBlocked: false,
blockingRequestIds: []
}
}
/**
* 构造跨版本原质检任务与原审计,默认完全未知。
* @returns 隔离审计和原任务
*/
export function videoAuditFixture() {
const identity = {
taskId: 'audit-task',
workflowExecutionId: 'audit-workflow',
requestId: 'local-request',
requestFingerprint: 'a'.repeat(64),
planFingerprint: 'b'.repeat(64),
sourceFingerprint: 'c'.repeat(64),
videoId: 'audit-video',
provider: 'vision-provider',
model: 'vision-model'
}
const audit: VideoAuditView = {
projectId: 'billing-project',
shotId: 'audit-shot',
taskId: identity.taskId,
workflowExecutionId: identity.workflowExecutionId,
currency: 'USD',
taskFingerprint: 'd'.repeat(64),
originalTaskStatus: 'failed',
originalWorkflowStatus: 'failed',
billingBlocked: true,
steps: [
{
name: 'spatialInteractionResult',
requestStatus: 'unresolved',
identity,
originalProviderRequestId: null,
originalSdkReceiptId: null,
hasOriginalReceipt: false,
evidenceSetFingerprint: 'e'.repeat(64),
reviewFingerprint: 'f'.repeat(64),
status: 'unreviewed',
released: false,
reviewId: null,
evidence: [],
reviews: []
}
],
history: { evidence: [], reviews: [] }
}
const original: VideoExecutionDetail = {
taskId: identity.taskId,
taskStatus: 'failed',
executionId: identity.workflowExecutionId,
videoId: identity.videoId,
needsReview: true,
billingBlocked: true,
workflowStatus: 'failed',
current: false,
staleReason: '动作规划已变化',
plan: {
purpose: 'video_validation',
projectId: audit.projectId,
shotId: audit.shotId,
videoId: identity.videoId,
fingerprint: identity.planFingerprint
},
output: {
billing: { actualAmount: null, reason: '原费用未知' },
result: { passed: false, qualityDecision: 'needs_review' },
steps: [{ name: 'spatialInteractionResult', status: 'unresolved' }]
}
}
return { audit, original }
}
/**
* 构造仅供隔离测试的完整材料声明,绝不提交正式历史任务。
* @returns 可供人工核验交互测试的证据包
*/
export function videoEvidenceFixture(): VideoAuditEvidence {
return {
identity: videoAuditFixture().audit.steps[0]!.identity,
correlation: 'unique',
providerRequestId: 'mock-provider-request',
artifacts: [
{
id: 'execution',
kind: 'provider-execution',
recordId: 'mock-execution',
sha256: '1'.repeat(64),
reference: '隔离执行原件'
},
{
id: 'bill',
kind: 'provider-billing',
recordId: 'mock-bill',
sha256: '2'.repeat(64),
reference: '隔离账单原件'
}
],
execution: { outcome: 'failed', evidenceIds: ['execution'] },
billing: { finding: 'charged', amount: 0.12, currency: 'USD', evidenceIds: ['bill'] }
}
}