feat(short-drama-agent-front): 接入有限图片授权与候选修订

This commit is contained in:
GJ committed 2026-11-18 11:52:36 +08:00
1 parent f6edc4eb70
commit b15a6011ce
37 files changed
+3569 -76

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# 接口数据同步说明
## 2026-11-18 V8-10.2~V8-10.12
按后端 `fd0ab65` 正式 Schema/Router 增量接入 bounded、失败 Motion 候选人工子版本、Provider 容量阻断、sceneTransition 规划状态、已有失败图片摄影修订及机器/有效质量分离。复用原授权设置、摄影与 Motion 编辑器、首帧候选/历史及 Workflow,不新建业务页面。
bounded 使用原 standing 预算及精确逐镜计划,保留旧 unknown/预留;单镜主动选用且一次成功后停止。Motion 保存、独立起点视觉、正式采用分别操作,起点启动携带精确计划指纹。摄影普通修订仅构图/机位,采用后只读刷新正式源/Preview/质量,不自动生图。旧图来源与费用在原历史按候选读取,实际账单未知不显示为0。
真实项目仅只读;Mock 写入及本地 Chrome 桌面/390px 验收,未执行真实收费模型。用户已在验收后授权将本轮全部 37 个文件提交并推送到 dev,保留正常提交钩子;开发交接中的未提交状态为验收时点记录,最终交付以 Git 记录为准。完整文件、API、测试/浏览器证据和边界见 [本轮接入交接](audits/v8-10-frontend-integration-2026-11-18.md)。
## 2026-11-16 集中 Git 交付
按用户明确授权,将本轮全部52个文件(新增26、修改26、删除0)集中提交并推送到dev,主题为 `feat(short-drama-agent-front): 接入联合修订与图片费用审计`。范围包括环境原文依据、人工图片追加/费用审计、时间语义及分镜界面修复,保留正常提交钩子。以下“未提交/未推送”属于各功能验收时点;实际提交号、全量钩子结果和远端同步状态以本次Git记录为准。
@@ -0,0 +1,126 @@
# V8-10.2~V8-10.12 前端接入交接
## 范围与基线
- 前端根目录 `dev`,起点 `f6edc4eb708b0f69b078b6c74b5d1ca3d6eb8e30`,起始干净;只修改前端,没有创建 worktree。
- 后端契约基线 `fd0ab65c3c2d78032cdf8c243621df2941315e40`。收尾只读核对时为 `1f9ceace`,相对基线仅增加第三张图片执行审计等文档,没有修改本轮接口。后端另有并行质量审计文档未提交,本轮没有改动它们。
- 已核对用户指定四份公开 API、四份前端 Prompt,以及实际授权 Schema/Repository、图片 Provider/Storyboard/Video Router 和相应服务。
- 所有写入验收使用隔离 Mock。正式项目仅 GET;没有启动图片、文本、Vision、Repair、视频、Primary 或历史 unknown 重试。
- 开发验收时未提交、未推送;验收后用户已明确授权将本轮全部改动提交并推送到 `dev`。本次集中交付包含新增 9、修改 28、删除 0,共 37 个文件;保留正常提交钩子,最终提交号与远端同步状态以 Git 记录及交付回复为准。
## 已有能力与真实缺口
| 原有实现 | 本轮真实增量 |
| --- | --- |
| standing、additional、精确费用 Preview、撤销、图片费用审计 | bounded 创建、逐镜计划与次数、总次数、原预算、逐项接受 unknown、首帧主动选用 |
| Motion Plan 人工版本、保存、Workflow 起点校验、正式采用 | failed_candidate 根与 manual 子、null 原指针、原 Task/Workflow/公开回执、完整来源预检、精确起点计划指纹 |
| Provider 按需能力检查、实际生成 Preview | 容量 409 撤销旧成功状态、保留实际阻断和公开上限 |
| 原普通摄影草案、联合采用、视线与场景沿用、草案历史 | 已有失败图片下的 composition/cameraPosition 修订、完整差异/历史/相邻版本、采用后正式预览与质量刷新 |
| 机器审核与有效质量、候选管理、历史生成输入原件 | failed/stale 组合摘要、原图片费用按候选读取、来源变化后重新读取质量、候选与历史弹窗交接 |
| 时间语义、正式连续性问题与门禁 | sceneTransition 人工规划确认与真实视频末态分开展示 |
没有新增业务路由、第二套摄影编辑器、时间轴、费用或 Workflow 页面。继续保留 V8-9 的 additional、独立证据/复核、联合环境依据、原历史和来源保护。普通镜头目录无默认勾选,进入分镜页不弹生成配置。
## API 与交互
| 正式 API | 接入结果与边界 |
| --- | --- |
| GET /projects/:id/image-authorizations | 沿原投影读取 standing、additional/bounded、逐镜 usedRequests、inputFingerprint、原 unknown/预留及审计状态 |
| POST /projects/:id/image-authorizations | mode=bounded 严格发送正式 Schema:原 standing、接受的未知请求及 SHA、固定 OpenAI/型号、逐镜 source/plan/options/maxRequests、总次数、期限、两项风险确认、人及说明;不发送新预算 |
| POST /projects/:id/image-authorizations/preview | 用户主动逐镜免费编译,取得真实 Source/费用计划;不是图片生成、质量通过或费用核清 |
| POST /projects/:id/image-authorizations/:authorizationId/revoke | 继续原撤销,显示已用/剩余;撤销、过期、用尽不再允许领取,历史及旧预留不删 |
| POST /storyboard-shots/:id/keyframe | 单镜明确选择许可并再次核对精确预览;bounded 仍使用 additionalAuthorizationId。一次成功停止;同计划完整结果可只读查看 |
| GET /storyboard-shots/:id/keyframe-provider-capability、GET /image-providers/capabilities | 按需检查,409 清旧 capability 和实际生成预检。实际需要数量沿后端业务错误展示,Provider 上限来自公开能力;不丢必需参考或换模型 |
| GET /storyboard-shots/:id/video-prompt/preview、GET /video-prompt/executions/:taskId | 免费发现/只读核对原失败候选;原 SDK 未公开全文不伪造,展示公开 observations、steps、usage、Task/Workflow/质量 |
| GET /motion-plan/revisions、POST /revisions/preview、POST /revisions | failed_candidate 根与 manual 子保持区分,originalRevisionId=null 合法。先免费预检再明确保存;保存不启动起点模型或正式采用 |
| POST /revisions/:id/start-state-validation/start、PUT /revisions/:id/active | 起点前再次免费核对完整计划,发送 expectedPlanFingerprint;只有当前保存版本、主首帧和来源匹配的有效证据才可独立采用。复用旧 Workflow/SSE,不自动生成 Video Prompt/视频 |
| POST /projects/:id/storyboard-derived-reviews/confirm | 下游摄影沿原普通模式,仅 composition/cameraPosition;不发送 jointRevision 或 direction-only phase,其他正式字段原样保留。保存和正式采用独立 |
| GET keyframes、quality-review、validations、generation-input | 资产列表只来自真实 keyframes;未执行计划不变成候选。旧图可查看原输入、机器结论、当前有效质量;费用在原历史中按 project/Shot/candidateId 精确过滤授权账本 |
- bounded 只使用原预算,当前 blocker 必须逐项明确接受且 inputFingerprint 一致;新的未知请求或在途请求继续停止领取。
- 授权期限进入预览快照;页面停留期间到期也撤销旧成功预检,提交时再检查,不用旧许可继续生成。
- 任何能力 valid 仅说明对应输入。费用、规划、起点像素、图片质量、Primary 和正式采用独立。
- `basis=confirmed_plan` 且 `verifiedVideoEndState=false` 展示“人工规划衔接已确认,视频末态尚未验证”,使用中性状态;不推断前镜真实视频尾态。
- `SCENE_CONTINUITY_REVIEW_STALE` 清旧成功预览、保留输入、重新只读来源并等待人工确认;不自动重提。摄影/Motion 409 同样保留人工稿并刷新来源。
- 摄影采用后读取正式 D/VS、草案 Current/Stale、正式 Keyframe Preview 和免费费用计划,并强制刷新原图有效质量。原机器失败与旧图片不被删除或改写。
- 旧 `qualityDecision=failed`、当前 `effectiveQualityStatus=stale` 显示“历史审核未通过,当前来源已变化”。completed 不等于质量 passed,passed 不等于 Primary。
- 长原文、来源/计划/回执与历史使用已有公共折叠。沿用 NMessage、主题变量、就地 loading、固定底栏;候选管理完全关闭后再进入原图历史,避免双重焦点约束。
## 实际文件与职责
新增 9 个文件:
- `src/features/image-authorization/BoundedAuthorizationFields.vue`:原设置中的逐镜有限风险表单,复用原抽屉 footer。
- `src/features/storyboard/components/SceneTransitionEvidence.vue`:分镜与首帧共用的正式人工规划依据展示。
- `tests/features/image-authorization/bounded.test.ts`:范围/期限/次数/原预算/未知集合和显式登记。
- `tests/features/storyboard/failed-motion-candidate.test.ts`:原失败根、人工保存、精确起点及独立采用。
- `tests/features/storyboard/camera-candidate.test.ts`:已有图片的普通摄影保存/采用、质量刷新、409 保留。
- `tests/features/production/v8-10-contract.test.ts`:容量、连续性、failed/stale/Primary、旧图费用和范围隔离。
- `tests/browser/v8-10.html`、`tests/browser/v8-10.ts`:复用真实组件的 Chrome 隔离入口,fetch 全拦截,未知请求 403,绝无真实网络 fallback。
- 本交接文档。
修改 28 个文件:
- `src/features/image-authorization/{ImageAuthorizationSettings.vue,api.ts,model.ts,types.ts}`:登记模式、许可历史、原撤销、正式契约与实际准入。
- `src/features/production/api.ts`:免费正式预览支持已有项目 scope。
- `src/features/production/components/{KeyframeDialog.vue,ModelCapabilities.vue,KeyframePreviewChecks.vue}`:单镜主动选许可、能力阻断、正式规划说明。
- `src/features/production/components/{KeyframeCard.vue,KeyframeValidationHistory.vue,ShotProductionAssets.vue}`:有效质量、只读图片、按候选费用、来源更新与历史弹窗交接。
- `src/features/production/effective-keyframe-quality.ts`:机器历史与当前过期状态的组合摘要。
- `src/features/storyboard/components/{MotionRevisionEditor.vue,ShotDerivedReview.vue,ShotTools.vue}`:复用现有动作、摄影和详情交互。
- `src/features/storyboard/{generation-spec.types.ts,motion-api.ts,motion-revision.ts,motion.types.ts,useMotionRevision.ts}`:正式连续性/失败候选/精确起点计划契约与编排。
- `src/features/subject-images/generation-preview.ts`:旧费用准入清除、衔接冲突及授权到期保护,原 unknown guard 保留。
- `src/lib/{billing-errors.ts,user-facing-text.ts}`:bounded、来源/活动锁的中文反馈,原码保留。
- `tests/features/image-authorization/settings.test.ts`:原 standing 用例按语义标签定位,保留原幂等验证。
- `tests/features/production/quality.test.ts`:公开能力“默认推荐”文案断言。
- `tests/features/storyboard/motion-revision.test.ts`:起点启动正式精确计划指纹。
- `tests/features/subject-images/generation-preview.test.ts`:规划来源冲突与停留到期不收费回归。
- `docs/api-contract-sync.md`:本轮契约同步索引。
删除 0 文件;没有改依赖、锁文件或后端文件。
## 正式 API 只读观察
2026-11-18 本轮 GET 及 Chrome 时点,不是本轮生产或质量结论:
- V02 授权投影 `billingBlocked=true`,unknown 1 条。原 standing 已请求 5 次、剩余 495 次、余额 98,719,355 微美元;一个 additional 已撤销、已用 1、剩余 1;三个 bounded 各已用 1、剩余 0,全部不可再次使用。
- 3.1:originalRevisionId=null、activeRevisionId=null,包含一个 failed_candidate 根和一个 manual 子,均未正式采用;失败根有原 Task/Workflow/回执来源。
- 3.2:三张 completed 候选均非 Primary。最新机器 unknown/有效 blocked;第二张 unknown/unknown;第一张 failed/stale。第三张已由其它任务生成,不能继续写成“只有计划、尚未生成”。
- Chrome 旧图原请求详情:原预留 USD 1、公开用量价 USD 0.076537、实际账单未知;与旧机器失败、当前过期分别展示。
- 后端另一个任务持续更新正式质量审计。最后复验历史交接时服务短暂不可达,页面显示连接失败,不沿用旧成功数据;此前上述 GET/历史读取成功。没有为制造成功状态写入正式数据。
## 自动化与 Chrome 验收
2026-11-18 最终自动化检查:
- `node_modules/.bin/vitest run`:122 个文件、941 项全部通过,77.35 秒。首轮发现两项旧断言(下拉框位置、能力文案)并按真实语义修正;最终重新全量通过,不将首轮结果记为全绿。
- `node_modules/.bin/vue-tsc --noEmit`:通过。
- `node_modules/.bin/vite build`:通过,1.15 秒。
- 修改范围 Oxlint、Vue ESLint、Oxfmt 及 `git diff --check`:通过。
- 新增 28 项测试;覆盖 bounded 范围/预算/旧 unknown/期限/撤销/用尽、Motion 根/子/保存/精确起点/采用/并发、普通摄影兼容/409/完整字段/质量刷新、Provider 容量、规划非视频末态、候选质量/Primary、项目切换与旧图费用隔离、停留授权到期及来源冲突不重发。
测试过程未调用真实模型,未模拟路由一律拒绝。
Chrome 使用已有本地 Google Chrome 与 `localhost:4312`,原生 AX、截图、键鼠和 DevTools Responsive,未使用 Playwright。
- 桌面人工填写 bounded:选择原 standing/Shot,逐镜费用计划,次数 2/总 2、期限/人/理由、逐项 unknown 接受和浮动风险确认;登记前按钮禁用,登记后已用 0/剩余 2、无生图。
- 单镜不默认选许可;显式选择、重新 Preview 后主动模拟生成一次,已用 1/剩余 1,原 standing 预算同步扣减;随后只读查看同计划结果不增加模型请求。
- 撤销剩余许可后显示不可领取,原 unknown、预留及未知实际账单保留。
- failed 候选读取/载入/修改/免费预检/保存分开;创建 failed 根/manual 子,active 仍为空,Vision 0。切换 failed 根后不能直接起点审核或采用。
- Provider 容量阻断实际显示必需 17、上限 16;原成功输入不再展示,确认生成禁用;不删参考、不换模型。
- sceneTransition 仅显示人工规划已确认、视频末态未验证,未显示质量 Passed。
- 摄影构图在原模式保存、免费预览和明确采用,显示完整差异、当前及邻镜版本、摄影历史与原图片/质量;采用不自动生图。
- 390×844 核对首帧、摄影、Motion、bounded 长表单,正文可滚动,标题与底部关闭/提交保持可见,单列字段无横向溢出;恢复桌面响应式设置。
- 正式分镜页进入时没有生成弹窗和目录复选框;真实 3.2 三候选质量区别可见,旧图费用/来源历史可读。候选关闭后原图历史独立接管焦点。
截图(本地验收产物,不进入源码):
- `/Users/goujun/.codex/visualizations/2026/11/15/01a1df1f-2851-7ff2-b840-d1a0f3154f74/v8-10-motion-mobile.png`
- `/Users/goujun/.codex/visualizations/2026/11/15/01a1df1f-2851-7ff2-b840-d1a0f3154f74/v8-10-bounded-mobile.png`
- `/Users/goujun/.codex/visualizations/2026/11/15/01a1df1f-2851-7ff2-b840-d1a0f3154f74/v8-10-real-candidates.png`
## 未接入与验收边界
- 本轮要求的前端能力已接入;真实收费端到端生成、起点 Vision、正式摄影/Motion 采用、真实费用核清均按用户限制未执行。
- 原模型公开接口没有提供 SDK 原始全文时,仅展示正式公开的观察、用量及回执元数据,不补造原件。
- 容量 409 未提供结构化实际数量时保留后端含实际数量的业务原因;不根据前端关键词计算参考数量。
- 完整旧输入沿已有 generation-input 原件展示,缺少记录或 OpenAI 账本匹配不推断为零费用,也不重编译历史输入。
@@ -0,0 +1,464 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox, NDatePicker, NInput, NInputNumber, NSelect } from 'naive-ui'
import WorkspaceSectionHeading from '../../components/ui/WorkspaceSectionHeading.vue'
import RawDataDetails from '../../components/ui/RawDataDetails.vue'
import { useActionMessage } from '../../components/ui/useActionMessage'
import { useQuery } from '../../composables/useQuery'
import { ApiError, errorMessage } from '../../lib/http'
import { projectsApi } from '../projects/api'
import { storyboardApi } from '../storyboard/api'
import GenerationModelControls from '../generation-config/components/GenerationModelControls.vue'
import { generationConfigApi } from '../generation-config/api'
import type { GenerationModelCatalog, GenerationOptions } from '../generation-config/types'
import { imageAuthorizationApi } from './api'
import { formatMicros } from './model'
import type { ImageAuthorizationList, ImageAuthorizationPreview, ImageBoundedTarget } from './types'
/** 原授权管理中的有限风险表单,操作由原抽屉固定底栏提交。 */
const props = defineProps<{
/** 正式项目。 */ projectId: string
/** 当前原费用投影。 */ list: ImageAuthorizationList | null
/** 正式模型目录。 */ catalog: GenerationModelCatalog | null
/** 实际活动锁。 */ disabled: boolean
}>()
/** 不新增预算面板,写入后刷新原授权与费用历史。 */
const emit = defineEmits<{ busy: [value: boolean]; changed: []; refresh: [] }>()
/** 用户选择的原standing。 */ const parentId = ref<string | null>(null)
/** 明确选中的正式镜头,普通浏览目录不增加勾选。 */ const shotIds = ref<string[]>([])
/** 每镜次数不预填。 */ const counts = ref<Record<string, number | null>>({})
/** 总次数不预填。 */ const total = ref<number | null>(null)
/** 明确有效期。 */ const expires = ref<number | null>(null)
/** 本次实际模型参数。 */ const options = ref<GenerationOptions>({})
/** 实际批准人。 */ const approvedBy = ref('')
/** 本次风险批准说明。 */ const note = ref('')
/** 主动接受的旧未知请求,不吞并新unknown。 */ const acceptedIds = ref<string[]>([])
/** 浮动费用及原未知风险的独立人工确认。 */ const acknowledged = ref(false)
/** 同步操作期间防止重复写入。 */ const saving = ref(false)
/** 免费编译期间的就地加载。 */ const preparing = ref(false)
/** 当前已冻结的精确费用计划,不保存实际图片载荷。 */ const plans = ref<Array<{
/** 正式镜头。 */ shotId: string
/** 实际型号。 */ model: string
/** 正式Source。 */ sourceFingerprint: string
/** 费用计划。 */ planFingerprint: string
}> | null>(null)
/** 错误不清空用户表单。 */ const error = ref('')
/** 相同内容失败后仍使用同一幂等键。 */ const nonce = ref(crypto.randomUUID())
/** 免费请求在切范围后失效。 */ let version = 0
/** 离开页面后不回填或通知其它项目。 */ let disposed = false
onScopeDispose(() => {
disposed = true
version++
})
/** 当前原预算和剩余额度。 */ const parent = computed(() =>
props.list?.authorizations.find(row => row.id === parentId.value)
)
/** 只列可用且覆盖首帧的原standing。 */ const parents = computed(
() =>
props.list?.authorizations
.filter(
row =>
row.input.mode === 'standing' &&
row.status === 'approved' &&
!row.expired &&
row.input.scopes.includes('keyframe')
)
.map(row => ({
label: `${row.input.approvedBy} · ${row.input.models.join(' / ')} · 剩余 ${formatMicros(row.remainingMicros)}`,
value: row.id
})) ?? []
)
/** Provider固定OpenAI,型号仅来自正式目录和父批准交集。 */ const catalog = computed(() =>
props.catalog
? {
...props.catalog,
images: props.catalog.images.filter(
row =>
row.provider === 'openai-image' &&
row.enabled &&
parent.value?.input.models.includes(row.model ?? '')
)
}
: null
)
/** 本次唯一实际型号,免费计划还会再次核对。 */ const model = computed(() => catalog.value?.images[0]?.model ?? '')
/** 当前全部有效费用阻断,必须明确逐项接受。 */ const blockers = computed(
() => props.list?.requests.filter(row => props.list?.blockingRequestIds.includes(row.id)) ?? []
)
/** 正式镜头列表按项目读取,ID不来自自由输入。 */ const targetKey = computed(() => props.projectId)
/** 复用原项目及摄影目录GET,不创建资产或计划。 */ const targets = useQuery(targetKey, async (value, signal) => {
const [project, profile] = await Promise.all([
projectsApi.detail(value, signal),
generationConfigApi.profile(value, signal)
])
if (project.id !== value || !Array.isArray(project.episodes)) throw new Error('当前项目镜头列表无法核对。')
const rows = await Promise.all(project.episodes.map(row => storyboardApi.directions(value, row.episode, signal)))
if (rows.some(row => row.projectId !== value)) throw new Error('镜头目录不属于当前项目。')
return {
aspectRatio: profile?.aspectRatio ?? null,
items: rows.flatMap(row =>
row.beats.flatMap(beat =>
beat.shots.map(shot => ({
label: `第 ${row.episodeNo} 集 · 镜头 ${beat.beatNo}.${shot.shotNo}`,
value: shot.shotId
}))
)
)
}
})
/** 编译范围变化立即废弃旧计划和人工确认。 */ const signature = computed(() =>
JSON.stringify([props.projectId, parentId.value, model.value, shotIds.value, options.value])
)
watch(
signature,
() => {
version++
plans.value = null
acknowledged.value = false
nonce.value = crypto.randomUUID()
error.value = ''
preparing.value = false
},
{ flush: 'sync' }
)
/** 新请求或父预算改变时必须重新接受风险,不把旧确认套给新集合。 */
watch(
() => JSON.stringify([blockers.value, parent.value]),
() => {
acceptedIds.value = []
acknowledged.value = false
},
{ flush: 'sync' }
)
watch(
[counts, total, expires, approvedBy, note, acceptedIds],
() => {
acknowledged.value = false
nonce.value = crypto.randomUUID()
error.value = ''
},
{ deep: true, flush: 'sync' }
)
watch(parentId, () => {
acceptedIds.value = []
expires.value = null
options.value = { ...catalog.value?.images[0]?.defaults }
})
watch(
() => props.projectId,
() => {
version++
parentId.value = null
shotIds.value = []
counts.value = {}
total.value = null
expires.value = null
approvedBy.value = ''
note.value = ''
acceptedIds.value = []
acknowledged.value = false
plans.value = null
error.value = ''
nonce.value = crypto.randomUUID()
},
{ flush: 'sync' }
)
watch(saving, value => emit('busy', value), { flush: 'sync' })
/** 原预算、接受集合、逐镜及总次数全部有效,才允许登记;仍不启动生成。 */
const canSubmit = computed(() => {
const grant = parent.value,
rows = plans.value
return (
!props.disabled &&
!saving.value &&
!preparing.value &&
!targets.loading.value &&
!targets.error.value &&
!!grant &&
grant.status === 'approved' &&
!grant.expired &&
Date.parse(grant.input.expiresAt) > Date.now() &&
grant.remainingRequests > 0 &&
grant.remainingMicros >= grant.input.perRequestMicros &&
!!rows?.length &&
rows.length === shotIds.value.length &&
rows.length <= 100 &&
blockers.value.length > 0 &&
blockers.value.length === props.list?.blockingRequestIds.length &&
blockers.value.every(
row =>
row.status === 'unknown' &&
row.input.projectId === props.projectId &&
row.input.authorizationId === grant.id &&
row.input.model === model.value &&
/^[a-f0-9]{64}$/.test(row.inputFingerprint ?? '') &&
acceptedIds.value.includes(row.id)
) &&
acceptedIds.value.length === blockers.value.length &&
rows.every(
row =>
Number.isInteger(counts.value[row.shotId]) &&
counts.value[row.shotId]! >= 1 &&
counts.value[row.shotId]! <= 100 &&
(!grant.input.targetIds || grant.input.targetIds.includes(row.shotId))
) &&
Number.isInteger(total.value) &&
total.value! >= 1 &&
total.value! <= 100 &&
total.value! <= rows.reduce((sum, row) => sum + (counts.value[row.shotId] ?? 0), 0) &&
!!expires.value &&
expires.value > Date.now() &&
expires.value <= Date.parse(grant.input.expiresAt) &&
!!approvedBy.value.trim() &&
!!note.value.trim() &&
acknowledged.value
)
})
/** 全局NMessage与就地说明并行,原费用保持原样。 */ const message = useActionMessage()
/** 用户主动编译所选镜头,来源/计划来自正式免费API。 */
async function prepare() {
if (
preparing.value ||
saving.value ||
props.disabled ||
!parent.value ||
!model.value ||
!shotIds.value.length ||
shotIds.value.length > 100
)
return
const current = ++version,
project = props.projectId,
ids = [...shotIds.value],
parameters = { ...options.value },
expectedModel = model.value
preparing.value = true
plans.value = null
acknowledged.value = false
error.value = ''
try {
const rows: ImageAuthorizationPreview[] = []
for (const shotId of ids)
rows.push(
await imageAuthorizationApi.preview(project, {
scope: 'keyframe',
targetId: shotId,
providerName: 'openai-image',
generationOptions: parameters
})
)
if (disposed || current !== version) return
if (
rows.some(
(row, index) =>
row.provider !== 'openai-image' ||
row.model !== expectedModel ||
row.context.projectId !== project ||
row.context.scope !== 'keyframe' ||
row.context.targetId !== ids[index] ||
!/^[a-f0-9]{64}$/.test(row.context.sourceFingerprint) ||
!/^[a-f0-9]{64}$/.test(row.planFingerprint)
)
)
throw new Error('当前型号或精确费用计划不匹配,请重新核对。')
plans.value = rows.map(row => ({
shotId: row.context.targetId,
model: row.model,
sourceFingerprint: row.context.sourceFingerprint,
planFingerprint: row.planFingerprint
}))
} catch (cause) {
if (current === version) {
error.value = errorMessage(cause)
message?.error(error.value)
}
} finally {
if (current === version) preparing.value = false
}
}
/** 底栏仅登记明确批准,不调用图片/模型;409清除预检,保留草稿并刷新正式授权。 */
async function submit() {
if (!canSubmit.value || !plans.value || !parent.value) return
if (!expires.value || expires.value <= Date.now() || Date.parse(parent.value.input.expiresAt) <= Date.now()) {
acknowledged.value = false
error.value = '本次许可或原授权已到期,请重新核对有效期。'
message?.error(error.value)
return
}
const project = props.projectId,
body = {
mode: 'bounded' as const,
idempotencyKey: nonce.value,
parentAuthorizationId: parent.value.id,
acceptedUnknownRequests: blockers.value.map(row => ({
requestId: row.id,
inputFingerprint: row.inputFingerprint!
})),
provider: 'openai-image' as const,
model: model.value,
targets: plans.value.map(
row =>
({
shotId: row.shotId,
sourceFingerprint: row.sourceFingerprint,
planFingerprint: row.planFingerprint,
generationOptions: { ...options.value },
maxRequests: counts.value[row.shotId]!
}) satisfies ImageBoundedTarget
),
maxRequests: total.value!,
expiresAt: new Date(expires.value!).toISOString(),
acknowledgeUnknownPriorBilling: true as const,
acknowledgeVariableBilling: true as const,
approvedBy: approvedBy.value.trim(),
approvalNote: note.value.trim()
}
saving.value = true
try {
const result = await imageAuthorizationApi.create(project, body)
if (disposed || project !== props.projectId) return
acknowledged.value = false
message?.info(
result.status === 'revoked'
? '原有限许可已撤销,不能领取。'
: '有限许可已登记,未生成图片;旧未知费用与预留仍保留。'
)
emit('changed')
} catch (cause) {
if (!disposed && project === props.projectId) {
error.value = errorMessage(cause)
message?.error(error.value)
if (cause instanceof ApiError && cause.status === 409) {
plans.value = null
acknowledged.value = false
emit('refresh')
}
}
} finally {
saving.value = false
}
}
/** 复用原设置固定底栏。 */ defineExpose({ canSubmit, saving, submit, submitLabel: '登记有限风险许可' })
</script>
<template>
<!-- 以下是原预算内有限风险接受,所有批准字段由用户明确填写。 -->
<section class="workspace-section-stack" aria-label="有限跨镜风险许可">
<WorkspaceSectionHeading
title="接受旧费用风险,有限继续"
description="使用原预算;旧未知请求、预留和费用阻断继续保留,不代表账单已核清。"
/>
<div class="workspace-form-field">
<span>原持续授权</span
><NSelect
v-model:value="parentId"
:options="parents"
:disabled="saving || disabled"
aria-label="有限许可原授权"
placeholder="选择原持续授权预算"
/>
</div>
<p v-if="parent" class="text-sm">
原预算 {{ formatMicros(parent.input.budgetMicros) }} · 已记账及未结预留
{{ formatMicros(parent.accountedMicros) }} · 剩余 {{ formatMicros(parent.remainingMicros) }} · 单次预留
{{ formatMicros(parent.input.perRequestMicros) }} · 剩余 {{ parent.remainingRequests }} 次
</p>
<GenerationModelControls
v-if="catalog?.images.length && targets.data.value?.aspectRatio"
type="image"
:catalog="catalog"
provider="openai-image"
:options="options"
:aspect-ratio="targets.data.value.aspectRatio"
:disabled="saving || disabled"
@update:options="options = $event"
/>
<p v-else-if="parent" class="text-sm">原授权型号未在当前OpenAI目录中启用。</p>
<div class="workspace-form-field">
<span>具体镜头</span
><NSelect
v-model:value="shotIds"
:options="targets.data.value?.items ?? []"
multiple
:loading="targets.loading.value"
:disabled="saving || disabled"
aria-label="有限许可镜头"
/>
</div>
<p v-if="targets.error.value" role="alert">{{ targets.error.value }}</p>
<NButton
class="self-start"
:disabled="saving || disabled || !parent || !model || !shotIds.length"
:loading="preparing"
@click="prepare"
>免费核对逐镜费用计划</NButton
>
<article v-for="row in plans ?? []" :key="row.shotId" class="workspace-section-stack">
<p class="text-sm">
{{ targets.data.value?.items.find(target => target.value === row.shotId)?.label }} · OpenAI /
{{ row.model }}
</p>
<RawDataDetails :value="row" title="当前来源与精确费用计划" />
<label class="workspace-form-field"
><span>本镜次数(1~100)</span
><NInputNumber
v-model:value="counts[row.shotId]"
:min="1"
:max="100"
:precision="0"
:disabled="saving"
:aria-label="`镜头 ${row.shotId} 批准次数`"
/></label>
</article>
<label class="workspace-form-field"
><span>总次数(1~100)</span
><NInputNumber
v-model:value="total"
:min="1"
:max="100"
:precision="0"
:disabled="saving || disabled"
aria-label="有限许可总次数"
/></label>
<div class="workspace-form-field">
<span>有效期(不晚于原授权)</span
><NDatePicker
v-model:value="expires"
type="datetime"
clearable
:disabled="saving || disabled"
aria-label="有限许可到期时间"
/>
</div>
<p v-if="!blockers.length" class="text-sm">当前没有需接受的未知阻断,请使用原有效授权。</p>
<article v-for="row in blockers" :key="row.id" class="space-y-2 text-sm">
<p>
原未知请求 {{ row.id }} · {{ row.input.model }} · 预留 {{ formatMicros(row.input.reservedMicros) }} ·
账单 {{ formatMicros(row.output?.actualBilledMicros) }}
</p>
<NCheckbox
:checked="acceptedIds.includes(row.id)"
:disabled="saving || row.status !== 'unknown'"
@update:checked="
acceptedIds = $event ? [...acceptedIds, row.id] : acceptedIds.filter(id => id !== row.id)
"
>我明确接受此原请求费用仍未知</NCheckbox
>
</article>
<label class="workspace-form-field"
><span>批准人</span
><NInput v-model:value="approvedBy" :maxlength="200" :disabled="saving" aria-label="有限许可批准人"
/></label>
<label class="workspace-form-field"
><span>批准说明</span
><NInput
v-model:value="note"
type="textarea"
:maxlength="2000"
:disabled="saving"
aria-label="有限许可批准说明"
/></label>
<NCheckbox v-model:checked="acknowledged" :disabled="saving || disabled"
>我已核对原未知费用、每镜计划及次数;接受按Token浮动计费,单次实际费用可能超过预留。本许可只供逐镜主动操作,不自动用完剩余次数。</NCheckbox
>
<p v-if="error" role="alert" class="text-sm">{{ error }}</p>
</section>
</template>
@@ -1,5 +1,6 @@
<script setup lang="ts">
import ImageBillingAuditPanel from './ImageBillingAuditPanel.vue'
import BoundedAuthorizationFields from './BoundedAuthorizationFields.vue'
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox, NDatePicker, NInput, NInputNumber, NSelect, NCollapse, NCollapseItem } from 'naive-ui'
import { useQuery } from '../../composables/useQuery'
@@ -52,6 +53,10 @@ function emptyAuthorizationDraft() {
}
/** 用户明确填写的持续授权草稿。 */
const draft = ref(emptyAuthorizationDraft())
/** 原授权页面中的登记模式,不增加新页面或预算。 */
const registrationMode = ref<'standing' | 'bounded'>('standing')
/** 有限许可仍由同一固定底栏提交。 */
const boundedPanel = ref<InstanceType<typeof BoundedAuthorizationFields> | null>(null)
/** 原设置抽屉内的费用审计模式,不叠加新主界面。 */
const auditRequestId = ref('')
/** 同一固定底栏提交当前图片审计。 */
@@ -97,18 +102,22 @@ const submitLabel = computed(
? '确认撤销授权'
: additionalRequestId.value
? '登记人工有限追加许可'
: '登记有限持续授权')
: registrationMode.value === 'bounded'
? '登记有限风险许可'
: '登记有限持续授权')
)
/** 读取失败时保守禁止写入,空表单允许主动校验。 */
const canSave = computed(() =>
auditRequestId.value
? !!auditPanel.value?.canSubmit
: !props.disabled &&
!saving.value &&
!!query.data.value &&
!query.loading.value &&
!query.error.value &&
(revokeId.value !== '' || additionalRequestId.value !== '' || !!modelOptions.value.length)
: registrationMode.value === 'bounded' && !revokeId.value && !additionalRequestId.value
? !!boundedPanel.value?.canSubmit
: !props.disabled &&
!saving.value &&
!!query.data.value &&
!query.loading.value &&
!query.error.value &&
(revokeId.value !== '' || additionalRequestId.value !== '' || !!modelOptions.value.length)
)
watch(saving, value => emit('busy', value), { flush: 'sync' })
watch(
@@ -126,6 +135,10 @@ async function save() {
await auditPanel.value?.submit()
return
}
if (registrationMode.value === 'bounded' && !revokeId.value && !additionalRequestId.value) {
await boundedPanel.value?.submit()
return
}
const project = props.projectId
if (revokeId.value) {
if (!revocation.value.revokedBy.trim() || !revocation.value.reason.trim()) {
@@ -257,6 +270,7 @@ watch(
() => props.projectId,
() => {
draft.value = emptyAuthorizationDraft()
registrationMode.value = 'standing'
revocation.value = { revokedBy: '', reason: '' }
validation.value = ''
auditRequestId.value = ''
@@ -303,6 +317,18 @@ defineExpose({ save, canSave, submitLabel })
<NButton class="self-start" :loading="query.loading.value" :disabled="saving" @click="query.refresh"
>刷新授权与请求</NButton
>
<div class="workspace-form-field">
<span>登记方式</span
><NSelect
v-model:value="registrationMode"
:disabled="saving"
:options="[
{ label: '有限持续授权', value: 'standing' },
{ label: '接受旧费用风险,有限继续', value: 'bounded' }
]"
aria-label="图片授权登记方式"
/>
</div>
<p v-if="query.loading.value && !query.data.value" role="status">正在读取授权…</p>
<p v-if="query.error.value" role="alert" class="text-sm text-muted">{{ query.error.value }}</p>
<p v-if="query.data.value?.billingBlocked" class="surface-inset p-4 text-sm" role="status">
@@ -408,8 +434,8 @@ defineExpose({ save, canSave, submitLabel })
<!-- 以下是原精确计划的人工追加次数和撤销,原unknown仍保留。 -->
<section v-if="query.data.value?.additionalAuthorizations?.length" class="workspace-section-stack">
<WorkspaceSectionHeading
title="人工有限追加许可"
description="只适用原精确计划,不增加预算;一次成功后停止,不自动消费剩余次数。"
title="人工有限许可"
description="只适用已批准的镜头与精确计划,使用原预算;每次由用户主动操作,不自动消费剩余次数。"
/>
<article
v-for="permit in query.data.value.additionalAuthorizations"
@@ -428,7 +454,23 @@ defineExpose({ save, canSave, submitLabel })
{{ permit.remainingRequests }} 次
</p>
<p v-if="permit.status === 'revoked'">剩余次数不可领取。</p>
<p>原请求 {{ permit.input.parentRequestId }} · 批准人 {{ permit.input.approvedBy }}</p>
<p v-else-if="permit.remainingRequests <= 0">次数已用尽,不可再次领取。</p>
<p>
{{ permit.input.mode === 'bounded' ? '有限跨镜风险许可' : '同计划人工追加' }} · 批准人
{{ permit.input.approvedBy }}
</p>
<p v-if="permit.input.mode === 'additional'">原请求 {{ permit.input.parentRequestId }}</p>
<template v-else
><p>
原持续授权 {{ permit.input.parentAuthorizationId }} · 到期
{{ new Date(permit.input.expiresAt).toLocaleString()
}}{{ Date.parse(permit.input.expiresAt) <= Date.now() ? ' · 已到期,不可领取' : '' }}
</p>
<p v-for="target in permit.targets ?? []" :key="target.shotId">
镜头 {{ target.shotId }} · 已用 {{ target.usedRequests }}/{{ target.maxRequests }} 次 · 剩余
{{ Math.max(0, target.maxRequests - target.usedRequests) }} 次
</p></template
>
<RawDataDetails :value="permit" title="追加许可与原计划详情" /><NButton
v-if="permit.status === 'approved'"
:disabled="saving || disabled"
@@ -508,6 +550,17 @@ defineExpose({ save, canSave, submitLabel })
>取消追加许可登记</NButton
>
</section>
<BoundedAuthorizationFields
v-else-if="registrationMode === 'bounded'"
ref="boundedPanel"
:project-id="projectId"
:list="query.data.value"
:catalog="catalog.data.value"
:disabled="disabled || query.loading.value || !!query.error.value"
@busy="saving = $event"
@changed="auditChanged"
@refresh="query.refresh"
/>
<!-- 以下是用户明确填写的有限持续授权,不预填金额、次数及日期 -->
<section v-else class="workspace-section-stack">
<WorkspaceSectionHeading
+5 -2
View File
@@ -1,6 +1,7 @@
import { request } from '../../lib/http'
import type {
ImageAdditionalAuthorizationInput,
ImageBoundedAuthorizationInput,
ImageAuthorizationInput,
ImageAuthorizationList,
ImageAuthorizationPreview,
@@ -40,8 +41,10 @@ export const imageAuthorizationApi = {
* @param input 本次不可变批准
* @returns 原授权标识及状态
*/
create: (projectId: string, input: ImageAuthorizationInput | ImageAdditionalAuthorizationInput) =>
request<{ authorizationId: string; status: string }>(root(projectId), { method: 'POST', body: input }),
create: (
projectId: string,
input: ImageAuthorizationInput | ImageAdditionalAuthorizationInput | ImageBoundedAuthorizationInput
) => request<{ authorizationId: string; status: string }>(root(projectId), { method: 'POST', body: input }),
/**
* 撤销未来领取并保留原件。
* @param projectId 正式项目
+91 -1
View File
@@ -123,6 +123,7 @@ export function imageChargeEligibility(
? {
allowed: true,
reusable: false,
expiresAt: grant.input.expiresAt,
message: `本次使用已批准的 OpenAI 图片授权,剩余 ${formatMicros(grant.remainingMicros)},可请求 ${grant.remainingRequests} 次。最终额度以提交时核验为准。`
}
: {
@@ -173,7 +174,11 @@ export function additionalImageEligibility(
planFingerprint: string
) {
const permit = list.additionalAuthorizations?.find(row => row.id === permitId)
const parent = list.requests.find(row => row.id === permit?.input.parentRequestId)
if (permit?.input.mode === 'bounded')
return boundedImageEligibility(list, permitId, projectId, targetId, model, sourceFingerprint, planFingerprint)
const parent = list.requests.find(
row => row.id === (permit?.input.mode === 'additional' ? permit.input.parentRequestId : undefined)
)
const grant = list.authorizations.find(row => row.id === parent?.input.authorizationId)
if (
!permit ||
@@ -221,6 +226,91 @@ export function additionalImageEligibility(
return {
allowed: true,
reusable: false,
expiresAt: grant.input.expiresAt,
message: `人工追加许可:已用 ${permit.usedRequests} 次,剩余 ${permit.remainingRequests} 次。原未知请求和预留保持;仅本次主动生成,不会自动用完剩余次数。`
}
}
/**
* 核对bounded总/逐镜次数、固定来源、原预算和本次仍被覆盖的未知费用,最终领取由服务端事务裁决。
* @param list 原项目费用投影
* @param permitId 用户主动选中的许可
* @param projectId 原项目
* @param shotId 本镜头
* @param model 当前实际型号
* @param source 当前正式来源
* @param plan 当前精确费用计划
* @returns 准入说明,不代表核清、质量或采用
*/
export function boundedImageEligibility(
list: ImageAuthorizationList,
permitId: string,
projectId: string,
shotId: string,
model: string,
source: string,
plan: string
) {
const permit = list.additionalAuthorizations?.find(row => row.id === permitId)
if (!permit || permit.input.mode !== 'bounded')
return { allowed: false, reusable: false, message: '请主动选择有效的有限许可。' }
const input = permit.input,
grant = list.authorizations.find(row => row.id === input.parentAuthorizationId),
target = permit.targets?.find(row => row.shotId === shotId)
if (
permit.status !== 'approved' ||
!Number.isSafeInteger(permit.remainingRequests) ||
permit.remainingRequests < 1 ||
!(Date.parse(input.expiresAt) > Date.now()) ||
input.provider !== 'openai-image' ||
input.model !== model ||
!target ||
target.sourceFingerprint !== source ||
target.planFingerprint !== plan ||
!Number.isSafeInteger(target.usedRequests) ||
target.usedRequests < 0 ||
target.usedRequests >= target.maxRequests ||
!grant ||
grant.input.mode !== 'standing' ||
grant.status !== 'approved' ||
grant.expired ||
!(Date.parse(grant.input.expiresAt) > Date.now()) ||
Date.parse(input.expiresAt) > Date.parse(grant.input.expiresAt) ||
!grant.input.models.includes(model) ||
!grant.input.scopes.includes('keyframe') ||
(grant.input.targetIds && !grant.input.targetIds.includes(shotId)) ||
grant.remainingRequests < 1 ||
grant.remainingMicros < grant.input.perRequestMicros
)
return {
allowed: false,
reusable: false,
message: '有限许可已失效、用尽,或镜头、型号、来源、计划与原预算不匹配,请刷新核对。'
}
const blockers = list.requests.filter(row => list.blockingRequestIds.includes(row.id))
if (
blockers.length !== list.blockingRequestIds.length ||
blockers.some(
row =>
row.status !== 'unknown' ||
row.input.projectId !== projectId ||
row.input.authorizationId !== grant.id ||
row.input.model !== model ||
!row.inputFingerprint ||
!input.acceptedUnknownRequests.some(
accepted => accepted.requestId === row.id && accepted.inputFingerprint === row.inputFingerprint
)
)
)
return {
allowed: false,
reusable: false,
message: '出现未被明确接受的未知费用或在途请求,已停止本许可后续领取。'
}
return {
allowed: true,
reusable: false,
expiresAt: input.expiresAt,
message: `有限许可:本镜已用 ${target.usedRequests}/${target.maxRequests} 次,总剩余 ${permit.remainingRequests} 次。使用原持续授权预算;旧未知费用仍保留,仅执行本次主动操作。`
}
}
+38 -1
View File
@@ -22,6 +22,7 @@ export interface ImageAuthorizationInput {
/** 原始图片请求与费用回执。 */
export interface ImageChargeRequest {
/** 服务端计算的原输入SHA,用于明确接受旧未知请求。 */ inputFingerprint?: string
/** 原请求标识。 */ id: string
/** 原执行状态。 */ status: string
/** 当前有效审计,不覆盖原状态、用量或账单。 */ billingAudit?: {
@@ -58,11 +59,17 @@ export interface ImageAuthorizationList {
/** 人工有限追加许可,不增加原预算。 */ additionalAuthorizations?: Array<{
/** 正式追加许可。 */ id: string
/** approved或revoked等真实状态。 */ status: string
/** 原不可变批准及服务端父输入摘要。 */ input: ImageAdditionalAuthorizationInput & {
/** 原不可变批准及服务端父输入摘要。 */ input: (
| ImageAdditionalAuthorizationInput
| ImageBoundedAuthorizationInput
) & {
/** 原完整输入摘要。 */ parentInputFingerprint: string
}
/** 已领取的模型请求次数。 */ usedRequests: number
/** 尚可人工领取次数。 */ remainingRequests: number
/** bounded逐镜正式计数,旧additional为null或缺省。 */ targets?: Array<
ImageBoundedTarget & { /** 已领取次数。 */ usedRequests: number }
> | null
}>
/** 服务端计算的授权投影。 */ authorizations: Array<{
/** 原批准记录。 */ id: string
@@ -118,3 +125,33 @@ export interface ImageAdditionalAuthorizationInput {
/** 实际批准人。 */ approvedBy: string
/** 批准说明。 */ approvalNote: string
}
/** 单镜白名单来自原免费费用计划,不接受浏览器自行拼接来源。 */
export interface ImageBoundedTarget {
/** 正式镜头。 */ shotId: string
/** 当前来源。 */ sourceFingerprint: string
/** 精确费用计划,区别于生图Preview。 */ planFingerprint: string
/** 本次正式参数。 */ generationOptions?: Record<string, unknown>
/** 可选实际宽度。 */ width?: number
/** 可选实际高度。 */ height?: number
/** 人工批准的本镜次数。 */ maxRequests: number
}
/** 明确接受旧未知费用的有限跨镜许可,不新增预算或清除旧账。 */
export interface ImageBoundedAuthorizationInput {
/** 跨镜有限模式。 */ mode: 'bounded'
/** 不可变批准幂等键。 */ idempotencyKey: string
/** 原standing批准。 */ parentAuthorizationId: string
/** 用户接受的原未知请求及正式输入版本。 */ acceptedUnknownRequests: Array<{
/** 原请求。 */ requestId: string
/** 原输入SHA。 */ inputFingerprint: string
}>
/** 固定供应方。 */ provider: 'openai-image'
/** 固定单一实际型号。 */ model: string
/** 逐镜精确白名单。 */ targets: ImageBoundedTarget[]
/** 总次数。 */ maxRequests: number
/** 不晚于原standing的有效期。 */ expiresAt: string
/** 明确接受旧未知费用。 */ acknowledgeUnknownPriorBilling: true
/** 接受单次浮动计费。 */ acknowledgeVariableBilling: true
/** 实际批准人。 */ approvedBy: string
/** 批准范围说明。 */ approvalNote: string
}
+3 -2
View File
@@ -174,9 +174,10 @@ export const productionApi = {
input: Pick<GenerateKeyframeInput, 'provider' | 'width' | 'height'> & {
/** 已保存草案中的原模型参数。 */ generationOptions?: Record<string, unknown>
},
signal?: AbortSignal
signal?: AbortSignal,
projectId?: string
) =>
request<KeyframeGenerationPreview>(`${shotPath(shotId)}/keyframe/preview`, {
request<KeyframeGenerationPreview>(keyframeScope(`${shotPath(shotId)}/keyframe/preview`, projectId), {
method: 'POST',
signal,
body: input
@@ -8,7 +8,11 @@ import { productionMessage } from '../production-messages'
import { useKeyframeVision } from '../keyframe-vision'
import { computed, ref, watch } from 'vue'
import SourceReviewDrawer from './SourceReviewDrawer.vue'
import { useEffectiveKeyframeQuality, effectiveQualityLabels } from '../effective-keyframe-quality'
import {
useEffectiveKeyframeQuality,
effectiveQualityLabels,
keyframeQualitySummary
} from '../effective-keyframe-quality'
import { NButton, NTag } from 'naive-ui'
import { AssetImage, AssetOpenLink, StatusBadge } from '../../../components/ui'
import { formatDate } from '../../../lib/format'
@@ -17,6 +21,7 @@ import type { ShotKeyframe } from '../types'
/** 首帧卡片统一主图标识、质量结论和晋升限制。 */
const props = defineProps<{
/** 摄影审核只读嵌入,保留图片与历史入口,不开放生成/编辑/采用。 */ readonly?: boolean
item: ShotKeyframe
/** 正式项目归属,用于查询候选审核。 */
projectId?: string
@@ -104,6 +109,7 @@ const qualityActionLabel = computed(() =>
const canSelect = computed(
() =>
props.item.status === 'completed' &&
!props.readonly &&
!!props.item.imageUrl &&
props.item.source !== 'provider_variant' &&
!props.item.isPrimary &&
@@ -159,6 +165,12 @@ const canSelect = computed(
>
</div>
<!-- 以下是候选的来源、画幅与后台审核状态 -->
<p
v-if="effectiveStatus === 'stale' && reviewQuery.data.value && !reviewQuery.error.value"
class="mt-2 text-xs text-muted"
>
{{ keyframeQualitySummary(reviewQuery.data.value.qualityDecision, effectiveStatus) }}
</p>
<p v-if="item.provider || item.model" class="mt-2 wrap-anywhere text-xs text-muted">
{{ [item.provider, item.model].filter(Boolean).join(' / ') }}
</p>
@@ -205,7 +217,7 @@ const canSelect = computed(
}}
</p>
<NButton
v-if="item.canRecoverSavedResult"
v-if="item.canRecoverSavedResult && !readonly"
class="mt-2"
size="small"
:disabled="blocked || recovering"
@@ -216,7 +228,11 @@ const canSelect = computed(
<p class="mt-2 text-[10px] text-muted">{{ formatDate(item.createdAt) }}</p>
<!-- 以下是集中排列的首帧辅助图标操作,提示与无障碍名称一致 -->
<div v-if="item.status === 'completed' && item.imageUrl" class="mt-4 flex flex-wrap items-center gap-2">
<WorkspaceActionTooltip placement="top" v-if="item.isPrimary && projectId" label="按当前来源人工复核">
<WorkspaceActionTooltip
placement="top"
v-if="item.isPrimary && projectId && !readonly"
label="按当前来源人工复核"
>
<NButton
square
class="workspace-action-button icon-button"
@@ -225,7 +241,11 @@ const canSelect = computed(
><ClipboardCheck :size="17"
/></NButton>
</WorkspaceActionTooltip>
<WorkspaceActionTooltip placement="top" v-if="!wrongCanvas && !stale" :label="qualityActionLabel">
<WorkspaceActionTooltip
placement="top"
v-if="!wrongCanvas && !stale && !readonly"
:label="qualityActionLabel"
>
<NButton
square
class="workspace-action-button icon-button"
@@ -236,7 +256,7 @@ const canSelect = computed(
</WorkspaceActionTooltip>
<WorkspaceActionTooltip
placement="top"
v-if="item.source !== 'provider_variant' && !wrongCanvas && !stale"
v-if="item.source !== 'provider_variant' && !wrongCanvas && !stale && !readonly"
label="编辑此首帧"
>
<NButton
@@ -4,6 +4,7 @@ import { imageAuthorizationApi } from '../../image-authorization/api'
import { formatMicros } from '../../image-authorization/model'
import { NSelect } from 'naive-ui'
import KeyframePreviewChecks from './KeyframePreviewChecks.vue'
import ModelCapabilities from './ModelCapabilities.vue'
import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '../../subject-images/generation-preview'
@@ -20,7 +21,7 @@ import type {
} from '../../generation-config/types'
import GenerationModelControls from '../../generation-config/components/GenerationModelControls.vue'
import { AppDialog, FieldLabel } from '../../../components/ui'
import { errorMessage } from '../../../lib/http'
import { ApiError, errorMessage } from '../../../lib/http'
import { productionApi } from '../api'
import { directionLabel } from '../../storyboard/model'
import type { ShotDirection, ShotVisualState } from '../../storyboard/types'
@@ -80,7 +81,9 @@ const imageProvider = ref('')
/** 当前用户主动选择的许可,重新打开或切换范围后不保留默认选择。 */
const additionalId = ref<string | null>(null)
/** 人工追加只属于OpenAI,不改变其它供应方的未知请求保护。 */
const canInspectAdditional = computed(() => !!props.additionalAllowed && imageProvider.value === 'openai-image')
const canInspectAdditional = computed(
() => (!!props.additionalAllowed || !props.disabled) && imageProvider.value === 'openai-image'
)
/** 仅需要核对原失败请求时读取已有许可,不自动创建。 */
const additionalKey = computed(() =>
open.value && canInspectAdditional.value ? JSON.stringify([props.projectId, props.shotId]) : ''
@@ -101,13 +104,19 @@ const additionalOptions = computed(() =>
permit =>
permit.status === 'approved' &&
permit.remainingRequests > 0 &&
additionalQuery.data.value?.requests.some(
row =>
row.id === permit.input.parentRequestId &&
row.input.projectId === props.projectId &&
row.input.targetId === props.shotId &&
row.input.scope === 'keyframe'
)
(permit.input.mode === 'bounded'
? Date.parse(permit.input.expiresAt) > Date.now() &&
permit.targets?.some(
target => target.shotId === props.shotId && target.usedRequests < target.maxRequests
)
: additionalQuery.data.value?.requests.some(
row =>
row.id ===
(permit.input.mode === 'additional' ? permit.input.parentRequestId : undefined) &&
row.input.projectId === props.projectId &&
row.input.targetId === props.shotId &&
row.input.scope === 'keyframe'
))
)
.map(permit => ({
label: `${permit.input.approvedBy} · 已用 ${permit.usedRequests} / 剩余 ${permit.remainingRequests} 次`,
@@ -120,7 +129,31 @@ const additionalPermit = computed(() =>
)
/** 原未知费用与预留保持显示。 */
const additionalParent = computed(() =>
additionalQuery.data.value?.requests.find(row => row.id === additionalPermit.value?.input.parentRequestId)
additionalQuery.data.value?.requests.find(
row =>
row.id ===
(additionalPermit.value?.input.mode === 'additional'
? additionalPermit.value.input.parentRequestId
: undefined)
)
)
/** 有限跨镜许可的本镜计数及原预算保持独立。 */
const boundedTarget = computed(() =>
additionalPermit.value?.input.mode === 'bounded'
? additionalPermit.value.targets?.find(row => row.shotId === props.shotId)
: null
)
/** 原standing预算,不把许可次数显示成另一笔预算。 */
const boundedBudget = computed(() =>
additionalPermit.value?.input.mode === 'bounded'
? additionalQuery.data.value?.authorizations.find(
row =>
row.id ===
(additionalPermit.value?.input.mode === 'bounded'
? additionalPermit.value.input.parentAuthorizationId
: undefined)
)
: null
)
watch(
[() => props.projectId, () => props.shotId, open],
@@ -146,6 +179,7 @@ const {
requiresCostConfirmation,
chargeNotice,
reusableResult,
invalidate: invalidatePreview,
loading,
submitting,
error,
@@ -188,7 +222,18 @@ const {
return result
},
reuseResult: props.reuseExisting ? result => props.reuseExisting!(result.previewFingerprint) : undefined,
generate: input => props.submitGeneration({ ...input, setPrimary: false })
generate: async input => {
const outcome = await props.submitGeneration({ ...input, setPrimary: false })
if (!outcome.accepted && outcome.cause instanceof ApiError && outcome.cause.status === 409) {
await additionalQuery.refresh()
if (
outcome.cause.code === 'SCENE_CONTINUITY_REVIEW_STALE' ||
outcome.cause.message.startsWith('SCENE_CONTINUITY_REVIEW_STALE')
)
await Promise.allSettled([productionApi.keyframeSpec(props.shotId, undefined, props.projectId)])
}
return outcome
}
})
/** 正式预览返回连续性阻断时,键盘和底栏提交均不可继续。 */
@@ -297,8 +342,18 @@ watch(
{{ formatMicros(additionalParent.input.reservedMicros) }} · 原账单
{{ formatMicros(additionalParent.output?.actualBilledMicros) }}
</p>
<p v-if="boundedTarget" class="text-sm">
本镜已用 {{ boundedTarget.usedRequests }}/{{ boundedTarget.maxRequests }} 次 · 原预算剩余
{{ formatMicros(boundedBudget?.remainingMicros) }}。旧未知费用未被核清。
</p>
</section>
<!-- 以下是正式摄影设计与画面状态 -->
<ModelCapabilities
v-if="open && imageProvider"
:shot-id="shotId"
:provider="imageProvider"
@checked="!$event && invalidatePreview()"
/>
<NCollapse v-if="direction || visualState" class="mt-5">
<NCollapseItem v-if="direction" name="direction" title="当前镜头设计">
<p class="text-xs leading-6">{{ directionSummary }}</p>
@@ -3,6 +3,7 @@ import { computed } from 'vue'
import { NCollapse, NCollapseItem, NTag } from 'naive-ui'
import { userFacingText } from '../../../lib/user-facing-text'
import type { KeyframeGenerationPreview } from '../types'
import SceneTransitionEvidence from '../../storyboard/components/SceneTransitionEvidence.vue'
/** 只展示服务端返回的画幅、尺寸和一致性门禁。 */
const props = defineProps<{
@@ -33,6 +34,7 @@ const size = computed(() => {
>连续性待确认 · 暂不能生成</NTag
>
</div>
<SceneTransitionEvidence :continuity="preview.continuity" />
<!-- 以下是具体待确认主体与规格检查问题 -->
<ul v-if="preview.continuity?.reviewIssues.length" class="text-muted">
<li v-for="issue in preview.continuity.reviewIssues" :key="issue.subjectRef + issue.code">
@@ -5,10 +5,18 @@ import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { computed, ref, watch } from 'vue'
import { NButton, NInput } from 'naive-ui'
import { NButton, NInput, NCollapse, NCollapseItem } from 'naive-ui'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { useQuery } from '../../../composables/useQuery'
import { imageAuthorizationApi } from '../../image-authorization/api'
import { formatMicros } from '../../image-authorization/model'
import { errorMessage } from '../../../lib/http'
import ReadonlyInspection from '../../../components/ui/ReadonlyInspection.vue'
import { useEffectiveKeyframeQuality, effectiveQualityLabels } from '../effective-keyframe-quality'
import {
useEffectiveKeyframeQuality,
effectiveQualityLabels,
keyframeQualitySummary
} from '../effective-keyframe-quality'
import { formatDate } from '../../../lib/format'
import { physicalRetryTarget, submitKeyframeVision, useKeyframeVision } from '../keyframe-vision'
import KeyframeExecutionHistory from './KeyframeExecutionHistory.vue'
@@ -43,6 +51,35 @@ const key = computed(() =>
? JSON.stringify([props.projectId, props.shotId, props.keyframeId])
: ''
)
/** 原图片的来源及费用仅在用户展开时读取,不把本镜其它图片或未执行计划混入。 */
const generationExpanded = ref<string[]>([])
/** 查询同时冻结项目、Shot及图片身份,切换旧图片后不回填其它候选费用。 */
const generationKey = computed(() =>
props.projectId && key.value && generationExpanded.value.includes('generation-records') ? key.value : ''
)
/** 复用原图片账本GET与历史详情,不提供核清、重试或新授权入口。 */
const generationRecords = useQuery(generationKey, async (value, signal) => {
if (!value) return []
const [projectId, shotId, candidateId] = JSON.parse(value) as [string, string, string]
const list = await imageAuthorizationApi.list(projectId, signal)
return list.requests.filter(
row =>
row.input.projectId === projectId &&
row.input.scope === 'keyframe' &&
row.input.targetId === shotId &&
row.input.candidateId === candidateId
)
})
watch(key, () => {
generationExpanded.value = []
})
/** 原执行标签只说明模型请求状态,不用于推导图片质量或账单。 */
const generationStatusLabels: Record<string, string> = {
unknown: '结果或费用未知',
completed: '执行完成',
running: '进行中',
failed: '执行失败'
}
/** 独立打开历史后恢复后台观察。 */
const visionKey = computed(() =>
key.value
@@ -296,8 +333,35 @@ const records = computed(() =>
}
"
>
<!-- 以下是当前选中旧图片的原来源、请求及费用;不修改任何历史或核清状态。 -->
<NCollapse v-if="projectId" v-model:expanded-names="generationExpanded" class="mb-4">
<NCollapseItem name="generation-records" title="原图片生成来源与费用">
<p v-if="generationRecords.loading.value" role="status">正在读取原图片请求…</p>
<p v-else-if="generationRecords.error.value" role="alert">{{ generationRecords.error.value }}</p>
<p v-else-if="!generationRecords.data.value?.length" class="text-xs text-muted">
未找到此图片的原OpenAI费用记录;不据此推断费用为0。
</p>
<article
v-for="row in generationRecords.data.value ?? []"
:key="row.id"
class="my-3 space-y-2 text-xs wrap-anywhere"
>
<p>原请求 {{ row.id }} · {{ generationStatusLabels[row.status] ?? '待确认' }}</p>
<p>
原预留 {{ formatMicros(row.input.reservedMicros) }} · 公开用量价
{{ formatMicros(row.output?.usageCostMicros) }} · 实际账单
{{ formatMicros(row.output?.actualBilledMicros) }}
</p>
<p v-if="row.billingAudit?.released">费用已核清;原执行、机器质量及主首帧状态保持独立。</p>
<RawDataDetails :value="row" title="原模型、来源、精确计划与回执" />
</article>
</NCollapseItem>
</NCollapse>
<section v-if="review" class="panel p-3 text-xs leading-6">
<p class="font-semibold">当前质量复核</p>
<p v-if="reviewQuery.status.value === 'stale'">
{{ keyframeQualitySummary(review.qualityDecision, 'stale') }}
</p>
<p>历史机器结论:{{ terminatedReview ? '已终止,无有效结论' : decisionLabel(review.qualityDecision) }}</p>
<p>当前状态:{{ effectiveQualityLabels[reviewQuery.status.value] }}</p>
<p v-if="review.manualReview">
@@ -17,10 +17,17 @@ const props = defineProps<{
/** 本次选择的图片模型,未提供时读取后端默认。 */
provider?: string
}>()
/** 当前检查期间及失败时撤销关联入口的旧预检,不授予其它门禁。 */
const emit = defineEmits<{ checked: [valid: boolean] }>()
/** 正式公开的Provider限制,能力编译失败时仍保留。 */
const providers = ref<ImageProviderCapability[] | null>(null)
/** 仅当前镜头及模型本次检查的实际结果。 */
const capability = ref<ShotProviderCapability | null>(null)
/** 当前能力阻断的业务原因。 */
const error = ref('')
/** 本次免费检查的就地加载。 */
const loading = ref(false)
/** 切换范围或卸载后丢弃迟到结果。 */
let revision = 0
onScopeDispose(() => {
revision++
@@ -30,6 +37,7 @@ watch([() => props.shotId, () => props.provider], () => {
revision++
providers.value = null
capability.value = null
emit('checked', false)
error.value = ''
loading.value = false
})
@@ -41,17 +49,23 @@ async function inspect() {
const provider = props.provider
loading.value = true
error.value = ''
capability.value = null
emit('checked', false)
try {
const list = await qualityApi.providers()
if (version !== revision) return
const result = shotId ? await qualityApi.capability(shotId, undefined, provider) : null
if (version !== revision) return
if (!Array.isArray(list) || list.some(item => !item.capabilities?.references))
throw new Error('模型能力接口返回不完整。')
providers.value = list
const result = shotId ? await qualityApi.capability(shotId, undefined, provider) : null
if (version !== revision) return
capability.value = result
emit('checked', result?.valid === true)
} catch (cause) {
if (version === revision) error.value = errorMessage(cause)
if (version === revision) {
capability.value = null
error.value = errorMessage(cause)
}
} finally {
if (version === revision) loading.value = false
}
@@ -61,12 +75,13 @@ async function inspect() {
<section class="mt-4 text-xs">
<NButton size="small" :loading="loading" :disabled="loading" @click="inspect">查看模型限制</NButton>
<FeedbackMessage v-if="error" :message="error" />
<p v-if="error" role="alert" class="mt-3 text-muted">{{ error }}</p>
<template v-if="providers">
<p v-if="!providers.some(item => item.active)" class="mt-2 text-danger">
没有可用的图片模型,请先到项目配置中选择模型。
</p>
<p v-for="item in providers" :key="item.provider" class="mt-2">
{{ item.provider }} · {{ item.active ? '当前启用' : '已注册' }} ·
{{ item.provider }} · {{ item.active ? '默认推荐' : '已注册' }} ·
{{
!item.capabilities.references.supported
? '不支持参考图'
@@ -86,5 +101,6 @@ async function inspect() {
本次计划输入 {{ capability.plannedReferenceCount }} 张 · 转为文字约束
{{ capability.omittedReferenceCount ?? 0 }} 张
</p>
<p v-if="capability?.valid" class="mt-2 text-muted">仅证明参考输入可编译,费用、连续性与质量仍需分别核对。</p>
</section>
</template>
@@ -359,6 +359,8 @@ function openShotKeyframeQuality() {
}
/** 当前查看历史的候选 ID;历史记录在独立弹窗内按候选隔离。 */
const historyKeyframeId = ref('')
/** 候选弹窗离场后再打开原图历史,避免两个焦点约束同时存在。 */
const pendingHistoryKeyframeId = ref('')
/** 历史候选画幅或来源失效时保留浏览、禁止人工采用。 */
const historyBlocked = computed(() => {
const item = keyframes.value.find(candidate => candidate.id === historyKeyframeId.value)
@@ -381,9 +383,20 @@ const visionHistoryRef = ref<InstanceType<typeof KeyframeValidationHistory> | nu
* @param keyframeId 需要查看历史的首帧 ID
*/
function openKeyframeHistory(keyframeId: string) {
if (candidatesOpen.value) {
pendingHistoryKeyframeId.value = keyframeId
candidatesOpen.value = false
return
}
historyKeyframeId.value = keyframeId
historyOpen.value = true
}
/** 候选管理关闭完成才交接至同镜头原图历史;切镜时待打开目标会清空。 */
function openPendingKeyframeHistory() {
const id = pendingHistoryKeyframeId.value
pendingHistoryKeyframeId.value = ''
if (id && !disposed) openKeyframeHistory(id)
}
const confirmingKeyframe = ref('')
const confirmingVideo = ref('')
const inspecting = ref(false)
@@ -439,6 +452,13 @@ const primaryQualityBlocked = computed(() => {
return !status || status === 'failed' || status === 'needs_review' || status === 'unknown'
})
const reviewRevision = ref(0)
/** 静态摄影/开拍状态改变时只刷新质量投影,不隐藏原Primary或删除历史图。 */
watch(
() => JSON.stringify([props.projectId, props.shot.shotId, props.shot.direction, props.shot.visualState]),
(_value, previous) => {
if (previous) reviewRevision.value++
}
)
/** 审核后强制更新每张卡片的数据库质量状态。 */
async function refreshAfterReview() {
reviewRevision.value += 1
@@ -486,6 +506,7 @@ watch(key, () => {
confirmingKeyframe.value = ''
historyOpen.value = false
historyKeyframeId.value = ''
pendingHistoryKeyframeId.value = ''
confirmingVideo.value = ''
videoCandidatesOpen.value = false
videoHistoryOpen.value = false
@@ -1160,6 +1181,7 @@ defineExpose({ inspectSpecs, inspecting })
title="首帧候选管理"
description="通过检查或人工复核后可设为主首帧。"
:width="keyframeCandidatesWidth"
@closed="openPendingKeyframeHistory"
>
<!-- 候选图片和对应的人工复核入口按相同候选 ID 分组。 -->
<div v-if="keyframeCandidates.length" class="asset-candidate-grid mt-4">
@@ -14,6 +14,20 @@ export const effectiveQualityLabels: Record<EffectiveKeyframeQualityStatus, stri
manual_accepted: '人工已接受',
unknown: '质量待确认'
}
/**
* 历史机器审核与当前有效来源分开展示,不把改源当新图Passed。
* @param machine 原机器结论
* @param current 当前服务端有效状态
* @returns 普通用户可读的组合摘要
*/
export function keyframeQualitySummary(
machine: EffectiveKeyframeQualityStatus,
current: EffectiveKeyframeQualityStatus
) {
if (current === 'stale' && machine === 'failed') return '历史审核未通过,当前来源已变化'
if (current === 'stale' && ['passed', 'manual_accepted'].includes(machine)) return '历史审核通过,当前来源已变化'
return effectiveQualityLabels[current]
}
/**
* 按项目、镜头、候选读取有效质量,执行及来源证据变化后重新回读,绝不采用工作流的历史 Passed。
@@ -1,9 +1,11 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { computed } from 'vue'
import { NButton, NCheckbox, NInput, NInputNumber, NSelect, NTag } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NInput, NInputNumber, NSelect, NTag } from 'naive-ui'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { AppDialog, AssetImage } from '../../../components/ui'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import { useMotionRevision } from '../useMotionRevision'
import { formatDate } from '../../../lib/format'
@@ -31,7 +33,6 @@ const {
preview,
error,
notice,
saved,
pending,
blocked,
formBlocked,
@@ -42,16 +43,48 @@ const {
/** 版本选项包含来源、创建时间及真实生效标记。 */
const options = computed(() =>
(state.context.data.value?.history.revisions ?? []).map(item => ({
label: `${item.isActive ? '生效 · ' : ''}${item.source === 'manual' ? '人工修订' : 'AI 原始'} · ${formatDate(item.createdAt)} · ${item.revisionId}`,
label: `${item.isActive ? '已采用 · ' : ''}${item.source === 'manual' ? '人工修订' : item.source === 'failed_candidate' ? '失败候选根(原质量失败)' : 'AI 原始'} · ${formatDate(item.createdAt)}`,
value: item.revisionId
}))
)
/** 结构错误与非阻断预警分别展示,不将预警当作通过资格。 */
const previewMessages = computed(() => [
...(preview.value?.formalIssues ?? []),
...(preview.value?.schemaIssues ?? []).map(item => `${item.path}:${item.message}`),
...(preview.value?.timelineIssues ?? []).map(item => item.message),
...(preview.value?.actionDensityIssues ?? []).map(item => item.message)
])
/** 完整交互原文按需编辑,未填写新事实时保持空数组。 */
const interactionsText = ref('[]')
/** 复制新版本时同步原交互;普通阶段编辑不改写原交互字段。 */
watch(
draft,
() => {
interactionsText.value = JSON.stringify(draft.value.interactions ?? [], null, 2)
state.interactionError.value = ''
},
{ immediate: true }
)
/**
* 保留未完成的JSON输入,只有完整对象数组才进入正式草稿。
* @param value 用户编辑的完整交互JSON
*/
function updateInteractions(value: string) {
interactionsText.value = value
try {
const parsed: unknown = JSON.parse(value)
if (
!Array.isArray(parsed) ||
parsed.length > 12 ||
parsed.some(row => !row || typeof row !== 'object' || Array.isArray(row))
)
throw new Error()
draft.value.interactions = parsed
state.interactionError.value = ''
} catch {
state.interactionError.value = '请提供完整交互对象数组,最多12项;没有交互时填写[]。'
}
}
/** 任务返回问题可能是视觉问题或门禁说明,按实际描述展示。 */
const taskIssues = computed(() =>
Array.isArray(record.value?.result?.issues)
@@ -118,6 +151,8 @@ function updateRefs(index: number, value: string) {
wide
>
<div class="motion-revision-layout">
<FeedbackMessage v-if="error" :message="error" />
<FeedbackMessage v-if="notice" :message="notice" type="info" />
<ContextNotice v-if="state.context.error.value || error" type="error" :show-icon="false">{{
state.context.error.value || error
}}</ContextNotice>
@@ -134,6 +169,11 @@ function updateRefs(index: number, value: string) {
>刷新版本与主首帧</NButton
>
</div>
<RawDataDetails
v-if="state.context.data.value"
:value="state.context.data.value.history"
title="完整修订历史与采用指针"
/>
<label v-if="options.length" class="motion-revision-field">
<span>编辑来源</span>
<NSelect
@@ -144,7 +184,13 @@ function updateRefs(index: number, value: string) {
@update:value="state.select($event)"
/>
</label>
<p v-else class="motion-revision-description">尚未初始化版本历史,首次保存会封存原始 AI 规划。</p>
<p v-else class="motion-revision-description">
{{
state.requiresCandidate.value
? '尚无正式原计划,可只读核对原失败候选后承接人工修订。'
: '尚未初始化版本历史,首次保存会封存原始 AI 规划。'
}}
</p>
<div class="motion-revision-source">
<div v-if="state.context.data.value?.primary?.imageUrl" class="motion-revision-thumbnail">
<AssetImage
@@ -161,11 +207,81 @@ function updateRefs(index: number, value: string) {
</div>
<div>
<dt>当前生效版本</dt>
<dd>{{ state.context.data.value?.history.activeRevisionId ?? 'AI 原始规划' }}</dd>
<dd>
{{
state.context.data.value?.history.activeRevisionId ??
(state.context.data.value?.preview.motionPlanAvailable
? 'AI 原始规划'
: '尚无正式采用版本')
}}
</dd>
</div>
</dl>
</div>
</section>
<!-- 以下是原失败Task/Workflow/质量及公开回执,读取和载入均不保存或启动模型。 -->
<section
v-if="state.requiresCandidate.value || state.failedCandidate.value || state.candidateOrigin.value"
class="workspace-section-stack"
aria-label="原失败动作候选"
>
<h3 class="text-sm font-semibold">原失败动作候选</h3>
<template v-if="state.requiresCandidate.value">
<label class="workspace-form-field"
><span>原Task(可选,留空查当前任务)</span
><NInput
v-model:value="state.failedTaskId.value"
:disabled="blocked || state.candidateLoading.value"
aria-label="原失败动作Task"
/></label>
<NButton
class="self-start"
:loading="state.candidateLoading.value"
:disabled="blocked"
@click="state.readCandidate"
>读取原失败候选</NButton
>
</template>
<p v-if="state.failedCandidate.value" class="text-sm">
原Task {{ state.failedCandidate.value.taskId }} · 原Workflow
{{ state.failedCandidate.value.executionId }} · 原质量
{{ state.failedCandidate.value.status === 'failed' ? '未通过' : '不可作为当前失败候选' }}
</p>
<RawDataDetails
v-if="state.failedCandidate.value"
:value="state.failedCandidate.value"
title="原模型候选、质量与公开回执"
/>
<RawDataDetails
v-if="state.candidateOrigin.value"
:value="state.candidateOrigin.value"
title="失败根版本来源证明"
/>
<NButton
v-if="state.candidateOrigin.value && !state.failedCandidate.value"
class="self-start"
:loading="state.candidateLoading.value"
:disabled="blocked"
@click="state.readOriginCandidate"
>查看原失败任务回执</NButton
>
<NButton
v-if="state.requiresCandidate.value && state.candidateReady.value"
class="self-start"
:disabled="blocked"
@click="state.useCandidate"
>载入人工草稿</NButton
>
<NCheckbox
v-if="state.requiresCandidate.value && state.candidateReady.value"
v-model:checked="state.failedAcknowledged.value"
:disabled="blocked"
>我已核对完整人工草稿与原失败来源;只保存人工子版本,原候选仍未通过,不启动起点审核或采用。</NCheckbox
>
</section>
<p v-if="state.revision.value?.source === 'failed_candidate'" class="text-sm">
这是原质量失败的根版本,不能直接起点审核或正式采用。修改后可保存人工子版本。
</p>
<!-- 以下是完整阶段表单模块,长文本独占一行,短字段共用两列 -->
<section
v-for="(beat, index) in draft.beats"
@@ -250,12 +366,43 @@ function updateRefs(index: number, value: string) {
:aria-label="`阶段 ${index + 1} 收尾状态`"
/>
</label>
<label
v-if="beat.performedActionIds"
class="motion-revision-field motion-revision-field-wide workspace-form-field"
><span>实际执行动作ID(原始绑定)</span
><NInput
:value="beat.performedActionIds.join(', ')"
:disabled="formBlocked"
@update:value="
beat.performedActionIds = $event
.split(/[,,\n]/)
.map(value => value.trim())
.filter(Boolean)
"
:aria-label="`阶段 ${index + 1} 执行动作ID`"
/></label>
</div>
</section>
<div class="motion-revision-section-action">
<NButton :disabled="blocked || draft.beats.length >= 5" @click="addBeat">添加动作阶段</NButton>
<span class="motion-revision-description">{{ draft.beats.length }} / 5 个阶段</span>
</div>
<!-- 以下是完整物理交互的高级原文编辑,不新增第二套时间轴。 -->
<NCollapse
><NCollapseItem name="interactions" title="物理交互(完整原文)"
><div class="workspace-section-stack">
<NInput
:value="interactionsText"
type="textarea"
:autosize="{ minRows: 4, maxRows: 15 }"
:disabled="formBlocked"
aria-label="完整物理交互JSON"
@update:value="updateInteractions"
/>
<p v-if="state.interactionError.value" role="alert">{{ state.interactionError.value }}</p>
</div></NCollapseItem
></NCollapse
>
<!-- 以下是整体约束与修改原因模块,标签和删除按钮分别对齐 -->
<section class="workspace-panel motion-revision-section" aria-label="整体动作约束">
<div class="motion-revision-section-heading">
@@ -301,19 +448,41 @@ function updateRefs(index: number, value: string) {
<!-- 以下是免费预检查结果模块,与收费校验证据分开 -->
<section v-if="preview" class="motion-revision-feedback" aria-label="免费预检查结果">
<h3>预检查结果</h3>
<p>{{ preview.valid ? '结构检查通过,仍须视觉校验;尚不可激活。' : '结构检查未通过,请修改草稿。' }}</p>
<p>
{{
preview.valid
? '正式文字预检通过,起点像素仍待独立审核;尚未采用。'
: '预检未通过,请修改草稿。'
}}
</p>
<p v-for="(message, index) in previewMessages" :key="index">{{ userFacingText(message) }}</p>
<p v-if="preview.startStatePlan">
本精确起点计划最多 {{ preview.startStatePlan.proposedMaximumProviderRequests }} 次 · 拟新增
{{ preview.startStatePlan.additionalProviderRequests }} 次 · 费用
{{ preview.startStatePlan.feeEstimate.amount ?? '未知' }}
{{ preview.startStatePlan.feeEstimate.currency }}
</p>
<RawDataDetails
v-if="preview.source"
:value="{
source: preview.source,
sourceFingerprint: preview.sourceFingerprint,
previewFingerprint: preview.previewFingerprint,
startStatePlan: preview.startStatePlan
}"
title="当前来源、版本与精确起点计划"
/>
</section>
<!-- 以下是收费视觉校验与激活模块,费用说明和操作成组排列 -->
<section class="workspace-panel motion-revision-section" aria-label="动作起点视觉校验">
<h3>起点视觉校验</h3>
<p class="motion-revision-description">检查修订与当前主首帧是否一致,会消耗模型额度。</p>
<NCheckbox v-model:checked="acknowledged" :disabled="blocked || !saved"
<NCheckbox v-model:checked="acknowledged" :disabled="!state.canValidate.value"
>我已确认本次起点视觉校验的模型费用和修订范围。</NCheckbox
>
<div class="motion-revision-validation-actions">
<NButton
:disabled="blocked || !saved || !acknowledged || !state.context.data.value?.primary"
:disabled="!state.canValidate.value || !acknowledged || !state.context.data.value?.primary"
@click="state.validate"
>启动起点视觉校验</NButton
>
@@ -345,7 +514,7 @@ function updateRefs(index: number, value: string) {
<div class="motion-revision-footer">
<div class="motion-revision-save-actions">
<NButton :disabled="blocked" :loading="pending" @click="state.precheck">免费预检查</NButton>
<NButton :disabled="blocked || preview?.valid !== true" @click="state.save">保存为新修订</NButton>
<NButton :disabled="!state.canSave.value" @click="state.save">保存为新修订</NButton>
</div>
<NButton @click="open = false">关闭</NButton>
</div>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import { computed } from 'vue'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import type { ShotContinuityEvidence } from '../generation-spec.types'
/** Storyboard及首帧共用正式人工规划依据,不复制或改写尾态与质量。 */
const props = defineProps<{ /** 当前正式编译的连续性证据。 */ continuity?: ShotContinuityEvidence | null }>()
/** 仅完整、匹配紧邻镜头的正式规划记录可显示确认;其余状态仍由服务端门禁决定。 */
const transition = computed(() => {
const value = props.continuity?.sceneTransition
return value?.basis === 'confirmed_plan' &&
value.verifiedVideoEndState === false &&
value.previousShotId === props.continuity?.previousShotId &&
value.subjectRef &&
value.subjectFormId &&
/^[a-f0-9]{64}$/.test(value.fingerprint) &&
/^[a-f0-9]{64}$/.test(value.requestFingerprint)
? value
: null
})
</script>
<template>
<!-- 以下是人工规划确认与尚未验证的视频末态,使用中性展示。 -->
<section v-if="transition" class="space-y-2 text-xs" aria-label="人工规划衔接">
<p>人工规划衔接已确认,视频末态尚未验证</p>
<RawDataDetails :value="transition" title="衔接规划来源详情" />
</section>
</template>
@@ -1,6 +1,11 @@
<script setup lang="ts">
import VisualStateContinuity from './VisualStateContinuity.vue'
import JointDraftReviewPanel from './JointDraftReviewPanel.vue'
import ShotDesign from './ShotDesign.vue'
import SceneTransitionEvidence from './SceneTransitionEvidence.vue'
import KeyframeCard from '../../production/components/KeyframeCard.vue'
import KeyframeValidationHistory from '../../production/components/KeyframeValidationHistory.vue'
import { jointDraftDifferences } from '../joint-review'
import DirectionCameraFields from './DirectionCameraFields.vue'
import DirectionStageReview from './DirectionStageReview.vue'
import { computed, onScopeDispose, ref, watch } from 'vue'
@@ -13,6 +18,8 @@ import { ApiError, errorMessage } from '../../../lib/http'
import { formatDate } from '../../../lib/format'
import { userFacingText } from '../../../lib/user-facing-text'
import { productionApi } from '../../production/api'
import { imageAuthorizationApi } from '../../image-authorization/api'
import type { KeyframeGenerationPreview } from '../../production/types'
import KeyframePreviewChecks from '../../production/components/KeyframePreviewChecks.vue'
import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import { preparationApi } from '../../storyboard-preparation/api'
@@ -118,6 +125,34 @@ const savingDraft = ref(false)
const providerEdited = ref(false)
/** 编辑保存的原稿时,保留其模型参数和显式尺寸。 */
const editingSavedInput = ref<DraftProviderInput | null>()
/** 只在首次读取回填,来源刷新不得覆盖人工构图。 */
const cameraInitialized = ref(false)
/** 同一摄影抽屉内按需展开正式内容、历史与图片。 */
const cameraExpanded = ref<string[]>([])
/** 图片历史只读定位,不启动审核或晋升。 */
const cameraHistoryAssetId = ref('')
/** 正式Source变化后重新读取每张原图的当前质量,原机器记录不改写。 */
const cameraReviewRevision = ref(0)
/** 摄影正式采用后的新来源预览,不能沿用旧草案指纹生图。 */
const cameraFormalPreview = ref<KeyframeGenerationPreview | null>(null)
/** 费用计划仅显示当前身份/来源,不等同授权或核清。 */
const cameraFeePlan = ref<Record<string, unknown> | null>(null)
/** 免费后续核对失败不改写已经成功的摄影采用事实。 */
const cameraAdoptionNotice = ref('')
/** 用户主动展开时才查询已有候选,不把未执行计划构造成图片。 */
const cameraAssetKey = computed(() =>
key.value && props.shot.direction && props.shot.visualState && cameraExpanded.value.includes('camera-assets')
? key.value
: ''
)
/** 候选列表只来自正式资产GET,保留失败/未知/Primary全部历史。 */
const cameraAssets = useQuery(cameraAssetKey, async (value, signal) => {
if (!value) return []
const [, shotId] = JSON.parse(value) as [string, string]
const rows = await productionApi.listKeyframes(shotId, signal)
if (!Array.isArray(rows) || rows.some(row => row.shotId !== shotId)) throw new Error('图片候选不属于当前镜头。')
return rows
})
/** 当前可查看的原稿,保留过期草案的全部内容。 */
const savedDraftText = computed(() =>
savedDraft.data.value ? JSON.stringify(savedDraft.data.value.draft, null, 2) : ''
@@ -146,6 +181,16 @@ const formalQuery = useQuery(key, async (value, signal) => {
throw new Error('无法核对当前镜头的正式摄影和即时状态。')
return { keyframe, generation, shot: { ...props.shot, direction, visualState } }
})
watch(
[() => formalQuery.data.value?.keyframe.formalSourceFingerprint, formalQuery.error],
([value, error], [previous]) => {
if (error || (value && previous && value !== previous)) {
cameraFormalPreview.value = null
cameraFeePlan.value = null
cameraReviewRevision.value++
}
}
)
/** 只允许目录中当前启用的模型。 */
const configuration = useQuery(key, async (id, signal) => {
if (!id) return null
@@ -157,6 +202,34 @@ const configuration = useQuery(key, async (id, signal) => {
})
/** 正式场景衔接证据;不会用前镜首帧冒充尾态。 */
const continuity = computed(() => formalQuery.data.value?.generation.continuity)
/** 原摄影修订事件仅只读展示,不能回写历史。 */
const cameraHistory = computed<unknown[]>(() => {
try {
const raw = JSON.parse(formalQuery.data.value?.shot.direction?.rawJson ?? 'null')
return Array.isArray(raw?.cameraRevisionHistory) ? raw.cameraRevisionHistory : []
} catch {
return []
}
})
/** 普通摄影完整差异,保存草案中的越界项也不能隐藏。 */
const cameraDifferences = computed(() => {
const value = formalQuery.data.value,
fingerprint = preflight.data.value?.current.evidence.shotFingerprint
if (!value || !fingerprint || mode.value !== 'camera') return []
const before = draftFromFormal(value.shot, value.keyframe, fingerprint)
const after =
useSaved.value && savedDraft.data.value
? savedDraft.data.value.draft
: {
...before,
direction: {
...before.direction,
composition: composition.value,
cameraPosition: cameraPosition.value
}
}
return jointDraftDifferences(before, after)
})
/** 使用现有镜头目录将前镜编号转换为用户可见坐标。 */
const previousShot = computed(() => props.shots.find(item => item.shotId === continuity.value?.previousShotId))
/** 只列出服务提供同形态、可填写的正式前镜场景状态。 */
@@ -224,6 +297,14 @@ watch(
{ flush: 'sync' }
)
watch(key, () => {
cameraInitialized.value = false
cameraExpanded.value = []
cameraHistoryAssetId.value = ''
cameraFormalPreview.value = null
cameraFeePlan.value = null
cameraAdoptionNotice.value = ''
composition.value = ''
cameraPosition.value = ''
useSaved.value = false
draftConflict.value = false
providerEdited.value = false
@@ -321,8 +402,10 @@ watch(
{ flush: 'sync' }
)
watch(formalQuery.data, value => {
composition.value = value?.shot.direction?.composition ?? ''
cameraPosition.value = value?.shot.direction?.cameraPosition ?? ''
if (!value || cameraInitialized.value) return
composition.value = value.shot.direction?.composition ?? ''
cameraPosition.value = value.shot.direction?.cameraPosition ?? ''
cameraInitialized.value = true
})
watch(configuration.data, value => {
const model = value?.catalog.images.find(item => item.enabled && item.provider === value.profile.imageProvider)
@@ -335,6 +418,8 @@ const canPreview = computed(
() =>
!!preflight.data.value?.current.evidence.shotFingerprint &&
!preflight.error.value &&
!preflight.loading.value &&
!formalQuery.loading.value &&
(useSaved.value
? savedDraft.data.value?.status === 'current' && !savedDraft.error.value
: (!!provider.value || (!providerEdited.value && editingSavedInput.value !== undefined)) &&
@@ -511,7 +596,13 @@ async function loadPreview() {
}
}
} catch (cause) {
if (!controller.signal.aborted) message?.error(errorMessage(cause))
if (!controller.signal.aborted) {
message?.error(errorMessage(cause))
if (cause instanceof ApiError && cause.status === 409) {
void formalQuery.refresh()
void preflight.refresh()
}
}
} finally {
if (!controller.signal.aborted) previewing.value = false
}
@@ -541,8 +632,56 @@ async function adopt() {
if (projectId !== props.projectId || selection.shotId !== props.shot.shotId) return
if (ok) {
message?.success('已采用当前镜头的审核结果')
open.value = false
emit('changed')
if (mode.value === 'camera' && formal.value) {
cameraAdoptionNotice.value = '摄影修订已正式采用;旧图及原审核保留,新来源仍需独立图片授权和质量审核。'
clearPreview()
await Promise.all([formalQuery.refresh(), savedDraft.refresh(), preflight.refresh()])
try {
const fresh = await productionApi.previewKeyframe(
selection.shotId,
{
provider: selection.provider,
generationOptions: selection.generationOptions,
width: selection.width,
height: selection.height
},
undefined,
projectId
)
if (projectId !== props.projectId || selection.shotId !== props.shot.shotId || !open.value) return
if (fresh.shotId !== selection.shotId) throw new Error('正式预览与当前镜头不匹配。')
cameraFormalPreview.value = fresh
if (fresh.provider === 'openai-image') {
const plan = await imageAuthorizationApi.preview(projectId, {
scope: 'keyframe',
targetId: selection.shotId,
providerName: fresh.provider,
generationOptions: selection.generationOptions,
width: selection.width,
height: selection.height
})
if (projectId !== props.projectId || selection.shotId !== props.shot.shotId || !open.value)
return
if (
plan.context.projectId !== projectId ||
plan.context.targetId !== selection.shotId ||
plan.model !== fresh.model
)
throw new Error('当前费用计划与正式预览不匹配。')
cameraFeePlan.value = {
provider: plan.provider,
model: plan.model,
context: plan.context,
planFingerprint: plan.planFingerprint,
billingBlocked: plan.authorization.billingBlocked
}
}
} catch (cause) {
message?.warning('摄影已采用,正式预览仍需核对:' + errorMessage(cause))
}
if (cameraAssetKey.value) await cameraAssets.refresh()
} else open.value = false
} else {
const operation = getOperation(projectId)
if (operation.cause instanceof ApiError && operation.cause.status === 409) {
@@ -618,6 +757,93 @@ async function adopt() {
</section>
<p v-else-if="preflight.loading.value" role="status" class="text-sm text-muted">正在读取正式审核状态…</p>
<NButton v-if="preflight.error.value" @click="preflight.refresh">重新读取审核状态</NButton>
<!-- 以下是原摄影、完整差异及历史,只读按需展开,不创建第二套摄影编辑器。 -->
<template v-if="formal">
<NButton
class="self-start"
:disabled="saving || savingDraft"
:loading="formalQuery.loading.value"
@click="formalQuery.refresh"
>刷新正式摄影与来源</NButton
>
<p v-if="formalQuery.error.value" role="alert" class="text-sm">{{ formalQuery.error.value }}</p>
<NCollapse v-model:expanded-names="cameraExpanded">
<NCollapseItem name="camera-formal" title="当前正式摄影与状态"
><ShotDesign
v-if="formalQuery.data.value && !formalQuery.error.value"
:shot="formalQuery.data.value.shot"
/></NCollapseItem>
<NCollapseItem name="camera-history" title="摄影修订历史"
><p v-if="!cameraHistory.length" class="text-sm text-muted">暂无摄影修订记录。</p>
<RawDataDetails
v-for="(event, index) in cameraHistory"
:key="index"
:value="event"
:title="`第 ${index + 1} 次摄影修订`"
/></NCollapseItem>
<NCollapseItem name="camera-assets" title="已有图片与质量(只读)">
<p v-if="cameraAssets.loading.value" role="status">正在读取原图片与审核…</p>
<p v-if="cameraAssets.error.value" role="alert">{{ cameraAssets.error.value }}</p>
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
<KeyframeCard
v-for="item in cameraAssets.data.value ?? []"
:key="item.id"
:item="item"
:project-id="projectId"
:shot-id="shot.shotId"
:shot-no="shot.shotNo"
:stale="false"
:blocked="true"
:validation-passed="null"
:review-revision="cameraReviewRevision"
:confirming="false"
readonly
@history="cameraHistoryAssetId = item.id"
/>
</div>
<KeyframeValidationHistory
v-if="cameraHistoryAssetId"
:key="cameraHistoryAssetId + ':' + cameraReviewRevision"
:project-id="projectId"
:shot-id="shot.shotId"
:keyframe-id="cameraHistoryAssetId"
initial-open
:disabled="true"
/>
</NCollapseItem>
</NCollapse>
<SceneTransitionEvidence
v-if="!formalQuery.error.value && !formalQuery.loading.value"
:continuity="continuity"
/>
<section
v-if="mode === 'camera' && cameraDifferences.length"
class="workspace-section-stack"
aria-label="摄影完整差异"
>
<WorkspaceSectionHeading :title="`完整字段差异(${cameraDifferences.length}项)`" />
<article v-for="(item, index) in cameraDifferences" :key="index" class="space-y-2 text-sm">
<h4>{{ item.label }}</h4>
<p class="whitespace-pre-wrap wrap-anywhere">修改前:{{ item.before || '(空)' }}</p>
<p class="whitespace-pre-wrap wrap-anywhere">修改后:{{ item.after || '(空)' }}</p>
</article>
</section>
<p v-if="cameraAdoptionNotice" role="status" class="text-sm">{{ cameraAdoptionNotice }}</p>
<ImageGenerationPreview
v-if="cameraFormalPreview"
:preview="cameraFormalPreview"
:loading="false"
error=""
stale-notice=""
display-only
/>
<KeyframePreviewChecks v-if="cameraFormalPreview" :preview="cameraFormalPreview" />
<RawDataDetails
v-if="cameraFeePlan"
:value="cameraFeePlan"
title="新来源费用计划(不代表授权或核清)"
/>
</template>
<!-- 以下是服务端待审草案、版本和保留的原稿 -->
<section class="space-y-3 text-sm">
@@ -813,6 +1039,14 @@ async function adopt() {
<!-- 以下是已冻结的草案、场景几何依据及实际模型输入 -->
<section v-if="reviewed && previewDisplay" class="space-y-4 text-sm">
<RawDataDetails
:value="{
formalSourceFingerprint: reviewed.selection.expectedCurrentFormalSourceFingerprint,
currentDerivedFingerprint: reviewed.preview.currentDerivedFingerprint,
adjacentDerivedVersions: reviewed.preview.adjacentDerivedVersions
}"
title="当前与相邻镜头版本"
/>
<WorkspaceSectionHeading title="草案预览" description="采用后可预览正式首帧。" />
<NTag size="small" :bordered="false">{{
reviewed.preview.productionGate.ready ? '项目制作已就绪' : '项目制作未就绪'
@@ -1,5 +1,6 @@
<script setup lang="ts">
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import SceneTransitionEvidence from './SceneTransitionEvidence.vue'
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
@@ -73,6 +74,7 @@ async function load(kind: 'references' | 'spec') {
controllers[kind] = controller
busy.value[kind] = true
errors.value[kind] = ''
if (kind === 'spec') spec.value = null
try {
if (kind === 'references') {
const result = await storyboardApi.references(shotId, controller.signal)
@@ -211,6 +213,7 @@ function exportResult(kind: 'spec' | 'prompt') {
><NButton @click="exportResult('spec')" text size="small"><Download :size="13" />导出方案</NButton>
</div>
<RawDataDetails :value="spec" title="完整生成方案(高级)" />
<SceneTransitionEvidence :continuity="spec.continuity" />
</template>
</section>
<section>
@@ -68,6 +68,16 @@ export interface ShotGenerationSpec {
/** 编译时读取的相邻镜头证据,首态与尾态分别记录。 */
export interface ShotContinuityEvidence {
/** 正式采用的有界人工规划,只解释场景文本差异,不证明真实视频末态。 */
sceneTransition?: {
/** 同集紧邻前镜。 */ previousShotId: string
/** 唯一共享场景。 */ subjectRef: string
/** 正式场景形态。 */ subjectFormId: string
/** 依据来自人工规划。 */ basis: 'confirmed_plan'
/** 当前来源与邻镜版本。 */ fingerprint: string
/** 原联合采用批次。 */ requestFingerprint: string
/** 尚未验证真实视频末态。 */ verifiedVideoEndState: false
}
/** 同集紧邻前镜。 */ previousShotId: string
/** 是否共用场景。 */ sameScene: boolean
/** 单独确认的前镜尾态。 */
+51 -6
View File
@@ -1,10 +1,35 @@
import type { MotionPlan, MotionRevision, MotionRevisionHistory, MotionRevisionPreview } from './motion-revision'
import type {
MotionPlan,
MotionRevision,
MotionRevisionHistory,
MotionRevisionPreview,
FailedMotionCandidate
} from './motion-revision'
import type { WorkflowExecutionStart } from '../workflows/execution.types'
import { request } from '../../lib/http'
import type { MotionPlanAudit, MotionPlanPreview } from './motion.types'
/** 动作查询与修订入口;只有明确启动视觉校验会调用模型。 */
export const motionApi = {
/**
* 免费发现本镜原受控任务,不登记批准或恢复执行。
* @param shotId 原镜头
* @returns 当前计划内最近任务身份
*/
candidatePlan: (shotId: string) =>
request<{ shotId: string; projectId: string; latestTask: { taskId: string; executionId: string } | null }>(
`/storyboard-shots/${encodeURIComponent(shotId)}/video-prompt/preview`
),
/**
* 只读原失败任务、质量、解析候选和公开回执,不重试原模型。
* @param shotId 原镜头
* @param taskId 原Task
* @returns 原公开执行证据
*/
candidate: (shotId: string, taskId: string) =>
request<FailedMotionCandidate>(
`/storyboard-shots/${encodeURIComponent(shotId)}/video-prompt/executions/${encodeURIComponent(taskId)}`
),
/**
* 查询真实修订历史。
* @param shotId 镜头 ID
@@ -19,12 +44,16 @@ export const motionApi = {
* 免费检查完整草稿,不激活版本。
* @param shotId 镜头 ID
* @param motionPlan 完整规划
* @param expectedSourceFingerprint 用户已经核对的来源
* @returns 结构检查与预警
*/
previewRevision: (shotId: string, motionPlan: MotionPlan) =>
previewRevision: (shotId: string, motionPlan: MotionPlan, expectedSourceFingerprint?: string) =>
request<MotionRevisionPreview>(
`/storyboard-shots/${encodeURIComponent(shotId)}/motion-plan/revisions/preview`,
{ method: 'POST', body: { motionPlan } }
{
method: 'POST',
body: { motionPlan, ...(expectedSourceFingerprint ? { expectedSourceFingerprint } : {}) }
}
),
/**
* 保存不可变修订,不调用模型。
@@ -34,7 +63,17 @@ export const motionApi = {
*/
saveRevision: (
shotId: string,
input: { motionPlan: MotionPlan; parentRevisionId: string | null; reason: string | null }
input: {
motionPlan: MotionPlan
parentRevisionId: string | null
reason: string | null
/** 首次明确承接原失败候选。 */ failedCandidate?: {
/** 原Task。 */ taskId: string
/** 当前源。 */ expectedSourceFingerprint: string
/** 本次预检。 */ expectedPreviewFingerprint: string
/** 人工确认原失败。 */ acknowledgeFailedCandidate: true
}
}
) =>
request<MotionRevision>(`/storyboard-shots/${encodeURIComponent(shotId)}/motion-plan/revisions`, {
method: 'POST',
@@ -50,9 +89,15 @@ export const motionApi = {
validateRevision: (
shotId: string,
revisionId: string,
input: { primaryKeyframeId: string; expectedRevisionId: string | null }
input: {
primaryKeyframeId: string
expectedRevisionId: string | null
/** 原精确起点计划。 */ expectedPlanFingerprint: string
}
) =>
request<WorkflowExecutionStart & { willCallModel: true }>(
request<
WorkflowExecutionStart & { willCallModel: boolean; /** 服务端复用原任务,不再次收费。 */ reused?: boolean }
>(
`/storyboard-shots/${encodeURIComponent(shotId)}/motion-plan/revisions/${encodeURIComponent(revisionId)}/start-state-validation/start`,
{ method: 'POST', body: input }
),
+64 -1
View File
@@ -4,6 +4,8 @@ import type { WorkflowExecution } from '../workflows/execution.types'
/** 可编辑的完整动作规划,与后端 schema 一致。 */
export interface MotionPlan {
/** 完整物理交互按正式Schema保留;高级编辑由服务端免费预检裁决。 */
interactions?: Array<Record<string, unknown>>
/** 一至五个动作阶段。 */
beats: MotionBeat[]
/** 一至八条整体运动约束。 */
@@ -16,7 +18,17 @@ export interface MotionRevision {
/** 所属镜头。 */
shotId: string
/** 修订来源。 */
source: 'ai_original' | 'manual'
source: 'ai_original' | 'manual' | 'failed_candidate'
/** 失败根的来源证明;人工子版本为null,不能把根reason JSON当人工说明。 */
candidateOrigin?: {
/** 原任务。 */ taskId: string
/** 原Workflow。 */ workflowExecutionId: string
/** 原批准。 */ authorizationId: string
/** 原来源。 */ sourceFingerprint: string
/** 原证据。 */ evidenceFingerprint: string
/** 原回执。 */ receiptFingerprint: string
/** 原质量仍失败。 */ originalBusinessStatus: 'failed'
} | null
/** 实际父版本。 */
parentRevisionId: string | null
/** 修改原因。 */
@@ -45,6 +57,18 @@ export interface MotionRevisionHistory {
}
/** 免费预检查不授予激活权限。 */
export interface MotionRevisionPreview {
/** 当前正式确定性问题,不能只检查结构。 */ formalIssues?: string[]
/** 当前正式来源。 */ sourceFingerprint?: string
/** 本次完整草案及模型输入版本。 */ previewFingerprint?: string
/** 免费文字检查不证明起点像素。 */ startStateStatus?: 'required_unknown'
/** 当前源及像素/事实只读证据。 */ source?: {
/** 原项目。 */ projectId: string
/** 当前生效版本。 */ activeRevisionId: string | null
/** 当前主首帧。 */ primaryKeyframeId: string
/** 原完整事实。 */ facts: unknown
/** 其它正式源证据。 */ [key: string]: unknown
}
/** 免费精确起点计划;缺失时禁止启动起点Vision或采用。 */ startStatePlan?: MotionStartStatePlan | null
/** 镜头 ID。 */
shotId: string
/** 仅结构合法。 */
@@ -66,6 +90,44 @@ export interface MotionRevisionPreview {
/** 不修改资产。 */
willModifyAssets: false
}
/** 原起点免费计划,模型请求身份与费用确认绑定。 */
export interface MotionStartStatePlan {
/** 正式计划版本。 */ version: 1
/** 当前主首帧。 */ primaryKeyframeId: string
/** 当前预期采用指针,可为空。 */ expectedRevisionId: string | null
/** 已保存动作版本的内容。 */ motionPlanFingerprint: string
/** 精确计划SHA,启动不得用顶层Preview替代。 */ fingerprint: string
/** 当前正式来源。 */ sourceFingerprint: string
/** 计划状态。 */ status: 'ready' | 'reusable' | 'blocked'
/** 本次可执行性。 */ executionAvailable: boolean
/** 最大拟调用数。 */ proposedMaximumProviderRequests: number
/** 当前新增调用数。 */ additionalProviderRequests: number
/** 当前费用未知,不推断为0。 */ feeEstimate: {
/** 币种。 */ currency: string
/** 尚无实际用量。 */ amount: number | null
/** 原因。 */ reason: string
}
/** 实际脱敏模型请求及其它原始证据。 */ [key: string]: unknown
}
/** 原受控Prompt执行的公开只读回执,不含未公开的原SDK文本。 */
export interface FailedMotionCandidate {
/** 原Task。 */ taskId: string
/** 原Workflow。 */ executionId: string
/** 原镜头。 */ shotId: string
/** 当前源是否匹配。 */ current: boolean
/** 原业务质量状态。 */ status: string
/** 原批准计划。 */ plan: { /** 原项目。 */ projectId: string; /** 原其它完整计划。 */ [key: string]: unknown }
/** 原失败质量。 */ qualityFailure: {
/** 原阶段。 */ phase?: string
/** 原问题。 */ [key: string]: unknown
} | null
/** 原已解析模型观察,保留失败不盖通过。 */ observations: {
/** 完整原失败候选。 */ motion_plan?: MotionPlan
/** 其它公开观察。 */ [key: string]: unknown
}
/** 原请求脱敏快照、用量和公开回执元数据。 */ [key: string]: unknown
}
/** 起点视觉校验的实际问题结构。 */
export interface MotionValidationIssue {
/** 起点冲突种类。 */
@@ -131,6 +193,7 @@ export function motionEvidenceCurrent(
execution?.status === 'completed' &&
execution.workflowName === 'motion-plan-start-state-validation' &&
revision &&
revision.source !== 'failed_candidate' &&
primary?.imageUrl &&
primary.status === 'completed' &&
primary.isPrimary &&
+1
View File
@@ -8,6 +8,7 @@ export interface MotionIssue {
/** 已保存动作阶段;时间和动作均来自后端,不在前端补造。 */
export interface MotionBeat {
/** 真实已执行动作ID,原样保留,不根据文本猜测。 */ performedActionIds?: string[]
startSecond: number
endSecond: number
action: string
+217 -10
View File
@@ -5,7 +5,12 @@ import { productionApi } from '../production/api'
import { useWorkflowExecution } from '../workflows/execution'
import { getOperation, runOperation } from '../workflows/operations'
import { ApiError, errorMessage } from '../../lib/http'
import { motionEvidenceCurrent, type MotionPlan, type MotionRevisionPreview } from './motion-revision'
import {
motionEvidenceCurrent,
type MotionPlan,
type MotionRevisionPreview,
type FailedMotionCandidate
} from './motion-revision'
/**
* 管理一个镜头的完整草稿、免费预检、保存和付费视觉任务;切镜后丢弃迟到 UI 更新。
@@ -60,6 +65,16 @@ export function useMotionRevision(
const draft = ref<MotionPlan>({ beats: [], globalMotionConstraints: [] })
/** 人工修改原因。 */
const reason = ref('')
/** 原失败Task可由正式免费计划发现,也可粘贴真实ID只读核对。 */
const failedTaskId = ref('')
/** 原模型候选、质量和Workflow公开回执,始终与人工草稿分开。 */
const failedCandidate = ref<FailedMotionCandidate | null>(null)
/** 用户确认承接原失败,而不是将其改为通过。 */
const failedAcknowledged = ref(false)
/** 只读候选查询就地加载,不启动原Workflow。 */
const candidateLoading = ref(false)
/** 完整交互JSON的输入错误保留在编辑器中。 */
const interactionError = ref('')
/** 只保留当前草稿的免费预检查。 */
const preview = ref<MotionRevisionPreview | null>(null)
/** 明确确认视觉模型费用。 */
@@ -81,10 +96,39 @@ export function useMotionRevision(
const revision = computed(
() => context.data.value?.history.revisions.find(item => item.revisionId === selectedId.value) ?? null
)
/** 沿真实父版本追溯失败根,重新打开人工子版本后仍可核对原任务,不改写原质量。 */
const candidateOrigin = computed(() => {
const rows = context.data.value?.history.revisions ?? [],
seen = new Set<string>()
let row = revision.value
while (row && !seen.has(row.revisionId)) {
if (row.candidateOrigin) return row.candidateOrigin
seen.add(row.revisionId)
row = rows.find(parent => parent.revisionId === row?.parentRevisionId) ?? null
}
return null
})
/** 草稿与所选修订内容保持一致才可校验或激活。 */
const saved = computed(
() => !!revision.value && JSON.stringify(draft.value) === JSON.stringify(revision.value.motionPlan)
)
/** 无正式原计划且尚无历史时,必须显式承接当前失败候选。 */
const requiresCandidate = computed(
() =>
context.data.value?.preview.motionPlanAvailable === false &&
context.data.value.history.revisions.length === 0
)
/** 原Task必须仍属于同项目同镜头、当前Motion阶段失败且有完整原候选。 */
const candidateReady = computed(
() =>
failedCandidate.value?.shotId === props.shotId &&
failedCandidate.value.taskId === failedTaskId.value.trim() &&
failedCandidate.value.plan?.projectId === props.projectId &&
failedCandidate.value.current &&
failedCandidate.value.status === 'failed' &&
failedCandidate.value.qualityFailure?.phase === 'motion_plan' &&
!!failedCandidate.value.observations?.motion_plan
)
/** 项目已有请求或后台任务时禁止重复发起。 */
const pending = computed(() => getOperation(props.projectId).pending)
/** 自动核对输入期间允许继续填写草稿,不让定时查询打断输入焦点。 */
@@ -105,6 +149,11 @@ export function useMotionRevision(
() =>
saved.value &&
!invalidated.value &&
revision.value?.source !== 'failed_candidate' &&
!!preview.value?.sourceFingerprint &&
!!record.value?.result?.plan &&
(record.value.result.plan as { sourceFingerprint?: string }).sourceFingerprint ===
preview.value.sourceFingerprint &&
motionEvidenceCurrent(
record.value,
revision.value,
@@ -114,6 +163,39 @@ export function useMotionRevision(
)
/** 查询与请求进行中临时禁用提交,不把有效证据误显示为失效。 */
const canActivate = computed(() => !blocked.value && evidenceValid.value)
/** 保存与正式采用独立;缺候选证据或交互输入不合法时不写入。 */
const canSave = computed(
() =>
!blocked.value &&
!interactionError.value &&
preview.value?.valid === true &&
(!requiresCandidate.value ||
(candidateReady.value &&
failedAcknowledged.value &&
!!reason.value.trim() &&
/^[a-f0-9]{64}$/.test(preview.value.sourceFingerprint ?? '') &&
/^[a-f0-9]{64}$/.test(preview.value.previewFingerprint ?? '')))
)
/** 只能启动已保存的非失败根版本,且必须有当前精确起点计划。 */
const canValidate = computed(
() =>
!blocked.value &&
saved.value &&
revision.value?.source !== 'failed_candidate' &&
!!preview.value?.valid &&
!!preview.value.startStatePlan &&
preview.value.source?.projectId === props.projectId &&
preview.value.source.primaryKeyframeId === context.data.value?.primary?.id &&
/^[a-f0-9]{64}$/.test(preview.value.sourceFingerprint ?? '') &&
preview.value.startStatePlan.version === 1 &&
preview.value.startStatePlan.sourceFingerprint === preview.value.sourceFingerprint &&
preview.value.startStatePlan.primaryKeyframeId === context.data.value?.primary?.id &&
preview.value.startStatePlan.expectedRevisionId === context.data.value?.history.activeRevisionId &&
preview.value.startStatePlan.motionPlanFingerprint === revision.value?.fingerprint &&
/^[a-f0-9]{64}$/.test(preview.value.startStatePlan.fingerprint) &&
['ready', 'reusable'].includes(preview.value.startStatePlan.status) &&
(preview.value.startStatePlan.status === 'reusable' || preview.value.startStatePlan.executionAvailable)
)
/** 当前版本和主首帧输入变化也撤销费用确认及旧证据。 */
const binding = computed(() =>
JSON.stringify([
@@ -126,10 +208,21 @@ export function useMotionRevision(
if (old && old !== '[null,null,null]') invalidated.value = true
acknowledged.value = false
})
/** 更换待核对Task只撤销承接确认,保留人工草稿等待新来源。 */
watch(
failedTaskId,
() => {
failedAcknowledged.value = false
preview.value = null
invalidated.value = true
},
{ flush: 'sync' }
)
watch(
draft,
() => {
preview.value = null
failedAcknowledged.value = false
acknowledged.value = false
if (!copying) invalidated.value = true
},
@@ -143,6 +236,10 @@ export function useMotionRevision(
error.value = ''
notice.value = ''
acknowledged.value = false
failedTaskId.value = ''
failedCandidate.value = null
failedAcknowledged.value = false
interactionError.value = ''
})
/**
* 复制所选版本或真实 AI 规划;改变来源后须重新取得视觉证据。
@@ -173,6 +270,7 @@ export function useMotionRevision(
select(
value.history.activeRevisionId ??
value.history.originalRevisionId ??
value.history.revisions.findLast(row => row.source === 'manual')?.revisionId ??
value.history.revisions.at(-1)?.revisionId ??
'',
true
@@ -211,6 +309,7 @@ export function useMotionRevision(
error.value = errorMessage(cause)
if (cause instanceof ApiError && cause.status === 409) {
invalidated.value = true
preview.value = null
acknowledged.value = false
await context.refresh()
changed()
@@ -222,45 +321,73 @@ export function useMotionRevision(
}
/** 免费检查本次完整草稿;编辑或切镜后丢弃迟到回执。 */
async function precheck() {
if (interactionError.value) return
const shotId = props.shotId
const plan = JSON.parse(JSON.stringify(draft.value)) as MotionPlan
const signature = JSON.stringify(plan)
await perform('免费检查动作修订', async () => {
const result = await motionApi.previewRevision(shotId, plan)
const result = await motionApi.previewRevision(
shotId,
{ ...plan, interactions: plan.interactions ?? [] },
preview.value?.sourceFingerprint
)
if (!disposed && props.shotId === shotId && signature === JSON.stringify(draft.value)) {
if (result.shotId !== shotId) throw new Error('预检查回执与镜头不匹配。')
if (result.shotId !== shotId || (result.source && result.source.projectId !== props.projectId))
throw new Error('预检查回执与当前项目或镜头不匹配。')
preview.value = result
}
})
}
/** 保存必须先获得当前草稿的结构通过结果,不激活或调用模型。 */
async function save() {
if (preview.value?.valid !== true) return
if (!canSave.value) return
const target = identity.value
const shotId = props.shotId
const plan = JSON.parse(JSON.stringify(draft.value)) as MotionPlan
const plan = {
...JSON.parse(JSON.stringify(draft.value)),
interactions: draft.value.interactions ?? []
} as MotionPlan
const parentRevisionId = selectedId.value || null
const failed = requiresCandidate.value
? {
taskId: failedCandidate.value!.taskId,
expectedSourceFingerprint: preview.value!.sourceFingerprint!,
expectedPreviewFingerprint: preview.value!.previewFingerprint!,
acknowledgeFailedCandidate: true as const
}
: undefined
await perform('保存动作修订', async () => {
const result = await motionApi.saveRevision(shotId, {
motionPlan: plan,
parentRevisionId,
reason: reason.value.trim() || null
reason: reason.value.trim() || null,
...(failed ? { failedCandidate: failed } : {})
})
if (result.shotId !== shotId || result.source !== 'manual' || result.isActive || !result.revisionId)
throw new Error('保存回执不是当前镜头的未生效人工版本。')
if (disposed || identity.value !== target) return
await context.refresh()
select(result.revisionId)
notice.value = '修订已保存,尚未生效;请确认模型费用后校验。'
failedAcknowledged.value = false
notice.value = '人工修订已保存,尚未采用。重新免费预检后,可另行确认起点视觉费用;未自动启动任何模型。'
})
}
/** 用户确认费用后重新读取首帧与生效指针,再启动视觉模型。 */
async function validate() {
if (!acknowledged.value || !saved.value || !revision.value || !context.data.value?.primary) return
if (
!acknowledged.value ||
!canValidate.value ||
!revision.value ||
!context.data.value?.primary ||
!preview.value?.startStatePlan
)
return
const target = identity.value
const selected = revision.value
const originalProjectId = props.projectId
const expectedBinding = binding.value
const frozenPlan = preview.value.startStatePlan.fingerprint,
sourceFingerprint = preview.value.sourceFingerprint
acknowledged.value = false
await perform('校验动作修订起点', async () => {
await context.refresh()
@@ -274,11 +401,27 @@ export function useMotionRevision(
throw new Error('主首帧或生效版本已变化,请刷新并重新确认费用。')
const primary = context.data.value?.primary
if (!primary?.imageUrl) throw new Error('尚无有效主首帧,不能启动视觉校验。')
const latest = await motionApi.previewRevision(selected.shotId, selected.motionPlan, sourceFingerprint)
if (disposed || identity.value !== target) return
if (
!latest.valid ||
latest.startStatePlan?.fingerprint !== frozenPlan ||
!['ready', 'reusable'].includes(latest.startStatePlan.status) ||
(latest.startStatePlan.status === 'ready' && !latest.startStatePlan.executionAvailable)
) {
preview.value = latest
throw new Error('精确起点计划已变化或尚不可执行,请重新核对并确认费用。')
}
preview.value = latest
const result = await motionApi.validateRevision(selected.shotId, selected.revisionId, {
primaryKeyframeId: primary.id,
expectedRevisionId: context.data.value!.history.activeRevisionId
expectedRevisionId: context.data.value!.history.activeRevisionId,
expectedPlanFingerprint: frozenPlan
})
if (!result.executionId || result.willCallModel !== true)
if (
!result.executionId ||
(result.willCallModel !== true && !(result.willCallModel === false && result.reused === true))
)
throw new Error('未返回有效视觉校验任务,请刷新,勿重复提交。')
if (!disposed && identity.value === target) invalidated.value = false
await execution.track(result.executionId, originalProjectId)
@@ -324,8 +467,72 @@ export function useMotionRevision(
: '此版本已生效。'
})
}
/** 主动读取原候选,只展示原失败证据,不自动载入或保存。 */
async function readCandidate() {
if (blocked.value || candidateLoading.value) return
const target = identity.value,
shotId = props.shotId,
projectId = props.projectId
candidateLoading.value = true
error.value = ''
failedAcknowledged.value = false
failedCandidate.value = null
try {
let taskId = failedTaskId.value.trim()
if (!taskId) {
const plan = await motionApi.candidatePlan(shotId)
if (plan.shotId !== shotId || plan.projectId !== projectId || !plan.latestTask?.taskId)
throw new Error('当前镜头没有可核对的原任务。')
taskId = plan.latestTask.taskId
}
const original = await motionApi.candidate(shotId, taskId)
if (disposed || identity.value !== target) return
if (original.taskId !== taskId || original.shotId !== shotId || original.plan?.projectId !== projectId)
throw new Error('原任务不属于当前项目或镜头。')
failedCandidate.value = original
failedTaskId.value = taskId
if (!candidateReady.value) error.value = '原任务不是当前可承接的动作质量失败候选,仅保留只读记录。'
} catch (cause) {
if (!disposed && target === identity.value) error.value = errorMessage(cause)
} finally {
if (target === identity.value) candidateLoading.value = false
}
}
/** 从已保存失败根读取原公开回执,不将历史候选重新载入人工草稿或恢复模型执行。 */
async function readOriginCandidate() {
if (!candidateOrigin.value || blocked.value || candidateLoading.value) return
failedTaskId.value = candidateOrigin.value.taskId
await readCandidate()
}
/** 将原失败候选显式载入人工草稿,原Task/质量/回执保持失败。 */
function useCandidate() {
if (!candidateReady.value || !failedCandidate.value?.observations.motion_plan || blocked.value) return
copying = true
selectedId.value = ''
draft.value = JSON.parse(JSON.stringify(failedCandidate.value.observations.motion_plan))
copying = false
preview.value = null
reason.value = ''
acknowledged.value = false
failedAcknowledged.value = false
invalidated.value = true
notice.value = '已载入人工草稿,原候选仍为失败;请修改并免费预检。'
}
return {
context,
canSave,
canValidate,
failedTaskId,
failedCandidate,
failedAcknowledged,
candidateLoading,
requiresCandidate,
candidateReady,
candidateOrigin,
readOriginCandidate,
interactionError,
readCandidate,
useCandidate,
selectedId,
draft,
reason,
@@ -136,7 +136,28 @@ export function useImageGenerationPreview<Input extends object, Preview extends
/** 过期说明在新预览返回后仍保留,提醒再次确认。 */
const staleNotice = ref('')
/** 当前预览的 OpenAI 准入结论,未知时不允许收费。 */
const charge = shallowRef<{ allowed: boolean; reusable: boolean; message: string } | null>(null)
const charge = shallowRef<{
allowed: boolean
reusable: boolean
message: string
/** 实际批准期限,不延长服务端授权。 */ expiresAt?: string
} | null>(null)
/** 面板停留期间到期也撤销旧成功预检,不等用户再次发送请求。 */
let expiryTimer: ReturnType<typeof setTimeout> | undefined
watch(
charge,
value => {
clearTimeout(expiryTimer)
if (!value?.expiresAt || !value.allowed || value.reusable) return
const delay = Date.parse(value.expiresAt) - Date.now()
if (delay >= 0 && delay <= 2_147_483_647)
expiryTimer = setTimeout(() => {
invalidate()
staleNotice.value = '本次授权已到期,请重新核对许可与费用计划。'
}, delay)
},
{ flush: 'sync' }
)
/** 授权保存或撤销使打开的预览失效。 */
const authorizationRevision = useProjectGenerationRevision()
/** 有效授权内无需逐张收费确认,其它供应方仍独立确认。 */
@@ -176,11 +197,11 @@ export function useImageGenerationPreview<Input extends object, Preview extends
revision++
controller?.abort()
preview.value = null
charge.value = null
acknowledged.value = false
loading.value = false
error.value = ''
staleNotice.value = ''
charge.value = null
}
watch(key, invalidate, { flush: 'sync' })
onBeforeUnmount(invalidate)
@@ -193,6 +214,7 @@ export function useImageGenerationPreview<Input extends object, Preview extends
const abort = new AbortController()
controller = abort
preview.value = null
charge.value = null
acknowledged.value = false
loading.value = true
error.value = ''
@@ -272,6 +294,11 @@ export function useImageGenerationPreview<Input extends object, Preview extends
/** 明确提交一次;预览过期只重读预览,绝不自动重新生成。 */
async function submit() {
if (charge.value?.expiresAt && Date.parse(charge.value.expiresAt) <= Date.now() && !reusableResult.value) {
invalidate()
staleNotice.value = '本次授权已到期,请重新核对许可与费用计划。'
return
}
if (!canSubmit.value || !preview.value) return
if (reusableResult.value && options.reuseResult) {
submitting.value = true
@@ -321,6 +348,17 @@ export function useImageGenerationPreview<Input extends object, Preview extends
}
acknowledged.value = false
charge.value = null
if (
result.cause instanceof ApiError &&
result.cause.status === 409 &&
(result.cause.code === 'SCENE_CONTINUITY_REVIEW_STALE' ||
result.cause.message.startsWith('SCENE_CONTINUITY_REVIEW_STALE'))
) {
invalidate()
staleNotice.value = '衔接规划来源已变化,请核对当前来源并重新预览;原输入已保留。'
error.value = errorMessage(result.cause)
return
}
if (
result.cause instanceof ApiError &&
result.cause.status === 409 &&
@@ -347,6 +385,7 @@ export function useImageGenerationPreview<Input extends object, Preview extends
staleNotice,
recoveryNotice,
canSubmit,
invalidate,
loadPreview,
submit
}
+2
View File
@@ -1,5 +1,7 @@
/** 用户可操作的图片授权及视频费用审计错误,保留原码用于业务判断。 */
const messages: Record<string, string> = {
IMAGE_BOUNDED_AUTHORIZATION_INVALID: '有限许可已失效、用尽,或镜头来源与原预算已变化,请刷新后重新核对。',
IMAGE_AUTHORIZATION_PLAN_STALE: '当前来源或精确费用计划已变化,原批准草稿保留,请重新免费预检。',
IMAGE_ADDITIONAL_AUTHORIZATION_INVALID: '人工追加许可无效、已撤销、用尽,或原精确计划与预算已变化,请重新核对。',
IMAGE_BILLING_AUDIT_CONFLICT: '原图片请求或批准版本冲突,请重新读取审计。',
IMAGE_BILLING_AUDIT_IDENTITY_MISMATCH: '材料与原图片请求身份不匹配,或供应方编号已归属其它请求。',
+3
View File
@@ -157,6 +157,9 @@ export function userFacingText(value: string | null | undefined, fallback = '暂
VISUAL_STATE_VIDEO_END_UNSUPPORTED: '缺少真实视频末态证据,不能把规划结束状态当作已验证结果。',
JOINT_REVISION_DRAFT_STALE: '已保存联合草案或修订号已变化,请重新读取并免费预检。',
JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: '本集原文依据缺失或版本已变化,请保留草案,重新读取原文并人工核对。',
SCENE_CONTINUITY_REVIEW_STALE: '已确认的衔接规划或相邻来源已变化,请保留草稿,重新核对来源。',
CAMERA_REVISION_ACTIVE: '此镜头仍有活动任务,暂不能采用摄影修订。请保留草稿并核对原任务。',
MOTION_PLAN_CANDIDATE_INVALID: '原失败动作候选或回执来源已失效,请保留草稿并重新核对。',
JOINT_REVISION_NEIGHBOR_STALE: '相邻镜头版本已变化,请重新核对连续性依据。',
JOINT_REVISION_STALE: '本镜摄影或开拍状态已变化,请保留草案并重新核对。',
JOINT_REVISION_SCOPE: '联合草案超出允许字段或存在未声明差异,请核对完整修改。',
+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>V8-10 · 隔离验收</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./v8-10.ts"></script>
</body>
</html>
+551
View File
@@ -0,0 +1,551 @@
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 MotionRevisionEditor from '../../src/features/storyboard/components/MotionRevisionEditor.vue'
import ProjectSettingsDialog from '../../src/features/generation-config/components/ProjectSettingsDialog.vue'
import KeyframeDialog from '../../src/features/production/components/KeyframeDialog.vue'
import KeyframeCard from '../../src/features/production/components/KeyframeCard.vue'
import type { MotionPlan, MotionRevisionHistory, MotionRevision } from '../../src/features/storyboard/motion-revision'
import type { ImageBoundedAuthorizationInput } from '../../src/features/image-authorization/types'
import { jointReviewFixture } from '../fixtures/joint-review'
import { additionalImageFixture } from '../fixtures/image-additional'
import { imagePreviewFixture } from '../fixtures/image-preview'
import { billingCatalog, billingProfile } from '../fixtures/billing'
import { keyframeFixture } from '../../src/features/production/testing/fixtures'
import '../../src/styles/styles.css'
import '../../src/styles/admin.css'
/** 只存在内存的独立项目,不接触真实资产或批准。 */
const projectId = 'v8-ten-isolated',
joint = jointReviewFixture(projectId),
shotId = joint.shot.shotId
/** 原未知账本保留,无自动新增或核清。 */
const images = additionalImageFixture(projectId)
images.requests[0]!.inputFingerprint = 'e'.repeat(64)
images.additionalAuthorizations = []
/** 草案初始与正式内容一致,只允许用户主动变更构图。 */
joint.saved.draft = structuredClone(joint.formal)
/** 图片使用本地内嵌占位,不访问任何图片模型。 */
const mockImage = 'http://localhost:4312/tests/browser/candidate.svg'
/** 两个已有图片及一个明确生成失败记录;免费计划不在资产列表中。 */
const assets = [
keyframeFixture({ id: 'old-failed', shotId, isPrimary: true, imageUrl: mockImage, provider: 'openai-image' }),
keyframeFixture({ id: 'quality-unknown', shotId, isPrimary: false, imageUrl: mockImage, provider: 'openai-image' }),
keyframeFixture({
id: 'generation-failed',
shotId,
isPrimary: false,
status: 'failed',
imageUrl: null,
error: '隔离生成失败,原费用保留'
})
]
/** 有限许可、摄影及模型动作分别计数,刷新页面不会触发生成。 */
const writes = ref(0),
generations = ref(0),
vision = ref(0),
reviewVersion = ref(0)
/** 免费能力409开关与正式来源版本。 */
let capacityBlocked = false,
adopted = false,
generated = false
/** 原失败动作原文,不因人工保存而改成通过。 */
const motionPlan: MotionPlan = {
beats: [
{
startSecond: 0,
endSecond: 4,
action: '人物保持起点站姿后缓慢前行',
cameraMotion: '保持静止',
physicalContinuity: '双脚支撑连续,保持正式空间',
subjectRefs: ['@CH0001'],
closingState: '人物保持站立',
performedActionIds: ['original-action']
}
],
globalMotionConstraints: ['保留正式身份与场景'],
interactions: []
}
/** 空原始指针合法,服务端保存时创建失败根与人工子版本。 */
const history: MotionRevisionHistory = { shotId, originalRevisionId: null, activeRevisionId: null, revisions: [] }
/** 当前正式人工规划仅声明视频末态未验证。 */
const continuity = {
previousShotId: 'previous-shot',
sameScene: true,
previousClosingState: null,
subjects: [],
reviewIssues: [],
sceneTransition: {
previousShotId: 'previous-shot',
subjectRef: '@SC0001',
subjectFormId: 'original-scene-form',
basis: 'confirmed_plan' as const,
fingerprint: 'a'.repeat(64),
requestFingerprint: 'b'.repeat(64),
verifiedVideoEndState: false as const
}
}
/**
* 正式响应包装,永远不回退到网络。
* @param data 隔离投影
* @returns Mock响应
*/
function ok(data: unknown) {
return Response.json({ data })
}
/**
* 全量拦截真实组件的请求,未知路由直接403;不连接模型或正式项目。
* @param input 原路径
* @param init 请求参数
* @returns 隔离正式契约响应
*/
window.fetch = async (input, init) => {
const path = String(input),
method = init?.method ?? 'GET',
body = init?.body ? JSON.parse(String(init.body)) : undefined
if (['POST', 'PUT'].includes(method)) writes.value++
if (path === `/api/projects/${projectId}`) return ok({ id: projectId, episodes: [{ episode: 1 }] })
if (path.includes('/workflow-executions/latest')) return ok(null)
if (path.endsWith('/generation-models')) return ok(billingCatalog)
if (path.endsWith('/creative-profile'))
return ok({
...billingProfile,
projectId,
aspectRatio: '16:9',
imageOptions: { size: '1536x1024', quality: 'auto', count: 1 }
})
if (path.endsWith('/resolve'))
return ok({
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
options: { size: '1536x1024', quality: 'auto', count: 1 }
})
if (path.endsWith('/image-providers/capabilities'))
return ok([
{
provider: 'openai-image',
active: true,
capabilities: { references: { supported: true, maxReferenceImages: 16 } }
}
])
if (path.includes('/keyframe-provider-capability'))
return capacityBlocked
? Response.json(
{
code: 'IMAGE_REFERENCE_CAPACITY_EXCEEDED',
message: '当前必需参考17张,OpenAI限制16张;不能丢弃必需参考。'
},
{ status: 409 }
)
: ok({
provider: 'openai-image',
valid: true,
referenceCount: 2,
plannedReferenceCount: 2,
omittedReferenceCount: 0,
maxReferenceImages: 16
})
if (path.includes('/storyboard-quality-confirmation'))
return ok({
current: { ...joint.approval.approval, valid: true, confirmation: joint.approval.record },
quality: joint.approval.quality
})
if (path.includes('/keyframe-review-draft')) {
if (method === 'PUT') {
joint.saved.draft = body.draft
joint.saved.revision++
joint.saved.providerInput = body.providerInput
joint.saved.status = 'current'
}
return ok(joint.saved)
}
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, formalSourceFingerprint: (adopted ? 'f' : 'c').repeat(64) })
if (path.includes('/generation-spec')) return ok({ projectId, shotId, subjects: [], continuity })
if (path.endsWith('/storyboard-derived-reviews/confirm')) {
adopted = true
joint.saved.status = 'stale'
joint.directions.beats[0]!.shots[0]!.direction = {
...body.shots[0].draft.direction,
rawJson: JSON.stringify({
cameraRevisionHistory: [
{ reviewer: body.reviewer, before: joint.formal.direction, after: body.shots[0].draft.direction }
]
})
}
reviewVersion.value++
return ok({ projectId, shots: [{ shotId, directionId: 'd', visualStateId: 'v' }] })
}
if (path.includes('/keyframe/preview')) {
if (capacityBlocked)
return Response.json(
{ code: 'IMAGE_REFERENCE_CAPACITY_EXCEEDED', message: '当前必需参考17张,OpenAI限制16张。' },
{ status: 409 }
)
const preview = {
...imagePreviewFixture(),
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
shotId,
continuity
}
return ok(
body.draft
? {
...preview,
draftFingerprint: 'd'.repeat(64),
currentDerivedFingerprint: 'c'.repeat(64),
adjacentDerivedVersions: [{ shotId: 'previous-shot', derivedFingerprint: 'a'.repeat(64) }],
productionReady: false,
productionGate: { ready: false, reason: '仅检查草案' },
sceneSources: []
}
: preview
)
}
if (path.endsWith('/image-authorizations/preview'))
return ok({
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: {
projectId,
scope: 'keyframe',
targetId: body.targetId,
sourceFingerprint: (adopted ? 'f' : 'c').repeat(64)
},
planFingerprint: 'b'.repeat(64),
authorization: images
})
if (path.endsWith('/image-authorizations')) {
if (method === 'POST') {
if (body.mode !== 'bounded') return Response.json({ message: '本隔离场景仅登记bounded' }, { status: 403 })
const existing = images.additionalAuthorizations!.find(
row => row.input.idempotencyKey === body.idempotencyKey
)
if (existing) return ok({ authorizationId: existing.id, status: existing.status })
const permit = {
id: 'bounded-' + images.additionalAuthorizations!.length,
status: 'approved',
input: { ...(body as ImageBoundedAuthorizationInput), parentInputFingerprint: 'a'.repeat(64) },
usedRequests: 0,
remainingRequests: body.maxRequests,
targets: body.targets.map((target: ImageBoundedAuthorizationInput['targets'][number]) => ({
...target,
usedRequests: 0
}))
}
images.additionalAuthorizations!.push(permit)
return ok({ authorizationId: permit.id, status: permit.status })
}
return ok(images)
}
if (path.endsWith('/revoke')) {
const permit = images.additionalAuthorizations!.find(row => row.id === path.split('/').at(-2))
if (permit) permit.status = 'revoked'
return ok({ authorizationId: permit?.id, status: 'revoked' })
}
if (/\/keyframe(?:\?|$)/.test(path) && method === 'POST') {
const permit = images.additionalAuthorizations!.find(row => row.id === body.additionalAuthorizationId)
if (!permit || permit.status !== 'approved' || permit.remainingRequests < 1)
return Response.json({ message: '许可已失效或用尽' }, { status: 409 })
if (!generated) {
generated = true
generations.value++
permit.usedRequests++
permit.remainingRequests--
permit.targets![0]!.usedRequests++
const grant = images.authorizations[0]!
grant.usedRequests++
grant.remainingRequests--
grant.accountedMicros += grant.input.perRequestMicros
grant.remainingMicros -= grant.input.perRequestMicros
images.requests.push({
...structuredClone(images.requests[0]!),
id: 'new-completed',
status: 'completed',
input: { ...images.requests[0]!.input, targetId: shotId, additionalAuthorizationId: permit.id },
output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'mock-result' } }
})
}
return ok({ id: 'new-completed', shotId, status: 'completed' })
}
if (path.endsWith('/keyframes')) return ok(assets)
if (path.includes('/quality-review'))
return ok({
shotId,
keyframeId: path.split('/keyframes/')[1]?.split('/')[0],
qualityDecision: path.includes('/old-failed/') ? 'failed' : 'unknown',
effectiveQualityStatus: path.includes('/old-failed/') ? 'stale' : 'unknown',
validationTaskId: null,
historicalGazePreview: [],
manualReview: null,
manualReviewAvailable: false
})
if (path.includes('/validations')) return ok([])
if (path.endsWith('/motion-plan/preview'))
return ok({
shotId,
durationSeconds: 4,
motionPlanAvailable: false,
beats: [],
globalMotionConstraints: [],
issues: [],
actionDensityIssues: [],
actionReviewSuggestions: [],
savedActionDensityIssues: null,
willCallModel: false,
willModifyAssets: false
})
if (path.endsWith('/video-prompt/preview'))
return ok({
shotId,
projectId,
latestTask: { taskId: 'original-failed-task', executionId: 'original-failed-workflow' }
})
if (path.includes('/video-prompt/executions/'))
return ok({
taskId: 'original-failed-task',
executionId: 'original-failed-workflow',
shotId,
plan: { projectId },
current: true,
status: 'failed',
qualityFailure: { phase: 'motion_plan', issues: ['原动作起点不匹配'] },
observations: { motion_plan: motionPlan },
steps: [
{
name: 'motion_plan',
status: 'completed',
providerRequestId: 'mock-provider-receipt',
usage: { inputTokens: 100 }
}
]
})
if (path.endsWith('/revisions/preview'))
return ok({
shotId,
valid: true,
motionPlanFingerprint: 'f'.repeat(64),
schemaIssues: [],
timelineIssues: [],
actionDensityIssues: [],
formalIssues: [],
requiresStartStateValidation: true,
canActivate: false,
willCallModel: false,
willModifyAssets: false,
startStateStatus: 'required_unknown',
sourceFingerprint: 'c'.repeat(64),
previewFingerprint: 'd'.repeat(64),
source: {
projectId,
activeRevisionId: history.activeRevisionId,
primaryKeyframeId: assets[0]!.id,
facts: {}
},
startStatePlan: {
version: 1,
primaryKeyframeId: assets[0]!.id,
expectedRevisionId: history.activeRevisionId,
motionPlanFingerprint: 'f'.repeat(64),
fingerprint: 'a'.repeat(64),
sourceFingerprint: 'c'.repeat(64),
status: 'ready',
executionAvailable: true,
proposedMaximumProviderRequests: 1,
additionalProviderRequests: 1,
feeEstimate: { currency: 'USD', amount: null, reason: '实际费用未知' }
}
})
if (path.endsWith('/motion-plan/revisions')) {
if (method === 'POST') {
const root: MotionRevision = {
revisionId: 'failed-root',
shotId,
source: 'failed_candidate',
parentRevisionId: null,
reason: '原质量失败',
candidateOrigin: {
taskId: 'original-failed-task',
workflowExecutionId: 'original-failed-workflow',
authorizationId: 'original-grant',
sourceFingerprint: 'c'.repeat(64),
evidenceFingerprint: 'e'.repeat(64),
receiptFingerprint: 'b'.repeat(64),
originalBusinessStatus: 'failed'
},
motionPlan,
durationSeconds: 4,
fingerprint: 'e'.repeat(64),
createdAt: new Date().toISOString(),
isActive: false
}
const manual: MotionRevision = {
...root,
revisionId: 'manual-child',
source: 'manual',
parentRevisionId: root.revisionId,
reason: body.reason,
candidateOrigin: null,
motionPlan: body.motionPlan,
fingerprint: 'f'.repeat(64)
}
history.revisions = [root, manual]
return ok(manual)
}
return ok(history)
}
if (path.endsWith('/start-state-validation/start')) {
vision.value++
return Response.json({ message: '此浏览器场景只验收保存,不执行Vision' }, { status: 403 })
}
return Response.json({ message: '未声明接口,禁止连接真实服务。' }, { status: 403 })
}
/** 复用原设置/摄影/首帧/动作编辑器,仅为测试提供外部打开按钮。 */
const Preview = defineComponent({
setup() {
const theme = useTheme(),
settings = ref(false),
keyframe = ref(false),
motion = 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', {}, 'V8-10 隔离验收'),
h(
'p',
{ style: 'margin:16px 0' },
'全部接口已拦截,真实模型请求0次。免费计划不计为图片候选。'
),
h(
'div',
{ class: 'workspace-action-group', style: 'margin:16px 0' },
[
h(
NButton,
{ onClick: () => (settings.value = true) },
() => '图片授权管理'
),
h(
NButton,
{ onClick: () => (keyframe.value = true) },
() => '首帧生成'
),
h(
NButton,
{ onClick: () => (motion.value = true) },
() => '人工动作修订'
),
h(
NButton,
{ onClick: () => (capacityBlocked = !capacityBlocked) },
() => '切换容量409'
),
h(
NButton,
{
onClick: () => {
const row =
images.additionalAuthorizations!.at(-1)
if (row?.input.mode === 'bounded')
row.input.expiresAt = '2000-01-01T00:00:00Z'
}
},
() => '模拟许可过期'
)
]
),
h(ShotDerivedReview, {
projectId,
episodeNo: 1,
shot: joint.shot,
shots: joint.shots,
disabled: false
}),
h(
'p',
{ role: 'status', style: 'margin:16px 0' },
`模拟写入 ${writes.value} · 图片生成 ${generations.value} · Vision ${vision.value} · 正式采用 ${history.activeRevisionId ?? '无'}`
),
h(
'div',
{
style: 'display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:16px'
},
assets.map(item =>
h(KeyframeCard, {
key: item.id,
item,
projectId,
shotId,
shotNo: 1,
stale: false,
blocked: true,
validationPassed: false,
confirming: false,
readonly: true,
reviewRevision: reviewVersion.value
})
)
)
]),
h(ProjectSettingsDialog, {
projectId,
disabled: false,
initialTab: 'image-authorization',
open: settings.value,
'onUpdate:open': value => (settings.value = value)
}),
h(KeyframeDialog, {
projectId,
shotId,
shotTitle: '隔离镜头',
disabled: false,
additionalAllowed: true,
open: keyframe.value,
'onUpdate:open': value => (keyframe.value = value),
reuseExisting: async () => generated,
submitGeneration: async input => ({
accepted: (
await fetch(
`/api/storyboard-shots/${shotId}/keyframe?projectId=${projectId}`,
{ method: 'POST', body: JSON.stringify(input) }
)
).ok
})
}),
h(MotionRevisionEditor, {
projectId,
shotId,
open: motion.value,
'onUpdate:open': value => (motion.value = value)
})
]
}
)
}
)
}
)
}
})
createApp(Preview).mount('#app')
@@ -0,0 +1,233 @@
import { flushPromises, mount } from '@vue/test-utils'
import { describe, expect, it, vi } from 'vitest'
import { NCheckbox, NDatePicker, NInput, NInputNumber, NSelect } from 'naive-ui'
import BoundedAuthorizationFields from '@/features/image-authorization/BoundedAuthorizationFields.vue'
import { boundedImageEligibility, imageChargeEligibility } from '@/features/image-authorization/model'
import { additionalImageFixture } from '../../fixtures/image-additional'
import { billingCatalog, billingProfile } from '../../fixtures/billing'
import { directionsResult } from '@/features/storyboard/testing/fixtures'
import type { ImageBoundedAuthorizationInput } from '@/features/image-authorization/types'
/** 独立的原unknown/standing和有限白名单,不代表真实批准。 */
function fixture() {
const list = additionalImageFixture('bounded-project')
list.requests[0]!.inputFingerprint = 'e'.repeat(64)
const input: ImageBoundedAuthorizationInput = {
mode: 'bounded',
idempotencyKey: 'test-bounded',
parentAuthorizationId: list.authorizations[0]!.id,
acceptedUnknownRequests: [{ requestId: list.requests[0]!.id, inputFingerprint: 'e'.repeat(64) }],
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
targets: [
{
shotId: 'shot-db-1-1',
sourceFingerprint: 'c'.repeat(64),
planFingerprint: 'b'.repeat(64),
maxRequests: 2
}
],
maxRequests: 2,
expiresAt: new Date(Date.now() + 3600000).toISOString(),
acknowledgeUnknownPriorBilling: true,
acknowledgeVariableBilling: true,
approvedBy: '隔离批准人',
approvalNote: '仅原预算内有限继续'
}
list.additionalAuthorizations = [
{
id: 'bounded-permit',
status: 'approved',
input: { ...input, parentInputFingerprint: 'a'.repeat(64) },
usedRequests: 0,
remainingRequests: 2,
targets: input.targets.map(row => ({ ...row, usedRequests: 0 }))
}
]
return list
}
/** 以字面真实范围调用正式准入逻辑。 */
function eligibility(list: ReturnType<typeof fixture>) {
return boundedImageEligibility(
list,
'bounded-permit',
'bounded-project',
'shot-db-1-1',
'gpt-image-2.5-flare',
'c'.repeat(64),
'b'.repeat(64)
)
}
describe('bounded沿原账本的有限风险许可', () => {
it('仅选中的白名单可使用,原unknown/预留及billingBlocked保持', () => {
const list = fixture()
expect(eligibility(list).allowed).toBe(true)
expect(
imageChargeEligibility(list, 'keyframe', 'shot-db-1-1', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed
).toBe(false)
expect(list.billingBlocked).toBe(true)
expect(list.requests[0]!.status).toBe('unknown')
expect(list.requests[0]!.output?.actualBilledMicros).toBeNull()
})
it.each([
'revoked',
'expired',
'total',
'per-shot',
'shot',
'source',
'plan',
'model',
'budget',
'parent',
'new-unknown',
'running',
'input-change'
])('拒绝许可/白名单/费用变化:%s', kind => {
const list = fixture(),
permit = list.additionalAuthorizations![0]!,
target = permit.targets![0]!,
grant = list.authorizations[0]!
if (kind === 'revoked') permit.status = 'revoked'
if (kind === 'expired' && permit.input.mode === 'bounded') permit.input.expiresAt = '2000-01-01T00:00:00Z'
if (kind === 'total') permit.remainingRequests = 0
if (kind === 'per-shot') target.usedRequests = target.maxRequests
if (kind === 'shot') target.shotId = 'other-shot'
if (kind === 'source') target.sourceFingerprint = 'f'.repeat(64)
if (kind === 'plan') target.planFingerprint = 'f'.repeat(64)
if (kind === 'model' && permit.input.mode === 'bounded') permit.input.model = 'other-model'
if (kind === 'budget') grant.remainingMicros = 0
if (kind === 'parent') grant.status = 'revoked'
if (kind === 'input-change') list.requests[0]!.inputFingerprint = 'f'.repeat(64)
if (kind === 'running') list.requests[0]!.status = 'running'
if (kind === 'new-unknown') {
list.requests.push({ ...structuredClone(list.requests[0]!), id: 'new-unknown' })
list.blockingRequestIds.push('new-unknown')
}
expect(eligibility(list).allowed).toBe(false)
})
it('同计划完整结果在已撤销/用尽后仍可只读复用,不新增次数', () => {
const list = fixture()
list.additionalAuthorizations![0]!.status = 'revoked'
const result = {
...structuredClone(list.requests[0]!),
id: 'completed-result',
status: 'completed',
input: { ...list.requests[0]!.input, targetId: 'shot-db-1-1' },
output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'existing' } }
}
list.requests.push(result)
expect(
imageChargeEligibility(list, 'keyframe', 'shot-db-1-1', 'gpt-image-2.5-flare', 'b'.repeat(64), {
id: 'bounded-permit',
projectId: 'bounded-project',
sourceFingerprint: 'c'.repeat(64)
})
).toMatchObject({ allowed: true, reusable: true })
})
it('用户明确填写/逐项接受后仅登记一次,body复用原预算且不生成', async () => {
const list = fixture(),
fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url)
if (path === '/api/projects/bounded-project')
return Response.json({ data: { id: 'bounded-project', episodes: [{ episode: 1 }] } })
if (path.endsWith('/creative-profile'))
return Response.json({ data: { ...billingProfile, aspectRatio: '1:1' } })
if (path.includes('/storyboard-directions?'))
return Response.json({ data: directionsResult('bounded-project') })
if (path.endsWith('/image-authorizations/preview')) {
const body = JSON.parse(String(init?.body))
return Response.json({
data: {
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: {
projectId: 'bounded-project',
scope: 'keyframe',
targetId: body.targetId,
sourceFingerprint: 'c'.repeat(64)
},
planFingerprint: 'b'.repeat(64),
authorization: list
}
})
}
if (path.endsWith('/image-authorizations') && init?.method === 'POST')
return Response.json({ data: { authorizationId: 'created-bounded', status: 'approved' } })
throw new Error('未模拟 ' + path)
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(BoundedAuthorizationFields, {
props: { projectId: 'bounded-project', list, catalog: billingCatalog, disabled: false }
})
try {
await flushPromises()
expect(wrapper.vm.canSubmit).toBe(false)
wrapper
.findAllComponents(NSelect)
.find(row => row.attributes('aria-label') === '有限许可原授权')!
.vm.$emit('update:value', list.authorizations[0]!.id)
wrapper
.findAllComponents(NSelect)
.find(row => row.attributes('aria-label') === '有限许可镜头')!
.vm.$emit('update:value', ['shot-db-1-1'])
await flushPromises()
await wrapper
.findAll('button')
.find(row => row.text() === '免费核对逐镜费用计划')!
.trigger('click')
await flushPromises()
for (const row of wrapper.findAllComponents(NInputNumber))
row.vm.$emit('update:value', row.attributes('aria-label') === '有限许可总次数' ? 1 : 2)
wrapper.getComponent(NDatePicker).vm.$emit('update:value', Date.now() + 1800000)
wrapper
.findAllComponents(NInput)
.find(row => row.attributes('aria-label') === '有限许可批准人')!
.vm.$emit('update:value', '人工批准人')
wrapper
.findAllComponents(NInput)
.find(row => row.attributes('aria-label') === '有限许可批准说明')!
.vm.$emit('update:value', '只批准本镜头一次,原费用保持未知')
wrapper
.findAllComponents(NCheckbox)
.find(row => row.text().includes('明确接受此原请求'))!
.vm.$emit('update:checked', true)
await flushPromises()
wrapper
.findAllComponents(NCheckbox)
.find(row => row.text().includes('我已核对原未知费用'))!
.vm.$emit('update:checked', true)
await flushPromises()
expect(wrapper.vm.canSubmit).toBe(true)
await Promise.all([wrapper.vm.submit(), wrapper.vm.submit()])
await flushPromises()
const create = fetcher.mock.calls.filter(
([url, init]) => String(url).endsWith('/image-authorizations') && init?.method === 'POST'
)
expect(create).toHaveLength(1)
const body = JSON.parse(String(create[0]![1]?.body))
expect(body).toMatchObject({
mode: 'bounded',
parentAuthorizationId: list.authorizations[0]!.id,
maxRequests: 1,
targets: [
{
shotId: 'shot-db-1-1',
maxRequests: 2,
sourceFingerprint: 'c'.repeat(64),
planFingerprint: 'b'.repeat(64)
}
],
acceptedUnknownRequests: [{ requestId: 'original-image-request', inputFingerprint: 'e'.repeat(64) }]
})
expect(body).not.toHaveProperty('budgetMicros')
expect(list.requests[0]!.status).toBe('unknown')
expect(list.billingBlocked).toBe(true)
expect(
fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/primary|\/vision/.test(String(url)))
).toBe(false)
} finally {
wrapper.unmount()
}
})
})
@@ -35,8 +35,10 @@ async function setup() {
/** 完整填写用户实际批准的金额、次数、时间与范围。 */
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'])
selects
.find(item => item.attributes('aria-label') === '授权型号')!
.vm.$emit('update:value', ['gpt-image-2.5-flare'])
selects.find(item => item.attributes('aria-label') === '授权范围')!.vm.$emit('update:value', ['keyframe'])
for (const [label, value] of [
['累计预算', '1.123456'],
['单次预留', '0.123456'],
+1 -1
View File
@@ -540,7 +540,7 @@ describe('质量面板渐进展示', () => {
expect(data.fetcher).not.toHaveBeenCalled()
await wrapper.get('button').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('qwen-image · 当前启用')
expect(wrapper.text()).toContain('qwen-image · 默认推荐')
expect(wrapper.text()).toContain('最多 3 张参考图')
expect(data.posts()).toHaveLength(0)
})
@@ -0,0 +1,229 @@
import { flushPromises, mount } from '@vue/test-utils'
import { describe, expect, it, vi } from 'vitest'
import ModelCapabilities from '@/features/production/components/ModelCapabilities.vue'
import KeyframePreviewChecks from '@/features/production/components/KeyframePreviewChecks.vue'
import KeyframeCard from '@/features/production/components/KeyframeCard.vue'
import KeyframeValidationHistory from '@/features/production/components/KeyframeValidationHistory.vue'
import { additionalImageFixture } from '../../fixtures/image-additional'
import { AssetImage } from '@/components/ui'
import { keyframeFixture } from '@/features/production/testing/fixtures'
import { imagePreviewFixture } from '../../fixtures/image-preview'
describe('V8-10免费输入与独立门禁', () => {
it('旧图片按需查看原费用与来源,切换项目/候选后不混入其它记录或未执行计划', async () => {
const fetcher = vi.fn<typeof fetch>(async url => {
const path = String(url)
if (path.endsWith('/image-authorizations')) {
const projectId = path.includes('/second-project/') ? 'second-project' : 'original-project',
list = additionalImageFixture(projectId)
list.requests[0]!.input.targetId = 'history-shot'
list.requests[0]!.input.candidateId = projectId === 'second-project' ? 'second-image' : 'old-image'
list.requests.push({
...structuredClone(list.requests[0]!),
id: 'another-candidate-request',
input: { ...list.requests[0]!.input, candidateId: 'unrelated-image' }
})
return Response.json({ data: list })
}
return Response.json({
data: path.includes('/quality-review')
? {
shotId: 'history-shot',
keyframeId: 'old-image',
qualityDecision: 'failed',
effectiveQualityStatus: 'stale',
validationTaskId: null,
historicalGazePreview: [],
manualReview: null,
manualReviewAvailable: false
}
: []
})
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(KeyframeValidationHistory, {
props: {
projectId: 'original-project',
shotId: 'history-shot',
keyframeId: 'old-image',
initialOpen: true,
disabled: true
}
})
try {
await flushPromises()
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/image-authorizations'))).toBe(false)
await wrapper
.findAll('.n-collapse-item__header-main')
.find(row => row.text() === '原图片生成来源与费用')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('原预留 USD 0.5')
expect(wrapper.text()).toContain('实际账单 未知')
expect(wrapper.text()).toContain('历史审核未通过,当前来源已变化')
expect(wrapper.text()).not.toContain('another-candidate-request')
await wrapper.setProps({ projectId: 'second-project', keyframeId: 'second-image' })
await flushPromises()
expect(wrapper.text()).not.toContain('原预留 USD 0.5')
await wrapper
.findAll('.n-collapse-item__header-main')
.find(row => row.text() === '原图片生成来源与费用')!
.trigger('click')
await flushPromises()
expect(
fetcher.mock.calls.some(([url]) => String(url) === '/api/projects/second-project/image-authorizations')
).toBe(true)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
} finally {
wrapper.unmount()
}
})
it.each(['failed', 'passed'] as const)(
'保留原机器%s、当前stale及已有Primary图,不允许旧通过晋升',
async machine => {
const fetcher = vi.fn<typeof fetch>(async url =>
Response.json({
data: String(url).includes('/quality-review')
? {
shotId: 'quality-shot',
keyframeId: 'old-image',
qualityDecision: machine,
effectiveQualityStatus: 'stale',
validationTaskId: 'original-machine-task',
manualReviewAvailable: false,
historicalGazePreview: [],
manualReview: null
}
: []
})
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(KeyframeCard, {
props: {
item: keyframeFixture({
id: 'old-image',
shotId: 'quality-shot',
isPrimary: true,
imageUrl: '/mock.png'
}),
projectId: 'quality-project',
shotId: 'quality-shot',
shotNo: 1,
stale: false,
blocked: true,
validationPassed: true,
confirming: false,
readonly: true
}
})
try {
await flushPromises()
expect(wrapper.text()).toContain(
machine === 'failed' ? '历史审核未通过,当前来源已变化' : '历史审核通过,当前来源已变化'
)
expect(wrapper.text()).toContain('主首帧')
expect(wrapper.getComponent(AssetImage).props('src')).toBe('/mock.png')
expect(wrapper.text()).not.toContain('质量通过')
expect(wrapper.text()).not.toContain('设为主首帧')
expect(wrapper.findAll('button').some(row => row.attributes('aria-label') === '质量检查')).toBe(false)
expect(fetcher.mock.calls.every(([, input]) => !input?.method || input.method === 'GET')).toBe(true)
} finally {
wrapper.unmount()
}
}
)
it('同一Provider再次检查容量409时清除旧成功记录,保留实际阻断与模型限制', async () => {
let blocked = false
const fetcher = vi.fn<typeof fetch>(async url => {
if (String(url).endsWith('/image-providers/capabilities'))
return Response.json({
data: [
{
provider: 'test-provider',
active: true,
capabilities: { references: { supported: true, maxReferenceImages: 3 } }
}
]
})
return blocked
? Response.json(
{
code: 'IMAGE_REFERENCE_CAPACITY_EXCEEDED',
message: '必需参考实际需要6张,当前Provider限制3张',
details: { code: 'IMAGE_REFERENCE_CAPACITY_EXCEEDED' }
},
{ status: 409 }
)
: Response.json({
data: {
provider: 'test-provider',
valid: true,
referenceCount: 7,
maxReferenceImages: 3,
plannedReferenceCount: 3,
omittedReferenceCount: 4,
requiresPlanning: true,
strategy: 'all'
}
})
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(ModelCapabilities, { props: { shotId: 'capacity-shot', provider: 'test-provider' } })
try {
await wrapper.get('button').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('本次计划输入 3 张')
blocked = true
await wrapper.get('button').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('必需参考实际需要6张')
expect(wrapper.text()).toContain('最多 3 张参考图')
expect(wrapper.text()).not.toContain('本次计划输入 3 张')
expect(wrapper.get('button').attributes('disabled')).toBeUndefined()
expect(fetcher.mock.calls.every(([, input]) => !input?.method || input.method === 'GET')).toBe(true)
} finally {
wrapper.unmount()
}
})
it('已确认规划只解释场景衔接,真实视频末态仍未验证且其它阻断继续展示', () => {
const base = imagePreviewFixture()
const wrapper = mount(KeyframePreviewChecks, {
props: {
preview: {
...base,
generationConfig: { options: {} },
continuity: {
previousShotId: 'previous',
sameScene: true,
previousClosingState: null,
subjects: [],
reviewIssues: [{ code: 'character_form_transition_unconfirmed', subjectRef: '@CH0001' }],
sceneTransition: {
previousShotId: 'previous',
subjectRef: '@SC0001',
subjectFormId: 'form',
basis: 'confirmed_plan',
fingerprint: 'a'.repeat(64),
requestFingerprint: 'b'.repeat(64),
verifiedVideoEndState: false
}
},
specConsistencySummary: {
blocking: true,
warningCount: 0,
hasWarnings: false,
requiresManualReview: true
}
}
}
})
try {
expect(wrapper.text()).toContain('人工规划衔接已确认,视频末态尚未验证')
expect(wrapper.text()).toContain('暂不能生成')
expect(wrapper.text()).toContain('角色形态变化待确认')
expect(wrapper.text()).not.toContain('质量通过')
} finally {
wrapper.unmount()
}
})
})
@@ -0,0 +1,246 @@
import { flushPromises, mount } from '@vue/test-utils'
import { describe, expect, it, vi } from 'vitest'
import { NCheckbox, NInput } from 'naive-ui'
import ShotDerivedReview from '@/features/storyboard/components/ShotDerivedReview.vue'
import { jointReviewFixture } from '../../fixtures/joint-review'
import { imagePreviewFixture } from '../../fixtures/image-preview'
import { billingCatalog, billingProfile } from '../../fixtures/billing'
import { keyframeFixture } from '@/features/production/testing/fixtures'
import type { SaveKeyframeDraft, SavedKeyframeDraft } from '@/features/storyboard/derived-review.types'
/**
* 通过真实摄影抽屉验证已有failed图片下的有界修订;所有接口隔离。
* @param conflict 是否模拟其它任务占用后改源
* @returns 实际抽屉、只读候选及原请求
*/
async function camera(conflict = false) {
const projectId = conflict ? 'camera-conflict' : 'camera-existing-images',
f = jointReviewFixture(projectId),
shotId = f.shot.shotId
let saved: SavedKeyframeDraft | null = null,
adopted = false
const rows = [
keyframeFixture({ id: 'old-failed-image', shotId, isPrimary: false }),
keyframeFixture({ id: 'original-primary', shotId, isPrimary: true })
]
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url),
body = init?.body ? JSON.parse(String(init.body)) : undefined
if (path.endsWith('/storyboard-quality-confirmation/preflight'))
return Response.json({
data: {
current: { ...f.approval.approval, valid: true, confirmation: f.approval.record },
quality: f.approval.quality
}
})
if (path.includes('/keyframe-review-draft')) {
if (init?.method === 'PUT') {
const input = body as SaveKeyframeDraft
saved = {
...f.saved,
revision: (saved?.revision ?? 0) + 1,
draft: input.draft,
providerInput: input.providerInput ?? null,
expectedCurrentFormalSourceFingerprint: input.expectedCurrentFormalSourceFingerprint ?? null
}
}
return Response.json({ data: saved })
}
if (path.includes('/keyframe-spec'))
return Response.json({
data: {
...f.keyframe,
formalSourceFingerprint: adopted ? 'f'.repeat(64) : f.keyframe.formalSourceFingerprint
}
})
if (path.includes('/generation-spec'))
return Response.json({ data: { projectId, shotId, subjects: [], continuity: null } })
if (path.includes('/storyboard-directions?')) return Response.json({ data: f.directions })
if (path.includes('/storyboard-visual-states?')) return Response.json({ data: f.visuals })
if (path.endsWith('/generation-models')) return Response.json({ data: billingCatalog })
if (path.endsWith('/creative-profile'))
return Response.json({
data: { ...billingProfile, projectId, imageOptions: { size: '1024x1024', quality: 'auto', count: 1 } }
})
if (path.includes('/keyframe/preview'))
return Response.json({
data: {
...imagePreviewFixture(),
shotId,
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
...(body.draft
? {
draftFingerprint: 'd'.repeat(64),
currentDerivedFingerprint: 'c'.repeat(64),
adjacentDerivedVersions: [],
productionReady: false,
productionGate: { ready: false, reason: '原费用仍阻断' },
sceneSources: []
}
: {})
}
})
if (path.endsWith('/storyboard-derived-reviews/confirm')) {
if (conflict) {
f.directions.beats[0]!.shots[0]!.direction!.composition = '另一位编辑已经更改正式构图'
return Response.json(
{ code: 'CAMERA_REVISION_ACTIVE', message: '原任务仍活动,请保留草稿' },
{ status: 409 }
)
}
adopted = true
if (saved) saved.status = 'stale'
f.directions.beats[0]!.shots[0]!.direction = {
...body.shots[0].draft.direction,
rawJson: JSON.stringify({
cameraRevisionHistory: [
{
reviewer: body.reviewer,
before: { composition: '人物居左', cameraPosition: '门口' },
after: {
composition: body.shots[0].draft.direction.composition,
cameraPosition: body.shots[0].draft.direction.cameraPosition
}
}
]
})
}
return Response.json({
data: {
projectId,
shots: [{ shotId, directionId: 'd', visualStateId: 'v', draftFingerprint: 'd'.repeat(64) }]
}
})
}
if (path.endsWith('/image-authorizations/preview'))
return Response.json({
data: {
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: { projectId, scope: 'keyframe', targetId: shotId, sourceFingerprint: 'f'.repeat(64) },
planFingerprint: 'b'.repeat(64),
authorization: { billingBlocked: true }
}
})
if (path.endsWith('/keyframes')) return Response.json({ data: rows })
if (path.includes('/quality-review'))
return Response.json({
data: {
shotId,
keyframeId: path.includes('/old-failed-image/') ? 'old-failed-image' : 'original-primary',
qualityDecision: path.includes('/old-failed-image/') ? 'failed' : 'passed',
effectiveQualityStatus: adopted
? 'stale'
: path.includes('/old-failed-image/')
? 'failed'
: 'passed',
validationTaskId: null,
historicalGazePreview: [],
manualReview: null,
manualReviewAvailable: false
}
})
if (path.includes('/validations')) return Response.json({ data: [] })
throw new Error('未模拟 ' + path)
})
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(ShotDerivedReview, {
props: { projectId, episodeNo: 1, shot: f.shot, shots: f.shots, disabled: false },
global: { stubs: { teleport: true } }
})
await wrapper.get('button').trigger('click')
await flushPromises()
return { wrapper, fetcher, rows }
}
/**
* 显式点击摄影抽屉中的原动作,不绕开禁用或确认逻辑。
* @param wrapper 真实抽屉
* @param text 当前按钮文字
*/
async function click(wrapper: Awaited<ReturnType<typeof camera>>['wrapper'], text: string) {
const row = wrapper.findAll('button').find(button => button.text() === text)!
expect(row.attributes('disabled')).toBeUndefined()
await row.trigger('click')
await flushPromises()
}
describe('已有失败图片的摄影修订', () => {
it('保存不采用;明确采用后旧failed转当前stale,原Primary/图片/审核和费用仍保留', async () => {
const { wrapper, fetcher, rows } = await camera()
try {
const input = wrapper.findAllComponents(NInput).find(row => row.attributes('aria-label') === '摄影构图')!
input.vm.$emit('update:value', '本次新构图,保持正式主体与原动作')
await flushPromises()
await click(wrapper, '保存草案')
expect(
fetcher.mock.calls.some(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
).toBe(false)
await wrapper
.findAll('.n-collapse-item__header-main')
.find(row => row.text() === '已有图片与质量(只读)')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('质量未通过')
expect(wrapper.findAll('.keyframe-card')).toHaveLength(2)
await click(wrapper, '免费预览摄影草案')
wrapper
.findAllComponents(NInput)
.find(row => row.attributes('aria-label') === '审核人')!
.vm.$emit('update:value', '明确摄影审核人')
wrapper.findAllComponents(NCheckbox).at(-1)!.vm.$emit('update:checked', true)
await flushPromises()
await click(wrapper, '正式采用本镜')
const confirm = fetcher.mock.calls.find(([url]) =>
String(url).endsWith('/storyboard-derived-reviews/confirm')
)!,
body = JSON.parse(String(confirm[1]?.body))
expect(body).not.toHaveProperty('phase')
expect(body.shots[0]).not.toHaveProperty('jointRevision')
expect(body.shots[0].draft.direction).toMatchObject({
composition: '本次新构图,保持正式主体与原动作',
shotSize: 'medium',
cameraAngle: 'eye-level',
cameraMovement: 'static',
lensIntent: 'normal',
depthOfField: 'shallow',
visualIntent: '观察来信'
})
expect(wrapper.text()).toContain('历史审核未通过,当前来源已变化')
expect(wrapper.text()).toContain('草案来源已变化')
expect(wrapper.text()).toContain('主首帧')
expect(wrapper.findAll('.keyframe-card')).toHaveLength(2)
expect(rows[1]!.isPrimary).toBe(true)
expect(
fetcher.mock.calls.some(
([url, init]) => init?.method === 'POST' && /\/keyframe$|\/validate|\/primary/.test(String(url))
)
).toBe(false)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/image-authorizations/preview'))).toBe(true)
} finally {
wrapper.unmount()
}
})
it('活动/来源409重读正式源但保留人工构图,不自动再次采用', async () => {
const { wrapper, fetcher } = await camera(true)
try {
const input = wrapper.findAllComponents(NInput).find(row => row.attributes('aria-label') === '摄影构图')!
input.vm.$emit('update:value', '这份人工构图必须保留')
await flushPromises()
await click(wrapper, '免费预览摄影草案')
wrapper
.findAllComponents(NInput)
.find(row => row.attributes('aria-label') === '审核人')!
.vm.$emit('update:value', '人工审核人')
wrapper.findAllComponents(NCheckbox).at(-1)!.vm.$emit('update:checked', true)
await flushPromises()
await click(wrapper, '正式采用本镜')
expect(input.props('value')).toBe('这份人工构图必须保留')
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm'))
).toHaveLength(1)
expect(wrapper.findAll('button').find(row => row.text() === '正式采用本镜')).toBeUndefined()
} finally {
wrapper.unmount()
}
})
})
@@ -0,0 +1,349 @@
import { defineComponent, h, ref } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useMotionRevision } from '@/features/storyboard/useMotionRevision'
import { motionEvidenceCurrent, type MotionPlan, type MotionRevision } from '@/features/storyboard/motion-revision'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
import { keyframeFixture } from '@/features/production/testing/fixtures'
/** 独立项目避免共享工作流或操作锁互相影响。 */ let serial = 0
/** 释放所有观察器。 */ const wrappers: VueWrapper[] = []
afterEach(() => {
wrappers.splice(0).forEach(wrapper => wrapper.unmount())
localStorage.clear()
})
/**
* 全量隔离原Task、失败根、人工子版本及起点任务,不调用真实模型。
* @param conflict 是否拒绝第一次保存
* @returns 真实编排、公开投影及Mock请求
*/
async function harness(conflict = false) {
const projectId = 'failed-motion-' + ++serial,
shotId = 'failed-motion-shot',
primary = keyframeFixture({ shotId })
const plan: MotionPlan = {
beats: [
{
startSecond: 0,
endSecond: 4,
action: '人物开始向前缓慢行走',
cameraMotion: '保持静止',
physicalContinuity: '双脚支撑保持正常连续',
subjectRefs: ['@CH0001'],
closingState: '人物停在原地保持站立',
performedActionIds: ['actual-action']
}
],
globalMotionConstraints: ['保持正式动作不重复'],
interactions: []
}
const history: {
shotId: string
originalRevisionId: string | null
activeRevisionId: string | null
revisions: MotionRevision[]
} = { shotId, originalRevisionId: null, activeRevisionId: null, revisions: [] }
const candidate = {
taskId: 'failed-task',
executionId: 'failed-workflow',
shotId,
plan: { projectId },
current: true,
status: 'failed',
qualityFailure: { phase: 'motion_plan', issues: ['原起点动作冲突'] },
observations: { motion_plan: plan },
steps: [
{
name: 'motion_plan',
status: 'completed',
providerRequestId: 'original-provider',
usage: { inputTokens: 100 }
}
]
}
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url),
body = init?.body ? JSON.parse(String(init.body)) : undefined
if (path.endsWith('/motion-plan/preview'))
return Response.json({
data: {
shotId,
episodeNo: 1,
beatNo: 1,
shotNo: 1,
durationSeconds: 4,
motionPlanAvailable: false,
beats: [],
globalMotionConstraints: [],
issues: [],
actionDensityIssues: [],
actionReviewSuggestions: [],
savedActionDensityIssues: null,
willCallModel: false,
willModifyAssets: false
}
})
if (path.endsWith('/keyframes')) return Response.json({ data: [primary] })
if (path.endsWith('/video-prompt/executions/failed-task')) return Response.json({ data: candidate })
if (path.endsWith('/revisions/preview'))
return Response.json({
data: {
shotId,
valid: true,
motionPlanFingerprint: 'f'.repeat(64),
schemaIssues: [],
timelineIssues: [],
actionDensityIssues: [],
formalIssues: [],
requiresStartStateValidation: true,
canActivate: false,
willCallModel: false,
willModifyAssets: false,
startStateStatus: 'required_unknown',
sourceFingerprint: 'c'.repeat(64),
previewFingerprint: 'd'.repeat(64),
source: {
projectId,
activeRevisionId: history.activeRevisionId,
primaryKeyframeId: primary.id,
facts: {}
},
startStatePlan: {
version: 1,
primaryKeyframeId: primary.id,
expectedRevisionId: history.activeRevisionId,
motionPlanFingerprint: 'f'.repeat(64),
fingerprint: 'a'.repeat(64),
sourceFingerprint: 'c'.repeat(64),
status: 'ready',
executionAvailable: true,
proposedMaximumProviderRequests: 1,
additionalProviderRequests: 1,
feeEstimate: { currency: 'CNY', amount: null, reason: '未知' }
}
}
})
if (path.endsWith('/revisions') && init?.method === 'POST') {
if (conflict)
return Response.json({ code: 'MOTION_PLAN_PREVIEW_STALE', message: '原来源已变化' }, { status: 409 })
const root: MotionRevision = {
revisionId: 'failed-root',
shotId,
source: 'failed_candidate',
parentRevisionId: null,
reason: JSON.stringify({ originalBusinessStatus: 'failed' }),
candidateOrigin: {
taskId: 'failed-task',
workflowExecutionId: 'failed-workflow',
authorizationId: 'original-grant',
sourceFingerprint: 'c'.repeat(64),
evidenceFingerprint: 'e'.repeat(64),
receiptFingerprint: 'b'.repeat(64),
originalBusinessStatus: 'failed'
},
motionPlan: plan,
durationSeconds: 4,
fingerprint: 'e'.repeat(64),
createdAt: '2026-11-18T00:00:00Z',
isActive: false
}
const manual: MotionRevision = {
...root,
revisionId: 'manual-child',
source: 'manual',
parentRevisionId: root.revisionId,
reason: body.reason,
candidateOrigin: null,
motionPlan: body.motionPlan,
fingerprint: 'f'.repeat(64)
}
history.revisions = [root, manual]
return Response.json({ data: manual }, { status: 201 })
}
if (path.endsWith('/revisions')) return Response.json({ data: history })
if (path.endsWith('/start-state-validation/start'))
return Response.json({
data: { executionId: 'validation-workflow', status: 'completed', willCallModel: false, reused: true }
})
if (path.includes('/workflow-executions/validation-workflow'))
return Response.json({
data: {
id: 'validation-workflow',
projectId,
workflowName: 'motion-plan-start-state-validation',
status: 'completed',
stage: 'completed',
current: 1,
total: 1,
currentResourceId: null,
metadata: { shotId, revisionId: 'manual-child' },
error: null,
startedAt: null,
completedAt: null,
createdAt: '2026-11-18T00:00:00Z',
updatedAt: '2026-11-18T00:00:00Z',
result: {
passed: true,
stale: false,
shotId,
revisionId: 'manual-child',
fingerprint: 'f'.repeat(64),
primaryKeyframeId: primary.id,
primaryKeyframeImageUrl: primary.imageUrl,
expectedRevisionId: null,
validation: { passed: true },
plan: { sourceFingerprint: 'c'.repeat(64), fingerprint: 'a'.repeat(64) }
}
}
})
if (path.endsWith('/active')) {
history.activeRevisionId = 'manual-child'
return Response.json({
data: {
shotId,
activeRevisionId: 'manual-child',
motionPlanFingerprint: 'f'.repeat(64),
changed: true,
videoPromptStale: true
}
})
}
throw new Error('未模拟 ' + path)
})
vi.stubGlobal('fetch', fetcher)
let state!: ReturnType<typeof useMotionRevision>
const wrapper = mount(
defineComponent({
setup() {
state = useMotionRevision({ projectId, shotId }, ref(true), () => {})
return () => h('div')
}
})
)
wrappers.push(wrapper)
await flushPromises()
return { state, history, candidate, fetcher, primary, projectId, shotId }
}
describe('失败动作候选只承接为人工子版本', () => {
it('原Task/Workflow失败保留,预检/保存/起点/采用分别主动执行', async () => {
const { state, fetcher, history, candidate } = await harness()
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
expect(state.requiresCandidate.value).toBe(true)
state.failedTaskId.value = 'failed-task'
await state.readCandidate()
expect(state.draft.value.beats).toHaveLength(0)
state.useCandidate()
state.draft.value.beats[0]!.action = '人工修订为保持当前站姿后缓慢行走'
state.reason.value = '只修订原失败动作,不改变身份与场景'
await state.precheck()
expect(state.preview.value?.startStateStatus).toBe('required_unknown')
expect(state.canSave.value).toBe(false)
state.failedAcknowledged.value = true
await state.save()
await flushPromises()
const save = fetcher.mock.calls.find(
([url, init]) => String(url).endsWith('/revisions') && init?.method === 'POST'
)!
expect(JSON.parse(String(save[1]?.body))).toMatchObject({
parentRevisionId: null,
failedCandidate: {
taskId: 'failed-task',
expectedSourceFingerprint: 'c'.repeat(64),
expectedPreviewFingerprint: 'd'.repeat(64),
acknowledgeFailedCandidate: true
}
})
expect(history.originalRevisionId).toBeNull()
expect(history.activeRevisionId).toBeNull()
expect(history.revisions.map(row => row.source)).toEqual(['failed_candidate', 'manual'])
expect(history.revisions[1]!.parentRevisionId).toBe('failed-root')
expect(state.candidateOrigin.value?.taskId).toBe('failed-task')
const preservedDraft = JSON.stringify(state.draft.value)
state.failedCandidate.value = null
await state.readOriginCandidate()
expect(JSON.stringify(state.draft.value)).toBe(preservedDraft)
expect(state.failedCandidate.value).toMatchObject({ executionId: 'failed-workflow' })
expect(candidate.status).toBe('failed')
expect(
fetcher.mock.calls.some(([url]) => /start-state-validation|\/active$|\/video-prompt$/.test(String(url)))
).toBe(false)
state.acknowledged.value = true
await state.validate()
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/start-state-validation/start'))).toBe(false)
await state.precheck()
state.acknowledged.value = true
await state.validate()
await flushPromises()
const start = fetcher.mock.calls.find(([url]) => String(url).endsWith('/start-state-validation/start'))!
expect(JSON.parse(String(start[1]?.body))).toEqual({
primaryKeyframeId: state.context.data.value!.primary!.id,
expectedRevisionId: null,
expectedPlanFingerprint: 'a'.repeat(64)
})
expect(history.activeRevisionId).toBeNull()
expect(state.canActivate.value).toBe(true)
await state.activate()
expect(history.activeRevisionId).toBe('manual-child')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1)
})
it('来源409保留人工草稿,不产生半个版本或自动重试', async () => {
const { state, fetcher, history } = await harness(true)
state.failedTaskId.value = 'failed-task'
await state.readCandidate()
state.useCandidate()
state.draft.value.beats[0]!.action = '保留这份人工输入等待重新核对来源'
state.reason.value = '只保存'
await state.precheck()
state.failedAcknowledged.value = true
await state.save()
expect(state.draft.value.beats[0]!.action).toBe('保留这份人工输入等待重新核对来源')
expect(state.preview.value).toBeNull()
expect(history.revisions).toHaveLength(0)
expect(
fetcher.mock.calls.filter(([url, init]) => String(url).endsWith('/revisions') && init?.method === 'POST')
).toHaveLength(1)
})
it('即便伪造通过的起点结果,failed_candidate根也不可直接采用', async () => {
const { state, fetcher, primary } = await harness()
state.failedTaskId.value = 'failed-task'
await state.readCandidate()
state.useCandidate()
state.reason.value = '保存测试'
await state.precheck()
state.failedAcknowledged.value = true
await state.save()
const manual = state.revision.value!
const execution: WorkflowExecution = {
stage: null,
current: 0,
total: 0,
currentResourceId: null,
metadata: null,
error: null,
startedAt: null,
completedAt: null,
createdAt: '2026-11-18T00:00:00Z',
updatedAt: '2026-11-18T00:00:00Z',
id: 'e',
projectId: 'p',
workflowName: 'motion-plan-start-state-validation',
status: 'completed',
result: {
passed: true,
stale: false,
validation: { passed: true },
shotId: manual.shotId,
revisionId: manual.revisionId,
fingerprint: manual.fingerprint,
primaryKeyframeId: primary.id,
primaryKeyframeImageUrl: primary.imageUrl,
expectedRevisionId: null
}
}
expect(motionEvidenceCurrent(execution, { ...manual, source: 'failed_candidate' }, primary, null)).toBe(false)
state.select('failed-root')
await state.precheck()
expect(state.canValidate.value).toBe(false)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/active'))).toBe(false)
})
})
@@ -89,7 +89,11 @@ describe('动作修订激活证据', () => {
vi.stubGlobal('fetch', fetcher)
await motionApi.previewRevision('s/1', revision.motionPlan)
await motionApi.saveRevision('s/1', { motionPlan: revision.motionPlan, parentRevisionId: null, reason: null })
await motionApi.validateRevision('s/1', 'r/1', { primaryKeyframeId: primary.id, expectedRevisionId: null })
await motionApi.validateRevision('s/1', 'r/1', {
primaryKeyframeId: primary.id,
expectedRevisionId: null,
expectedPlanFingerprint: 'a'.repeat(64)
})
await motionApi.activateRevision('s/1', 'r/1', { expectedRevisionId: null, validationExecutionId: 'e1' })
const calls = fetcher.mock.calls
expect(calls.map(([url]) => url)).toEqual([
@@ -105,7 +109,8 @@ describe('动作修订激活证据', () => {
})
expect(JSON.parse(String(calls[2]?.[1]?.body))).toEqual({
primaryKeyframeId: primary.id,
expectedRevisionId: null
expectedRevisionId: null,
expectedPlanFingerprint: 'a'.repeat(64)
})
expect(JSON.parse(String(calls[3]?.[1]?.body))).toEqual({
expectedRevisionId: null,
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/lib/http'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '@/features/subject-images/generation-preview'
import { imagePreviewFixture } from '../../fixtures/image-preview'
import { imageAuthorizationsFixture } from '../../fixtures/billing'
/** 仅挂载实际状态逻辑,所有请求均为无费用替身。 */
let wrapper: VueWrapper | undefined
@@ -45,6 +46,93 @@ function setup(
}
describe('生图预览与版本确认', () => {
it('规划来源409清除当前成功状态,保留输入并等待确认,不自动重复生成', async () => {
const { flow, prompt, load, generate } = setup(
vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({
accepted: false,
cause: new ApiError('SCENE_CONTINUITY_REVIEW_STALE: 来源已变化', 409, {
code: 'SCENE_CONTINUITY_REVIEW_STALE'
})
})),
undefined,
'scene-stale-project:shot'
)
prompt.value = '保留这份用户输入'
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(flow.preview.value).toBeNull()
expect(prompt.value).toBe('保留这份用户输入')
expect(flow.canSubmit.value).toBe(false)
expect(flow.staleNotice.value).toContain('衔接规划来源已变化')
expect(generate).toHaveBeenCalledOnce()
expect(load).toHaveBeenCalledOnce()
})
it('停留页面期间批准到期也清除成功预检,不把旧费用准入继续用于生成', async () => {
vi.useFakeTimers()
try {
vi.setSystemTime(new Date('2026-11-18T00:00:00Z'))
const list = imageAuthorizationsFixture(),
open = ref(true),
generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({ accepted: true }))
list.authorizations[0]!.input.expiresAt = new Date(Date.now() + 1000).toISOString()
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async () =>
Response.json({
data: {
provider: 'openai-image',
model: 'gpt-image-2.5-flare',
context: {
projectId: 'expiry-project',
scope: 'keyframe',
targetId: 'expiry-shot',
sourceFingerprint: 'c'.repeat(64)
},
planFingerprint: 'b'.repeat(64),
authorization: list
}
})
)
)
let flow!: ReturnType<typeof useImageGenerationPreview<object, ReturnType<typeof imagePreviewFixture>>>
wrapper = mount(
defineComponent({
setup() {
flow = useImageGenerationPreview({
open,
target: () => 'expiry-project:expiry-shot',
input: () => ({}),
disabled: () => false,
chargeContext: () => ({
projectId: 'expiry-project',
scope: 'keyframe',
targetId: 'expiry-shot',
exactPreview: true
}),
load: async () => ({
...imagePreviewFixture(),
provider: 'openai-image',
model: 'gpt-image-2.5-flare'
}),
generate
})
return () => null
}
})
)
await flow.loadPreview()
expect(flow.canSubmit.value).toBe(true)
await vi.advanceTimersByTimeAsync(1001)
expect(flow.preview.value).toBeNull()
expect(flow.canSubmit.value).toBe(false)
await flow.submit()
expect(generate).not.toHaveBeenCalled()
expect(flow.staleNotice.value).toContain('授权已到期')
} finally {
vi.useRealTimers()
}
})
it('预览成功且确认后才携带版本提交,修改描述立即清除旧确认', async () => {
const { flow, prompt, generate } = setup()
flow.acknowledged.value = true