diff --git a/docs/api-contract-sync.md b/docs/api-contract-sync.md index 141d60b..94ef851 100644 --- a/docs/api-contract-sync.md +++ b/docs/api-contract-sync.md @@ -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记录为准。 diff --git a/docs/audits/v8-10-frontend-integration-2026-11-18.md b/docs/audits/v8-10-frontend-integration-2026-11-18.md new file mode 100644 index 0000000..310a338 --- /dev/null +++ b/docs/audits/v8-10-frontend-integration-2026-11-18.md @@ -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 账本匹配不推断为零费用,也不重编译历史输入。 diff --git a/src/features/image-authorization/BoundedAuthorizationFields.vue b/src/features/image-authorization/BoundedAuthorizationFields.vue new file mode 100644 index 0000000..70a0d6a --- /dev/null +++ b/src/features/image-authorization/BoundedAuthorizationFields.vue @@ -0,0 +1,464 @@ + + diff --git a/src/features/image-authorization/ImageAuthorizationSettings.vue b/src/features/image-authorization/ImageAuthorizationSettings.vue index 4a7ce52..768a476 100644 --- a/src/features/image-authorization/ImageAuthorizationSettings.vue +++ b/src/features/image-authorization/ImageAuthorizationSettings.vue @@ -1,5 +1,6 @@ + diff --git a/src/features/storyboard/components/ShotDerivedReview.vue b/src/features/storyboard/components/ShotDerivedReview.vue index 59aa226..69e6960 100644 --- a/src/features/storyboard/components/ShotDerivedReview.vue +++ b/src/features/storyboard/components/ShotDerivedReview.vue @@ -1,6 +1,11 @@ + + diff --git a/tests/browser/v8-10.ts b/tests/browser/v8-10.ts new file mode 100644 index 0000000..af7bda2 --- /dev/null +++ b/tests/browser/v8-10.ts @@ -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') diff --git a/tests/features/image-authorization/bounded.test.ts b/tests/features/image-authorization/bounded.test.ts new file mode 100644 index 0000000..38a7d23 --- /dev/null +++ b/tests/features/image-authorization/bounded.test.ts @@ -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) { + 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(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() + } + }) +}) diff --git a/tests/features/image-authorization/settings.test.ts b/tests/features/image-authorization/settings.test.ts index 7620f74..2f1ab4b 100644 --- a/tests/features/image-authorization/settings.test.ts +++ b/tests/features/image-authorization/settings.test.ts @@ -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'], diff --git a/tests/features/production/quality.test.ts b/tests/features/production/quality.test.ts index 3db71ce..aa1fb6a 100644 --- a/tests/features/production/quality.test.ts +++ b/tests/features/production/quality.test.ts @@ -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) }) diff --git a/tests/features/production/v8-10-contract.test.ts b/tests/features/production/v8-10-contract.test.ts new file mode 100644 index 0000000..d5abfd0 --- /dev/null +++ b/tests/features/production/v8-10-contract.test.ts @@ -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(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(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(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() + } + }) +}) diff --git a/tests/features/storyboard/camera-candidate.test.ts b/tests/features/storyboard/camera-candidate.test.ts new file mode 100644 index 0000000..011a92f --- /dev/null +++ b/tests/features/storyboard/camera-candidate.test.ts @@ -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(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>['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() + } + }) +}) diff --git a/tests/features/storyboard/failed-motion-candidate.test.ts b/tests/features/storyboard/failed-motion-candidate.test.ts new file mode 100644 index 0000000..e855afa --- /dev/null +++ b/tests/features/storyboard/failed-motion-candidate.test.ts @@ -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(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 + 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) + }) +}) diff --git a/tests/features/storyboard/motion-revision.test.ts b/tests/features/storyboard/motion-revision.test.ts index 46a1b12..8d67c17 100644 --- a/tests/features/storyboard/motion-revision.test.ts +++ b/tests/features/storyboard/motion-revision.test.ts @@ -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, diff --git a/tests/features/subject-images/generation-preview.test.ts b/tests/features/subject-images/generation-preview.test.ts index 11170f1..01a84df 100644 --- a/tests/features/subject-images/generation-preview.test.ts +++ b/tests/features/subject-images/generation-preview.test.ts @@ -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>(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>(async () => ({ accepted: true })) + list.authorizations[0]!.input.expiresAt = new Date(Date.now() + 1000).toISOString() + vi.stubGlobal( + 'fetch', + vi.fn(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>> + 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