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

@@ -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,