feat(short-drama-agent-front): 完善分镜审核与制作准备流程

This commit is contained in:
GJ committed 2026-10-19 21:59:22 +08:00
1 parent c4b43b9725
commit 1da56e0d46
72 files changed
+2801 -528

No files matched your search

+2
View File
@@ -67,6 +67,7 @@
- 错误、校验未通过、需要修复的区域使用柔和浅红背景,深色主题使用对应柔和深红底面。禁止使用上下两条绿色横线表示错误或待修复状态,也不能借用绿色选中态来标记错误。 - 错误、校验未通过、需要修复的区域使用柔和浅红背景,深色主题使用对应柔和深红底面。禁止使用上下两条绿色横线表示错误或待修复状态,也不能借用绿色选中态来标记错误。
- 错误入口按钮的文字、图标和焦点提示与红色底面保持一致;默认、悬停、按下、聚焦各状态都不能被主题主色覆盖成绿色。保留清晰的键盘焦点提示。 - 错误入口按钮的文字、图标和焦点提示与红色底面保持一致;默认、悬停、按下、聚焦各状态都不能被主题主色覆盖成绿色。保留清晰的键盘焦点提示。
- 只有执行完成且结果明确通过校验时,成功任务区域才使用柔和浅绿背景。执行结束但校验失败、质量待审或结果未确认时,不能显示成绿色成功状态,也不能用满格绿色进度条暗示业务成功。 - 只有执行完成且结果明确通过校验时,成功任务区域才使用柔和浅绿背景。执行结束但校验失败、质量待审或结果未确认时,不能显示成绿色成功状态,也不能用满格绿色进度条暗示业务成功。
- 卡片内的定位、复查、修订和历史入口使用带图标、独立中性底面的按钮,不添加边框,不能与说明文字混在一起;复用 `workspace-action-button` / `workspace-action-group`,不把辅助操作改成绿色主按钮。
- 工具栏中相邻按钮保持一致的高度、内边距、图标大小和间距。问题入口使用图标加文字;分镜结构校验失败时文案为“分镜校验未通过”,其他问题按真实类型命名。 - 工具栏中相邻按钮保持一致的高度、内边距、图标大小和间距。问题入口使用图标加文字;分镜结构校验失败时文案为“分镜校验未通过”,其他问题按真实类型命名。
- 移动端的工具栏操作优先只显示图标,保留完整的 `aria-label`、提示文本和足够点击区域;普通表单的底部关闭、取消、提交按钮仍保留文字。 - 移动端的工具栏操作优先只显示图标,保留完整的 `aria-label`、提示文本和足够点击区域;普通表单的底部关闭、取消、提交按钮仍保留文字。
- 页面左侧汇总状态在运行、成功、失败等状态下均有意义,应保留;右侧操作入口负责打开对应处理界面,避免把状态展示和操作混成重复文案。 - 页面左侧汇总状态在运行、成功、失败等状态下均有意义,应保留;右侧操作入口负责打开对应处理界面,避免把状态展示和操作混成重复文案。
@@ -74,6 +75,7 @@
### 设置、问题处理与任务进度 ### 设置、问题处理与任务进度
- 拆解设置与问题处理分开:设置界面负责模块选择、分组预览、启动拆解、候选确认与提交;问题界面负责错误查看、分镜定位、人工修订、读取修复清单及阶段恢复。 - 拆解设置与问题处理分开:设置界面负责模块选择、分组预览、启动拆解、候选确认与提交;问题界面负责错误查看、分镜定位、人工修订、读取修复清单及阶段恢复。
- 质量规则确认以服务端 revision、fingerprint、confirmed 和独立 confirm 接口为准,不能用 LocalStorage 或格式版本 policy.version 代替。规则保存携带 expectedRevision,拆解启动携带本次已确认修订;候选提交预检查必须包含 qualityPolicyMatches。
- 首次拆解前只确认表现方式、动作许可和自定义规则,不显示精确动作例外的空白编辑行。已有例外可只读核对,隐藏输入不能清空已有规则或在保存时覆盖后来新增的例外。 - 首次拆解前只确认表现方式、动作许可和自定义规则,不显示精确动作例外的空白编辑行。已有例外可只读核对,隐藏输入不能清空已有规则或在保存时覆盖后来新增的例外。
- 新增精确动作例外统一放在拆解后的问题修订中,从当前版本的真实冲突证据自动带入角色、部位或物品及动作,用户填写允许原因。证据缺失时不能猜测或用其他镜头代替;按后端实际范围说明影响,保存例外不能直接标记质量通过。 - 新增精确动作例外统一放在拆解后的问题修订中,从当前版本的真实冲突证据自动带入角色、部位或物品及动作,用户填写允许原因。证据缺失时不能猜测或用其他镜头代替;按后端实际范围说明影响,保存例外不能直接标记质量通过。
- 不在拆解设置中重复堆放详细错误列表和修复说明;问题按剧集、节拍、镜头分组并去重,保留后端原始问题及可定位位置。 - 不在拆解设置中重复堆放详细错误列表和修复说明;问题按剧集、节拍、镜头分组并去重,保留后端原始问题及可定位位置。
+48
View File
@@ -1,5 +1,53 @@
# 接口数据同步说明 # 接口数据同步说明
## 2026-10-19 导航修复复核与配置冲突同步
后端基线 `dev@6a6fd52d`,前端根目录 dev;保留已有未提交工作,不修改后端、不提交或推送。
- Chrome 真实读取“掩耳盗铃”:导航 `script/breakdown/storyboard.ready=true`,`visualStyle/identity/subjectAssets.ready=false`;制作入口 `ready=true`、`storyboardValid=true`,正式镜头/镜头设计/画面状态均为 61。视觉风格入口已解锁,后续入口按实际准备情况受限;原导航不一致已解决,不需要前端覆盖阶段接口。
- 计划继续 POST,只发送后端解析的 `imageProvider/imageGenerationOptions/videoProvider`。执行范围及视频生成参数保留在最终启动快照和 POST start 中,不能把未解析的参数描述成已通过计划预检。
- 沿用已有配置阻断联合类型与空阶段保护;补充明确的缺配置状态及“前往项目配置”,复用项目标题栏已有全屏抽屉,保存后仍需重新检查,不自动创建配置或启动生成。
- 配置 409 同时识别顶层 code 和真实 details.code。画幅需重新核对、活动任务、模型参数变更受限使用易懂中文和统一 NMessage,保留草稿、原始错误和已保存配置,不自动重试、清理素材或重新生成;成功保存也不再留下重复常驻提示。
- 制作计划人工阻断数按独立准备问题说明,各阶段影响数量不能直接相加。模型目录、智能时长 specialValues、项目画布与参考图尺寸的独立关系保持既有实现,不按模型品牌硬编码或覆盖正式镜头时长。
本轮 70 个测试文件、541 项测试通过;静态检查、类型检查、生产构建及差异检查通过。沿用本会话既有约定,未执行格式化或格式检查。真实接口只读验证;缺配置、正常计划和配置冲突在本地 Chrome 临时隔离页面验证,所有请求在页面内模拟,不回退到真实网络。440×956 窄屏核对恢复入口换行和固定底栏;临时页面已删除,恢复真实项目桌面页面。
接口核对范围、改动文件及仍需后端处理的既有诊断列表问题见 `frontend-contract-audit-2026-10-19.md`。
## 2026-10-19 正式分镜审核与制作前准备
以同级后端 `dev@82756627` 的实际路由、Schema、事务及服务回执为准;先接功能,再调整诊断卡片布局;项目配置同步补图标。本轮保留此前未提交更新,只修改前端根目录 dev。
- 项目顶部统一新增“制作前检查”,在后续页面尚未开放时也可操作:当前项目质量规则确认 → 历史正式分镜规则来源确认 → 正式问题修订 → 整体人工审核 → 镜头设计/画面状态补齐或更新 → 制作入口复检。
- 对接正式质量复检 `storyboard-quality-recheck`、历史规则来源 `storyboard-review-baseline/preview|confirm`、整体审核 `storyboard/quality-confirmation` GET/POST 以及 `production/entry-readiness`。只读复检的 canConfirm=false 不代替显式审核;preflightEligible 也不独立放行。实际审核同时绑定项目、Checkpoint、规则修订/指纹及正式 Shot 数量/内容;确认前重读,变化后要求重新核对,不自动替用户确认新版本。
- 正式动作读取、确定性关联建议、付费语义候选及保存使用 `storyboard-shot-repair/preview/:shotId|candidate` 与 `storyboard-shot-repair`。保存真实指纹、完整动作与阶段;已有手部和通用资源证据、持续对象及释放/交接字段保留。模型建议不等同于已保存;保存成功后仍需重新复检和整体审核。
- 主体遗漏通过正式坐标 locate 定位;剧情段落主体与镜头主体分别使用其预览/确认接口及各自内容版本。段落写入不自动继续镜头写入,不用候选 Checkpoint 修复替代正式数据修订。
- 旧手部诊断、建议与修订历史路径迁移到 action-resource 与 storyboard-shot-revision-history。列表优先展示 resourceAudit,同时保留旧 handAudit 的含义边界;正式修订历史与诊断历史均按需读取。诊断关闭动画完成后才打开正式修订抽屉。
- 制作计划读取前先核对 entry-readiness,未满足时不再发 production/plan。覆盖率完整仍需逐集核对 staleCount;过期、缺失或未明确返回新旧版本状态都暂停进入计划。计划启动时沿用原有再次预检、参数变化撤销确认及任务互斥。
- 制作计划区分 `configuration.status=ready` 与 `blocked / CREATIVE_PROFILE_REQUIRED`。配置缺失时显示保存项目配置的中文提示,既不读取空阶段/明细,也不允许启动;独立配置查询后发生变化的情况同样阻断。模型时长选项继续读取真实模型元数据,不硬编码智能时长默认值。
- 镜头设计与画面状态页面接入当前整体审核,不能只凭已有数量启用生成;费用确认后再次核对审核来源。真实后台任务继续使用既有 WorkflowExecution,不自动重跑 Breakdown、不自动调用模型。
- 诊断卡片定位、复查、修订与历史入口改为图标加中性独立底面的无边框按钮。窄屏只显示图标,保留完整名称与提示;保存和生成才使用绿色主操作。长表单固定底栏、移除操作使用图标,规则/原因校验不在打开时立即显示。
验证:69 个测试文件、529 项测试、静态检查、类型检查、生产构建及差异检查通过。按既有约定未执行格式化或格式检查。本地 Chrome 复用 `localhost:4312`,验证真实制作前检查与有效审核、只读正式动作编辑、桌面及 440×956 窄屏操作图标、无边框入口与固定底栏;最终恢复桌面页面。人工确认、修订写入及收费模型分支仅在隔离测试中验证,未改写真实项目或调用收费模型。
历史记录:本节验收时导航尚存在旧待审标记问题;后续已由后端 `6a6fd52d` 修复并重新核对,见本文件顶部记录及 `backend-production-navigation-follow-up.md`。
## 2026-10-18 质量规则确认与诊断更新
核对同级后端 `dev@2b079bd1` 的公开文档、正式路由、质量规则事务、诊断预检查、结果汇总、修订资格及恢复服务。本次只修改前端根目录 `dev`。
- 质量规则 GET 保留服务端 `revision/fingerprint/confirmed/confirmedRevision/confirmedAt`;PUT 使用 `{ policy, expectedRevision }`;用户明确勾选后调用独立 Confirm。删除本地浏览器确认依据,跨浏览器已确认且规则未变时跳过规则表单,仍保留每次模型调用的费用确认。
- 确认前及最终启动前重新读取同项目规则;实际启动携带 `expectedRevision`,零版本有效。取消、切换项目或预览、活动锁与迟到响应不能生成启动许可;真正保存或确认期间锁定关闭。服务返回版本冲突时不自动重试写入。
- 全局规则保存与问题中的动作例外追加均重读最新规则,并携带其真实 revision;例外完整保留。普通保存不伪造明确确认。候选提交安全检查新增 `qualityPolicyMatches`,缺失或 false 均不放行。
- 单镜头诊断预览接入正式 `diagnosis-preflight/:shotId`;费用确认后再次核对预检查和镜头摘要,来源、规则或内容改变时撤销启动。可复用的有效历史诊断不重复调用模型。
- 动作诊断使用全屏 AppDrawer,正文独立滚动、固定灰色关闭按钮;版本过期、手部免费检查、证据覆盖率、全身动作疑点和 AI 待复查分别展示,不将“已修订”或局部无冲突描述为全部通过。未诊断长列表仍按需查看。
- 指定镜头的诊断历史与修订资格按需读取,返回项目/镜头/诊断归属不一致时不展示为有效资格。没有提供当前完整动作规划时不从模型建议或旧保存记录构造可写表单;补充接口需求见 `backend-diagnosis-follow-up.md`。
- 诊断任务的服务中断摘要直接展示可复用/待核查数量及费用未知提示,不自动重新提交;诊断执行结束不再使用素材生成成功文案或满格绿色进度条。
验证:66 个测试文件、516 项测试通过;类型检查、静态检查、生产构建及差异检查通过。沿用既有约定未运行格式化或格式检查。Chrome 复用已有 `localhost:4312` 标签页,对真实本地服务验证首次规则确认、取消保留预览、单镜头规则记录不完整时禁用启动、按需历史读取,以及 440×956 窄屏固定底栏;模型执行、规则保存/确认及修订写入只使用测试隔离验证,未对真实用户数据执行写请求或收费模型调用。界面恢复到桌面视口。
## 2026-10-17 拆解任务发现与过程展示 ## 2026-10-17 拆解任务发现与过程展示
- 项目布局通过 `GET /projects/:projectId/workflow-executions/latest?workflowName=breakdown` 发现服务端最新拆解任务,并通过同项目 `workflow-executions/events` 订阅任务变化。后端发起的新任务不再依赖当前浏览器保存过启动回执;没有任务时明确返回 null。 - 项目布局通过 `GET /projects/:projectId/workflow-executions/latest?workflowName=breakdown` 发现服务端最新拆解任务,并通过同项目 `workflow-executions/events` 订阅任务变化。后端发起的新任务不再依赖当前浏览器保存过启动回执;没有任务时明确返回 null。
+30
View File
@@ -0,0 +1,30 @@
# 分镜诊断修订:对接缺口与处理记录
2026-10-19 更新:下文第 1 项已由正式 `storyboard-shot-repair/preview/:shotId` 补齐当前动作数据,并已在前端接入普通人工修订、确定性候选和收费模型候选;请勿重复开发。主体遗漏也已分别接入剧情段落与镜头的预览/确认。第 2 项仍需核对新格式手部具体问题的列表返回,原始证据可通过历史查看。以下保留当时的需求与验收边界。
请基于当前 `short-drama-agent` 的正式接口完成以下补充。前端已接入质量规则 GET/PUT/Confirm、拆解 expectedRevision、诊断 Preflight、诊断及修订状态、历史、修订资格和中断核查摘要;当前没有开放正式手部修订保存按钮。
## 1. 提供带版本的正式镜头动作编辑数据
现有 `storyboard-legacy-action-repair-readiness/:shotId/:diagnosisId` 只返回候选位置、动作编号、建议和 `expectedFingerprint`,未返回正式 Shot 当前的完整 `requiredActions`、`subjectRefs`、`durationPlanning`。`storyboard-legacy-action-diagnosis-preview` 明确只给摘要;诊断历史也不是正式镜头原始动作。前端不能使用模型建议、旧 Checkpoint 或过期快照猜测可写草稿。
请扩展既有只读资格接口,或提供一个正式只读编辑数据接口,返回同一次读取的:
- projectId、shotId、episodeNo、beatNo、shotNo、title、当前 durationSeconds;
- 与当前正式镜头一致的 requiredActions、subjectRefs、完整 durationPlanning;
- expectedFingerprint,以及诊断与规则修订/指纹绑定信息;
- 真实 eligible、blockingReasons,保留既有生产资产保护、来源链、活动任务和确定性冲突检查。
字段名称及最终路由由你结合现有结构确定并写入公开 API 文档,不要为前端直接开放任意原始数据库对象。GET 不调用模型、不写入或自动修复。
前端随后只编辑现有 POST schema 允许的 durationPlanning,提交 `{ shotId, diagnosisId, expectedFingerprint, confirmed: true, reason, durationPlanning }`,不上传修改后的 requiredActions 或 resourceOccupancy 等未许可字段。POST 继续使用现有事务,保存前重新检查版本、规则、诊断归属、来源链及资产锁,不新增绕过门禁的写入路径。
## 2. 核对诊断列表的手部问题结构
当前 `storyboard-legacy-action-diagnosis-persistence.service.save` 将 issuesJson 保存为 `{ handConflicts, bodyMotionFindings, qualityCodes }`,而 results.list 的 `issues` 只有在 issuesJson 本身是数组时才返回,导致新格式的手部具体问题在列表中成为空数组;bodyMotionFindings 另行返回。
请保留旧数组兼容,明确将新结构的手部问题以稳定字段返回,并记录质量代码、全身疑点各自的公开结构。镜头或规则过期时仍清空当前有效问题,不能把历史证据伪装成当前冲突。
## 验收
补充接口契约、跨项目/跨镜头 404、过期诊断/规则/镜头 409、已有资产或运行任务阻断、读取后到保存前并发变化、修订成功后保留历史及 AI 待复查的回归测试。验证不得调用真实收费模型、覆盖现有用户镜头或伪造质量通过。
@@ -0,0 +1,25 @@
# 制作前审核与导航状态同步(已修复)
2026-10-19 复核:后端 `dev@6a6fd52d` 已修复。真实项目的导航 `breakdown.ready=true`,制作入口 `ready=true`、`storyboardValid=true`;视觉风格、身份和主体素材仍分别未就绪,限制符合实际条件。本文件原提示词仅保留为历史记录,不要再次按旧问题开发。
原请求:请在 `short-drama-agent` 当前 dev 中修复下面的状态不一致。前端已接入正式质量复检、规则来源确认、整体人工审核、正式镜头修订、设计补齐及制作入口检查,不需要重复新增这些接口。
## 修复前的真实只读复现(历史)
2026-10-19,本地 Chrome 通过 `localhost:4312` 的 `/api` 代理读取项目 `cmv9eqf6v0000k6idvk1y3256`(掩耳盗铃):
- `GET /projects/:projectId/production/entry-readiness` 返回 `ready=true`、`storyboardValid=true`,正式镜头 61、镜头设计 61、画面状态 61,两项覆盖率均为 1。前端制作前检查也读到当前有效的人工审核记录。
- 同项目 `GET /projects/:projectId/stage-readiness` 的 `breakdown.ready=false`,原因为“Storyboard 结构校验可能已通过,但仍有未完成的人工质量审核;请核对当前审核证据”。因此导航中的视觉风格及后续步骤仍被锁定。
- 该项目视觉风格、身份及主体素材也有各自未完成条件;同步拆解审核状态后,仍须保留这些独立限制,不能一并放行所有制作阶段。
## 原修复要求(已完成)
当前 `project-stage-readiness.service.ts` 调用 `breakdown-storyboard-validation.service.ts`;后者只读取最新拆解保存记录中的 `storyboardShotValidation` 和 `storyboardNeedsManualReview`,未复用当前正式审核的有效性。
请将导航的拆解质量判断与当前正式分镜审核服务统一:核对真实结构、来源、规则修订及内容版本,只有当前有效审核才解除待审核限制。旧保存记录的人工待审标记不应继续盖过已经有效的当前审核;也不能仅因存在一条历史审核记录就放行。规则或正式镜头变化后,导航应与整体审核同步失效。
不要直接把 `production/entry-readiness.ready` 作为导航中拆解完成的唯一条件,因为制作入口还要求镜头设计和画面状态,可能反向锁住完成这些步骤所需的入口。保留剧本、视觉风格、身份、主体图片和镜头生成方案各自的真实条件,不修改历史保存记录来伪造通过,也不要求前端绕过导航接口。
## 验收
补充回归:当前审核有效但旧记录仍待审、无审核、旧审核内容版本不符、规则变化、正式镜头变化、结构失败、来源不一致,以及其他素材尚未就绪。针对同一项目核对导航与制作入口的原因在业务上自洽,并更新公开文档。验证不得启动真实收费模型、覆盖正式数据或替用户作出人工审核。
@@ -0,0 +1,78 @@
# 前后端接口复核记录
基线:前端当前 dev(HEAD `c4b43b9`,包含此前未提交工作),只读核对后端 dev `6a6fd52d`。本轮没有提交、push 或修改后端。
## 真实导航与制作入口
本地 Chrome 复用 `localhost:4312`,读取项目“掩耳盗铃”(`cmv9eqf6v0000k6idvk1y3256`):
| 检查 | 当前结果 | 页面含义 |
| --- | --- | --- |
| 导航 script | ready=true | 剧本已完成 |
| 导航 breakdown | ready=true | 当前正式分镜审核有效,视觉风格入口开放 |
| 导航 visualStyle / identity / subjectAssets | ready=false | 分别仍需准备,不会因拆解通过而自动解锁全部步骤 |
| 导航 storyboard | ready=true | 镜头生成方案符合此阶段的条件,不等同于视频已生成 |
| 制作 entry-readiness | ready=true、storyboardValid=true | 分镜准入通过,镜头设计和画面状态覆盖完整 |
| 正式镜头 / 镜头设计 / 画面状态 | 61 / 61 / 61 | 数量覆盖完整;前端仍单独核对 staleCount |
旧导航待审问题已解决。前端继续只使用 stage-readiness 决定导航,不从旧 Checkpoint 或任务 completed 状态推导审核结论。无需为了本次后端修复新增导航接口或重复审核状态。
## 修复的真实问题
1. 计划请求曾夹带启动阶段、生成上限和视频参数。计划只解析三项模型参数,现由 API 层按真实字段构造 POST body;实际启动仍携带完整参数并再次预检。
2. 缺少项目配置已有空值保护,但缺少就地恢复操作。现在保留独立业务状态,在计划位置打开已有项目配置抽屉;配置读取后消失的竞态同样阻断,不读取空统计、不启动。
3. 配置冲突仅显示原始说明且留在正文。现在识别实际 details.code 与顶层 code,将三类 409 转成中文 NMessage 警告,保留草稿、不发布保存成功、不重试写入;普通失败保持错误级别。保存成功不再遗留常驻成功说明。
4. 计划的 manualBlocked 是独立人工根因数量,原说明把它描述成各阶段累加。现明确独立计数及阶段影响数量可能重叠。
## 原本正确并保留的契约
以 API 模块对照后端实际路由及挂载顺序:盘点 162 处 request 调用,153 处直接匹配;其余 9 处为动态 action、媒介类型、资产路径及可选查询,逐一展开核对,未发现新增方法或路径错误。另核对任务发现 SSE 路径。
| 模块 | 核对要点与结论 |
| --- | --- |
| 项目创建、编辑、阶段 | POST /projects、PUT /projects/:id、GET stage-readiness 正确;未完成阶段保持独立限制。未改写用户当前其他编辑页改动 |
| 拆解与正式审核 | candidate 与正式数据分开;规则保存/确认、正式质量复检、人工审核、版本保护沿用当前接口,不用执行完成替代审核 |
| Direction / VisualState | 按集读取、项目生成 start、202 句柄及 staleCount 正确;不只看覆盖数量 |
| Creative Profile | GET 可为 null、PUT 完整配置正确;本轮只补冲突反馈和恢复操作 |
| 模型目录 | GET generation-models、schema/options/defaults/specialValues 驱动;-1 不按品牌补造。项目画布与参考图尺寸独立;不把默认时长写入正式镜头 |
| Production | POST plan、POST start、GET status 正确;已有 blocked 联合类型保留,正常计划组件只接收非空阶段 |
| 主体图片 | 预览、生成、批量 start、切主图及模块范围保持正式接口,不混用素材和任务回执 |
| 首帧 | 预览、质量任务、候选编辑、版本权限沿用现有独立流程,不默认晋升或把旧通过当当前许可 |
| 视频提示词、视频生成 | 读取和生成分开;生成提交参数、异步句柄及任务终态沿用现有实现,不触发真实模型作验收 |
| WorkflowExecution | latest/get/events 的路径、工作流范围和空结果处理正确;202 是观察句柄,不能当资产或审核完成 |
方法/路径盘点不代表对全部收费分支进行了真实执行。请求体、返回空值、变更服务与既有测试重点核对配置、计划、导航、质量审核及长任务;其余接口本轮没有新增差异,不进行无关重构。
## 尚需后端处理的既有问题
诊断列表的新格式手部具体问题仍可能遗漏:`storyboard-legacy-action-diagnosis-persistence.service.ts:78` 保存对象 `{ handConflicts, bodyMotionFindings, qualityCodes }`,`storyboard-legacy-action-diagnosis-results.service.ts:141` 的 issues 仍只接受数组。前端不从其他镜头或历史证据猜测当前冲突。该问题与本次已修复的导航无关;原需求及边界见 `backend-diagnosis-follow-up.md` 第 2 项,正式编辑数据缺口第 1 项此前已解决,不应重复开发。
## 本轮改动文件
| 文件 | 用途 |
| --- | --- |
| src/features/production/api.ts | 计划请求字段限制,保留 POST |
| src/features/production/useAdvancedProduction.ts | 缺少配置的明确业务状态及并发保护 |
| src/features/production/components/AdvancedProduction.vue | 复用配置恢复入口 |
| src/features/production/components/ProductionPlanPanel.vue | 独立人工阻断计数说明 |
| src/features/generation-config/context.ts | 共用现有配置抽屉打开入口 |
| src/features/generation-config/components/CreativeProfileSettings.vue | 保存成功及冲突统一消息,保留草稿 |
| src/features/projects/ProjectLayout.vue | 提供已有抽屉的打开方法 |
| src/lib/http.ts、src/lib/user-facing-text.ts | 保留原始错误,转换配置业务码说明 |
| tests/features/generation-config/profile-settings.test.ts(新增) | 冲突不重试、不成功、不覆盖草稿;成功消息 |
| tests/features/generation-config/options.test.ts、profile-draft.test.ts | 目录智能时长、画布与参考图尺寸独立 |
| tests/features/production/backend-contract.test.ts、capabilities.test.ts | 计划/启动字段边界、缺配置恢复及竞态 |
| tests/features/projects/access.test.ts | 旧待审标记不覆盖当前阶段,下游仍独立受限 |
| tests/lib/user-facing-text.test.ts | 顶层及详情业务码转换 |
| docs/api-contract-sync.md、backend-production-navigation-follow-up.md、本文件 | 当前结果、历史问题关闭和交付记录 |
其余工作区原有修改和新增均保留,未一并提交。
## 验证
- TypeScript、Oxlint/ESLint、生产构建、差异检查通过。
- 全量 70 个文件 / 541 项测试通过。测试阻止未模拟请求连接真实服务。
- 沿用本会话此前约定,未执行格式化或格式检查;未宣称其通过。
- Chrome 真实服务:导航和制作入口当前结果、视觉风格入口解锁;未写配置、审核或触发模型。
- Chrome 临时隔离页面:实际组件的缺配置、正常计划、配置保存成功、配置冲突、440×956 视口换行与固定底栏。所有请求在页面内模拟,禁止回退到真实网络。页面已删除并恢复真实项目桌面。
- 未进行真实收费生成、素材覆盖、审核确认或数据库变更。GitHub 无新增 Commit,本轮只保留在前端 dev 工作区。
+11 -5
View File
@@ -29,7 +29,7 @@ import ActionExceptionRepair from './components/ActionExceptionRepair.vue'
import { useBreakdownQuality } from './useBreakdownQuality' import { useBreakdownQuality } from './useBreakdownQuality'
import { useBreakdownStartPolicy } from './useBreakdownStartPolicy' import { useBreakdownStartPolicy } from './useBreakdownStartPolicy'
import type { DiagnosisLocation } from './diagnosis' import type { DiagnosisLocation } from './diagnosis'
import { errorMessage } from '../../lib/http' import { ApiError, errorMessage } from '../../lib/http'
import { downloadText } from '../../lib/format' import { downloadText } from '../../lib/format'
/** 拆解工作区:先预览真实分组,再启动;恢复操作根据 checkpoint 分阶段展示。 */ /** 拆解工作区:先预览真实分组,再启动;恢复操作根据 checkpoint 分阶段展示。 */
@@ -436,7 +436,9 @@ async function loadPreview() {
async function run(action: BreakdownAction) { async function run(action: BreakdownAction) {
if (project.value?.status !== 'completed' || operation.value.pending || error.value) return if (project.value?.status !== 'completed' || operation.value.pending || error.value) return
if (breakdownBusy.value || backgroundExecution.discovering.value || backgroundExecution.discoveryError.value) return if (breakdownBusy.value || backgroundExecution.discovering.value || backgroundExecution.discoveryError.value) return
if (action === 'start' && (!canStart.value || !startPolicy.consumePermit())) return if (action === 'start' && !canStart.value) return
const permit = action === 'start' ? startPolicy.consumePermit() : null
if (action === 'start' && !permit) return
const labels: Record<BreakdownAction, string> = { const labels: Record<BreakdownAction, string> = {
start: '正在拆解剧本', start: '正在拆解剧本',
retry: '正在重试失败抽取', retry: '正在重试失败抽取',
@@ -444,17 +446,21 @@ async function run(action: BreakdownAction) {
'resume-storyboard': '正在修复分镜绑定' 'resume-storyboard': '正在修复分镜绑定'
} }
const id = project.value.id const id = project.value.id
await runOperation( const success = await runOperation(
id, id,
labels[action], labels[action],
async () => { async () => {
const started = await breakdownApi.run(id, action, action === 'start' ? input.value : undefined) const started = await breakdownApi.run(id, action, action === 'start' ? { ...input.value, ...permit! } : undefined)
await backgroundExecution.track(started.executionId) await backgroundExecution.track(started.executionId)
return started return started
}, },
{ type: 'info', content: '拆解任务已提交,可在“拆解设置”中查看进度。' } { type: 'info', content: '拆解任务已提交,可在“拆解设置”中查看进度。' }
) )
await refresh() await refresh()
const cause = operation.value.cause
if (!success && action === 'start' && id === projectId.value && cause instanceof ApiError &&
['QUALITY_POLICY_NOT_CONFIRMED', 'QUALITY_POLICY_VERSION_CONFLICT'].includes(cause.code ?? ''))
await startPolicy.prepare()
} }
/** 刷新候选和正式阶段状态,不重放候选生成请求。 */ /** 刷新候选和正式阶段状态,不重放候选生成请求。 */
@@ -526,7 +532,7 @@ const rules = {
> >
<!-- 以下是在同一全屏抽屉内核对真实质量规则的模块,不叠加第二个抽屉 --> <!-- 以下是在同一全屏抽屉内核对真实质量规则的模块,不叠加第二个抽屉 -->
<div v-if="startPolicy.reviewOpen.value && startPolicy.policy.value" class="breakdown-policy-review"> <div v-if="startPolicy.reviewOpen.value && startPolicy.policy.value" class="breakdown-policy-review">
<p class="text-sm leading-6 text-muted">请核对动作与物理规则,修改将在继续时保存。当前浏览器会记住确认,规则未变时不再重复提醒。</p> <p class="text-sm leading-6 text-muted">请核对动作与物理规则,修改将在继续时保存。确认会保存到当前项目,规则未变时不再重复提醒。</p>
<QualityPolicySettings <QualityPolicySettings
ref="qualityForm" ref="qualityForm"
:key="startPolicy.editorKey.value" :key="startPolicy.editorKey.value"
+33 -3
View File
@@ -1,3 +1,4 @@
import type { DiagnosisPreflight, DiagnosisHistory, DiagnosisRepairReadiness } from './diagnosis.types'
import { optionalResource, request } from '../../lib/http' import { optionalResource, request } from '../../lib/http'
import type { import type {
BreakdownAction, BreakdownAction,
@@ -23,6 +24,35 @@ import type {
/** Breakdown API;预览为只读查询,启动和恢复返回可持续观察的后台任务。 */ /** Breakdown API;预览为只读查询,启动和恢复返回可持续观察的后台任务。 */
export const breakdownApi = { export const breakdownApi = {
/**
* 只读核对指定正式镜头的诊断来源及可复用记录。
* @param id 项目编号
* @param shotId 正式镜头编号
* @param signal 取消信号
* @returns 不调用模型的检查结果
*/
diagnosisPreflight: (id: string, shotId: string, signal?: AbortSignal) =>
request<DiagnosisPreflight>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnosis-preflight/${encodeURIComponent(shotId)}`, { signal }),
/**
* 查看指定镜头的诊断历史及版本失效情况。
* @param id 项目编号
* @param shotId 正式镜头编号
* @param signal 取消信号
* @returns 最近诊断历史
*/
diagnosisHistory: (id: string, shotId: string, signal?: AbortSignal) =>
request<DiagnosisHistory>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnoses/${encodeURIComponent(shotId)}`, { signal }),
/**
* 核对指定诊断能否进入人工修订,不自动应用建议。
* @param id 项目编号
* @param shotId 正式镜头编号
* @param diagnosisId 真实诊断编号
* @param signal 取消信号
* @returns 候选及资产、来源和版本限制
*/
diagnosisRepairReadiness: (id: string, shotId: string, diagnosisId: string, signal?: AbortSignal) =>
request<DiagnosisRepairReadiness>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-repair-readiness/${encodeURIComponent(shotId)}/${encodeURIComponent(diagnosisId)}`, { signal }),
/** /**
* 只读重新审核当前候选,不提供正式提交许可。 * 只读重新审核当前候选,不提供正式提交许可。
* @param id 当前项目 * @param id 当前项目
@@ -103,17 +133,17 @@ export const breakdownApi = {
}, },
handOccupancyDiagnostics: (id: string, signal?: AbortSignal) => handOccupancyDiagnostics: (id: string, signal?: AbortSignal) =>
request<StoryboardHandOccupancyDiagnostics>( request<StoryboardHandOccupancyDiagnostics>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-hand-occupancy-diagnostics`, `/projects/${encodeURIComponent(id)}/breakdown/storyboard-action-resource-diagnostics`,
{ signal } { signal }
), ),
handRepairPreview: (id: string, signal?: AbortSignal) => handRepairPreview: (id: string, signal?: AbortSignal) =>
request<StoryboardHandRepairPreview>( request<StoryboardHandRepairPreview>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-hand-occupancy-repair-preview`, `/projects/${encodeURIComponent(id)}/breakdown/storyboard-action-resource-repair-preview`,
{ signal } { signal }
), ),
handRepairHistory: (id: string, shotId: string, signal?: AbortSignal) => handRepairHistory: (id: string, shotId: string, signal?: AbortSignal) =>
request<StoryboardHandRepairHistory>( request<StoryboardHandRepairHistory>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-hand-occupancy-repair-history/${encodeURIComponent(shotId)}`, `/projects/${encodeURIComponent(id)}/breakdown/storyboard-shot-revision-history/${encodeURIComponent(shotId)}`,
{ signal } { signal }
), ),
legacyActionDiagnosisPreview: (id: string, episodeNo: number, beatNo?: number, shotNo?: number) => { legacyActionDiagnosisPreview: (id: string, episodeNo: number, beatNo?: number, shotNo?: number) => {
+2 -1
View File
@@ -3,6 +3,7 @@ import type { CandidateCommitPreview } from './candidate.types'
/** 安全检查项与用户可理解的阻断原因共用一份映射。 */ /** 安全检查项与用户可理解的阻断原因共用一份映射。 */
export const candidateCheckLabels: Record<keyof CandidateCommitPreview['checks'], string> = { export const candidateCheckLabels: Record<keyof CandidateCommitPreview['checks'], string> = {
qualityPolicyMatches: '质量规则与当前已确认版本一致',
episodeNumbersMatch: '剧集范围与候选一致', episodeNumbersMatch: '剧集范围与候选一致',
episodeFingerprintsMatch: '剧本正文版本未变化', episodeFingerprintsMatch: '剧本正文版本未变化',
noActiveExecutions: '没有正在执行的制作任务', noActiveExecutions: '没有正在执行的制作任务',
@@ -12,7 +13,7 @@ export const candidateCheckLabels: Record<keyof CandidateCommitPreview['checks']
noProtectedShots: '没有需要保护的镜头资产' noProtectedShots: '没有需要保护的镜头资产'
} }
/** 必须逐项校验的固定安全门禁,不根据响应动态减少检查项。 */ /** 必须逐项校验的固定安全门禁,不根据响应动态减少检查项。 */
export const candidateCheckKeys = ['episodeNumbersMatch', 'episodeFingerprintsMatch', 'noActiveExecutions', 'noActiveVideos', 'noSubjectIdentities', 'noSubjectImages', 'noProtectedShots'] as const export const candidateCheckKeys = ['qualityPolicyMatches', 'episodeNumbersMatch', 'episodeFingerprintsMatch', 'noActiveExecutions', 'noActiveVideos', 'noSubjectIdentities', 'noSubjectImages', 'noProtectedShots'] as const
/** /**
* 安全预检查必须逐项通过且属于当前项目和候选,不能只相信 ready。 * 安全预检查必须逐项通过且属于当前项目和候选,不能只相信 ready。
@@ -120,6 +120,8 @@ export interface CandidateCommitPreview {
ready: boolean ready: boolean
/** 剧本版本、活动任务及下游资产保护。 */ /** 剧本版本、活动任务及下游资产保护。 */
checks: { checks: {
/** 候选使用的质量规则与当前明确确认版本一致。 */
qualityPolicyMatches: boolean
/** 剧集编号一致。 */ /** 剧集编号一致。 */
episodeNumbersMatch: boolean episodeNumbersMatch: boolean
/** 剧本正文指纹一致。 */ /** 剧本正文指纹一致。 */
@@ -6,7 +6,7 @@ import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHead
import QualityPolicyExceptions from '../../generation-config/components/QualityPolicyExceptions.vue' import QualityPolicyExceptions from '../../generation-config/components/QualityPolicyExceptions.vue'
import { projectsApi } from '../../projects/api' import { projectsApi } from '../../projects/api'
import { actionResourceOptions, policyDraft } from '../../projects/quality-policy' import { actionResourceOptions, policyDraft } from '../../projects/quality-policy'
import { invalidateQualityPolicyConfirmation, qualityPolicySignature } from '../../projects/quality-policy-confirmation' import { validateQualityPolicyReceipt, qualityPolicySignature } from '../../projects/quality-policy-confirmation'
import type { ProjectQualityPolicyResult } from '../../projects/types' import type { ProjectQualityPolicyResult } from '../../projects/types'
import { getOperation, runOperation } from '../../workflows/operations' import { getOperation, runOperation } from '../../workflows/operations'
import { actionExceptionTargets, type ActionExceptionTarget } from '../action-exceptions' import { actionExceptionTargets, type ActionExceptionTarget } from '../action-exceptions'
@@ -71,9 +71,8 @@ let controller: AbortController | undefined
*/ */
async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> { async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> {
const result = await projectsApi.qualityPolicy(id, signal) const result = await projectsApi.qualityPolicy(id, signal)
if (result.projectId !== id) throw new Error('规则所属项目不一致,请重新读取。') validateQualityPolicyReceipt(result, id)
qualityPolicySignature(result.policy) return { ...result, policy: policyDraft(result.policy) }
return { projectId: id, policy: policyDraft(result.policy) }
} }
/** 按需读取已有规则;无真实拆解结果时不创建例外。 */ /** 按需读取已有规则;无真实拆解结果时不创建例外。 */
@@ -152,11 +151,11 @@ async function save() {
const signature = qualityPolicySignature(input) const signature = qualityPolicySignature(input)
writing.value = true writing.value = true
const success = await runOperation(id, '正在保存动作例外', async () => { const success = await runOperation(id, '正在保存动作例外', async () => {
const result = await projectsApi.saveQualityPolicy(id, input) const result = await projectsApi.saveQualityPolicy(id, input, latest.revision)
invalidateQualityPolicyConfirmation(id) validateQualityPolicyReceipt(result, id)
if (result.projectId !== id || qualityPolicySignature(result.policy) !== signature) if (result.projectId !== id || qualityPolicySignature(result.policy) !== signature)
throw new Error('规则保存回执与提交内容不一致,请重新读取确认。') throw new Error('规则保存回执与提交内容不一致,请重新读取确认。')
if (version === generation) receipt.value = { projectId: id, policy: policyDraft(result.policy) } if (version === generation) receipt.value = { ...result, policy: policyDraft(result.policy) }
}, { type: 'info', content: '动作例外已保存,当前分镜仍需审核,不会自动放行提交。' }) }, { type: 'info', content: '动作例外已保存,当前分镜仍需审核,不会自动放行提交。' })
if (version !== generation) return if (version !== generation) return
if (success) { if (success) {
@@ -0,0 +1,120 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import { RefreshCw, History } from '@lucide/vue'
import { preparationApi } from '../../storyboard-preparation/api'
import type { StoryboardHandRepairHistory } from '../types'
import { breakdownApi } from '../api'
import { diagnosisReason, diagnosisStatusLabels } from '../diagnosis'
import type { DiagnosisHistory, DiagnosisRepairReadiness } from '../diagnosis.types'
import type { LegacyActionDiagnosisResults } from '../types'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { errorMessage } from '../../../lib/http'
import { userFacingText } from '../../../lib/user-facing-text'
import { formatDate } from '../../../lib/format'
/** 单镜头按需核对修订条件和历史,不从诊断建议拼装可写草稿。 */
const props = defineProps<{
/** 所属正式项目。 */
projectId: string
/** 当前列表记录,切换版本后旧请求失效。 */
shot: LegacyActionDiagnosisResults['shots'][number]
}>()
/** 默认收起,避免对全项目每个镜头预先发起请求。 */
const expanded = ref<string[]>([])
/** 明确的按钮控制 Naive 折叠,折叠标题不再伪装成卡片操作。 */
const showDetails = computed(() => expanded.value.includes('review'))
/** 当前真实诊断历史。 */
const history = ref<DiagnosisHistory | null>(null)
/** 正式动作和主体修订共用的不可变记录。 */
const revisions = ref<StoryboardHandRepairHistory | null>(null)
/** 当前诊断对应的修订资格。 */
const readiness = ref<DiagnosisRepairReadiness | null>(null)
/** 当前列表与资格必须同时有效,不能把旧诊断或直接应用标记解释成修订许可。 */
const repairEligible = computed(() => readiness.value?.eligible === true && readiness.value.requiresManualReview === true &&
readiness.value.canApplyDirectly === false && readiness.value.willCallModel === false && readiness.value.willModifyAssets === false &&
props.shot.status === 'conflict_found' && props.shot.policyStatus === 'current' && props.shot.shotStale === false)
/** 只读请求加载,始终允许关闭主窗口。 */
const loading = ref(false)
/** 保留可重试的查询错误。 */
const error = ref('')
/** 同镜头诊断和版本状态组成请求身份。 */
const target = computed(() => JSON.stringify([props.projectId, props.shot.shotId, props.shot.diagnosisId, props.shot.policyStatus, props.shot.shotStale, props.shot.latestRepairId]))
/** 请求代次用于拦截迟到结果。 */
let version = 0
/** 只读请求关闭时取消。 */
let controller: AbortController | undefined
/** 读取指定镜头历史与对应诊断资格,始终验证返回归属。 */
async function load() {
if (loading.value) return
const current = ++version
const id = props.projectId, shotId = props.shot.shotId, diagnosisId = props.shot.diagnosisId
controller?.abort(); controller = new AbortController()
loading.value = true; error.value = ''
try {
const [records, checked, changes] = await Promise.all([
breakdownApi.diagnosisHistory(id, shotId, controller.signal),
diagnosisId ? breakdownApi.diagnosisRepairReadiness(id, shotId, diagnosisId, controller.signal) : Promise.resolve(null),
preparationApi.revisions(id, shotId, controller.signal)
])
if (current !== version) return
if (changes.projectId !== id || changes.shotId !== shotId || !Array.isArray(changes.revisions) || records.projectId !== id || records.shotId !== shotId || !Array.isArray(records.revisions) ||
checked && (checked.projectId !== id || checked.shotId !== shotId || checked.diagnosisId !== diagnosisId))
throw new Error('记录与当前镜头不一致,请重新读取。')
history.value = records; readiness.value = checked; revisions.value = changes
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
}
/** 收起或切换上下文时废弃旧请求,不把旧资格沿用到新版本。 */
function reset() { version++; controller?.abort(); loading.value = false; history.value = null; readiness.value = null; revisions.value = null; error.value = '' }
watch(expanded, value => { if (value.includes('review')) void load(); else reset() })
watch(target, () => { reset(); if (expanded.value.includes('review')) void load() })
onScopeDispose(reset)
</script>
<template>
<!-- 以下是指定诊断的只读修订条件与历史记录,普通列表不暴露内部编号 -->
<div class="diagnosis-shot-tools">
<NButton size="small" :aria-label="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'" :title="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'" :aria-expanded="showDetails" @click="expanded = showDetails ? [] : ['review']"><template #icon><History :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">{{ showDetails ? '收起修订条件与历史' : '修订条件与诊断历史' }}</span></NButton>
<NCollapse v-show="showDetails" v-model:expanded-names="expanded" class="diagnosis-shot-details">
<NCollapseItem name="review" title="修订条件与诊断历史">
<div class="space-y-3 text-xs leading-6">
<NButton size="small" :loading="loading" @click="load"><template #icon><RefreshCw :size="14" aria-hidden="true" /></template>刷新记录</NButton>
<p v-if="error" class="text-danger" role="alert">{{ error }}</p>
<p v-if="loading" role="status" class="text-muted">正在核对当前镜头记录…</p>
<section v-if="readiness" class="space-y-2" aria-label="当前诊断修订条件">
<p>{{ repairEligible ? '已满足人工修订的前提,仍需人工核对完整动作。' : '当前暂不能按这份诊断修订镜头。' }}</p>
<p v-for="reason in readiness.blockingReasons" :key="reason" class="text-muted">{{ diagnosisReason(reason) }}</p>
<p v-if="repairEligible" class="text-muted">可点击“查看并修订动作”,读取当前正式规划后再明确保存。</p>
<article v-for="(candidate, index) in readiness.repairCandidates" :key="index" class="space-y-1">
<p>阶段 {{ candidate.phaseNo }} · {{ candidate.characterRef }}</p><p>{{ userFacingText(candidate.suggestion) }}</p>
</article>
</section>
<section v-if="revisions" class="space-y-3" aria-label="正式修订历史">
<p class="font-medium">正式修订 · {{ revisions.count }} 条</p>
<p v-if="!revisions.revisions.length" class="text-muted">尚无保存的正式修订。</p>
<article v-for="record in revisions.revisions" :key="record.id" class="space-y-1"><p class="text-muted">{{ formatDate(record.createdAt) }}</p><p>{{ record.reason }}</p></article>
</section>
<section v-if="history" class="space-y-3" aria-label="诊断历史">
<p v-if="!history.revisions.length" class="text-muted">尚无保存的诊断记录。</p>
<article v-for="record in history.revisions" :key="record.id" class="space-y-1">
<p>{{ formatDate(record.createdAt) }} · {{ diagnosisStatusLabels[record.effectiveStatus as keyof typeof diagnosisStatusLabels] || '结果待核对' }}</p>
<p class="text-muted">{{ record.shotStale ? '镜头已变化' : '镜头内容一致' }} · {{ record.policyStatus === 'current' ? '规则版本一致' : record.policyStatus === 'stale' ? '规则版本已变化' : '缺少规则版本' }}</p>
<RawDataDetails :value="record" title="完整诊断证据(高级)" />
</article>
</section>
</div>
</NCollapseItem>
</NCollapse>
</div>
</template>
<style scoped>
.diagnosis-shot-tools { display: contents; }
.diagnosis-shot-tools > .n-button { min-height: 34px; }
/* 展开仍由 Naive 组件管理;入口使用独立可聚焦按钮,避免重复折叠标题。 */
.diagnosis-shot-details { flex-basis: 100%; min-width: 0; }
.diagnosis-shot-details :deep(.n-collapse-item__header) { display: none; }
.diagnosis-shot-details :deep(.n-collapse-item__content-wrapper) { padding-top: 16px; }
</style>
@@ -1,4 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { Trash2 } from '@lucide/vue'
import type { ResourceOccupancy } from '../repair.types'
import { computed } from 'vue' import { computed } from 'vue'
import { NButton, NCheckbox, NFormItem, NInput, NInputNumber, NSelect } from 'naive-ui' import { NButton, NCheckbox, NFormItem, NInput, NInputNumber, NSelect } from 'naive-ui'
import { actionResourceOptions } from '../../projects/quality-policy' import { actionResourceOptions } from '../../projects/quality-policy'
@@ -70,6 +72,24 @@ function addEvidence(index: number, kind: 'hand' | 'resource') {
shareable: false shareable: false
}) })
} }
/**
* 保留明确的持续对象,清空时删除可选字段,不提交非法空字符串。
* @param resource 当前资源证据
* @param value 用户输入的对象引用
*/
function updateContinuity(resource: ResourceOccupancy, value: string) {
if (value.trim()) resource.continuityRef = value
else delete resource.continuityRef
}
/**
* 只记录明确释放或交接;清空不猜测隐含事件。
* @param resource 当前资源证据
* @param value 用户选择的事件
*/
function updateTransition(resource: ResourceOccupancy, value: 'release' | 'transfer' | null) {
if (value) resource.transition = value
else delete resource.transition
}
</script> </script>
<template> <template>
@@ -103,7 +123,7 @@ function addEvidence(index: number, kind: 'hand' | 'resource') {
:disabled="disabled" :disabled="disabled"
/></NFormItem> /></NFormItem>
<NCheckbox v-model:checked="action.mustPerformInShot" :disabled="disabled">本镜必须完成</NCheckbox> <NCheckbox v-model:checked="action.mustPerformInShot" :disabled="disabled">本镜必须完成</NCheckbox>
<NButton :disabled="disabled" @click="draft.requiredActions.splice(index, 1)">移除</NButton> <NButton class="icon-button" :aria-label="`移除动作 ${index + 1}`" :disabled="disabled" @click="draft.requiredActions.splice(index, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
</div> </div>
</section> </section>
<!-- 以下是动作阶段编辑模块,同阶段动作视为同时发生 --> <!-- 以下是动作阶段编辑模块,同阶段动作视为同时发生 -->
@@ -123,9 +143,7 @@ function addEvidence(index: number, kind: 'hand' | 'resource') {
> >
<div class="flex flex-wrap items-center justify-between gap-3"> <div class="flex flex-wrap items-center justify-between gap-3">
<h4 class="text-sm">阶段 {{ index + 1 }}</h4> <h4 class="text-sm">阶段 {{ index + 1 }}</h4>
<NButton text :disabled="disabled" @click="draft.durationPlanning.phases.splice(index, 1)" <NButton class="icon-button" :aria-label="`移除阶段 ${index + 1}`" :disabled="disabled" @click="draft.durationPlanning.phases.splice(index, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
>移除阶段</NButton
>
</div> </div>
<NFormItem label="阶段描述" <NFormItem label="阶段描述"
><NInput v-model:value="phase.action" :aria-label="`阶段 ${index + 1} 描述`" :disabled="disabled" ><NInput v-model:value="phase.action" :aria-label="`阶段 ${index + 1} 描述`" :disabled="disabled"
@@ -181,7 +199,7 @@ function addEvidence(index: number, kind: 'hand' | 'resource') {
:disabled="disabled" :disabled="disabled"
/></NFormItem> /></NFormItem>
<NCheckbox v-model:checked="hand.shareable" :disabled="disabled">可共享</NCheckbox> <NCheckbox v-model:checked="hand.shareable" :disabled="disabled">可共享</NCheckbox>
<NButton :disabled="disabled" @click="phase.handOccupancy?.splice(handIndex, 1)">移除</NButton> <NButton class="icon-button" :aria-label="`移除阶段 ${index + 1} 手部证据 ${handIndex + 1}`" :disabled="disabled" @click="phase.handOccupancy?.splice(handIndex, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
</div> </div>
<div <div
v-for="(resource, resourceIndex) in phase.resourceOccupancy" v-for="(resource, resourceIndex) in phase.resourceOccupancy"
@@ -217,9 +235,9 @@ function addEvidence(index: number, kind: 'hand' | 'resource') {
:disabled="disabled" :disabled="disabled"
/></NFormItem> /></NFormItem>
<NCheckbox v-model:checked="resource.shareable" :disabled="disabled">可共享</NCheckbox> <NCheckbox v-model:checked="resource.shareable" :disabled="disabled">可共享</NCheckbox>
<NButton :disabled="disabled" @click="phase.resourceOccupancy?.splice(resourceIndex, 1)" <NFormItem label="持续对象" :show-feedback="false"><NInput :value="resource.continuityRef || ''" placeholder="仅填写已有明确对象引用" :disabled="disabled" @update:value="updateContinuity(resource, $event)" /></NFormItem>
>移除</NButton <NFormItem label="释放或交接" :show-feedback="false"><NSelect :value="resource.transition ?? null" clearable :options="[{ label: '明确释放', value: 'release' }, { label: '明确交接', value: 'transfer' }]" placeholder="未声明" :disabled="disabled" @update:value="updateTransition(resource, $event)" /></NFormItem>
> <NButton class="icon-button" :aria-label="`移除阶段 ${index + 1} 资源证据 ${resourceIndex + 1}`" :disabled="disabled" @click="phase.resourceOccupancy?.splice(resourceIndex, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
</div> </div>
</section> </section>
</section> </section>
@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue' import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem, NInputNumber, NSelect, NSpin, NTag } from 'naive-ui' import { NButton, NCollapse, NCollapseItem, NInputNumber, NSelect, NSpin, NTag } from 'naive-ui'
import { RefreshCw, ScanLine } from '@lucide/vue' import { RefreshCw, ScanLine, MapPin, RotateCcw, Wrench } from '@lucide/vue'
import { breakdownApi } from '../api' import { breakdownApi } from '../api'
import { diagnosisInput, diagnosisStatusLabels, scopeDiagnosisShots, summarizeDiagnosis } from '../diagnosis' import { diagnosisInput, diagnosisStatusLabels, scopeDiagnosisShots, summarizeDiagnosis, diagnosisHasAttention, diagnosisCanStart, diagnosisReason, handAuditLabels, resourceAuditLabels, bodyDimensionLabels } from '../diagnosis'
import type { DiagnosisLocation, DiagnosisScope } from '../diagnosis' import type { DiagnosisLocation, DiagnosisScope } from '../diagnosis'
import type { import type {
LegacyActionDiagnosisPreview, LegacyActionDiagnosisPreview,
@@ -14,8 +14,13 @@ import type {
import ConfirmAction from '../../workflows/ConfirmAction.vue' import ConfirmAction from '../../workflows/ConfirmAction.vue'
import WorkflowExecutionPanel from '../../workflows/WorkflowExecutionPanel.vue' import WorkflowExecutionPanel from '../../workflows/WorkflowExecutionPanel.vue'
import { useWorkflowExecution } from '../../workflows/execution' import { useWorkflowExecution } from '../../workflows/execution'
import { AppDialog } from '../../../components/ui' import { AppDrawer } from '../../../components/ui'
import { useActionMessage } from '../../../components/ui/useActionMessage' import { useActionMessage } from '../../../components/ui/useActionMessage'
import FormalRepairDrawer from '../../storyboard-preparation/FormalRepairDrawer.vue'
import type { PreparationIssue } from '../../storyboard-preparation/types'
import DiagnosisShotDetails from './DiagnosisShotDetails.vue'
import type { DiagnosisPreflight } from '../diagnosis.types'
import { userFacingText } from '../../../lib/user-facing-text'
import { errorMessage } from '../../../lib/http' import { errorMessage } from '../../../lib/http'
/** 当前分镜上下文;诊断入口与列表共用同一个正式剧集。 */ /** 当前分镜上下文;诊断入口与列表共用同一个正式剧集。 */
@@ -36,12 +41,18 @@ const execution = useWorkflowExecution(
computed(() => props.projectId), computed(() => props.projectId),
'storyboard-legacy-action-diagnosis' 'storyboard-legacy-action-diagnosis'
) )
/** 居中诊断弹窗是否打开。 */ /** 全屏诊断抽屉是否打开。 */
const dialogOpen = ref(false) const dialogOpen = ref(false)
/** 首批诊断数据完成前保留固定加载区域,不渲染会闪现的空结果。 */ /** 首批诊断数据完成前保留固定加载区域,不渲染会闪现的空结果。 */
const dialogDataReady = ref(false) const dialogDataReady = ref(false)
/** 等待弹窗离场后再转移焦点,避免焦点陷阱把定位焦点拉回。 */ /** 等待弹窗离场后再转移焦点,避免焦点陷阱把定位焦点拉回。 */
const pendingLocation = ref<DiagnosisLocation | null>(null) const pendingLocation = ref<DiagnosisLocation | null>(null)
/** 等诊断抽屉离场后打开正式动作修订,不叠加主界面。 */
const pendingRepair = ref<PreparationIssue | null>(null)
/** 已交接到正式修订的真实目标。 */
const repairTarget = ref<PreparationIssue | null>(null)
/** 正式修订界面由离场事件打开。 */
const repairOpen = ref(false)
/** 本次查看及提交的诊断范围。 */ /** 本次查看及提交的诊断范围。 */
const scope = ref<DiagnosisScope>({ kind: 'project' }) const scope = ref<DiagnosisScope>({ kind: 'project' })
/** 当前集摘要与弹窗结果分开保存,切换弹窗范围不会改变摘要含义。 */ /** 当前集摘要与弹窗结果分开保存,切换弹窗范围不会改变摘要含义。 */
@@ -58,6 +69,8 @@ const resultsBusy = ref(false)
const resultsError = ref('') const resultsError = ref('')
/** 只读范围预览;全项目按正式剧集汇总,任何一集失败都不能启动。 */ /** 只读范围预览;全项目按正式剧集汇总,任何一集失败都不能启动。 */
const previews = ref<LegacyActionDiagnosisPreview[] | null>(null) const previews = ref<LegacyActionDiagnosisPreview[] | null>(null)
/** 单镜头启动必须完成来源及版本检查。 */
const preflight = ref<DiagnosisPreflight | null>(null)
/** 只读范围预览的读取状态。 */ /** 只读范围预览的读取状态。 */
const previewBusy = ref(false) const previewBusy = ref(false)
/** 范围预览的读取错误。 */ /** 范围预览的读取错误。 */
@@ -121,7 +134,7 @@ const visibleShots = computed(() =>
resultFilter.value === 'all' || resultFilter.value === 'all' ||
(resultFilter.value === 'pending' (resultFilter.value === 'pending'
? shot.status === 'not_diagnosed' ? shot.status === 'not_diagnosed'
: !['not_diagnosed', 'no_conflict_found'].includes(shot.status)) : diagnosisHasAttention(shot))
) )
) )
/** 预览展示范围内的实际镜头总数,不把待补证据数量冒充付费数量。 */ /** 预览展示范围内的实际镜头总数,不把待补证据数量冒充付费数量。 */
@@ -140,7 +153,8 @@ const canStart = computed(
concurrencyValid.value && concurrencyValid.value &&
!previewBusy.value && !previewBusy.value &&
!execution.active.value && !execution.active.value &&
!starting.value !starting.value &&
(scope.value.kind !== 'shot' || diagnosisCanStart(preflight.value, props.projectId, previews.value?.[0]?.candidates[0]?.shotId ?? ''))
) )
/** 费用确认使用当前预览范围及并发,不虚构模型价格。 */ /** 费用确认使用当前预览范围及并发,不虚构模型价格。 */
const confirmation = computed( const confirmation = computed(
@@ -214,6 +228,7 @@ async function loadPreview() {
const target = scope.value const target = scope.value
const version = ++previewVersion const version = ++previewVersion
previews.value = null previews.value = null
preflight.value = null
previewBusy.value = true previewBusy.value = true
previewError.value = '' previewError.value = ''
try { try {
@@ -229,7 +244,17 @@ async function loadPreview() {
) )
) )
) )
if (version === previewVersion) previews.value = data if (version !== previewVersion) return
if (target.kind === 'shot') {
const candidate = data[0]?.candidates[0]
if (!candidate || data.length !== 1 || data[0]!.candidates.length !== 1) throw new Error('未取得唯一的正式镜头,请刷新结果。')
const checked = await breakdownApi.diagnosisPreflight(id, candidate.shotId)
if (version !== previewVersion) return
if (checked.projectId !== id || checked.shotId !== candidate.shotId || checked.episodeNo !== target.episodeNo || checked.beatNo !== target.beatNo || checked.shotNo !== target.shotNo)
throw new Error('检查结果与当前镜头不一致,请重新预览。')
preflight.value = checked
}
previews.value = data
} catch (cause) { } catch (cause) {
if (version === previewVersion) previewError.value = errorMessage(cause) if (version === previewVersion) previewError.value = errorMessage(cause)
} finally { } finally {
@@ -316,6 +341,8 @@ function issueDescriptions(issues: unknown[]) {
* @param location 可选的节拍或镜头坐标 * @param location 可选的节拍或镜头坐标
*/ */
function open(location?: DiagnosisLocation) { function open(location?: DiagnosisLocation) {
if (repairOpen.value) return
pendingRepair.value = null
pendingLocation.value = null pendingLocation.value = null
scope.value = location scope.value = location
? location.shotNo === undefined ? location.shotNo === undefined
@@ -339,19 +366,51 @@ function locate(location: DiagnosisLocation) {
/** 弹窗关闭动画结束后定位镜头,键盘焦点与正文高亮保持一致。 */ /** 弹窗关闭动画结束后定位镜头,键盘焦点与正文高亮保持一致。 */
function finishLocate() { function finishLocate() {
if (!pendingLocation.value) return if (pendingLocation.value) { const location = pendingLocation.value; pendingLocation.value = null; emit('locate', location) }
const location = pendingLocation.value if (pendingRepair.value) { repairTarget.value = pendingRepair.value; pendingRepair.value = null; repairOpen.value = true }
}
/**
* 交接到用户选中的正式镜头,不沿用旧诊断动作作为草稿。
* @param item 当前列表的真实镜头
*/
function requestRepair(item: LegacyActionDiagnosisResults['shots'][number]) {
if (!dialogOpen.value || starting.value || execution.active.value) return
pendingLocation.value = null pendingLocation.value = null
emit('locate', location) pendingRepair.value = { episodeNo: item.episodeNo, beatNo: item.beatNo, shotNo: item.shotNo, shotId: item.shotId, message: `核对当前正式镜头:${item.title}` }
dialogOpen.value = false
} }
/** 费用确认后提交固定范围,并保存后台任务句柄。 */ /** 费用确认后提交固定范围,并保存后台任务句柄。 */
async function startDiagnosis() { async function startDiagnosis() {
if (!canStart.value) return if (!canStart.value) return
const id = props.projectId const id = props.projectId
const input = diagnosisInput(scope.value, concurrency.value) const target = scope.value
const version = previewVersion
const input = diagnosisInput(target, concurrency.value)
starting.value = true starting.value = true
try { try {
if (target.kind === 'shot') {
const previous = preflight.value
if (!previous) return
const checked = await breakdownApi.diagnosisPreflight(id, previous.shotId)
if (version !== previewVersion || !dialogOpen.value || !diagnosisCanStart(checked, id, previous.shotId)) {
if (version === previewVersion) { preflight.value = checked; void loadResults() }
return
}
const latestPreview = await breakdownApi.legacyActionDiagnosisPreview(id, target.episodeNo, target.beatNo, target.shotNo)
if (version !== previewVersion || !dialogOpen.value) return
if (JSON.stringify(latestPreview.candidates) !== JSON.stringify(previews.value?.[0]?.candidates)) {
previews.value = null
throw new Error('镜头内容已变化,请重新预览后确认诊断。')
}
preflight.value = checked
if (checked.policyRevision !== previous.policyRevision || checked.policyFingerprint !== previous.policyFingerprint) {
previews.value = null
throw new Error('诊断使用的质量规则已变化,请重新预览后确认。')
}
}
if (version !== previewVersion || !dialogOpen.value || id !== props.projectId) return
const task = await breakdownApi.startLegacyActionDiagnosis(id, input) const task = await breakdownApi.startLegacyActionDiagnosis(id, input)
await execution.track(task.executionId, id) await execution.track(task.executionId, id)
} catch (cause) { } catch (cause) {
@@ -366,6 +425,9 @@ watch(
[() => props.projectId, () => props.episodeNo], [() => props.projectId, () => props.episodeNo],
() => { () => {
pendingLocation.value = null pendingLocation.value = null
pendingRepair.value = null
repairOpen.value = false
repairTarget.value = null
dialogOpen.value = false dialogOpen.value = false
++handVersion ++handVersion
handDiagnostics.value = null handDiagnostics.value = null
@@ -390,6 +452,7 @@ watch(
++previewVersion ++previewVersion
++resultsVersion ++resultsVersion
previews.value = null previews.value = null
preflight.value = null
previewBusy.value = false previewBusy.value = false
previewError.value = '' previewError.value = ''
results.value = null results.value = null
@@ -440,12 +503,12 @@ defineExpose({ open })
> >
<NTag v-if="execution.active.value" type="info" size="small" :bordered="false">诊断中</NTag> <NTag v-if="execution.active.value" type="info" size="small" :bordered="false">诊断中</NTag>
</div> </div>
<NButton text :disabled="!projectId" aria-haspopup="dialog" :aria-expanded="dialogOpen" @click="open()" <NButton size="small" :disabled="!projectId" aria-haspopup="dialog" :aria-expanded="dialogOpen" @click="open()"
>查看诊断</NButton >查看诊断</NButton
> >
</div> </div>
<!-- 以下是居中动作诊断弹窗,正文自然增高,仅超过可用视口后统一滚动 --> <!-- 以下是全屏动作诊断抽屉,正文独立滚动,操作底栏固定 -->
<AppDialog v-model:open="dialogOpen" title="动作诊断" :width="640" @closed="finishLocate"> <AppDrawer v-model:open="dialogOpen" title="动作诊断" @closed="finishLocate">
<NSpin <NSpin
:show="dialogOverlayLoading" :show="dialogOverlayLoading"
description="正在加载诊断数据…" description="正在加载诊断数据…"
@@ -501,6 +564,7 @@ defineExpose({ open })
><span>已过期 {{ counts.stale }}</span> <span>未诊断 {{ counts.pending }}</span ><span>已过期 {{ counts.stale }}</span> <span>未诊断 {{ counts.pending }}</span
><span>未发现冲突 {{ counts.clear }}</span> ><span>未发现冲突 {{ counts.clear }}</span>
</div> </div>
<p class="mb-3 text-xs text-muted">动作占用检查只核对已有证据,与 AI 复查、整体人工审核分别记录。</p>
<NSelect <NSelect
v-model:value="resultFilter" v-model:value="resultFilter"
aria-label="筛选诊断结果" aria-label="筛选诊断结果"
@@ -538,7 +602,7 @@ defineExpose({ open })
tabindex="0" tabindex="0"
aria-label="镜头诊断列表" aria-label="镜头诊断列表"
> >
<article v-for="item in visibleShots" :key="item.shotId" class="diagnosis-result-item"> <article v-for="item in visibleShots" :key="item.shotId" class="diagnosis-result-item" :class="{ 'problem-surface': item.status === 'conflict_found' || item.status === 'invalid_evidence' || item.handAudit?.status === 'conflict_found' || item.handAudit?.status === 'invalid_evidence' }">
<div class="diagnosis-section-heading"> <div class="diagnosis-section-heading">
<span class="text-xs text-muted" <span class="text-xs text-muted"
>第 {{ item.episodeNo }} 集 / 节拍 {{ item.beatNo }} / 镜头 >第 {{ item.episodeNo }} 集 / 节拍 {{ item.beatNo }} / 镜头
@@ -548,7 +612,7 @@ defineExpose({ open })
:type=" :type="
item.status === 'conflict_found' item.status === 'conflict_found'
? 'error' ? 'error'
: item.status === 'no_conflict_found' : item.status === 'no_conflict_found' && !diagnosisHasAttention(item)
? 'success' ? 'success'
: 'default' : 'default'
" "
@@ -563,9 +627,31 @@ defineExpose({ open })
:key="index" :key="index"
class="text-muted" class="text-muted"
> >
{{ description }} {{ userFacingText(description) }}
</p> </p>
<NButton text size="small" @click="locate(item)">定位镜头</NButton> <!-- 以下是修订状态、局部手部检查与 AI 全身疑点,结论各自保留 -->
<p v-if="item.requiresPostRepairDiagnosis" class="text-xs text-muted">镜头已修订,AI 待复查</p>
<p v-else-if="item.repairStatus === 'repaired'" class="text-xs text-muted">镜头已修订,已有当前版本 AI 诊断</p>
<p v-else-if="item.repairStatus === 'repair_history_stale'" class="text-xs text-muted">此前修订记录已过期</p>
<p v-if="item.shotStale" class="text-xs text-muted">镜头内容已变化,旧诊断不作为当前结论。</p>
<p v-if="item.policyStatus === 'stale'" class="text-xs text-muted">质量规则已变化,需要重新核对。</p>
<p v-else-if="item.policyStatus === 'unknown'" class="text-xs text-muted">旧诊断没有完整的质量规则记录。</p>
<div v-if="item.resourceAudit" class="space-y-1 text-xs text-muted"><p>{{ resourceAuditLabels[item.resourceAudit.status] }}<template v-if="item.resourceAudit.expectedActionCount > 0"> · 已覆盖 {{ item.resourceAudit.coveredActionCount }} / {{ item.resourceAudit.expectedActionCount }} 个动作</template></p></div>
<div v-else-if="item.handAudit" class="space-y-1 text-xs text-muted">
<p>{{ handAuditLabels[item.handAudit.status] }}<template v-if="item.handAudit.expectedActionCount > 0"> · 手部动作证据 {{ item.handAudit.coveredActionCount }} / {{ item.handAudit.expectedActionCount }}</template></p>
</div>
<article v-for="(finding, index) in item.bodyMotionFindings" :key="index" class="space-y-1 text-xs">
<p>{{ bodyDimensionLabels[finding.dimension] || '其他动作' }} · {{ finding.status === 'conflict' ? '发现冲突' : finding.status === 'needs_review' ? '需要复核' : '证据不足' }}</p>
<p>{{ userFacingText(finding.description) }}</p><p class="text-muted">原文:{{ finding.quote }}</p>
</article>
<!-- 以下是明确的卡片操作区,按钮有独立底面和图标,不与说明混在一起 -->
<div class="diagnosis-card-actions workspace-action-group">
<NButton size="small" aria-label="定位镜头" title="定位镜头" @click="locate(item)"><template #icon><MapPin :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">定位镜头</span></NButton>
<NButton v-if="item.requiresPostRepairDiagnosis || item.status === 'stale' || item.status === 'not_diagnosed'" size="small" aria-label="复查本镜头" title="复查本镜头" :disabled="starting || execution.active.value" @click="open(item)"><template #icon><RotateCcw :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">复查本镜头</span></NButton>
<NButton size="small" aria-label="查看并修订动作" title="查看并修订动作" :disabled="starting || execution.active.value" @click="requestRepair(item)"><template #icon><Wrench :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">查看并修订动作</span></NButton>
<DiagnosisShotDetails :project-id="projectId" :shot="item" />
</div>
</article> </article>
</div> </div>
</template> </template>
@@ -677,6 +763,11 @@ defineExpose({ open })
{{ previews.reduce((sum, item) => sum + item.invalidSnapshotCount, 0) }} 镜 {{ previews.reduce((sum, item) => sum + item.invalidSnapshotCount, 0) }} 镜
</p> </p>
</div> </div>
<div v-if="preflight" class="mt-3 space-y-2 text-xs" :class="preflight.errors.length ? 'problem-surface p-4' : 'text-muted'">
<p v-if="preflight.existingValid">本镜头已有同版本有效诊断,无需重复调用模型。</p>
<p v-for="code in preflight.errors" :key="code">{{ diagnosisReason(code) }}</p>
<p v-if="preflight.shouldDiagnose">已完成来源预检查,正式诊断仍会再次核对当前版本。</p>
</div>
<p v-if="previewError" class="text-danger" role="alert">{{ previewError }}</p> <p v-if="previewError" class="text-danger" role="alert">{{ previewError }}</p>
<p class="text-xs text-muted mt-3">AI 诊断会产生模型费用,仅保存诊断记录,不修改镜头。</p> <p class="text-xs text-muted mt-3">AI 诊断会产生模型费用,仅保存诊断记录,不修改镜头。</p>
<p v-if="execution.active.value" class="text-xs text-muted mt-3"> <p v-if="execution.active.value" class="text-xs text-muted mt-3">
@@ -714,7 +805,9 @@ defineExpose({ open })
@confirm="startDiagnosis" @confirm="startDiagnosis"
/> />
</template> </template>
</AppDialog> </AppDrawer>
<!-- 以下是等待诊断抽屉关闭后才打开的正式动作修订模块 -->
<FormalRepairDrawer v-model:open="repairOpen" :project-id="projectId" :issue="repairTarget" @saved="loadSummary" />
</template> </template>
<style> <style>
@@ -731,15 +824,16 @@ defineExpose({ open })
} }
/* 加载占位保留最低高度,正文可随内容自然增高,最大高度由公共弹窗按视口限制。 */ /* 加载占位保留最低高度,正文可随内容自然增高,最大高度由公共弹窗按视口限制。 */
.diagnosis-dialog-body { .diagnosis-dialog-body {
min-height: min(600px, calc(100dvh - 160px)); min-height: 240px;
} }
.diagnosis-dialog-content { .diagnosis-dialog-content {
@apply space-y-4; display: grid;
gap: 24px;
padding-bottom: 4px; padding-bottom: 4px;
} }
/* 各分区使用主题次级底色和留白区分,移除贯穿弹窗的分隔线。 */ /* 各分区使用主题次级底色和留白区分,移除贯穿弹窗的分隔线。 */
.diagnosis-section { .diagnosis-section {
@apply p-4 bg-(--app-subtle) text-sm leading-6; @apply text-sm leading-6;
} }
.diagnosis-section h3, .diagnosis-section h3,
.diagnosis-evidence-title { .diagnosis-evidence-title {
@@ -782,6 +876,12 @@ defineExpose({ open })
.diagnosis-result-item { .diagnosis-result-item {
@apply p-3 bg-(--app-control) space-y-2; @apply p-3 bg-(--app-control) space-y-2;
} }
.diagnosis-result-item.problem-surface {
background: var(--app-danger-soft);
}
.diagnosis-card-actions { display: flex; flex-wrap: wrap; gap: 8px; padding-top: 8px; }
.diagnosis-card-actions .n-button { min-height: 34px; }
.diagnosis-result-item { padding: 20px; }
.diagnosis-result-item .n-tag { .diagnosis-result-item .n-tag {
flex-shrink: 0; flex-shrink: 0;
} }
@@ -801,6 +901,10 @@ defineExpose({ open })
.diagnosis-repair { .diagnosis-repair {
@apply bg-(--app-surface) p-3 mt-3; @apply bg-(--app-surface) p-3 mt-3;
} }
@media (max-width: 639px) {
.diagnosis-card-actions .diagnosis-action-label { display: none; }
.diagnosis-card-actions .n-button { min-width: 34px; padding-inline: 8px; }
}
@media (max-width: 760px) { @media (max-width: 760px) {
.storyboard-diagnosis-summary { .storyboard-diagnosis-summary {
@apply items-start; @apply items-start;
+63 -1
View File
@@ -1,3 +1,5 @@
import { userFacingText } from '../../lib/user-facing-text'
import type { DiagnosisPreflight, DiagnosisHandAudit } from './diagnosis.types'
import type { LegacyActionDiagnosisResults } from './types' import type { LegacyActionDiagnosisResults } from './types'
/** 诊断及定位共用的镜头坐标。 */ /** 诊断及定位共用的镜头坐标。 */
@@ -72,10 +74,70 @@ const diagnosisCountKeys = {
/** 状态始终保留文字,避免仅通过颜色区分问题。 */ /** 状态始终保留文字,避免仅通过颜色区分问题。 */
export const diagnosisStatusLabels = { export const diagnosisStatusLabels = {
conflict_found: '手部冲突', conflict_found: '动作冲突',
no_conflict_found: '未发现冲突', no_conflict_found: '未发现冲突',
insufficient_evidence: '证据不足', insufficient_evidence: '证据不足',
invalid_evidence: '证据无效', invalid_evidence: '证据无效',
stale: '诊断过期', stale: '诊断过期',
not_diagnosed: '尚未诊断' not_diagnosed: '尚未诊断'
} as const } as const
/**
* 来源或规则检查的内部代码使用中文指引,未知原因也不直接展示内部标识。
* @param code 服务返回的阻断原因
* @returns 可操作的中文说明
*/
export function diagnosisReason(code: string): string {
const labels: Record<string, string> = {
QUALITY_POLICY_NOT_CONFIRMED: '请先确认项目质量规则。',
QUALITY_POLICY_VERSION_CONFLICT: '质量规则已更新,请重新核对。',
QUALITY_POLICY_SNAPSHOT_UNKNOWN: '这份分镜缺少可信的质量规则记录,请先确认规则并重新生成拆解候选。',
QUALITY_POLICY_SNAPSHOT_INVALID: '分镜的质量规则记录不完整,请重新生成拆解候选。',
QUALITY_POLICY_SNAPSHOT_STALE: '分镜与质量规则版本不一致,请核对最新拆解结果。',
STORYBOARD_SOURCE_MISMATCH: '镜头与已提交分镜不一致,请刷新最新结果后核对。'
}
return labels[code.split(':')[0]!] ?? userFacingText(code, '当前镜头暂不满足检查条件,请刷新后核对。')
}
/**
* 单镜头预检查只能提供当前范围的执行前提,不替代实际执行中的再次检查。
* @param value 只读预检查
* @param projectId 当前项目
* @param shotId 当前正式镜头
* @returns 是否可以进入费用确认
*/
export function diagnosisCanStart(value: DiagnosisPreflight | null, projectId: string, shotId: string): boolean {
return !!value && value.projectId === projectId && value.shotId === shotId &&
value.eligibleForFurtherValidation === true && value.shouldDiagnose === true && value.existingValid === false &&
Array.isArray(value.errors) && value.errors.length === 0 && value.requiresExecutionValidation === true &&
Number.isSafeInteger(value.policyRevision) && value.policyRevision! >= 0 &&
typeof value.policyFingerprint === 'string' && /^[a-f\d]{64}$/.test(value.policyFingerprint) &&
value.willCallModel === false && value.willModifyAssets === false
}
/**
* 待复查和全身疑点即使没有手部冲突,也需要留在默认问题列表。
* @param shot 当前镜头诊断
* @returns 是否需要用户关注
*/
export function diagnosisHasAttention(shot: LegacyActionDiagnosisResults['shots'][number]): boolean {
return !['not_diagnosed', 'no_conflict_found'].includes(shot.status) || shot.requiresPostRepairDiagnosis === true ||
!!shot.bodyMotionFindings?.length || !!(shot.resourceAudit ?? shot.handAudit) && ['conflict_found', 'invalid_evidence', 'invalid_snapshot'].includes((shot.resourceAudit ?? shot.handAudit)!.status)
}
/** 免费手部检查的结论,不能据此标记 AI 已通过。 */
export const handAuditLabels: Record<DiagnosisHandAudit['status'], string> = {
insufficient_evidence: '手部证据不足', invalid_snapshot: '镜头记录不完整', invalid_evidence: '手部证据无效',
conflict_found: '手部仍有冲突', partial_evidence: '部分动作缺少手部证据', no_conflict_found: '现有手部证据未发现冲突'
}
/** 全身动作维度的中文说明。 */
export const bodyDimensionLabels: Record<string, string> = {
feet: '脚部动作', balance: '身体平衡', gaze: '视线方向', prop_interaction: '道具交互',
physical_continuity: '动作衔接', cross_shot_continuity: '镜头间衔接'
}
/** 通用动作资源结论不冒充覆盖全部剧情语义。 */
export const resourceAuditLabels: typeof handAuditLabels = {
insufficient_evidence: '动作占用证据不足', invalid_snapshot: '镜头记录不完整', invalid_evidence: '动作占用证据无效',
conflict_found: '动作占用仍有冲突', partial_evidence: '部分动作缺少占用证据', no_conflict_found: '现有动作占用证据未发现冲突'
}
+122
View File
@@ -0,0 +1,122 @@
import type { StoryboardHandRepairPreview } from './types'
/** 单镜头只读检查,实际诊断仍需再次核对来源。 */
export interface DiagnosisPreflight {
/** 所属项目。 */
projectId: string
/** 正式镜头编号。 */
shotId: string
/** 剧集编号。 */
episodeNo: number
/** 剧情段落编号。 */
beatNo: number
/** 段落内镜头编号。 */
shotNo: number
/** 已提交分镜采用的规则修订。 */
policyRevision: number | null
/** 已提交规则内容版本。 */
policyFingerprint: string | null
/** 当前可复用的历史诊断。 */
existingDiagnosisId: string | null
/** 是否已有同规则及镜头版本的有效诊断。 */
existingValid: boolean
/** 是否可以继续执行检查。 */
eligibleForFurtherValidation: boolean
/** 阻断原因,展示时映射中文。 */
errors: string[]
/** 执行时必须再次检查。 */
requiresExecutionValidation: true
/** 是否确实需要新诊断。 */
shouldDiagnose: boolean
/** 当前查询不调用模型。 */
willCallModel: false
/** 当前查询不修改资产。 */
willModifyAssets: false
}
/** 全身动作疑点,不确定结论保持待复核。 */
export interface BodyMotionFinding {
/** 检查维度,兼容未来新增维度。 */
dimension: string
/** 模型建议的结论。 */
status: 'conflict' | 'needs_review' | 'insufficient_evidence'
/** 问题说明。 */
description: string
/** 当前镜头的原文证据。 */
quote: string
/** 可选的关联镜头编号。 */
relatedShotNo?: number
}
/** 不调用模型的手部证据复检,与 AI 诊断独立。 */
export interface DiagnosisHandAudit {
/** 证据完整性或冲突结论。 */
status: 'insufficient_evidence' | 'invalid_snapshot' | 'invalid_evidence' | 'conflict_found' | 'partial_evidence' | 'no_conflict_found'
/** 检出的冲突数。 */
issueCount: number
/** 有效证据数量。 */
evidenceCount: number
/** 需要覆盖的必需动作数。 */
expectedActionCount: number
/** 已有证据覆盖的必需动作数。 */
coveredActionCount: number
/** 覆盖率,无法计算时为空。 */
coverage: number | null
}
/** 诊断历史保留原始结果,分别标注镜头与规则是否过期。 */
export interface DiagnosisHistory {
/** 所属项目。 */
projectId: string
/** 正式镜头编号。 */
shotId: string
/** 本次返回条数。 */
count: number
/** 不可变诊断记录。 */
revisions: Array<{
/** 诊断编号。 */
id: string
/** 原始诊断结论。 */
status: string
/** 当前有效结论。 */
effectiveStatus: string
/** 镜头是否变化。 */
shotStale: boolean
/** 规则对应情况。 */
policyStatus: 'unknown' | 'current' | 'stale'
/** 任一版本过期均不可作为当前结果。 */
stale: boolean
/** 诊断使用的规则修订。 */
qualityPolicyRevision: number | null
/** 诊断模型品牌。 */
modelName: string
/** 完整问题证据仅供核对,不用于生成修订草稿。 */
issuesJson: unknown
/** 生成时间。 */
createdAt: string
}>
}
/** 指定诊断进入人工修订前的只读条件,不代表可直接覆盖镜头。 */
export interface DiagnosisRepairReadiness {
/** 所属项目。 */
projectId: string
/** 正式镜头编号。 */
shotId: string
/** 本次核对的诊断编号。 */
diagnosisId: string
/** 已通过服务检查的具体修复候选。 */
repairCandidates: StoryboardHandRepairPreview['candidates']
/** 具备人工修订前提。 */
eligible: boolean
/** 未满足的安全条件。 */
blockingReasons: string[]
/** 必须由用户复核。 */
requiresManualReview: true
/** 不允许一键直接应用。 */
canApplyDirectly: false
/** 查询不调用模型。 */
willCallModel: false
/** 查询不修改资产。 */
willModifyAssets: false
}
+2
View File
@@ -72,6 +72,8 @@ export function actionDraftIssue(draft: ShotActionDraft): string {
) )
return '阶段衔接与建议时长需填写有效秒数。' return '阶段衔接与建议时长需填写有效秒数。'
for (const phase of planning.phases) { for (const phase of planning.phases) {
if (phase.resourceOccupancy?.some(item => item.transition && !item.continuityRef?.trim())) return '释放或交接需要填写明确的持续对象。'
if (phase.resourceOccupancy?.some(item => item.transition === 'release' && item.usage !== 'other')) return '明确释放不能同时声明持有或支撑,请核对资源用途。'
if (!phase.action.trim()) return '请填写每个阶段的动作描述。' if (!phase.action.trim()) return '请填写每个阶段的动作描述。'
if (!Number.isFinite(phase.estimatedSeconds) || phase.estimatedSeconds <= 0) return '阶段时长必须大于 0 秒。' if (!Number.isFinite(phase.estimatedSeconds) || phase.estimatedSeconds <= 0) return '阶段时长必须大于 0 秒。'
const references = [ const references = [
+4
View File
@@ -36,6 +36,10 @@ export interface ResourceOccupancy {
usage: 'support' | 'hold' | 'move' | 'interact' | 'other' usage: 'support' | 'hold' | 'move' | 'interact' | 'other'
/** 是否允许共享。 */ /** 是否允许共享。 */
shareable: boolean shareable: boolean
/** 明确持续持有或支撑的对象。 */
continuityRef?: string
/** 明确释放或交接,不根据文本猜测。 */
transition?: 'release' | 'transfer'
} }
/** 镜头完整动作时长规划,保留手部及通用资源证据。 */ /** 镜头完整动作时长规划,保留手部及通用资源证据。 */
+25
View File
@@ -1,3 +1,4 @@
import type { BodyMotionFinding, DiagnosisHandAudit } from './diagnosis.types'
/** 三种可配置的抽取模块,分镜并不是第四个模块。 */ /** 三种可配置的抽取模块,分镜并不是第四个模块。 */
export type BreakdownModule = 'character' | 'scene' | 'prop' export type BreakdownModule = 'character' | 'scene' | 'prop'
@@ -34,6 +35,8 @@ export interface BreakdownTask {
/** 传给预览与启动接口的相同配置。 */ /** 传给预览与启动接口的相同配置。 */
export interface BreakdownInput { export interface BreakdownInput {
/** 启动时携带已确认的服务端修订,预览无需此字段。 */
expectedRevision?: number
/** 仅生成候选,正式资产由独立确认入口提交。 */ /** 仅生成候选,正式资产由独立确认入口提交。 */
candidateOnly?: boolean candidateOnly?: boolean
groupSize: number groupSize: number
@@ -312,6 +315,28 @@ export interface LegacyActionDiagnosisResults {
shotNo: number shotNo: number
title: string title: string
diagnosisId: string | null diagnosisId: string | null
/** 规则是否与当前版本一致,旧回执缺省时不推断有效。 */
policyStatus?: 'not_diagnosed' | 'unknown' | 'current' | 'stale'
/** 镜头内容是否已经变化。 */
shotStale?: boolean
/** 最近手部修订的有效性。 */
repairStatus?: 'not_repaired' | 'repaired' | 'repair_history_stale'
/** 当前版本缺少 AI 复查。 */
requiresPostRepairDiagnosis?: boolean
/** 当前镜头手部证据的免费检查。 */
handAudit?: DiagnosisHandAudit
/** 通用手、脚、身体、支撑与道具证据摘要,优先于旧手部摘要。 */
resourceAudit?: DiagnosisHandAudit
/** 全身动作疑点,不与手部确定性结果合并。 */
bodyMotionFindings?: BodyMotionFinding[]
/** 原诊断使用的规则修订。 */
qualityPolicyRevision?: number | null
/** 规则内容版本。 */
qualityPolicyFingerprint?: string | null
/** 最近手部修订编号。 */
latestRepairId?: string | null
/** 最近手部修订时间。 */
latestRepairAt?: string | null
status: status:
| 'not_diagnosed' | 'not_diagnosed'
| 'stale' | 'stale'
@@ -3,8 +3,7 @@ import { projectsApi } from '../projects/api'
import { policyDraft } from '../projects/quality-policy' import { policyDraft } from '../projects/quality-policy'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../projects/types' import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../projects/types'
import { import {
qualityPolicyConfirmationEpoch, qualityPolicySignature, qualityPolicyConfirmed, qualityPolicySignature, validateQualityPolicyReceipt
readQualityPolicyConfirmation, rememberQualityPolicyConfirmation
} from '../projects/quality-policy-confirmation' } from '../projects/quality-policy-confirmation'
import { errorMessage } from '../../lib/http' import { errorMessage } from '../../lib/http'
import { showActionFeedback, useActionMessage } from '../../components/ui/useActionMessage' import { showActionFeedback, useActionMessage } from '../../components/ui/useActionMessage'
@@ -17,12 +16,10 @@ interface StartPermit {
scope: string scope: string
/** 本次重新读取并确认的质量规则。 */ /** 本次重新读取并确认的质量规则。 */
signature: string signature: string
} /** 服务端已确认的规则修订。 */
revision: number
/** 存储受限时仅在当前页面有效的确认,规则变更后通过代次撤销。 */ /** 同修订的服务端内容版本。 */
interface SessionConfirmation extends StartPermit { fingerprint: string
/** 当前项目在本页面的规则失效代次。 */
epoch: number
} }
/** /**
@@ -33,9 +30,8 @@ interface SessionConfirmation extends StartPermit {
*/ */
async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> { async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> {
const result = await projectsApi.qualityPolicy(id, signal) const result = await projectsApi.qualityPolicy(id, signal)
if (result.projectId !== id) throw new Error('质量规则所属项目不一致,请重新读取。') validateQualityPolicyReceipt(result, id)
qualityPolicySignature(result.policy) return { ...result, policy: policyDraft(result.policy) }
return { projectId: id, policy: policyDraft(result.policy) }
} }
/** /**
@@ -61,7 +57,7 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
/** 用户可重试的错误反馈。 */ /** 用户可重试的错误反馈。 */
const error = ref('') const error = ref('')
/** 编辑器只在服务端版本变化时重建,失败保留草稿。 */ /** 编辑器只在服务端版本变化时重建,失败保留草稿。 */
const editorKey = computed(() => policy.value ? `${policy.value.projectId}:${qualityPolicySignature(policy.value.policy)}` : '') const editorKey = computed(() => policy.value ? `${policy.value.projectId}:${policy.value.revision}:${policy.value.fingerprint}:${qualityPolicySignature(policy.value.policy)}` : '')
/** 应用统一消息层。 */ /** 应用统一消息层。 */
const message = useActionMessage() const message = useActionMessage()
/** 取消项目或配置变更前的旧请求。 */ /** 取消项目或配置变更前的旧请求。 */
@@ -70,23 +66,9 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
let generation = 0 let generation = 0
/** 普通启动弹窗对应的规则内容。 */ /** 普通启动弹窗对应的规则内容。 */
let preparedSignature = '' let preparedSignature = ''
/** 存储不可写时,仅本次页面会话使用的确认。 */ /** 成功重读同修订确认后才能消费的一次性启动许可。 */
let fallback: SessionConfirmation | null = null
/** 成功重读后才能消费的一次性启动许可。 */
let permit: StartPermit | null = null let permit: StartPermit | null = null
/**
* 判断规则内容是否经过本浏览器明确确认。
* @param id 当前项目
* @param signature 最新服务端内容
* @returns 是否允许跳过规则确认界面
*/
function confirmed(id: string, signature: string): boolean {
return readQualityPolicyConfirmation(id) === signature ||
(fallback?.projectId === id && fallback.signature === signature &&
fallback.epoch === qualityPolicyConfirmationEpoch(id))
}
/** 撤销未完成请求和启动许可,不撤销用户已经完成的规则确认。 */ /** 撤销未完成请求和启动许可,不撤销用户已经完成的规则确认。 */
function reset() { function reset() {
generation++ generation++
@@ -114,7 +96,7 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
if (current !== generation || !allowed.value) return if (current !== generation || !allowed.value) return
policy.value = result policy.value = result
const signature = qualityPolicySignature(result.policy) const signature = qualityPolicySignature(result.policy)
if (confirmed(id, signature)) { if (qualityPolicyConfirmed(result)) {
preparedSignature = signature preparedSignature = signature
startOpen.value = true startOpen.value = true
} else reviewOpen.value = true } else reviewOpen.value = true
@@ -135,7 +117,8 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
if (!allowed.value || busy.value || !reviewOpen.value || !policy.value) return false if (!allowed.value || busy.value || !reviewOpen.value || !policy.value) return false
const id = projectId.value const id = projectId.value
const current = ++generation const current = ++generation
const expected = qualityPolicySignature(policy.value.policy) const reviewed = policy.value
const expected = qualityPolicySignature(reviewed.policy)
controller?.abort() controller?.abort()
controller = new AbortController() controller = new AbortController()
const signal = controller.signal const signal = controller.signal
@@ -145,7 +128,7 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
const draftSignature = qualityPolicySignature(draft) const draftSignature = qualityPolicySignature(draft)
let result = await read(id, signal) let result = await read(id, signal)
if (current !== generation || !allowed.value) return false if (current !== generation || !allowed.value) return false
if (qualityPolicySignature(result.policy) !== expected) { if (result.revision !== reviewed.revision || result.fingerprint !== reviewed.fingerprint || qualityPolicySignature(result.policy) !== expected) {
policy.value = result policy.value = result
showActionFeedback(message, '质量规则已在其他位置更新,请重新核对后确认。', 'warning') showActionFeedback(message, '质量规则已在其他位置更新,请重新核对后确认。', 'warning')
return false return false
@@ -153,24 +136,31 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
if (draftSignature !== expected) { if (draftSignature !== expected) {
reading.value = false reading.value = false
saving.value = true saving.value = true
const saved = await projectsApi.saveQualityPolicy(id, policyDraft(draft)) const saved = await projectsApi.saveQualityPolicy(id, policyDraft(draft), result.revision)
if (current !== generation || !allowed.value) return false if (current !== generation || !allowed.value) return false
if (saved.projectId !== id || qualityPolicySignature(saved.policy) !== draftSignature) validateQualityPolicyReceipt(saved, id)
if (qualityPolicySignature(saved.policy) !== draftSignature)
throw new Error('质量规则保存结果与草稿不一致,请重新读取。') throw new Error('质量规则保存结果与草稿不一致,请重新读取。')
saving.value = false result = saved
reading.value = true }
result = await read(id, signal) // 确认是独立写入;确认按钮只在用户明确核对后才调用此接口。
if (current !== generation || !allowed.value) return false reading.value = false
if (qualityPolicySignature(result.policy) !== draftSignature) { saving.value = true
policy.value = result const confirmed = validateQualityPolicyReceipt(await projectsApi.confirmQualityPolicy(id, result.revision), id)
showActionFeedback(message, '质量规则保存后又有更新,请重新核对。', 'warning') if (current !== generation || !allowed.value) return false
return false if (!qualityPolicyConfirmed(confirmed) || confirmed.revision !== result.revision ||
} confirmed.fingerprint !== result.fingerprint || qualityPolicySignature(confirmed.policy) !== draftSignature)
throw new Error('质量规则确认结果不一致,请重新核对。')
saving.value = false
reading.value = true
result = await read(id, signal)
if (current !== generation || !allowed.value) return false
if (!qualityPolicyConfirmed(result) || result.revision !== confirmed.revision || result.fingerprint !== confirmed.fingerprint) {
policy.value = result
showActionFeedback(message, '质量规则已变化,请重新核对后确认。', 'warning')
return false
} }
const signature = qualityPolicySignature(result.policy) const signature = qualityPolicySignature(result.policy)
const persisted = rememberQualityPolicyConfirmation(id, signature)
fallback = persisted ? null : { projectId: id, scope: scope.value, signature, epoch: qualityPolicyConfirmationEpoch(id) }
if (!persisted) showActionFeedback(message, '当前浏览器未能记住确认,下次进入时可能再次提醒。', 'info')
policy.value = result policy.value = result
preparedSignature = signature preparedSignature = signature
reviewOpen.value = false reviewOpen.value = false
@@ -204,7 +194,7 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
const result = await read(id, controller.signal) const result = await read(id, controller.signal)
if (current !== generation || !allowed.value) return false if (current !== generation || !allowed.value) return false
const signature = qualityPolicySignature(result.policy) const signature = qualityPolicySignature(result.policy)
if (signature !== preparedSignature || !confirmed(id, signature)) { if (signature !== preparedSignature || !qualityPolicyConfirmed(result) || result.revision !== policy.value?.revision || result.fingerprint !== policy.value?.fingerprint) {
policy.value = result policy.value = result
preparedSignature = '' preparedSignature = ''
startOpen.value = false startOpen.value = false
@@ -212,7 +202,7 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
showActionFeedback(message, '质量规则已变化,请重新确认后再启动拆解。', 'warning') showActionFeedback(message, '质量规则已变化,请重新确认后再启动拆解。', 'warning')
return false return false
} }
permit = { projectId: id, scope: currentScope, signature } permit = { projectId: id, scope: currentScope, signature, revision: result.revision, fingerprint: result.fingerprint }
startOpen.value = false startOpen.value = false
return true return true
} catch (cause) { } catch (cause) {
@@ -225,14 +215,15 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
} }
/** /**
* 消费同项目、同预览范围的本地一次性启动许可;后端仍需要独立门禁。 * 消费同项目、同预览范围的本地一次性启动许可,真实写入仍由服务事务复查。
* @returns 是否允许本次提交 * @returns 本次确认的服务修订,缺少许可时为空
*/ */
function consumePermit(): boolean { function consumePermit(): { expectedRevision: number } | null {
const current = permit const current = permit
permit = null permit = null
return !!current && allowed.value && current.projectId === projectId.value && return current && allowed.value && current.projectId === projectId.value && current.scope === scope.value &&
current.scope === scope.value && confirmed(current.projectId, current.signature) policy.value && qualityPolicyConfirmed(policy.value) && current.revision === policy.value.revision &&
current.fingerprint === policy.value.fingerprint ? { expectedRevision: current.revision } : null
} }
/** 用户取消只读确认时撤销未完成请求,保存请求进行中禁止重复取消。 */ /** 用户取消只读确认时撤销未完成请求,保存请求进行中禁止重复取消。 */
+15 -6
View File
@@ -59,16 +59,20 @@ function syncActive() {
active.value = current active.value = current
} }
/** 内容或尺寸变化时同步实际顶部留白与章节位置;隐藏标签不覆盖已有阅读位置。 */ /** 内容或尺寸变化时同步章节位置并对齐滚动像素,避免首集与跳转后的标题出现小数偏差。 */
function measure() { function measure() {
if (!viewport?.clientHeight || !readerContent.value) return if (!viewport?.clientHeight || !readerContent.value) return
viewportHeight.value = viewport.clientHeight viewportHeight.value = viewport.clientHeight
readingInset = parseFloat(getComputedStyle(readerContent.value).paddingTop) || 32 readingInset = parseFloat(getComputedStyle(readerContent.value).paddingTop) || 32
const origin = viewport.getBoundingClientRect().top - viewport.scrollTop const origin = viewport.getBoundingClientRect().top - viewport.scrollTop
positions = [...readerContent.value.querySelectorAll<HTMLElement>('[data-episode]')].map(item => ({ positions = [...readerContent.value.querySelectorAll<HTMLElement>('[data-episode]')].map(item => {
episode: Number(item.dataset.episode), // 先扣除上次微调,再按滚动距离取整,反复测量时不会累积偏移。
top: item.getBoundingClientRect().top - origin const previousOffset = parseFloat(item.style.getPropertyValue('--reader-chapter-offset')) || 0
})) const top = item.getBoundingClientRect().top - origin - previousOffset
const alignedTop = readingInset + Math.round(top - readingInset)
item.style.setProperty('--reader-chapter-offset', `${alignedTop - top}px`)
return { episode: Number(item.dataset.episode), top: alignedTop }
})
syncActive() syncActive()
} }
@@ -384,8 +388,13 @@ onBeforeUnmount(() => observer?.disconnect())
/* 正文紧邻目录左对齐,保留阅读行宽,不在宽屏内容区居中。 */ /* 正文紧邻目录左对齐,保留阅读行宽,不在宽屏内容区居中。 */
max-width: 900px; max-width: 900px;
} }
.reader-chapter {
/* 浏览器会取整滚动距离;整章最多微调半像素,让标题、摘要与正文使用相同起点。 */
translate: 0 var(--reader-chapter-offset, 0px);
}
.reader-chapter + .reader-chapter { .reader-chapter + .reader-chapter {
@apply mt-12 pt-9; /* 章节间隔全部放在外部,目录定位到章节顶部时不再额外带入 36px 内边距。 */
@apply mt-21;
} }
.reader-chapter:last-child { .reader-chapter:last-child {
/* 末集较短时仍可定位到阅读线,不必把倒数第二集误认为当前集。 */ /* 末集较短时仍可定位到阅读线,不必把倒数第二集误认为当前集。 */
@@ -4,7 +4,8 @@ import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHead
import { computed, onScopeDispose, ref, watch } from 'vue' import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NFormItem, NSelect, NSpin } from 'naive-ui' import { NButton, NFormItem, NSelect, NSpin } from 'naive-ui'
import { errorMessage } from '../../../lib/http' import { ApiError, errorMessage } from '../../../lib/http'
import { showActionFeedback, useActionMessage } from '../../../components/ui/useActionMessage'
import { generationConfigApi } from '../api' import { generationConfigApi } from '../api'
import type { import type {
CreativeProfileAspectRatio, CreativeProfileAspectRatio,
@@ -33,15 +34,15 @@ const props = withDefaults(
const emit = defineEmits<{ saved: [profile: CreativeProfileInput]; busy: [saving: boolean] }>() const emit = defineEmits<{ saved: [profile: CreativeProfileInput]; busy: [saving: boolean] }>()
/** 成功保存后通知当前项目生成表单更新默认值。 */ /** 成功保存后通知当前项目生成表单更新默认值。 */
const revision = useProjectGenerationRevision() const revision = useProjectGenerationRevision()
/** 保存结果复用全局消息层,读取失败仍保留可核对的正文状态。 */
const feedback = useActionMessage()
/** 配置和模型目录读取状态。 */ /** 配置和模型目录读取状态。 */
const loading = ref(false) const loading = ref(false)
/** 配置保存状态。 */ /** 配置保存状态。 */
const saving = ref(false) const saving = ref(false)
/** 读取或保存错误。 */ /** 配置读取失败的可恢复状态,不用于保存反馈。 */
const error = ref('') const error = ref('')
/** 真实保存结果提示。 */
const notice = ref('')
/** 后端支持的图片与视频模型目录。 */ /** 后端支持的图片与视频模型目录。 */
const catalog = ref<GenerationModelCatalog | null>(null) const catalog = ref<GenerationModelCatalog | null>(null)
/** 当前项目的独立编辑草稿。 */ /** 当前项目的独立编辑草稿。 */
@@ -181,7 +182,6 @@ async function load() {
catalog.value = null catalog.value = null
loading.value = true loading.value = true
error.value = '' error.value = ''
notice.value = ''
try { try {
const [nextCatalog, saved] = await Promise.all([ const [nextCatalog, saved] = await Promise.all([
generationConfigApi.catalog(signal), generationConfigApi.catalog(signal),
@@ -205,17 +205,17 @@ async function save() {
const input = creativeProfileDraft(profile.value) const input = creativeProfileDraft(profile.value)
saving.value = true saving.value = true
error.value = '' error.value = ''
notice.value = ''
try { try {
const saved = await generationConfigApi.saveProfile(projectId, input) const saved = await generationConfigApi.saveProfile(projectId, input)
if (disposed || props.projectId !== projectId) return if (disposed || props.projectId !== projectId) return
if (saved.projectId !== projectId) throw new Error('保存结果与当前项目不匹配,请重新读取配置。') if (saved.projectId !== projectId) throw new Error('保存结果与当前项目不匹配,请重新读取配置。')
profile.value = creativeProfileDraft(saved) profile.value = creativeProfileDraft(saved)
notice.value = '项目生成配置已保存,后续首帧和视频生成会继承此配置。' showActionFeedback(feedback, '项目生成配置已保存,后续制作将使用此配置。', 'success')
revision.value++ revision.value++
emit('saved', profile.value) emit('saved', profile.value)
} catch (cause) { } catch (cause) {
if (!disposed && props.projectId === projectId) error.value = errorMessage(cause) if (!disposed && props.projectId === projectId)
showActionFeedback(feedback, errorMessage(cause), cause instanceof ApiError && cause.status === 409 ? 'warning' : 'error')
} finally { } finally {
saving.value = false saving.value = false
} }
@@ -261,7 +261,6 @@ onScopeDispose(() => {
<ContextNotice v-if="validationIssues.length" type="warning" :show-icon="false" class="mb-3"> <ContextNotice v-if="validationIssues.length" type="warning" :show-icon="false" class="mb-3">
<p v-for="issue in validationIssues" :key="issue">{{ issue }}</p> <p v-for="issue in validationIssues" :key="issue">{{ issue }}</p>
</ContextNotice> </ContextNotice>
<ContextNotice v-if="notice" type="success" :show-icon="false" class="mb-3">{{ notice }}</ContextNotice>
<ContextNotice <ContextNotice
v-if="!loading && (!enabledImages.length || !enabledVideos.length)" v-if="!loading && (!enabledImages.length || !enabledVideos.length)"
type="warning" type="warning"
@@ -5,7 +5,7 @@ import type { SelectRenderLabel, SelectRenderTag } from 'naive-ui'
import { projectsApi } from '../../projects/api' import { projectsApi } from '../../projects/api'
import { policyDraft, policyIssue } from '../../projects/quality-policy' import { policyDraft, policyIssue } from '../../projects/quality-policy'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../../projects/types' import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../../projects/types'
import { invalidateQualityPolicyConfirmation, qualityPolicySignature } from '../../projects/quality-policy-confirmation' import { validateQualityPolicyReceipt, qualityPolicySignature } from '../../projects/quality-policy-confirmation'
import { errorMessage } from '../../../lib/http' import { errorMessage } from '../../../lib/http'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue' import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import QualityPolicyExceptions from './QualityPolicyExceptions.vue' import QualityPolicyExceptions from './QualityPolicyExceptions.vue'
@@ -31,8 +31,6 @@ const error = ref('')
const notice = ref('') const notice = ref('')
/** 服务端策略的独立草稿。 */ /** 服务端策略的独立草稿。 */
const policy = ref<ProjectQualityPolicy | null>(null) const policy = ref<ProjectQualityPolicy | null>(null)
/** 已保存内容用于区分真实规则变更与无变化保存。 */
let savedSignature = ''
/** 基础规则的原始内容,用于阻止覆盖其他入口并发修改的通用规则。 */ /** 基础规则的原始内容,用于阻止覆盖其他入口并发修改的通用规则。 */
let savedGeneralSignature = '' let savedGeneralSignature = ''
/** 整体表现方式及通俗示例,仅说明含义,不自动修改动作许可。 */ /** 整体表现方式及通俗示例,仅说明含义,不自动修改动作许可。 */
@@ -117,8 +115,7 @@ async function load() {
try { try {
const result = props.initialPolicy ?? await projectsApi.qualityPolicy(id, controller.signal) const result = props.initialPolicy ?? await projectsApi.qualityPolicy(id, controller.signal)
if (current !== version) return if (current !== version) return
if (result.projectId !== id) throw new Error('质量策略所属项目不一致,请重新读取。') validateQualityPolicyReceipt(result, id)
savedSignature = qualityPolicySignature(result.policy)
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] }) savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
policy.value = policyDraft(result.policy) policy.value = policyDraft(result.policy)
rulesText.value = policy.value.customRules.join('\n') rulesText.value = policy.value.customRules.join('\n')
@@ -153,8 +150,7 @@ async function save() {
try { try {
const latest = await projectsApi.qualityPolicy(id, controller.signal) const latest = await projectsApi.qualityPolicy(id, controller.signal)
if (current !== version || props.disabled) return if (current !== version || props.disabled) return
if (latest.projectId !== id) throw new Error('质量规则所属项目不一致,请重新读取。') validateQualityPolicyReceipt(latest, id)
qualityPolicySignature(latest.policy)
if (qualityPolicySignature({ ...latest.policy, actionExceptions: [] }) !== savedGeneralSignature) if (qualityPolicySignature({ ...latest.policy, actionExceptions: [] }) !== savedGeneralSignature)
throw new Error('质量规则已在其他位置更新,请重新打开配置后再保存。') throw new Error('质量规则已在其他位置更新,请重新打开配置后再保存。')
// 例外由问题修订入口管理,基础配置永远合并服务端最新例外,不提交隐藏的旧副本。 // 例外由问题修订入口管理,基础配置永远合并服务端最新例外,不提交隐藏的旧副本。
@@ -162,16 +158,13 @@ async function save() {
else delete input.actionExceptions else delete input.actionExceptions
loading.value = false loading.value = false
saving.value = true saving.value = true
const result = await projectsApi.saveQualityPolicy(id, input) const result = await projectsApi.saveQualityPolicy(id, input, latest.revision)
if (current !== version) return if (current !== version) return
if (result.projectId !== id) throw new Error('质量策略保存回执所属项目不一致。') validateQualityPolicyReceipt(result, id)
const signature = qualityPolicySignature(result.policy)
if (signature !== savedSignature) invalidateQualityPolicyConfirmation(id)
savedSignature = signature
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] }) savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
policy.value = policyDraft(result.policy) policy.value = policyDraft(result.policy)
rulesText.value = policy.value.customRules.join('\n') rulesText.value = policy.value.customRules.join('\n')
notice.value = '质量策略已保存,后续创作、拆解和生成使用此策略。' notice.value = result.confirmed ? '质量规则已保存,当前版本已经确认。' : '质量规则已保存。下次启动拆解前需要核对并确认。'
emit('saved') emit('saved')
} catch (cause) { } catch (cause) {
if (current === version) error.value = errorMessage(cause) if (current === version) error.value = errorMessage(cause)
@@ -2,6 +2,8 @@ import { inject, ref, type InjectionKey, type Ref } from 'vue'
/** 项目内共享的配置修订号,成功保存后通知已挂载的生成表单重新读取。 */ /** 项目内共享的配置修订号,成功保存后通知已挂载的生成表单重新读取。 */
export const projectGenerationRevisionKey: InjectionKey<Ref<number>> = Symbol('project-generation-revision') export const projectGenerationRevisionKey: InjectionKey<Ref<number>> = Symbol('project-generation-revision')
/** 工作区辅助入口打开同一个项目配置抽屉,避免新建重复表单或覆盖当前路由。 */
export const projectSettingsOpenKey: InjectionKey<() => void> = Symbol('project-settings-open')
/** /**
* 读取项目配置修订号,独立使用组件时保留本地修订状态。 * 读取项目配置修订号,独立使用组件时保留本地修订状态。
+9 -4
View File
@@ -10,7 +10,7 @@ import type {
ProjectVideoStatus, ProjectVideoStatus,
ProjectVideoInputPlan, ProjectVideoInputPlan,
PromptReadiness, PromptReadiness,
ProductionPlan, ProductionPlanResponse,
ProductionPlanInput, ProductionPlanInput,
ProductionStartInput, ProductionStartInput,
ProviderInputSpec, ProviderInputSpec,
@@ -62,12 +62,17 @@ export const productionApi = {
* @param projectId 正式项目 ID * @param projectId 正式项目 ID
* @param signal 取消信号 * @param signal 取消信号
* @param input 与启动同源的模型及图片参数 * @param input 与启动同源的模型及图片参数
* @returns 后端实际生产计划 * @returns 后端实际生产计划或配置阻断状态
*/ */
plan: (projectId: string, signal?: AbortSignal, input: ProductionPlanInput = {}) => plan: (projectId: string, signal?: AbortSignal, input: ProductionPlanInput = {}) =>
request<ProductionPlan>(`${projectPath(projectId)}/production/plan`, { request<ProductionPlanResponse>(`${projectPath(projectId)}/production/plan`, {
method: 'POST', method: 'POST',
body: input, // 计划只解析这三项;阶段范围及视频参数只由启动接口消费。
body: {
imageProvider: input.imageProvider,
imageGenerationOptions: input.imageGenerationOptions,
videoProvider: input.videoProvider
},
signal signal
}), }),
/** 读取真实主资产完成状态,不能用任务提交回执代替。 */ /** 读取真实主资产完成状态,不能用任务提交回执代替。 */
@@ -4,7 +4,9 @@ import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue' import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NInputNumber, NSelect } from 'naive-ui' import { NButton, NCheckbox, NCollapse, NCollapseItem, NInputNumber, NSelect } from 'naive-ui'
import { computed, ref, watch } from 'vue' import { computed, inject, ref, watch } from 'vue'
import { Settings2 } from '@lucide/vue'
import { projectSettingsOpenKey } from '../../generation-config/context'
import ConfirmAction from '../../workflows/ConfirmAction.vue' import ConfirmAction from '../../workflows/ConfirmAction.vue'
import { downloadText, formatDate } from '../../../lib/format' import { downloadText, formatDate } from '../../../lib/format'
import { useAdvancedProduction } from '../useAdvancedProduction' import { useAdvancedProduction } from '../useAdvancedProduction'
@@ -19,6 +21,7 @@ const {
execution, execution,
checking, checking,
error, error,
configurationRequired,
check, check,
blocked, blocked,
safeMode, safeMode,
@@ -34,6 +37,8 @@ const {
preflight, preflight,
start start
} = useAdvancedProduction() } = useAdvancedProduction()
/** 配置缺失时打开项目标题栏已有的全屏配置,不创建第二份表单。 */
const openProjectSettings = inject(projectSettingsOpenKey, undefined)
/** 本轮真实生产回执。 */ /** 本轮真实生产回执。 */
const receipt = computed(() => session.value.pipelineReceipt) const receipt = computed(() => session.value.pipelineReceipt)
/** 高级工具折叠状态。 */ /** 高级工具折叠状态。 */
@@ -141,6 +146,13 @@ const confirmationDescription = computed(
@confirm="start" @confirm="start"
/> />
</div> </div>
<!-- 以下是项目配置缺失的恢复入口,保存后仍须重新检查制作条件。 -->
<div v-if="configurationRequired" class="mt-3 flex flex-wrap items-center gap-3">
<span class="text-xs text-muted">请先保存项目生成配置,再重新检查制作条件。</span>
<NButton v-if="openProjectSettings" class="workspace-action-button" :disabled="operation.pending" @click="openProjectSettings">
<template #icon><Settings2 :size="15" aria-hidden="true" /></template>前往项目配置
</NButton>
</div>
<!-- 以下是后台任务与真实结果模块。 --> <!-- 以下是后台任务与真实结果模块。 -->
<WorkflowExecutionPanel <WorkflowExecutionPanel
v-if="execution.executionId.value" v-if="execution.executionId.value"
@@ -95,9 +95,9 @@ const problems = computed(() => [
计划会根据当前素材自动更新。已有有效结果会直接复用;重新生成的过期主体图会自动设为当前主图,手动生成的候选仍可在形态图片页自行确认。 计划会根据当前素材自动更新。已有有效结果会直接复用;重新生成的过期主体图会自动设为当前主图,手动生成的候选仍可在形态图片页自行确认。
</p> </p>
<ContextNotice v-if="plan.hasManualBlockers" type="warning" :show-icon="false" class="mt-3"> <ContextNotice v-if="plan.hasManualBlockers" type="warning" :show-icon="false" class="mt-3">
各阶段合计 当前有
{{ plan.manualBlocked }} {{ plan.manualBlocked }}
项需人工处理(同一镜头可能重复计数)。可先生成就绪的主体参考图;成功结果会保留,遇到阻塞时后续阶段可能暂停。 项独立准备问题需人工处理。上表各阶段的影响数量可能重叠,不能直接相加。可先生成就绪的主体参考图;成功结果会保留,遇到阻塞时后续阶段可能暂停。
</ContextNotice> </ContextNotice>
<NCollapse v-if="problems.length" class="mt-3" :default-expanded-names="['issues']"> <NCollapse v-if="problems.length" class="mt-3" :default-expanded-names="['issues']">
<NCollapseItem name="issues" title="查看还需要准备的内容"> <NCollapseItem name="issues" title="查看还需要准备的内容">
+64
View File
@@ -534,6 +534,15 @@ export interface ProductionPlanStage {
/** 后端执行计划只读取资产,不触发模型生成。 */ /** 后端执行计划只读取资产,不触发模型生成。 */
export interface ProductionPlan { export interface ProductionPlan {
/** 项目配置就绪状态;兼容尚未返回此字段的服务版本。 */
configuration?: {
/** 当前配置可用于制作计划。 */
status: 'ready'
/** 无配置错误。 */
code: null
/** 无配置阻断说明。 */
reason: null
}
projectId: string projectId: string
providers: { image: string; video: string } providers: { image: string; video: string }
/** 实际解析后的图片模型与参数。 */ /** 实际解析后的图片模型与参数。 */
@@ -566,6 +575,61 @@ export interface ProductionPlan {
} }
} }
/** 缺少项目配置时仅返回入口状态,各制作阶段不可读取或执行。 */
export interface ProductionConfigurationBlockedPlan {
/** 所属项目编号。 */
projectId: string
/** 配置未完成时禁止启动。 */
canStart: false
/** 配置未完成时禁止自动执行。 */
canAutoRun: false
/** 当前存在人工配置阻断。 */
hasManualBlockers: true
/** 配置阻断数量。 */
manualBlocked: number
/** 真实配置阻断原因,原始值保留用于业务判断。 */
configuration: {
/** 配置尚不可用。 */
status: 'blocked'
/** 缺少项目生成配置。 */
code: 'CREATIVE_PROFILE_REQUIRED'
/** 面向展示层转换的业务说明。 */
reason: string
}
/** 正式分镜入口可能已就绪,但不能替代项目配置。 */
entryReadiness: {
/** 分镜入口是否就绪。 */
ready: boolean
/** 当前阻断原因。 */
reason?: string | null
}
/** 配置缺失时没有可执行的模型选择。 */
providers: null
/** 配置缺失时没有可执行的生成参数。 */
generationConfig: null
/** 未完成制作。 */
completed: false
/** 配置补齐前的明确阶段。 */
stage: 'configuration_required'
/** 未计算角色身份阶段。 */
characterIdentity: null
/** 未计算身份母版阶段。 */
stableIdentityAnchors: null
/** 未计算主体图片阶段。 */
subjectImages: null
/** 未计算首帧阶段。 */
keyframes: null
/** 未计算视频提示词阶段。 */
videoPrompts: null
/** 未计算视频阶段。 */
videos: null
/** 不存在阶段明细,不能用于启动判断。 */
details: null
}
/** 计划预检明确区分配置阻断与可读取的制作阶段。 */
export type ProductionPlanResponse = ProductionPlan | ProductionConfigurationBlockedPlan
/** 真实制作状态;只有主体主图、主首帧和主视频均有效才完成。 */ /** 真实制作状态;只有主体主图、主首帧和主视频均有效才完成。 */
export interface ProjectProductionStatus { export interface ProjectProductionStatus {
projectId: string projectId: string
@@ -1,4 +1,5 @@
import { computed, onScopeDispose, ref, watch } from 'vue' import { computed, onScopeDispose, ref, watch } from 'vue'
import { preparationApi, assertCurrentStoryboardDesigns } from '../storyboard-preparation/api'
import { projectsApi } from '../projects/api' import { projectsApi } from '../projects/api'
import { useProjectContext } from '../projects/context' import { useProjectContext } from '../projects/context'
import { subjectImagesApi } from '../subject-images/api' import { subjectImagesApi } from '../subject-images/api'
@@ -12,6 +13,18 @@ import { productionApi } from './api'
import { getProductionSession } from './model' import { getProductionSession } from './model'
import type { ProductionPlan, ProductionStartInput, ProductionStage } from './types' import type { ProductionPlan, ProductionStartInput, ProductionStage } from './types'
/** 缺少项目配置属于可恢复业务状态,保留独立身份供界面提供配置入口。 */
class ProductionConfigurationRequiredError extends Error {
/**
* 保留计划返回的业务原因,不伪造 HTTP 请求失败状态。
* @param message 原始业务说明,默认使用公开配置状态码
*/
constructor(message = 'CREATIVE_PROFILE_REQUIRED') {
super(message)
this.name = 'ProductionConfigurationRequiredError'
}
}
/** /**
* 指定续跑阶段会跳过上游生成,必须使用已有有效资产而非可生成数量。 * 指定续跑阶段会跳过上游生成,必须使用已有有效资产而非可生成数量。
* @param plan 后端当前真实生产计划 * @param plan 后端当前真实生产计划
@@ -46,17 +59,20 @@ export function productionResumeIssues(
* @returns 无消耗计划、实际状态与同源请求参数 * @returns 无消耗计划、实际状态与同源请求参数
*/ */
export async function checkPipeline(projectId: string, scope: ProductionStartInput = {}) { export async function checkPipeline(projectId: string, scope: ProductionStartInput = {}) {
const entry = await preparationApi.entry(projectId)
if (entry.ready !== true) throw new Error(entry.reason || '请先完成正式分镜检查与人工审核,再进入制作计划。')
const project = await projectsApi.detail(projectId)
if (project.id !== projectId) throw new Error('预检返回了其他项目的数据,请重新读取。')
await assertCurrentStoryboardDesigns(projectId, project.episodes.map(item => item.episode), entry.derivedAssets.shotCount)
const profile = await generationConfigApi.profile(projectId) const profile = await generationConfigApi.profile(projectId)
const providers = profile if (!profile) throw new ProductionConfigurationRequiredError()
? { const providers = {
imageProvider: profile.imageProvider, imageProvider: profile.imageProvider,
videoProvider: profile.videoProvider, videoProvider: profile.videoProvider,
imageGenerationOptions: { ...profile.imageOptions }, imageGenerationOptions: { ...profile.imageOptions },
videoGenerationOptions: { ...profile.videoOptions } videoGenerationOptions: { ...profile.videoOptions }
} }
: undefined const [checkpoints, forms, plan, status] = await Promise.all([
const [project, checkpoints, forms, plan, status] = await Promise.all([
projectsApi.detail(projectId),
projectsApi.checkpoints(projectId), projectsApi.checkpoints(projectId),
subjectImagesApi.listForms(projectId), subjectImagesApi.listForms(projectId),
productionApi.plan(projectId, undefined, providers), productionApi.plan(projectId, undefined, providers),
@@ -69,11 +85,12 @@ export async function checkPipeline(projectId: string, scope: ProductionStartInp
forms.some(form => form.subject.projectId !== projectId) forms.some(form => form.subject.projectId !== projectId)
) )
throw new Error('预检返回了其他项目的数据,请重新读取。') throw new Error('预检返回了其他项目的数据,请重新读取。')
if (plan.stage === 'configuration_required')
throw new ProductionConfigurationRequiredError(plan.configuration.reason || undefined)
const issues: string[] = [] const issues: string[] = []
if (plan.entryReadiness && !plan.entryReadiness.ready) if (plan.entryReadiness && !plan.entryReadiness.ready)
issues.push(plan.entryReadiness.reason || '项目尚未满足生产入口条件。') issues.push(plan.entryReadiness.reason || '项目尚未满足生产入口条件。')
issues.push(...productionResumeIssues(plan, scope)) issues.push(...productionResumeIssues(plan, scope))
if (!profile) issues.push('尚未配置项目画布与生成模型,请先在右上角“项目配置”中保存配置。')
const shotIds = new Set(plan.details.keyframes.map(item => item.shotId)) const shotIds = new Set(plan.details.keyframes.map(item => item.shotId))
if ( if (
shotIds.size !== plan.keyframes.total || shotIds.size !== plan.keyframes.total ||
@@ -131,6 +148,8 @@ export function useAdvancedProduction() {
const checking = ref(false) const checking = ref(false)
/** 预检错误或已有任务说明。 */ /** 预检错误或已有任务说明。 */
const error = ref('') const error = ref('')
/** 配置未保存时展示已有项目配置的恢复入口,不根据错误文案猜测状态。 */
const configurationRequired = ref(false)
/** 默认使用无视频测试模式,只有用户明确切换后才允许提交高费用视频任务。 */ /** 默认使用无视频测试模式,只有用户明确切换后才允许提交高费用视频任务。 */
const safeMode = ref(true) const safeMode = ref(true)
/** 本轮有限首帧数量,保留原安全模式字段。 */ /** 本轮有限首帧数量,保留原安全模式字段。 */
@@ -180,6 +199,7 @@ export function useAdvancedProduction() {
version++ version++
check.value = null check.value = null
error.value = '' error.value = ''
configurationRequired.value = false
checking.value = false checking.value = false
}) })
@@ -190,6 +210,7 @@ export function useAdvancedProduction() {
check.value = null check.value = null
checking.value = false checking.value = false
error.value = '' error.value = ''
configurationRequired.value = false
}, },
{ deep: true, flush: 'sync' } { deep: true, flush: 'sync' }
) )
@@ -202,11 +223,15 @@ export function useAdvancedProduction() {
checking.value = true checking.value = true
check.value = null check.value = null
error.value = '' error.value = ''
configurationRequired.value = false
try { try {
const result = await checkPipeline(projectId, scope.value) const result = await checkPipeline(projectId, scope.value)
if (current === version && id.value === projectId) check.value = result if (current === version && id.value === projectId) check.value = result
} catch (cause) { } catch (cause) {
if (current === version) error.value = errorMessage(cause) if (current === version) {
configurationRequired.value = cause instanceof ProductionConfigurationRequiredError
error.value = errorMessage(cause)
}
} finally { } finally {
if (current === version) checking.value = false if (current === version) checking.value = false
} }
@@ -229,7 +254,13 @@ export function useAdvancedProduction() {
const confirmedVersion = version const confirmedVersion = version
let submitted = false let submitted = false
await runOperation(projectId, '高级串联生产', async () => { await runOperation(projectId, '高级串联生产', async () => {
const result = await checkPipeline(projectId, scope.value) const result = await checkPipeline(projectId, scope.value).catch(cause => {
if (!disposed && id.value === projectId && confirmedVersion === version && cause instanceof ProductionConfigurationRequiredError) {
check.value = null
configurationRequired.value = true
}
throw cause
})
if ( if (
confirmedVersion !== version || confirmedVersion !== version ||
disposed || disposed ||
@@ -294,6 +325,7 @@ export function useAdvancedProduction() {
execution, execution,
checking, checking,
error, error,
configurationRequired,
check, check,
blocked, blocked,
safeMode, safeMode,
+19 -3
View File
@@ -3,6 +3,7 @@ import ContextNotice from '../../components/ui/ContextNotice.vue'
import { computed, h, inject, onScopeDispose, provide, ref, watch, watchEffect } from 'vue' import { computed, h, inject, onScopeDispose, provide, ref, watch, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { Settings2 } from '@lucide/vue'
import { NScrollbar, NButton, NPageHeader, NSpin, NEllipsis } from 'naive-ui' import { NScrollbar, NButton, NPageHeader, NSpin, NEllipsis } from 'naive-ui'
import { EmptyState, WorkspaceRefreshButton } from '../../components/ui' import { EmptyState, WorkspaceRefreshButton } from '../../components/ui'
import { projectContextKey, useProjectData } from './context' import { projectContextKey, useProjectData } from './context'
@@ -13,8 +14,9 @@ import { useWorkflowExecution } from '../workflows/execution'
import { clearEpisodeSourceInvalidations, invalidateEpisodeSource } from '../storyboard/model' import { clearEpisodeSourceInvalidations, invalidateEpisodeSource } from '../storyboard/model'
import { useActionMessage } from '../../components/ui/useActionMessage' import { useActionMessage } from '../../components/ui/useActionMessage'
import { productionMessage } from '../production/production-messages' import { productionMessage } from '../production/production-messages'
import StoryboardPreparation from '../storyboard-preparation/StoryboardPreparation.vue'
import ProjectSettingsDialog from '../generation-config/components/ProjectSettingsDialog.vue' import ProjectSettingsDialog from '../generation-config/components/ProjectSettingsDialog.vue'
import { projectGenerationRevisionKey } from '../generation-config/context' import { projectGenerationRevisionKey, projectSettingsOpenKey } from '../generation-config/context'
import CreateDramaSkeleton from '../create-drama/CreateDramaSkeleton.vue' import CreateDramaSkeleton from '../create-drama/CreateDramaSkeleton.vue'
import BreakdownSkeleton from '../breakdown/BreakdownSkeleton.vue' import BreakdownSkeleton from '../breakdown/BreakdownSkeleton.vue'
import VisualStyleSkeleton from '../visual-style/VisualStyleSkeleton.vue' import VisualStyleSkeleton from '../visual-style/VisualStyleSkeleton.vue'
@@ -36,6 +38,11 @@ const generationRevision = ref(0)
provide(projectGenerationRevisionKey, generationRevision) provide(projectGenerationRevisionKey, generationRevision)
/** 项目标题栏共用配置弹窗开关。 */ /** 项目标题栏共用配置弹窗开关。 */
const settingsOpen = ref(false) const settingsOpen = ref(false)
/** 打开标题栏已有的项目配置抽屉,保留当前镜头与工作区。 */
function openProjectSettings() {
settingsOpen.value = true
}
provide(projectSettingsOpenKey, openProjectSettings)
/** 既有配置恢复链接打开同一个全局弹窗,不切换工作区。 */ /** 既有配置恢复链接打开同一个全局弹窗,不切换工作区。 */
watch( watch(
() => route.query.configure, () => route.query.configure,
@@ -257,9 +264,13 @@ onScopeDispose(() => {
}}</NEllipsis> }}</NEllipsis>
</template> </template>
<template #extra> <template #extra>
<NButton size="small" :disabled="!context.project.value" @click="settingsOpen = true" <!-- 以下是制作前检查入口,后续页面受限时仍可完成正式分镜审核 -->
>项目配置</NButton <div class="flex items-center gap-2">
<StoryboardPreparation v-if="context.project.value?.id === id" :key="id" :project-id="id" :disabled="!!context.error.value" @changed="context.refresh()" />
<NButton class="workspace-action-button" size="small" aria-label="项目配置" title="项目配置" :disabled="!context.project.value" @click="settingsOpen = true"
><template #icon><Settings2 :size="15" aria-hidden="true" /></template><span class="project-config-label">项目配置</span></NButton
> >
</div>
</template> </template>
</NPageHeader> </NPageHeader>
</header> </header>
@@ -372,3 +383,8 @@ onScopeDispose(() => {
} }
} }
</style> </style>
<style scoped>
/* 窄屏的两个项目操作统一显示图标,保留按钮的完整可访问名称。 */
@media (max-width: 639px) { .project-config-label { display: none; } }
</style>
+13 -2
View File
@@ -27,12 +27,23 @@ export const projectsApi = {
* 显式替换完整质量策略,不触发模型生成。 * 显式替换完整质量策略,不触发模型生成。
* @param id 当前项目编号 * @param id 当前项目编号
* @param policy 用户明确确认的完整策略 * @param policy 用户明确确认的完整策略
* @param expectedRevision 最后读取的服务端修订版本
* @returns 服务端实际保存的策略 * @returns 服务端实际保存的策略
*/ */
saveQualityPolicy: (id: string, policy: ProjectQualityPolicy) => saveQualityPolicy: (id: string, policy: ProjectQualityPolicy, expectedRevision: number) =>
request<ProjectQualityPolicyResult>(`/projects/${encodeURIComponent(id)}/quality-policy`, { request<ProjectQualityPolicyResult>(`/projects/${encodeURIComponent(id)}/quality-policy`, {
method: 'PUT', method: 'PUT',
body: policy body: { policy, expectedRevision }
}),
/**
* 用户明确确认当前规则;普通保存不能代替确认。
* @param id 当前项目
* @param expectedRevision 用户核对的服务端修订版本
* @returns 服务保存的确认状态
*/
confirmQualityPolicy: (id: string, expectedRevision: number) =>
request<ProjectQualityPolicyResult>(`/projects/${encodeURIComponent(id)}/quality-policy/confirm`, {
method: 'POST', body: { expectedRevision }
}), }),
list: (signal?: AbortSignal) => request<Project[]>('/projects', { signal }), list: (signal?: AbortSignal) => request<Project[]>('/projects', { signal }),
detail: (id: string, signal?: AbortSignal) => detail: (id: string, signal?: AbortSignal) =>
@@ -3,17 +3,25 @@ import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import { computed, reactive, watch } from 'vue' import { computed, reactive, watch } from 'vue'
import { NButton, NInput } from 'naive-ui' import { NButton, NInput } from 'naive-ui'
import { AppDialog } from '../../../components/ui' import { AppDrawer } from '../../../components/ui'
import { errorMessage } from '../../../lib/http' import { errorMessage } from '../../../lib/http'
import { projectsApi } from '../api' import { projectsApi } from '../api'
import type { Project } from '../types' import type { Project } from '../types'
/** 编辑项目基础信息;不会触发已有剧本或制作资产重生成。 */ /** 待编辑的项目基础信息;不会触发已有剧本或制作资产重生成。 */
const props = defineProps<{ project: Project | null }>() const props = defineProps<{
/** 当前选中的项目。 */
project: Project | null
}>()
/** 编辑项目全屏抽屉的显隐状态。 */
const open = defineModel<boolean>('open', { default: false }) const open = defineModel<boolean>('open', { default: false })
/** 保存成功后通知列表刷新项目。 */
const emit = defineEmits<{ changed: [] }>() const emit = defineEmits<{ changed: [] }>()
/** 项目名称、故事主题和风格的编辑草稿。 */
const form = reactive({ title: '', topic: '', style: '' }) const form = reactive({ title: '', topic: '', style: '' })
/** 保存请求状态及错误提示。 */
const state = reactive({ pending: false, error: '' }) const state = reactive({ pending: false, error: '' })
/** 基础信息发生有效变更后才允许保存。 */
const dirty = computed( const dirty = computed(
() => () =>
!!props.project && !!props.project &&
@@ -32,6 +40,7 @@ watch(
}, },
{ immediate: true } { immediate: true }
) )
/** 保存项目基础信息,成功后关闭抽屉并刷新列表。 */
async function save() { async function save() {
if ( if (
!props.project || !props.project ||
@@ -60,40 +69,53 @@ async function save() {
} }
</script> </script>
<template> <template>
<AppDialog <!-- 以下是编辑项目全屏抽屉模块,标题与底栏固定、正文独立滚动 -->
<AppDrawer
v-model:open="open" v-model:open="open"
:title="`编辑项目 · ${project?.title || project?.topic || ''}`" :title="`编辑项目 · ${project?.title || project?.topic || ''}`"
description="仅更新项目基础信息,不自动重生成剧本或制作资产。" description="仅更新项目基础信息,不自动重生成剧本或制作资产。"
:busy="state.pending"
> >
<!-- 以下是保存失败提示模块 -->
<FeedbackMessage v-if="state.error" :message="state.error" /> <FeedbackMessage v-if="state.error" :message="state.error" />
<!-- 以下是单列铺满可用宽度的项目基本信息模块 -->
<section class="dialog-form-stack"> <section class="dialog-form-stack">
<label class="block text-xs">项目名称<NInput v-model:value="form.title" class="mt-2" /></label> <label class="block text-xs"
<!-- 以下是与新增弹窗共用内边距的故事主题编辑模块 --> >项目名称<NInput v-model:value="form.title" :disabled="state.pending" class="mt-2"
/></label>
<!-- 以下是加高的故事主题编辑模块,随内容自动增高 -->
<label class="block text-xs" <label class="block text-xs"
>故事主题<NInput >故事主题<NInput
v-model:value="form.topic" v-model:value="form.topic"
:disabled="state.pending"
type="textarea" type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }" :autosize="{ minRows: 10, maxRows: 20 }"
class="project-story-input mt-2" class="project-story-input mt-2"
/></label> /></label>
<!-- 以下是与新增弹窗共用内边距的多行风格编辑模块,随内容自动增高 -->
<!-- 以下是与故事主题保持相同高度规则的风格编辑模块 -->
<label class="block text-xs" <label class="block text-xs"
>风格<NInput >风格<NInput
v-model:value="form.style" v-model:value="form.style"
:disabled="state.pending"
type="textarea" type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }" :autosize="{ minRows: 10, maxRows: 20 }"
class="project-story-input mt-2" class="project-story-input mt-2"
/></label> /></label>
</section> </section>
<!-- 以下是固定底部操作模块,保存期间禁止重复操作或关闭 -->
<template #footer> <template #footer>
<NButton @click="open = false">取消</NButton> <NButton :disabled="state.pending" @click="open = false">取消</NButton>
<NButton <NButton
type="primary" type="primary"
:loading="state.pending" :loading="state.pending"
:disabled="!dirty || !form.title.trim() || !form.topic.trim() || !form.style.trim()" :disabled="state.pending || !dirty || !form.title.trim() || !form.topic.trim() || !form.style.trim()"
@click="save" @click="save"
>保存项目</NButton >保存项目</NButton
> >
</template> </template>
</AppDialog> </AppDrawer>
</template> </template>
@@ -1,8 +1,5 @@
import { policyIssue } from './quality-policy' import { policyIssue } from './quality-policy'
import type { ProjectQualityPolicy } from './types' import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from './types'
/** 同一页面中主动保存规则后,也撤销无法持久化的临时确认。 */
const invalidations = new Map<string, number>()
/** /**
* 只比较质量规则的规范化内容,不把模型参数或对象属性顺序作为变更。 * 只比较质量规则的规范化内容,不把模型参数或对象属性顺序作为变更。
@@ -32,62 +29,29 @@ export function qualityPolicySignature(policy: ProjectQualityPolicy): string {
} }
/** /**
* 隔离项目及本地确认格式版本。 * 核对服务回执的项目、内容与修订字段;缺失时不能使用默认版本补齐。
* @param result 规则接口原始回执
* @param projectId 当前项目 * @param projectId 当前项目
* @returns 本地 UX 记忆键 * @returns 已核对的完整回执
*/ */
function confirmationKey(projectId: string): string { export function validateQualityPolicyReceipt(result: ProjectQualityPolicyResult, projectId: string): ProjectQualityPolicyResult {
return `short-drama:breakdown-quality-confirmation:v1:${projectId}` if (!result || result.projectId !== projectId) throw new Error('质量规则所属项目不一致,请重新读取。')
qualityPolicySignature(result.policy)
if (!Number.isSafeInteger(result.revision) || result.revision < 0 ||
!/^[a-f\d]{64}$/.test(result.fingerprint) || typeof result.confirmed !== 'boolean' ||
!(result.confirmedRevision === null || Number.isSafeInteger(result.confirmedRevision) && result.confirmedRevision >= 0) ||
!(result.confirmedAt === null || typeof result.confirmedAt === 'string' && Number.isFinite(Date.parse(result.confirmedAt))))
throw new Error('质量规则确认信息不完整,请重新读取。')
if (result.confirmed && !qualityPolicyConfirmed(result)) throw new Error('质量规则确认版本不一致,请重新读取。')
return result
} }
/** /**
* 读取当前浏览器明确确认过的规则,不将默认值当作确认。 * 仅认可服务保存的同修订明确确认,浏览器本地记录不构成确认。
* @param projectId 当前项目 * @param result 已读取的规则回执
* @returns 已确认内容或空值,损坏与不可用存储均不视为确认 * @returns 当前修订是否已经明确确认
*/ */
export function readQualityPolicyConfirmation(projectId: string): string | null { export function qualityPolicyConfirmed(result: ProjectQualityPolicyResult): boolean {
try { return result.confirmed === true && result.confirmedRevision === result.revision &&
const raw = localStorage.getItem(confirmationKey(projectId)) typeof result.confirmedAt === 'string' && Number.isFinite(Date.parse(result.confirmedAt))
if (!raw) return null
const parsed: unknown = JSON.parse(raw)
if (!parsed || typeof parsed !== 'object' || !('signature' in parsed) ||
!('formatVersion' in parsed) || parsed.formatVersion !== 1 ||
typeof parsed.signature !== 'string') return null
return parsed.signature
} catch {
return null
}
}
/**
* 仅在用户明确确认后记住当前浏览器的规则内容,不能代替后端门禁。
* @param projectId 当前项目
* @param signature 已核对的规则内容
* @returns 是否成功持久化,失败时调用方只保留本次会话确认
*/
export function rememberQualityPolicyConfirmation(projectId: string, signature: string): boolean {
try {
localStorage.setItem(confirmationKey(projectId), JSON.stringify({ formatVersion: 1, signature }))
return true
} catch {
return false
}
}
/**
* 规则有实质变化时撤销本地确认,无变化保存不调用此方法。
* @param projectId 规则所属项目
*/
export function invalidateQualityPolicyConfirmation(projectId: string) {
invalidations.set(projectId, qualityPolicyConfirmationEpoch(projectId) + 1)
try { localStorage.removeItem(confirmationKey(projectId)) } catch { /* 存储受限时仍撤销页面内确认。 */ }
}
/**
* 当前页面内的确认失效代次,用于存储受限的降级场景。
* @param projectId 当前项目
* @returns 规则失效代次
*/
export function qualityPolicyConfirmationEpoch(projectId: string): number {
return invalidations.get(projectId) ?? 0
} }
+10
View File
@@ -186,4 +186,14 @@ export interface ProjectQualityPolicyResult {
projectId: string projectId: string
/** 服务端实际保存或解析的策略。 */ /** 服务端实际保存或解析的策略。 */
policy: ProjectQualityPolicy policy: ProjectQualityPolicy
/** 服务端修订版本,独立于规则格式版本。 */
revision: number
/** 服务端规则内容指纹。 */
fingerprint: string
/** 当前修订是否已明确确认。 */
confirmed: boolean
/** 最近明确确认的修订,尚未确认时为空。 */
confirmedRevision: number | null
/** 服务端记录的确认时间。 */
confirmedAt: string | null
} }
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton } from 'naive-ui'
import { Save } from '@lucide/vue'
import AppDrawer from '../../components/ui/AppDrawer.vue'
import FormalRepairEditor from './FormalRepairEditor.vue'
import type { PreparationIssue } from './types'
import { getOperation } from '../workflows/operations'
import { hasActiveWorkflowExecution } from '../workflows/execution'
/** 从诊断定位到正式修订,必须等诊断抽屉离场后再打开。 */
const props = defineProps<{
/** 当前项目。 */ projectId: string
/** 从真实列表选择的目标。 */ issue: PreparationIssue | null
}>()
/** 调用方管理离场时机,不叠加两层主抽屉。 */
const open = defineModel<boolean>('open', { default: false })
/** 写入完成后回到列表重新读取诊断。 */
const emit = defineEmits<{ saved: [] }>()
/** 正式编辑器底栏入口。 */
const editor = ref<InstanceType<typeof FormalRepairEditor> | null>(null)
/** 真实写入期间禁止重复操作和意外关闭。 */
const busy = ref(false)
/** 同项目活动任务与真实请求互斥。 */
const locked = computed(() => getOperation(props.projectId).pending || hasActiveWorkflowExecution(props.projectId))
/** 只有真实保存回执通过后关闭,局部修订不自动标记审核通过。 */
function saved() { open.value = false; emit('saved') }
</script>
<template>
<!-- 以下是独立正式修订抽屉,正文与底栏同步铺满视口 -->
<AppDrawer v-model:open="open" title="修订当前正式镜头" :busy="busy" description="读取当前正式动作,保存前会再次核对版本、任务和已有素材。修订后仍需重新检查。">
<FormalRepairEditor v-if="open && issue" ref="editor" :project-id="projectId" :issue="issue" :disabled="locked" @busy="busy = $event" @saved="saved" />
<template #footer><NButton :disabled="busy" @click="open = false">取消</NButton><NButton type="primary" :disabled="busy || locked || !editor?.canSave" :loading="busy" @click="editor?.save()"><template #icon><Save :size="15" /></template>保存本次修订</NButton></template>
</AppDrawer>
</template>
@@ -0,0 +1,198 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox, NFormItem, NInput } from 'naive-ui'
import { Lightbulb, RefreshCw } from '@lucide/vue'
import ShotActionEditor from '../breakdown/components/ShotActionEditor.vue'
import WorkspaceSectionHeading from '../../components/ui/WorkspaceSectionHeading.vue'
import ConfirmAction from '../workflows/ConfirmAction.vue'
import { actionDraft, actionDraftIssue } from '../breakdown/repair'
import type { ShotActionDraft } from '../breakdown/repair.types'
import { preparationApi } from './api'
import type { PreparationIssue, FormalShotRepairPreview, LocatedStoryboardShot, BeatSubjectPreview, FormalRepairResult } from './types'
import { errorMessage } from '../../lib/http'
import { userFacingText } from '../../lib/user-facing-text'
import { getOperation, runOperation } from '../workflows/operations'
/** 正式动作与主体修订只使用当前正式镜头,不能写入候选快照代替正式修复。 */
const props = defineProps<{
/** 当前项目。 */ projectId: string
/** 用户选中的具体问题。 */ issue: PreparationIssue
/** 活动任务及外部操作锁。 */ disabled: boolean
}>()
/** 保存完成后刷新复检;真实请求期间交给父抽屉锁定关闭。 */
const emit = defineEmits<{ saved: []; busy: [value: boolean] }>()
/** 当前正式目标。 */
const target = ref<LocatedStoryboardShot | null>(null)
/** 完整正式动作预览。 */
const preview = ref<FormalShotRepairPreview | null>(null)
/** 独立编辑草稿。 */
const draft = ref<ShotActionDraft | null>(null)
/** 缺失主体的段落证据。 */
const beat = ref<BeatSubjectPreview | null>(null)
/** 独立的镜头主体只读预检查。 */
const subjectCheck = ref<FormalRepairResult | null>(null)
/** 用户明确填写的原因。 */
const reason = ref('')
/** 修改内容后必须重新勾选。 */
const acknowledged = ref(false)
/** 只读加载允许退出。 */
const loading = ref(false)
/** 模型候选与真正保存锁定重复操作。 */
const writing = ref(false)
/** 查询和写入错误。 */
const error = ref('')
/** 点击保存时的字段校验。 */
const issueText = ref('')
/** 模型候选解释,不代表已经保存。 */
const candidateReason = ref('')
/** 主体问题与动作问题使用各自正式 API。 */
const subjectMode = computed(() => !!props.issue.subjectRef)
/** 当前目标是否具备进一步操作前提,版本实际保存前仍会核对。 */
const canSave = computed(() => !!target.value && !props.disabled && !loading.value && !writing.value &&
(subjectMode.value ? !!beat.value?.candidate || subjectCheck.value?.written === false : !!draft.value && preview.value?.classification.status !== 'unchanged'))
/** 同一阶段或动作证据变化后撤销旧确认。 */
watch(draft, () => { acknowledged.value = false; issueText.value = '' }, { deep: true })
watch(reason, () => { issueText.value = '' })
/** 迟到响应隔离。 */
let version = 0
/** 当前只读请求。 */
let controller: AbortController | undefined
/** 从精确坐标或明确的正式 ID 读取当前版本,不代选相邻镜头。 */
async function load() {
const current = ++version, id = props.projectId, issue = props.issue
controller?.abort(); controller = new AbortController()
loading.value = true; error.value = ''; acknowledged.value = false; preview.value = null; target.value = null; draft.value = null; beat.value = null; subjectCheck.value = null
try {
if (!issue.shotNo) throw new Error('这个问题没有唯一镜头位置,请先核对原分镜。')
let located: LocatedStoryboardShot
if (issue.shotId) {
const result = await preparationApi.repairPreview(id, issue.shotId, controller.signal)
if (current !== version) return
if (result.projectId !== id || result.shotId !== issue.shotId || !/^[a-f\d]{64}$/.test(result.expectedFingerprint)) throw new Error('镜头读取结果不一致。')
located = { projectId: id, shotId: issue.shotId, episodeNo: issue.episodeNo, beatNo: issue.beatNo, shotNo: issue.shotNo, expectedFingerprint: result.expectedFingerprint, written: false }
if (!subjectMode.value) preview.value = result
} else located = await preparationApi.locate(id, { episodeNo: issue.episodeNo, beatNo: issue.beatNo, shotNo: issue.shotNo }, controller.signal)
if (current !== version) return
if (located.projectId !== id || located.episodeNo !== issue.episodeNo || located.beatNo !== issue.beatNo || located.shotNo !== issue.shotNo || !located.shotId || !/^[a-f\d]{64}$/.test(located.expectedFingerprint)) throw new Error('目标镜头与当前问题不一致,请刷新。')
target.value = located
if (subjectMode.value) {
const result = await preparationApi.beatSubjectPreview(id, located.shotId, issue.subjectRef!, controller.signal)
if (current !== version) return
if (result.projectId !== id || result.shotId !== located.shotId || result.subjectRef !== issue.subjectRef || result.written !== false) throw new Error('主体证据与当前问题不一致。')
beat.value = result
} else {
const result = preview.value ?? await preparationApi.repairPreview(id, located.shotId, controller.signal)
if (current !== version) return
if (result.projectId !== id || result.shotId !== located.shotId || result.expectedFingerprint !== located.expectedFingerprint || !result.requiredActions?.length || !result.durationPlanning?.phases?.length) throw new Error('缺少当前镜头的完整动作规划,不能推测修订。')
preview.value = result; draft.value = actionDraft(result)
}
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
}
/** 用户选择明确的关联修复建议,仅改变本地草稿。 */
function adopt() {
if (!preview.value?.classification.proposed || props.disabled || writing.value) return
draft.value = actionDraft({ requiredActions: preview.value.requiredActions, durationPlanning: preview.value.classification.proposed })
}
/** 显式预览正式镜头主体追加,不把段落版本当成镜头版本。 */
async function checkSubject() {
if (!target.value || !beat.value || beat.value.status === 'upstream-missing' || props.disabled || writing.value || loading.value) return
const current = version, id = props.projectId, selected = target.value
loading.value = true; error.value = ''; subjectCheck.value = null; acknowledged.value = false
try {
const result = await preparationApi.subjectPreview(id, { shotId: selected.shotId, subjectRef: props.issue.subjectRef!, expectedFingerprint: selected.expectedFingerprint, confirmed: true }, controller?.signal)
if (current !== version) return
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== false) throw new Error('主体修复预览与当前镜头不一致。')
subjectCheck.value = result
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
}
/** 费用确认后仅生成模型建议,服务预检未通过或版本变化均不采用。 */
async function generateCandidate() {
if (!target.value || props.disabled || loading.value || writing.value) return
const selected = target.value, current = version, id = props.projectId
writing.value = true; error.value = ''; acknowledged.value = false
const ok = await runOperation(id, '生成动作修复建议', async () => {
const result = await preparationApi.repairCandidate(id, selected.shotId, selected.expectedFingerprint)
if (current !== version) return
if (result.projectId !== id || result.shotId !== selected.shotId || result.sourceFingerprint !== selected.expectedFingerprint || result.written !== false || result.preflight.written !== false || result.preflight.readyForVersionedWrite !== true || result.preflight.beforeFingerprint !== selected.expectedFingerprint) throw new Error('修复建议未通过当前版本检查,请重新预览。')
draft.value = actionDraft(result.candidate); candidateReason.value = result.candidate.reasoning
}, { type: 'info', content: '修复建议已生成,尚未修改正式镜头,请人工核对。' })
if (current === version) { if (!ok) error.value = getOperation(id).error; writing.value = false }
}
/** 校验原因、确认及完整动作,保存前再次核对当前正式版本。 */
async function save() {
if (!canSave.value || !target.value) return
issueText.value = !reason.value.trim() ? '请填写修订原因。' : reason.value.trim().length > 500 ? '修订原因最多 500 字。' : !acknowledged.value ? '请先核对并确认修订内容。' : !subjectMode.value && draft.value ? actionDraftIssue(draft.value) : ''
if (issueText.value) return
const selected = target.value, current = version, id = props.projectId
loading.value = true; error.value = ''
try {
const latest = await preparationApi.repairPreview(id, selected.shotId, controller?.signal)
if (current !== version || props.disabled) return
if (latest.projectId !== id || latest.shotId !== selected.shotId || latest.expectedFingerprint !== selected.expectedFingerprint) {
acknowledged.value = false; throw new Error('镜头内容已变化,请重新读取并核对修订。')
}
loading.value = false; writing.value = true
const common = { shotId: selected.shotId, subjectRef: props.issue.subjectRef ?? '', expectedFingerprint: selected.expectedFingerprint, confirmed: true as const, reason: reason.value.trim() }
const ok = await runOperation(id, '保存正式镜头修订', async () => {
if (subjectMode.value && beat.value?.candidate) {
const fresh = await preparationApi.beatSubjectPreview(id, selected.shotId, common.subjectRef)
if (current !== version) return
if (!fresh.candidate || fresh.projectId !== id || fresh.shotId !== selected.shotId || fresh.subjectRef !== common.subjectRef || fresh.candidate.expectedFingerprint !== beat.value.candidate.expectedFingerprint) throw new Error('剧情段落来源已变化,请重新预览。')
const result = await preparationApi.repairBeatSubject(id, { ...common, expectedFingerprint: fresh.candidate.expectedFingerprint })
if (result.projectId !== id || result.shotId !== selected.shotId || result.beatId !== fresh.beatId || result.written !== true) throw new Error('剧情段落修订结果尚未确认,请刷新。')
} else if (subjectMode.value) {
const result = await preparationApi.repairSubject(id, common)
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== true) throw new Error('主体修订结果尚未确认,请刷新。')
} else {
const result = await preparationApi.repair(id, { ...actionDraft(draft.value!), shotId: selected.shotId, expectedFingerprint: selected.expectedFingerprint, confirmed: true, reason: reason.value.trim() })
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== true) throw new Error('动作修订结果尚未确认,请刷新。')
}
}, { type: 'info', content: '修订已保存,仍需重新检查并完成人工审核。' })
if (current !== version) return
if (ok) { acknowledged.value = false; emit('saved') } else error.value = getOperation(id).error
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) { loading.value = false; writing.value = false } }
}
watch(writing, value => emit('busy', value), { flush: 'sync' })
watch(() => JSON.stringify([props.projectId, props.issue]), () => { reason.value = ''; issueText.value = ''; candidateReason.value = ''; void load() }, { immediate: true })
onScopeDispose(() => { version++; controller?.abort(); emit('busy', false) })
/** 父抽屉固定底栏调用同一个保存入口。 */
defineExpose({ save, canSave })
</script>
<template>
<!-- 以下是当前正式镜头问题及可取消的读取状态 -->
<div class="formal-repair-editor space-y-6">
<WorkspaceSectionHeading :title="`第 ${issue.episodeNo} 集 · 剧情段落 ${issue.beatNo} · 镜头 ${issue.shotNo ?? '待核对'}`" :description="userFacingText(issue.message)" />
<p v-if="loading" role="status" class="text-sm text-muted">正在核对当前正式镜头…</p>
<div v-if="error" class="problem-surface p-4 space-y-3" role="alert"><p>{{ error }}</p><NButton :disabled="writing || loading" @click="load"><template #icon><RefreshCw :size="15" /></template>重新读取</NButton></div>
<!-- 以下是主体遗漏的段落证据,段落修订和镜头修订分开确认 -->
<section v-if="beat" class="space-y-4">
<WorkspaceSectionHeading :title="`补齐主体:${beat.subjectName}`" description="先核对剧情段落是否包含这个主体,再核对镜头引用。每次只保存当前明确的修订,不改写原始剧本。" />
<p class="text-sm leading-6">剧情段落:{{ beat.beat.description }}</p><p class="text-sm leading-6">当前镜头:{{ beat.shot.description }}</p>
<p v-if="beat.candidate" class="text-sm text-muted">本次将把 {{ beat.subjectName }} 加入当前剧情段落;完成后再单独预览镜头引用修复。</p>
<NButton v-else-if="beat.status !== 'upstream-missing'" :disabled="disabled || writing || loading" @click="checkSubject"><template #icon><Lightbulb :size="15" /></template>检查镜头主体引用</NButton>
<p v-else class="text-sm text-muted">当前没有符合来源要求的主体补充建议,暂不能保存。</p>
<p v-if="subjectCheck" class="text-sm text-muted">主体引用预览通过,保存时仍会重新核对内容和已有资产。</p>
</section>
<!-- 以下是当前正式动作及显式生成建议模块,读取不会调用模型 -->
<template v-if="preview && draft">
<div class="flex flex-wrap gap-3">
<NButton v-if="preview.classification.proposed" :disabled="disabled || writing" @click="adopt"><template #icon><Lightbulb :size="15" /></template>采用明确的关联修复建议</NButton>
<ConfirmAction v-if="preview.classification.status === 'needs_semantic_repair'" label="生成动作修复建议" description="会调用文字模型并产生费用,只生成当前镜头的修复建议,不保存镜头、不生成图片或视频。建议仍需人工核对。" :disabled="disabled || writing || loading" :loading="writing" @confirm="generateCandidate" />
</div>
<p v-if="candidateReason" class="text-sm leading-6 text-muted">建议说明:{{ userFacingText(candidateReason) }}</p>
<p v-if="preview.classification.status === 'unchanged'" class="text-sm text-muted">当前动作规划没有可直接修订的确定性问题,暂不开放保存。可返回诊断列表复查当前镜头。</p>
<ShotActionEditor v-model="draft" :disabled="disabled || writing || loading || preview.classification.status === 'unchanged'" />
</template>
<!-- 以下是明确填写原因与最终核对,打开或添加字段时不自动显示错误 -->
<section v-if="target && (draft || beat)" class="space-y-4">
<NFormItem label="修订原因"><NInput v-model:value="reason" type="textarea" aria-label="修订原因" placeholder="说明如何处理这个问题,以及依据" :autosize="{ minRows: 2, maxRows: 6 }" :disabled="writing" /></NFormItem>
<NCheckbox v-model:checked="acknowledged" aria-label="确认正式镜头修订" :disabled="disabled || writing || loading">我已核对当前镜头及修订内容,保存后重新检查</NCheckbox>
<p v-if="issueText" role="alert" class="text-sm text-danger">{{ issueText }}</p>
</section>
</div>
</template>
@@ -0,0 +1,187 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NCheckbox, NFormItem, NInput, NTag } from 'naive-ui'
import { ArrowLeft, CheckCheck, RefreshCw, Save, ShieldCheck, Wrench } from '@lucide/vue'
import AppDrawer from '../../components/ui/AppDrawer.vue'
import WorkspaceSectionHeading from '../../components/ui/WorkspaceSectionHeading.vue'
import QualityPolicySettings from '../generation-config/components/QualityPolicySettings.vue'
import FormalRepairEditor from './FormalRepairEditor.vue'
import ConfirmAction from '../workflows/ConfirmAction.vue'
import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
import { useWorkflowExecution, hasActiveWorkflowExecution } from '../workflows/execution'
import { getOperation, runOperation } from '../workflows/operations'
import { storyboardApi } from '../storyboard/api'
import { projectsApi } from '../projects/api'
import { useStoryboardPreparation } from './useStoryboardPreparation'
import { currentStoryboardApproval } from './model'
import { preparationApi } from './api'
import type { PreparationIssue } from './types'
import { qualityPolicyConfirmed, qualityPolicySignature, validateQualityPolicyReceipt } from '../projects/quality-policy-confirmation'
import { userFacingText } from '../../lib/user-facing-text'
/** 制作前检查统一入口,即使后续页面尚未开放也可以补齐审核。 */
const props = withDefaults(defineProps<{
/** 当前正式项目。 */ projectId: string
/** 外部项目读取失败或主任务锁。 */ disabled?: boolean
}>(), { disabled: false })
/** 所有写入或后台终态后让调用方刷新实际导航状态。 */
const emit = defineEmits<{ changed: [] }>()
/** 全屏入口,未打开不读取完整复检。 */
const open = ref(false)
/** 当前项目任务观察与表单共同绑定项目。 */
const id = computed(() => props.projectId)
/** 首次打开后才观察派生任务,关闭不丢失正在运行的任务。 */
const watchedProject = ref('')
/** 镜头设计与画面状态沿用真实持久化任务。 */
const directionTask = useWorkflowExecution(watchedProject, 'storyboard-direction')
/** 画面状态单独观察,不把 HTTP 受理当作完成。 */
const visualTask = useWorkflowExecution(watchedProject, 'storyboard-visual-state')
/** 活动任务及发现失败时暂停写入,不依赖本次点击的加载状态。 */
const locked = computed(() => props.disabled || getOperation(id.value).pending || hasActiveWorkflowExecution(id.value) ||
directionTask.discovering.value || visualTask.discovering.value || !!directionTask.discoveryError.value || !!visualTask.discoveryError.value)
/** 复检与独立人工确认流程。 */
const flow = useStoryboardPreparation(id, locked)
/** 当前查看的正式修订目标,在同一抽屉中切换正文。 */
const repairIssue = ref<PreparationIssue | null>(null)
/** 正式修订编辑器,底栏调用统一保存。 */
const repairEditor = ref<InstanceType<typeof FormalRepairEditor> | null>(null)
/** 真实正式修订写入时锁定关闭。 */
const repairWriting = ref(false)
/** 项目质量规则表单,完整保留旧例外。 */
const policyEditor = ref<InstanceType<typeof QualityPolicySettings> | null>(null)
/** 规则确认及派生生成启动中的真实请求。 */
const actionWriting = ref(false)
/** 明确核对项目规则,打开时不默认勾选。 */
const policyAcknowledged = ref(false)
/** 旧分镜重新采用当前规则的明确确认。 */
const baselineAcknowledged = ref(false)
/** 当前正式分镜的整体人工确认。 */
const reviewAcknowledged = ref(false)
/** 真实审核人,不自动代填。 */
const reviewer = ref('')
/** 两种确认使用用户当前填写的说明,不使用模型代填。 */
const reviewNote = ref('')
/** 当前提交后的反馈,普通加载不加常驻错误。 */
const actionError = ref('')
/** 真实写入期间统一锁定抽屉。 */
const busy = computed(() => flow.writing.value || repairWriting.value || actionWriting.value)
/** 必要分项检查只依据真实返回,不使用结构通过代替质量通过。 */
const checks = computed(() => {
const data = flow.data.value
if (!data) return []
return [
{ label: '项目质量规则已确认', passed: flow.policyConfirmed.value },
{ label: '正式分镜采用的规则来源一致', passed: data.quality.provenance.qualityPolicyConsistent === true },
{ label: '结构与镜头来源检查通过', passed: data.quality.structure.valid === true && data.quality.sourceAudit.valid === true },
{ label: '主体引用与动作问题已处理', passed: data.quality.preflightEligible === true },
{ label: '当前版本已完成人工审核', passed: flow.approved.value },
{ label: '可以进入制作计划', passed: data.entry.ready === true }
]
})
/** 任何规则或镜头证据变化都撤销旧勾选,不清空人工说明。 */
watch(flow.sourceKey, () => { policyAcknowledged.value = false; baselineAcknowledged.value = false; reviewAcknowledged.value = false })
/** 打开时读取;关闭立即废弃旧结果及未完成只读请求。 */
watch([open, id], ([shown]) => {
if (shown) watchedProject.value = id.value
else if (watchedProject.value !== id.value) watchedProject.value = ''
repairIssue.value = null; actionError.value = ''
if (shown) void flow.load()
else flow.cancel()
}, { flush: 'sync' })
/** 两个独立派生任务终态后重新读取真实准入。 */
for (const task of [directionTask, visualTask]) watch(() => task.query.data.value?.status, (status, before) => {
if (status !== before && ['completed', 'failed'].includes(status ?? '')) { if (open.value) void flow.load(); emit('changed') }
})
/** 明确确认当前项目规则,必要时先 CAS 保存,不调用拆解或模型。 */
async function confirmPolicy() {
if (locked.value || busy.value || flow.reading.value || !policyAcknowledged.value || !flow.data.value) return
const draft = policyEditor.value?.validatedDraft()
if (!draft) return
const projectId = id.value, expected = flow.data.value.policy
actionWriting.value = true; actionError.value = ''
const ok = await runOperation(projectId, '确认项目质量规则', async () => {
let current = validateQualityPolicyReceipt(await projectsApi.qualityPolicy(projectId), projectId)
if (id.value !== projectId || !open.value) throw new Error('项目或确认页面已变化,请重新核对。')
if (current.revision !== expected.revision || current.fingerprint !== expected.fingerprint) throw new Error('质量规则已变化,请刷新后重新核对。')
if (qualityPolicySignature(draft) !== qualityPolicySignature(current.policy)) current = validateQualityPolicyReceipt(await projectsApi.saveQualityPolicy(projectId, draft, current.revision), projectId)
if (qualityPolicySignature(current.policy) !== qualityPolicySignature(draft)) throw new Error('规则保存内容尚未确认,请重新核对。')
if (id.value !== projectId || !open.value) throw new Error('项目或确认页面已变化,请重新核对。')
const result = validateQualityPolicyReceipt(await projectsApi.confirmQualityPolicy(projectId, current.revision), projectId)
if (!qualityPolicyConfirmed(result) || result.revision !== current.revision || result.fingerprint !== current.fingerprint) throw new Error('规则确认结果不一致,请刷新。')
}, { type: 'info', content: '项目质量规则已确认,还需核对正式分镜的来源和质量。' })
actionWriting.value = false
if (id.value !== projectId) return
if (!ok) actionError.value = getOperation(projectId).error
await flow.load(); emit('changed')
}
/**
* 保存用户当前明确选择的审核记录,两种确认不能互相替代。
* @param kind 旧分镜规则来源或整体审核
*/
async function confirmReview(kind: 'baseline' | 'approval') {
if (!(kind === 'baseline' ? baselineAcknowledged.value : reviewAcknowledged.value)) return
if (await flow.confirm(kind, reviewer.value, reviewNote.value)) emit('changed')
}
/**
* 费用确认后重新核对正式审核,再启动需要补齐或更新的派生设计。
* @param kind 镜头设计或画面状态
*/
async function generate(kind: 'direction' | 'visual') {
if (locked.value || busy.value || flow.reading.value || !flow.approved.value || !flow.data.value) return
const projectId = id.value, expected = flow.data.value.approval.evidence
actionWriting.value = true; actionError.value = ''
const ok = await runOperation(projectId, kind === 'direction' ? '补齐镜头设计' : '补齐画面状态', async () => {
const latest = await preparationApi.approval(projectId)
if (id.value !== projectId || !open.value) return
if (!currentStoryboardApproval(latest, projectId) || latest.evidence.shotFingerprint !== expected.shotFingerprint || latest.evidence.checkpointId !== expected.checkpointId || latest.evidence.qualityPolicyRevision !== expected.qualityPolicyRevision || latest.evidence.qualityPolicyFingerprint !== expected.qualityPolicyFingerprint) throw new Error('正式分镜审核已变化,请重新检查并确认。')
const result = kind === 'direction' ? await storyboardApi.generateDirections(projectId, { concurrency: 2, force: false }) : await storyboardApi.generateVisualStates(projectId, { concurrency: 2, force: false, maxRepairAttempts: 2 })
if (!result.executionId) throw new Error('未取得任务编号,请刷新状态,避免重复提交。')
await (kind === 'direction' ? directionTask : visualTask).track(result.executionId, projectId)
}, { type: 'info', content: '设计任务已受理,请等待实际结果;已有当前有效设计会跳过。' })
actionWriting.value = false
if (id.value === projectId && !ok) actionError.value = getOperation(projectId).error
}
/** 正式保存后返回全局复检,不把局部修复当作整体通过。 */
async function repaired() { repairIssue.value = null; repairWriting.value = false; await flow.load(); emit('changed') }
</script>
<template>
<!-- 以下是项目顶部始终可到达的制作前检查入口 -->
<NButton size="small" class="preparation-trigger workspace-action-button" :disabled="disabled || !projectId" aria-label="制作前检查" @click="open = true"><template #icon><ShieldCheck :size="15" aria-hidden="true" /></template><span class="preparation-trigger-label">制作前检查</span></NButton>
<AppDrawer v-model:open="open" :title="repairIssue ? '修订正式分镜问题' : '制作前检查'" :busy="busy" description="先核对分镜、处理问题并完成人工审核,再补齐设计和进入镜头制作。">
<!-- 以下是在同一抽屉内查看当前正式镜头的修订模块 -->
<FormalRepairEditor v-if="open && repairIssue" ref="repairEditor" :project-id="projectId" :issue="repairIssue" :disabled="locked" @busy="repairWriting = $event" @saved="repaired" />
<div v-else-if="open" class="preparation-content space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3"><span class="text-sm text-muted">检查只读取已有数据;确认、修订和生成均需单独操作。</span><NButton :loading="flow.reading.value" :disabled="busy" @click="flow.load"><template #icon><RefreshCw :size="15" /></template>刷新检查</NButton></div>
<p v-if="flow.reading.value && !flow.data.value" role="status" class="text-sm text-muted">正在检查当前正式分镜…</p>
<p v-if="flow.error.value || actionError" role="alert" class="problem-surface p-4 text-sm">{{ flow.error.value || actionError }}</p>
<p v-if="flow.notice.value" role="status" class="text-sm text-muted">{{ flow.notice.value }}</p>
<template v-if="flow.data.value">
<!-- 以下是分项检查,未知或未通过不伪装成成功 -->
<section class="space-y-4"><WorkspaceSectionHeading title="当前准备情况" description="结构通过、局部修订完成和整体审核是不同步骤。" /><div class="preparation-checks"><div v-for="check in checks" :key="check.label" class="flex items-center justify-between gap-4 text-sm"><span>{{ check.label }}</span><NTag :type="check.passed ? 'success' : 'default'" size="small" :bordered="false">{{ check.passed ? '已满足' : '待完成' }}</NTag></div></div></section>
<!-- 以下是第一次明确确认规则,不显示空白精确例外 -->
<section v-if="!flow.policyConfirmed.value" class="space-y-4"><WorkspaceSectionHeading title="核对项目质量规则" description="确认故事允许哪些动作;已有精确例外会继续保留。" /><QualityPolicySettings ref="policyEditor" :key="flow.data.value.policy.revision" :project-id="projectId" :initial-policy="flow.data.value.policy" :disabled="locked || busy" /><NCheckbox v-model:checked="policyAcknowledged" :disabled="locked || busy">我已核对当前项目质量规则</NCheckbox><NButton type="primary" :disabled="!policyAcknowledged || locked || busy || flow.reading.value" :loading="actionWriting" @click="confirmPolicy"><template #icon><ShieldCheck :size="15" /></template>确认项目质量规则</NButton></section>
<!-- 以下是旧分镜缺少规则记录时的明确重新核对,不重跑拆解 -->
<section v-if="!flow.data.value.quality.provenance.qualityPolicyConsistent" class="space-y-4"><WorkspaceSectionHeading title="核对旧分镜采用的规则" description="旧分镜没有完整规则记录时,由复核人明确采用当前已确认规则重新检查。不会重写历史记录,也不会重新拆解。" /><p v-for="reason in flow.data.value.baseline.reasons" :key="reason" class="text-sm text-muted">{{ userFacingText(reason) }}</p><template v-if="flow.baselineAllowed.value"><NFormItem label="复核人"><NInput aria-label="来源复核人" v-model:value="reviewer" placeholder="填写实际复核人" /></NFormItem><NFormItem label="核对说明"><NInput aria-label="来源核对说明" v-model:value="reviewNote" type="textarea" placeholder="说明核对范围及采用当前规则的依据" /></NFormItem><NCheckbox v-model:checked="baselineAcknowledged" :disabled="locked || busy">我已核对旧分镜,明确采用当前规则继续复检</NCheckbox><NButton type="primary" :disabled="!baselineAcknowledged || locked || busy || flow.reading.value" @click="confirmReview('baseline')">确认规则来源</NButton></template></section>
<!-- 以下是正式主体、动作及来源问题,局部修订独立确认 -->
<section class="space-y-4"><WorkspaceSectionHeading title="处理正式分镜问题" description="只修订明确的问题镜头。涉及规则来源或现有素材保护时,先处理对应限制。" /><p v-if="!flow.issues.value.length" class="text-sm text-muted">当前未返回具体镜头问题,请继续核对上面的来源条件和人工审核。</p><article v-for="(item, index) in flow.issues.value" :key="`${item.kind}-${index}`" class="problem-surface p-4 space-y-3"><p class="text-xs text-muted">第 {{ item.episodeNo }} 集 · 剧情段落 {{ item.beatNo }} · 镜头 {{ item.shotNo ?? '待核对' }}</p><p class="text-sm leading-6">{{ userFacingText(item.message) }}</p><NButton class="workspace-action-button" v-if="item.kind !== 'source' && item.shotNo" :disabled="locked || busy || flow.reading.value" @click="repairIssue = item"><template #icon><Wrench :size="15" /></template>查看并修订</NButton></article></section>
<!-- 以下是正式整体人工审核,不以只读预检或旧记录代替 -->
<section class="space-y-4"><WorkspaceSectionHeading title="人工确认整体分镜" description="检查通过后,由复核人核对动作、主体及镜头衔接。规则或镜头变化后原审核会失效。" /><p v-if="flow.approved.value" class="text-sm text-muted">当前正式分镜已有有效审核记录。</p><p v-else-if="!flow.reviewable.value" class="text-sm text-muted">请先处理规则来源、动作与主体问题,再进行整体审核。</p><template v-else><NFormItem label="审核人"><NInput aria-label="整体审核人" v-model:value="reviewer" placeholder="填写实际审核人" /></NFormItem><NFormItem label="审核说明"><NInput aria-label="整体审核说明" v-model:value="reviewNote" type="textarea" placeholder="说明已核对的动作、主体、画面衔接及结论" /></NFormItem><NCheckbox v-model:checked="reviewAcknowledged" :disabled="locked || busy">我已人工核对当前版本的全部正式分镜</NCheckbox><NButton type="primary" :disabled="!reviewAcknowledged || locked || busy || flow.reading.value" @click="confirmReview('approval')"><template #icon><CheckCheck :size="15" /></template>确认整体审核</NButton></template></section>
<!-- 以下是审核之后的设计补齐与真实生产入口状态 -->
<section class="space-y-4"><WorkspaceSectionHeading title="补齐镜头设计与画面状态" description="先更新镜头设计,再更新画面状态。只补齐缺失或过期结果,生成可能产生模型费用。" /><p class="text-sm text-muted">已保存镜头设计 {{ flow.data.value.entry.derivedAssets.directionCount }} / {{ flow.data.value.entry.derivedAssets.shotCount }} · 画面状态 {{ flow.data.value.entry.derivedAssets.visualStateCount }} / {{ flow.data.value.entry.derivedAssets.shotCount }}</p><div class="flex flex-wrap gap-3"><ConfirmAction label="补齐或更新镜头设计" description="处理整个项目中缺失或过期的镜头设计,已有当前有效结果会跳过。会调用文字模型并产生费用,不生成图片或视频。" :disabled="!flow.approved.value || flow.data.value.entry.ready || locked || busy || flow.reading.value" @confirm="generate('direction')" /><ConfirmAction label="补齐或更新画面状态" description="根据正式镜头和最新镜头设计处理整个项目的画面状态,已有当前有效结果会跳过。会调用文字模型并可能进行最多两次修复,可能产生费用。" :disabled="!flow.approved.value || flow.data.value.entry.ready || locked || busy || flow.reading.value || flow.data.value.entry.derivedAssets.directionCount !== flow.data.value.entry.derivedAssets.shotCount" @confirm="generate('visual')" /></div><p class="text-sm" :class="flow.data.value.entry.ready ? 'text-muted' : 'text-danger'">{{ flow.data.value.entry.ready ? '正式分镜已满足制作入口条件。制作计划还会继续检查主体素材和镜头资产。' : userFacingText(flow.data.value.entry.reason, '制作入口尚未满足条件。') }}</p></section>
</template>
<!-- 以下是服务持久化的派生任务,关闭抽屉后仍可观察 -->
<WorkflowExecutionPanel v-if="directionTask.executionId.value" title="镜头设计任务" :execution="directionTask.query.data.value ?? null" :loading="directionTask.query.loading.value" :error="directionTask.query.error.value ?? ''" @refresh="directionTask.query.refresh()" @dismiss="directionTask.dismiss()" />
<WorkflowExecutionPanel v-if="visualTask.executionId.value" title="画面状态任务" :execution="visualTask.query.data.value ?? null" :loading="visualTask.query.loading.value" :error="visualTask.query.error.value ?? ''" @refresh="visualTask.query.refresh()" @dismiss="visualTask.dismiss()" />
</div>
<template #footer><NButton :disabled="busy" @click="open = false">关闭</NButton><template v-if="repairIssue"><NButton :disabled="busy" @click="repairIssue = null"><template #icon><ArrowLeft :size="15" /></template>返回检查</NButton><NButton type="primary" :loading="repairWriting" :disabled="!repairEditor?.canSave || busy || locked" @click="repairEditor?.save()"><template #icon><Save :size="15" /></template>保存本次修订</NButton></template></template>
</AppDrawer>
</template>
<style scoped>
.preparation-checks { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 40px; }
.preparation-checks > div { min-width: 0; }
@media (max-width: 760px) { .preparation-checks { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 639px) { .preparation-trigger-label { display: none; } }
</style>
+147
View File
@@ -0,0 +1,147 @@
import { storyboardApi } from '../storyboard/api'
import { request } from '../../lib/http'
import type { DiagnosisLocation } from '../breakdown/diagnosis'
import type { StoryboardHandRepairHistory } from '../breakdown/types'
import type { StoryboardRecheck, ReviewBaselinePreview, StoryboardApproval, StoryboardApprovalState, StoryboardReviewInput, ProductionEntryReadiness, LocatedStoryboardShot, FormalShotRepairPreview, FormalRepairCandidate, FormalRepairInput, FormalRepairResult, BeatSubjectPreview, BeatSubjectRepairResult, SubjectRepairInput } from './types'
/**
* 所有制作前检查都绑定正式项目。
* @param id 正式项目编号
* @returns 编码后的项目路径
*/
function root(id: string): string { return `/projects/${encodeURIComponent(id)}` }
/** 正式分镜审核、版本化修复和制作入口,不使用测试路由。 */
export const preparationApi = {
/**
* 只读复检,不自动审核。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
recheck: (id: string, signal?: AbortSignal) => request<StoryboardRecheck>(`${root(id)}/breakdown/storyboard-quality-recheck`, { signal }),
/**
* 读取旧分镜规则来源的确认条件。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
baseline: (id: string, signal?: AbortSignal) => request<ReviewBaselinePreview>(`${root(id)}/breakdown/storyboard-review-baseline/preview`, { signal }),
/**
* 明确确认历史规则来源,不改写历史拆解。
* @param id 当前项目编号
* @param input 人工核对内容与原始版本
* @returns 正式接口的实际业务回执
*/
confirmBaseline: (id: string, input: StoryboardReviewInput) => request<StoryboardApproval>(`${root(id)}/breakdown/storyboard-review-baseline/confirm`, { method: 'POST', body: input }),
/**
* 读取人工审核凭据及当前内容证据。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
approval: (id: string, signal?: AbortSignal) => request<StoryboardApprovalState>(`${root(id)}/storyboard/quality-confirmation`, { signal }),
/**
* 明确确认当前分镜的整体审核。
* @param id 当前项目编号
* @param input 人工审核内容与原始版本
* @returns 正式接口的实际业务回执
*/
confirmApproval: (id: string, input: StoryboardReviewInput) => request<StoryboardApproval>(`${root(id)}/storyboard/quality-confirmation`, { method: 'POST', body: input }),
/**
* 只读制作入口结论,必须在制作计划前核对。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
entry: (id: string, signal?: AbortSignal) => request<ProductionEntryReadiness>(`${root(id)}/production/entry-readiness`, { signal }),
/**
* 通过精确坐标获得正式镜头和内容版本。
* @param id 当前项目编号
* @param target 精确的剧集段落及镜头
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
locate: (id: string, target: Required<DiagnosisLocation>, signal?: AbortSignal) => request<LocatedStoryboardShot>(`${root(id)}/breakdown/storyboard-shots/locate?${new URLSearchParams({ episodeNo: String(target.episodeNo), beatNo: String(target.beatNo), shotNo: String(target.shotNo) })}`, { signal }),
/**
* 读取当前正式镜头可编辑动作和确定性建议。
* @param id 当前项目编号
* @param shotId 正式镜头编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
repairPreview: (id: string, shotId: string, signal?: AbortSignal) => request<FormalShotRepairPreview>(`${root(id)}/breakdown/storyboard-shot-repair/preview/${encodeURIComponent(shotId)}`, { signal }),
/**
* 用户确认费用后才调用文字模型生成建议,不保存镜头。
* @param id 当前项目编号
* @param shotId 正式镜头编号
* @param expectedFingerprint 已核对的原始镜头内容
* @returns 正式接口的实际业务回执
*/
repairCandidate: (id: string, shotId: string, expectedFingerprint: string) => request<FormalRepairCandidate>(`${root(id)}/breakdown/storyboard-shot-repair/candidate`, { method: 'POST', body: { shotId, expectedFingerprint }, timeoutMs: 0 }),
/**
* 明确保存动作,事务内继续检查来源、资产和任务。
* @param id 当前项目编号
* @param input 明确确认的动作修订与原始版本
* @returns 正式接口的实际业务回执
*/
repair: (id: string, input: FormalRepairInput) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-repair`, { method: 'POST', body: input }),
/**
* 按需读取不可变正式修订历史。
* @param id 当前项目编号
* @param shotId 正式镜头编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
revisions: (id: string, shotId: string, signal?: AbortSignal) => request<StoryboardHandRepairHistory>(`${root(id)}/breakdown/storyboard-shot-revision-history/${encodeURIComponent(shotId)}`, { signal }),
/**
* 只读核对缺失主体的上游段落和当前镜头证据。
* @param id 当前项目编号
* @param shotId 正式镜头编号
* @param subjectRef 当前项目已有主体
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
beatSubjectPreview: (id: string, shotId: string, subjectRef: string, signal?: AbortSignal) => request<BeatSubjectPreview>(`${root(id)}/breakdown/storyboard-beat-subject-repair/preview`, { method: 'POST', body: { shotId, subjectRef }, signal }),
/**
* 用户确认后按段落内容版本追加主体。
* @param id 当前项目编号
* @param input 明确确认的段落主体修订与段落版本
* @returns 正式接口的实际业务回执
*/
repairBeatSubject: (id: string, input: SubjectRepairInput) => request<BeatSubjectRepairResult>(`${root(id)}/breakdown/storyboard-beat-subject-repair`, { method: 'POST', body: input }),
/**
* 只读核对当前镜头主体追加,前置段落证据须已完整。
* @param id 当前项目编号
* @param input 待检查的镜头主体与原始版本
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
subjectPreview: (id: string, input: SubjectRepairInput, signal?: AbortSignal) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair/preview`, { method: 'POST', body: { shotId: input.shotId, subjectRef: input.subjectRef, expectedFingerprint: input.expectedFingerprint, confirmed: true }, signal }),
/**
* 用户确认后按镜头内容版本追加已有主体。
* @param id 当前项目编号
* @param input 明确确认的镜头主体修订与镜头版本
* @returns 正式接口的实际业务回执
*/
repairSubject: (id: string, input: SubjectRepairInput) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair`, { method: 'POST', body: input })
}
/**
* 覆盖率完整也可能是旧设计,进入制作计划前逐集核对服务明确返回的过期数量。
* @param projectId 当前项目
* @param episodeNos 正式剧集范围
* @param expectedShotCount 入口统计的正式镜头数
* @returns 当前版本检查完成,缺失或过期时抛出可操作错误
*/
export async function assertCurrentStoryboardDesigns(projectId: string, episodeNos: number[], expectedShotCount: number): Promise<void> {
const numbers = [...new Set(episodeNos)]
if (!numbers.length || !Number.isSafeInteger(expectedShotCount) || expectedShotCount <= 0) throw new Error('正式镜头范围尚未确认,请刷新制作前检查。')
const records = await Promise.all(numbers.map(async episodeNo => {
const [direction, visual] = await Promise.all([storyboardApi.directions(projectId, episodeNo), storyboardApi.visualStates(projectId, episodeNo)])
if (direction.projectId !== projectId || visual.projectId !== projectId || direction.episodeNo !== episodeNo || visual.episodeNo !== episodeNo) throw new Error('设计检查结果与当前项目或剧集不一致。')
if (direction.staleCount !== 0 || visual.staleCount !== 0 || direction.shotCount !== direction.directionCount || visual.shotCount !== visual.visualStateCount || direction.coverage !== 1 || visual.coverage !== 1 || direction.shotCount !== visual.shotCount)
throw new Error('镜头设计或画面状态已过期、缺失或版本尚未确认,请先补齐或更新设计。')
return direction.shotCount
}))
if (records.reduce((total, count) => total + count, 0) !== expectedShotCount) throw new Error('设计与正式镜头范围不一致,请刷新后核对。')
}
@@ -0,0 +1,17 @@
import type { StoryboardApprovalState } from './types'
/**
* 当前有效审核必须同时绑定项目、规则、保存记录及正式镜头内容,不能只看 valid 或旧记录存在。
* @param state 服务返回的审核凭据及当前证据
* @param projectId 当前项目
* @returns 是否具有当前内容对应的有效整体审核
*/
export function currentStoryboardApproval(state: StoryboardApprovalState | null | undefined, projectId: string): boolean {
const record = state?.confirmation, evidence = state?.evidence
return state?.valid === true && !!record && !!evidence && evidence.valid === true &&
record.projectId === projectId && !!evidence.checkpointId && record.checkpointId === evidence.checkpointId &&
Number.isSafeInteger(evidence.qualityPolicyRevision) && evidence.qualityPolicyRevision! >= 0 &&
record.qualityPolicyRevision === evidence.qualityPolicyRevision && record.qualityPolicyFingerprint === evidence.qualityPolicyFingerprint &&
/^[a-f\d]{64}$/.test(evidence.qualityPolicyFingerprint ?? '') && record.shotCount === evidence.shotCount &&
evidence.shotCount > 0 && record.shotFingerprint === evidence.shotFingerprint && /^[a-f\d]{64}$/.test(evidence.shotFingerprint)
}
@@ -0,0 +1,188 @@
import type { DiagnosisLocation } from '../breakdown/diagnosis'
import type { ShotActionDraft, ShotDurationPlanning } from '../breakdown/repair.types'
/** 正式分镜检查中可定位的问题。 */
export interface PreparationIssue extends Omit<DiagnosisLocation, 'shotNo'> {
/** 段落级问题没有唯一镜头时为空。 */
shotNo?: number | null
/** 正式镜头编号,缺失时按坐标查询。 */
shotId?: string
/** 当前问题类型。 */
code?: string
/** 真实问题说明。 */
message: string
/** 缺失的主体引用。 */
subjectRef?: string
}
/** 正式分镜的只读确定性复检,不等于人工确认。 */
export interface StoryboardRecheck {
/** 所属项目。 */
projectId: string
/** 综合问题状态,当前接口不返回全局通过。 */
status: 'blocked' | 'insufficient_evidence' | 'needs_review'
/** 结构检查。 */
structure: { /** 是否有检查记录。 */ hasValidation: boolean; /** 明确结构结论。 */ valid: boolean | null; /** 原因。 */ reason: string | null }
/** 正式镜头及引用问题统计。 */
coverage: { /** 剧集数。 */ episodeCount: number; /** 剧情段落数。 */ beatCount: number; /** 镜头数。 */ shotCount: number; /** 引用问题数。 */ issueCount: number }
/** 主体遗漏。 */
issues: PreparationIssue[]
/** 动作检查,单独区分阻断与待复核。 */
actionAudit: { /** 所属项目。 */ projectId: string; /** 镜头数。 */ shotCount: number; /** 问题数。 */ issueCount: number; /** 阻断数。 */ blockedCount: number; /** 待复核数。 */ needsReviewCount: number; /** 可定位问题。 */ issues: PreparationIssue[] }
/** 正式镜头来源检查。 */
sourceAudit: { /** 所属项目。 */ projectId: string; /** 源记录。 */ checkpointId: string | null; /** 镜头数。 */ shotCount: number; /** 来源一致。 */ valid: boolean; /** 来源问题。 */ issues: PreparationIssue[] }
/** 多项来源证据,不能用结构通过替代。 */
provenance: {
/** 最新保存记录。 */ checkpointId: string | null
/** 分镜已正式提交。 */ sourceCommitted: boolean
/** 规则来源一致。 */ qualityPolicyConsistent: boolean
/** 分项规则证据。 */ qualityPolicyChecks: Record<string, boolean>
/** 人工确认的历史规则来源有效。 */ baselineConsistent: boolean
/** 各项镜头数量一致。 */ shotCountsConsistent: boolean
/** 各项使用同一保存记录。 */ checkpointConsistent: boolean
}
/** 可以继续进入人工审核,不能代替正式生产准入。 */
preflightEligible: boolean
/** 本接口始终不直接确认。 */
canConfirm: false
}
/** 历史分镜缺少规则快照时,明确建立新审核来源的只读预览。 */
export interface ReviewBaselinePreview {
/** 是否具备确认前提。 */ eligible: boolean
/** 阻断原因。 */ reasons: string[]
/** 原正式保存记录。 */ checkpointId: string | null
/** 正式镜头数。 */ shotCount: number
/** 全项目正式镜头内容版本。 */ shotFingerprint: string | null
}
/** 用户审核记录,规则、正式镜头或保存记录变化后失效。 */
export interface StoryboardApproval {
/** 记录编号。 */ id: string
/** 所属项目。 */ projectId: string
/** 本次采用的保存记录。 */ checkpointId: string
/** 规则修订。 */ qualityPolicyRevision: number
/** 规则内容版本。 */ qualityPolicyFingerprint: string
/** 审核镜头数。 */ shotCount: number
/** 正式镜头内容版本。 */ shotFingerprint: string
/** 审核人。 */ reviewer: string
/** 审核说明。 */ reviewNote: string
/** 明确确认时间。 */ confirmedAt: string
}
/** 当前人工确认记录及重新读取的正式内容证据。 */
export interface StoryboardApprovalState {
/** 当前确认仍然有效。 */ valid: boolean
/** 历史确认,不因存在而自动视为有效。 */ confirmation: StoryboardApproval | null
/** 最新证据。 */ evidence: {
/** 来源完整。 */ valid: boolean
/** 当前保存记录。 */ checkpointId: string | null
/** 当前规则修订。 */ qualityPolicyRevision: number | null
/** 当前规则内容。 */ qualityPolicyFingerprint: string | null
/** 当前镜头数。 */ shotCount: number
/** 当前镜头内容。 */ shotFingerprint: string
}
}
/** 确认审核或历史规则来源时统一绑定当前版本。 */
export interface StoryboardReviewInput {
/** 审核人。 */ reviewer: string
/** 明确填写的审核说明。 */ reviewNote: string
/** 用户核对的保存记录。 */ expectedCheckpointId: string
/** 用户核对的镜头版本。 */ expectedShotFingerprint: string
}
/** 正式制作入口的只读结论。 */
export interface ProductionEntryReadiness {
/** 当前允许进入制作计划。 */ ready: boolean
/** 存在拆解结构检查。 */ hasStoryboardValidation: boolean
/** 明确结构结论。 */ storyboardValid: boolean | null
/** 当前阻断原因。 */ reason: string | null
/** 已保存的派生设计数量,不能代替新旧版本检查。 */
derivedAssets: { /** 正式镜头数。 */ shotCount: number; /** 镜头设计数。 */ directionCount: number; /** 镜头设计覆盖。 */ directionCoverage: number; /** 画面状态数。 */ visualStateCount: number; /** 画面状态覆盖。 */ visualStateCoverage: number }
}
/** 通过真实坐标查询得到的正式镜头身份。 */
export interface LocatedStoryboardShot extends Required<DiagnosisLocation> {
/** 项目编号。 */ projectId: string
/** 正式镜头编号。 */ shotId: string
/** 当前镜头内容版本。 */ expectedFingerprint: string
/** 只读请求。 */ written: false
}
/** 当前正式动作及确定性修复候选,不能从旧检查点补齐。 */
export interface FormalShotRepairPreview extends ShotActionDraft {
/** 所属项目。 */ projectId: string
/** 目标正式镜头。 */ shotId: string
/** 当前内容版本。 */ expectedFingerprint: string
/** 真实修复分类。 */ classification: {
/** 仅可补齐明确动作;语义问题需人工或模型。 */ status: 'candidate' | 'needs_semantic_repair' | 'unchanged'
/** 候选源版本。 */ beforeFingerprint: string
/** 明确的确定性建议,缺失时不猜测。 */ proposed: ShotDurationPlanning | null
/** 具体语义疑点。 */ semanticIssues: { /** 动作编号。 */ actionId: string; /** 动作描述。 */ description: string; /** 原阶段位置。 */ phaseIndex: number }[]
/** 原始问题。 */ originalIssues: { /** 问题类别。 */ code: string; /** 说明。 */ message: string }[]
}
/** 未写入。 */ written: false
/** 只读。 */ willCallModel: false
}
/** 真实模型候选只通过独立的保存操作写入。 */
export interface FormalRepairCandidate {
/** 所属项目。 */ projectId: string
/** 目标镜头。 */ shotId: string
/** 生成时原始内容。 */ sourceFingerprint: string
/** 完整候选。 */ candidate: ShotActionDraft & { /** 模型修改依据。 */ reasoning: string }
/** 当前预检结果,不自动代替用户确认。 */ preflight: FormalRepairResult
/** 尚未写入。 */ written: false
/** 未更换素材。 */ willModifyAssets: false
}
/** 正式动作修复保存或预检查回执。 */
export interface FormalRepairResult {
/** 所属项目。 */ projectId: string
/** 正式镜头。 */ shotId: string
/** 实际是否已经保存。 */ written: boolean
/** 保存前内容版本。 */ beforeFingerprint: string
/** 保存后内容版本。 */ afterFingerprint: string
/** 满足版本化写入条件。 */ readyForVersionedWrite?: boolean
/** 局部审核状态。 */ status?: string
/** 未解决的警告。 */ warnings?: string[]
/** 没有调用模型。 */ willCallModel?: false
}
/** 正式动作保存只发送允许的动作与规划字段。 */
export interface FormalRepairInput extends ShotActionDraft {
/** 正式镜头编号。 */ shotId: string
/** 绑定原始版本。 */ expectedFingerprint: string
/** 用户明确确认。 */ confirmed: true
/** 用户填写的原因。 */ reason: string
}
/** 上游剧情段落主体修复的只读证据与候选。 */
export interface BeatSubjectPreview {
/** 所属项目。 */ projectId: string
/** 目标镜头。 */ shotId: string
/** 剧情段落。 */ beatId: string
/** 正式保存记录。 */ checkpointId: string
/** 缺失主体。 */ subjectRef: string
/** 真实主体名称。 */ subjectName: string
/** 主体介绍。 */ subjectDescription: string | null
/** 剧情段落原始内容。 */ beat: { /** 标题。 */ title: string; /** 正文。 */ description: string; /** 重点。 */ visualFocus: string; /** 已有引用。 */ subjectRefs: string[] }
/** 当前镜头内容。 */ shot: { /** 标题。 */ title: string; /** 正文。 */ description: string; /** 重点。 */ visualFocus: string }
/** 来源情况。 */ status: 'upstream-present' | 'revision-present' | 'upstream-missing'
/** 不修改数据。 */ written: false
/** 真实可审核候选。 */ candidate: null | {
/** 候选源记录。 */ checkpointId: string
/** 所属段落。 */ beatId: string
/** 目标主体。 */ subjectRef: string
/** 段落内容版本,与镜头指纹不可混用。 */ expectedFingerprint: string
/** 明确建议增加的引用。 */ proposed: { /** 来源引用。 */ upstreamRefs: string[]; /** 正式段落引用。 */ persistedRefs: string[] }
/** 必须人工核对。 */ requiresHumanReview: true
}
}
/** 主体修复请求,明确区分镜头指纹与段落指纹。 */
export interface SubjectRepairInput {
/** 真实镜头。 */ shotId: string
/** 项目已有主体。 */ subjectRef: string
/** 目标内容版本。 */ expectedFingerprint: string
/** 用户明确确认。 */ confirmed: true
/** 保存时填写原因,预览时不发送。 */ reason?: string
}
/** 段落主体修订回执,其版本不能作为镜头版本使用。 */
export interface BeatSubjectRepairResult {
/** 所属项目。 */ projectId: string
/** 目标镜头。 */ shotId: string
/** 目标段落。 */ beatId: string
/** 来源记录。 */ checkpointId: string
/** 修订后段落内容版本。 */ resultFingerprint: string
/** 真实保存状态。 */ written: true
}
@@ -0,0 +1,151 @@
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import { currentStoryboardApproval } from './model'
import { preparationApi, assertCurrentStoryboardDesigns } from './api'
import { projectsApi } from '../projects/api'
import { qualityPolicyConfirmed, validateQualityPolicyReceipt } from '../projects/quality-policy-confirmation'
import { getOperation, runOperation } from '../workflows/operations'
import { errorMessage } from '../../lib/http'
/**
* 只读核对当前项目各项真实返回,不补默认通过状态。
* @param id 项目编号
* @param signal 取消信号
* @returns 当前各项检查结果
*/
async function read(id: string, signal: AbortSignal) {
const [quality, approval, baseline, entry, policy] = await Promise.all([
preparationApi.recheck(id, signal), preparationApi.approval(id, signal),
preparationApi.baseline(id, signal), preparationApi.entry(id, signal), projectsApi.qualityPolicy(id, signal)
])
validateQualityPolicyReceipt(policy, id)
if (quality.projectId !== id || quality.actionAudit.projectId !== id || quality.sourceAudit.projectId !== id ||
approval.confirmation && approval.confirmation.projectId !== id)
throw new Error('检查结果与当前项目不一致,请重新读取。')
let currentEntry = entry
if (entry.ready === true) {
try {
const project = await projectsApi.detail(id, signal)
if (project.id !== id) throw new Error('制作检查项目不一致。')
await assertCurrentStoryboardDesigns(id, project.episodes.map(item => item.episode), entry.derivedAssets.shotCount)
} catch (cause) { currentEntry = { ...entry, ready: false, reason: errorMessage(cause) } }
}
return { quality, approval, baseline, entry: currentEntry, policy }
}
/**
* 正式分镜检查与两种独立人工确认,不能把结构通过或存在旧记录当作生产许可。
* @param projectId 当前正式项目
* @param locked 活动任务或外部操作锁
* @returns 只读数据、版本约束下的确认和刷新方法
*/
export function useStoryboardPreparation(projectId: Ref<string>, locked: Ref<boolean>) {
/** 所有数据仅按需读取,缺失时禁止写入。 */
const data = ref<Awaited<ReturnType<typeof read>> | null>(null)
/** 普通查询允许关闭。 */
const reading = ref(false)
/** 真实确认写入期间锁定关闭。 */
const writing = ref(false)
/** 当前可操作的错误。 */
const error = ref('')
/** 仅说明写入成功,不等同于准入通过。 */
const notice = ref('')
/** 请求代次隔离项目切换和关闭。 */
let version = 0
/** 只读请求取消控制器。 */
let controller: AbortController | undefined
/** 人工确认使用的完整内容身份,规则变化或镜头变化都要求重新核对。 */
const sourceKey = computed(() => JSON.stringify(data.value ? {
projectId: projectId.value, evidence: data.value.approval.evidence, baseline: data.value.baseline,
policyRevision: data.value.policy.revision, policyFingerprint: data.value.policy.fingerprint,
quality: data.value.quality
} : null))
/** 规则已经由项目独立确认。 */
const policyConfirmed = computed(() => !!data.value && qualityPolicyConfirmed(data.value.policy))
/** 历史来源确认只适用于服务明确允许的旧正式分镜,不改写拆解记录。 */
const baselineAllowed = computed(() => {
const value = data.value
return !!value && policyConfirmed.value && !value.quality.provenance.qualityPolicyConsistent &&
value.baseline.eligible === true && !!value.baseline.checkpointId &&
value.baseline.checkpointId === value.quality.provenance.checkpointId && value.baseline.shotCount > 0 &&
/^[a-f\d]{64}$/.test(value.baseline.shotFingerprint ?? '')
})
/** 只读预检满足后才能人工审核;canConfirm=false 只是查询本身不写入。 */
const reviewable = computed(() => {
if (!data.value || !policyConfirmed.value) return false
const { quality: q, approval: a, policy } = data.value
return q.preflightEligible === true && q.structure.valid === true && q.sourceAudit.valid === true &&
q.provenance.sourceCommitted === true && q.provenance.qualityPolicyConsistent === true &&
q.provenance.shotCountsConsistent === true && q.provenance.checkpointConsistent === true &&
q.coverage.shotCount > 0 && q.issues.length === 0 && q.actionAudit.issueCount === 0 &&
a.evidence.valid === true && a.evidence.checkpointId === q.provenance.checkpointId &&
!!a.evidence.checkpointId && a.evidence.shotCount === q.coverage.shotCount &&
a.evidence.qualityPolicyRevision === policy.revision && a.evidence.qualityPolicyFingerprint === policy.fingerprint &&
/^[a-f\d]{64}$/.test(a.evidence.shotFingerprint)
})
/** 当前有效的人工审核,不因存在历史记录而显示通过。 */
const approved = computed(() => reviewable.value && currentStoryboardApproval(data.value?.approval, projectId.value))
/** 所有动作、主体和来源问题按真实位置保留,不合并成虚构镜头。 */
const issues = computed(() => data.value ? [
...data.value.quality.issues.map(item => ({ ...item, kind: 'subject' as const })),
...data.value.quality.actionAudit.issues.map(item => ({ ...item, kind: 'action' as const })),
...data.value.quality.sourceAudit.issues.map(item => ({ ...item, kind: 'source' as const }))
] : [])
/** 主动刷新时保留旧正文,但取消旧确认资格直到新查询完成。 */
async function load() {
if (writing.value) return
const current = ++version, id = projectId.value
controller?.abort(); controller = new AbortController()
reading.value = true; error.value = ''
try { const result = await read(id, controller.signal); if (current === version) data.value = result }
catch (cause) { if (current === version) { data.value = null; error.value = errorMessage(cause) } }
finally { if (current === version) reading.value = false }
}
/**
* 用户明确核对后确认当前版本,确认前重新读取,发生变化时绝不自动改签新版本。
* @param kind 历史规则来源或整体分镜审核
* @param reviewer 明确填写的复核人
* @param reviewNote 明确填写的核对说明
* @returns 是否保存了与用户核对一致的记录
*/
async function confirm(kind: 'baseline' | 'approval', reviewer: string, reviewNote: string): Promise<boolean> {
if (locked.value || reading.value || writing.value || !data.value ||
!(kind === 'baseline' ? baselineAllowed.value : reviewable.value && !approved.value)) return false
if (!reviewer.trim() || reviewer.trim().length > 120 || !reviewNote.trim() || reviewNote.trim().length > 4000) {
error.value = '请填写复核人和核对说明;姓名最多 120 字,说明最多 4000 字。'; return false
}
const id = projectId.value, current = version, expected = sourceKey.value
const source = kind === 'baseline' ? data.value.baseline : data.value.approval.evidence
const input = { reviewer: reviewer.trim(), reviewNote: reviewNote.trim(), expectedCheckpointId: source.checkpointId!, expectedShotFingerprint: source.shotFingerprint! }
controller?.abort(); controller = new AbortController(); reading.value = true; error.value = ''; notice.value = ''
try {
const latest = await read(id, controller.signal)
if (current !== version || locked.value) return false
data.value = latest
if (sourceKey.value !== expected) { error.value = '规则或镜头检查结果已变化,请重新核对并确认。'; return false }
reading.value = false; writing.value = true
const ok = await runOperation(id, kind === 'baseline' ? '确认历史分镜规则来源' : '确认正式分镜审核', async () => {
const record = await (kind === 'baseline' ? preparationApi.confirmBaseline(id, input) : preparationApi.confirmApproval(id, input))
if (record.projectId !== id || record.checkpointId !== input.expectedCheckpointId ||
record.shotFingerprint !== input.expectedShotFingerprint || record.qualityPolicyRevision !== latest.policy.revision ||
record.qualityPolicyFingerprint !== latest.policy.fingerprint)
throw new Error('确认回执与核对内容不一致,请刷新后检查。')
}, { type: 'info', content: '审核记录已保存,请以刷新后的检查结果为准。' })
if (current !== version) return false
const writeError = !ok ? getOperation(id).error : ''
if (!ok) error.value = writeError
else notice.value = kind === 'baseline' ? '已确认旧分镜采用的规则来源,仍需处理问题并完成整体审核。' : '整体审核记录已保存,镜头或规则变化后需要重新审核。'
writing.value = false
await load()
if (writeError) error.value = writeError
return ok
} catch (cause) { if (current === version) error.value = errorMessage(cause); return false }
finally { if (current === version) { reading.value = false; writing.value = false } }
}
/** 关闭或离开时只废弃请求;已提交写入不能由迟到回执污染新项目。 */
function cancel() { version++; controller?.abort(); reading.value = false; writing.value = false; data.value = null; error.value = ''; notice.value = '' }
watch(projectId, cancel, { flush: 'sync' })
onScopeDispose(cancel)
return { data, reading, writing, error, notice, sourceKey, policyConfirmed, baselineAllowed, reviewable, approved, issues, load, confirm, cancel }
}
+7 -3
View File
@@ -72,6 +72,8 @@ const {
allowed, allowed,
blocked, blocked,
directionComplete, directionComplete,
approval,
approved,
visualStateComplete, visualStateComplete,
hasCurrentEpisodeShots, hasCurrentEpisodeShots,
executions, executions,
@@ -224,6 +226,8 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
<template> <template>
<WorkspacePage split compact mobile-scroll class="storyboard-workspace-page compact-shot-workspace"> <WorkspacePage split compact mobile-scroll class="storyboard-workspace-page compact-shot-workspace">
<template #notice> <template #notice>
<!-- 以下是正式分镜审核先于派生生成的明确提示,查看已有设计仍可继续 -->
<ContextNotice v-if="!approved" type="info" :show-icon="false"><p>{{ approval.loading.value ? '正在核对正式分镜审核…' : approval.error.value ? '整体审核记录暂时无法读取,已暂停镜头设计与画面状态生成。' : '当前正式分镜尚未完成整体审核,或规则与镜头版本已变化。请先打开顶部“制作前检查”。' }}</p><NButton v-if="approval.error.value" :loading="approval.loading.value" @click="approval.refresh">重新读取审核记录</NButton></ContextNotice>
<ContextNotice v-if="episodeSourceUnavailable" type="info" :show-icon="false"> <ContextNotice v-if="episodeSourceUnavailable" type="info" :show-icon="false">
本集镜头已重新生成。新标题和剧情详情尚未提供,当前只显示正式镜头编号;请按实际生成规格核对内容。 本集镜头已重新生成。新标题和剧情详情尚未提供,当前只显示正式镜头编号;请按实际生成规格核对内容。
</ContextNotice> </ContextNotice>
@@ -546,11 +550,11 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
:show-icon="false" :show-icon="false"
class="mt-4" class="mt-4"
> >
<strong>镜头生产前置设计未完成。</strong> <strong>镜头生产前置设计尚未补齐或更新。</strong>
当前导演设计 {{ data.directions.directionCount }}/{{ data.directions.shotCount }},即时视觉状态 当前导演设计 {{ data.directions.directionCount }}/{{ data.directions.shotCount }},即时视觉状态
{{ data.visualStates.visualStateCount }}/{{ {{ data.visualStates.visualStateCount }}/{{
data.visualStates.shotCount data.visualStates.shotCount
}}。请先补齐后再进入镜头生产,避免 后续镜头制作受阻。 </ContextNotice }}。<span v-if="data.directions.staleCount || data.visualStates.staleCount">其中过期镜头设计 {{ data.directions.staleCount }} 条、画面状态 {{ data.visualStates.staleCount }} 条。</span>请先补齐或更新后再进入镜头生产。 </ContextNotice
><ContextNotice ><ContextNotice
v-if="!prerequisites.directionEpisode || !prerequisites.visualEpisode" v-if="!prerequisites.directionEpisode || !prerequisites.visualEpisode"
type="info" type="info"
@@ -565,7 +569,7 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
:show-icon="false" :show-icon="false"
class="mt-4" class="mt-4"
> >
本集导演设计尚未补齐,请先完成第 01 步,再生成本集即时状态。 本集导演设计尚未补齐或版本已变化,请先完成第 01 步,再生成本集即时状态。
</ContextNotice> </ContextNotice>
</NScrollbar> </NScrollbar>
<div v-if="!data && query.loading.value" class="panel p-8 text-sm text-muted" role="status"> <div v-if="!data && query.loading.value" class="panel p-8 text-sm text-muted" role="status">
@@ -105,6 +105,7 @@ export function directionsResult(projectId: string, episodeNo = 1, complete = tr
projectId, projectId,
episodeNo, episodeNo,
shotCount: 2, shotCount: 2,
staleCount: 0,
directionCount: complete ? 2 : 0, directionCount: complete ? 2 : 0,
coverage: complete ? 1 : 0, coverage: complete ? 1 : 0,
beats: [1, 2].map(beatNo => ({ beats: [1, 2].map(beatNo => ({
@@ -122,6 +123,7 @@ export function visualStatesResult(projectId: string, episodeNo = 1, complete =
projectId, projectId,
episodeNo, episodeNo,
shotCount: 2, shotCount: 2,
staleCount: 0,
visualStateCount: complete ? 2 : 0, visualStateCount: complete ? 2 : 0,
coverage: complete ? 1 : 0, coverage: complete ? 1 : 0,
beats: [1, 2].map(beatNo => ({ beats: [1, 2].map(beatNo => ({
+8
View File
@@ -41,6 +41,8 @@ export interface EpisodeDirections {
episodeNo: number episodeNo: number
shotCount: number shotCount: number
directionCount: number directionCount: number
/** 因镜头修订过期的设计数量,缺失时不视为已核对。 */
staleCount: number
coverage: number coverage: number
beats: { beatNo: number; shots: { shotId: string; shotNo: number; direction: ShotDirection | null }[] }[] beats: { beatNo: number; shots: { shotId: string; shotNo: number; direction: ShotDirection | null }[] }[]
} }
@@ -51,6 +53,8 @@ export interface EpisodeVisualStates {
episodeNo: number episodeNo: number
shotCount: number shotCount: number
visualStateCount: number visualStateCount: number
/** 早于镜头修订或镜头设计的画面状态数量。 */
staleCount: number
coverage: number coverage: number
beats: { beatNo: number; shots: { shotId: string; shotNo: number; visualState: ShotVisualState | null }[] }[] beats: { beatNo: number; shots: { shotId: string; shotNo: number; visualState: ShotVisualState | null }[] }[]
} }
@@ -71,6 +75,8 @@ export interface EpisodeGenerationResult {
shotCount: number shotCount: number
directionCount?: number directionCount?: number
visualStateCount?: number visualStateCount?: number
/** 本轮结束后仍然过期的记录。 */
staleCount?: number
error?: string error?: string
repaired?: boolean repaired?: boolean
repairAttempts?: number repairAttempts?: number
@@ -79,6 +85,8 @@ export interface EpisodeGenerationResult {
/** 两种设计批处理返回相同的汇总结构。 */ /** 两种设计批处理返回相同的汇总结构。 */
export interface StoryboardBatchResult { export interface StoryboardBatchResult {
/** 本轮结束后仍然过期的设计记录,不因覆盖率完整而忽略。 */
staleCount?: number
projectId: string projectId: string
episodeCount: number episodeCount: number
completedEpisodes: number completedEpisodes: number
+20 -4
View File
@@ -6,6 +6,8 @@ import { useQuery } from '../../composables/useQuery'
import { useProjectContext } from '../projects/context' import { useProjectContext } from '../projects/context'
import { formalBreakdownSnapshot } from '../workflows/selectors' import { formalBreakdownSnapshot } from '../workflows/selectors'
import { getOperation, runOperation } from '../workflows/operations' import { getOperation, runOperation } from '../workflows/operations'
import { preparationApi } from '../storyboard-preparation/api'
import { currentStoryboardApproval } from '../storyboard-preparation/model'
import { storyboardApi } from './api' import { storyboardApi } from './api'
import { import {
currentEpisodeSource, currentEpisodeSource,
@@ -75,6 +77,12 @@ export function useStoryboard() {
return { directions, visualStates } return { directions, visualStates }
}) })
const data = query.data const data = query.data
/** 镜头设计与画面状态的新接口要求当前整体审核,独立读取而不影响只读查看。 */
const approval = useQuery(id, (projectId, signal) => projectId ? preparationApi.approval(projectId, signal) : Promise.resolve(null))
/** 有效审核必须绑定正式内容;旧记录或未知状态不放行。 */
const approved = computed(() => !approval.loading.value && !approval.error.value && currentStoryboardApproval(approval.data.value, id.value))
/** 正式修订或审核后随项目数据刷新核对凭据,避免沿用旧权限。 */
watch(context.checkpoints, () => { if (approval.data.value || approval.error.value) void approval.refresh() })
/** 当前工作区的响应式状态或派生业务条件。 */ /** 当前工作区的响应式状态或派生业务条件。 */
const session = computed(() => getStoryboardSession(id.value)) const session = computed(() => getStoryboardSession(id.value))
/** 单集重生成返回的是最新镜头正文,优先于不会随局部覆盖更新的历史 Breakdown 快照。 */ /** 单集重生成返回的是最新镜头正文,优先于不会随局部覆盖更新的历史 Breakdown 快照。 */
@@ -118,14 +126,14 @@ export function useStoryboard() {
() => () =>
!!data.value?.directions.shotCount && !!data.value?.directions.shotCount &&
data.value.directions.directionCount === data.value.directions.shotCount && data.value.directions.directionCount === data.value.directions.shotCount &&
data.value.directions.coverage === 1 data.value.directions.coverage === 1 && data.value.directions.staleCount === 0
) )
/** 当前工作区的响应式状态或派生业务条件。 */ /** 当前工作区的响应式状态或派生业务条件。 */
const visualStateComplete = computed( const visualStateComplete = computed(
() => () =>
!!data.value?.visualStates.shotCount && !!data.value?.visualStates.shotCount &&
data.value.visualStates.visualStateCount === data.value.visualStates.shotCount && data.value.visualStates.visualStateCount === data.value.visualStates.shotCount &&
data.value.visualStates.coverage === 1 data.value.visualStates.coverage === 1 && data.value.visualStates.staleCount === 0
) )
/** 当前工作区的响应式状态或派生业务条件。 */ /** 当前工作区的响应式状态或派生业务条件。 */
const hasCurrentEpisodeShots = computed( const hasCurrentEpisodeShots = computed(
@@ -133,8 +141,8 @@ export function useStoryboard() {
) )
const allowed = computed<Record<StoryboardCommand, boolean>>(() => ({ const allowed = computed<Record<StoryboardCommand, boolean>>(() => ({
'shots-current': !blocked.value && episodeNo.value > 0 && hasCurrentEpisodeShots.value, 'shots-current': !blocked.value && episodeNo.value > 0 && hasCurrentEpisodeShots.value,
'direction-all': !blocked.value && prerequisites.value.directionProject && batchValid.value, 'direction-all': approved.value && !blocked.value && prerequisites.value.directionProject && batchValid.value,
'visual-all': !blocked.value && prerequisites.value.visualProject && batchValid.value && repairsValid.value, 'visual-all': approved.value && !blocked.value && prerequisites.value.visualProject && batchValid.value && repairsValid.value,
prompts: !blocked.value && shots.value.length > 0 && batchValid.value prompts: !blocked.value && shots.value.length > 0 && batchValid.value
})) }))
@@ -194,6 +202,7 @@ export function useStoryboard() {
const repairs = maxRepairAttempts.value const repairs = maxRepairAttempts.value
const targetEpisode = episodeNo.value const targetEpisode = episodeNo.value
const target = getStoryboardSession(projectId) const target = getStoryboardSession(projectId)
const expectedApproval = JSON.stringify(approval.data.value?.evidence)
const titles: Record<StoryboardCommand, string> = { const titles: Record<StoryboardCommand, string> = {
'shots-current': `第 ${targetEpisode} 集镜头`, 'shots-current': `第 ${targetEpisode} 集镜头`,
'direction-all': '项目导演设计', 'direction-all': '项目导演设计',
@@ -202,6 +211,11 @@ export function useStoryboard() {
} }
target.receipt = null target.receipt = null
await runOperation(projectId, `生成${titles[command]}`, async () => { await runOperation(projectId, `生成${titles[command]}`, async () => {
if (command === 'direction-all' || command === 'visual-all') {
const latest = await preparationApi.approval(projectId)
if (id.value !== projectId || !currentStoryboardApproval(latest, projectId) || JSON.stringify(latest.evidence) !== expectedApproval)
throw new Error('正式分镜审核已变化,请重新进行制作前检查并核对费用。')
}
if (command === 'shots-current') { if (command === 'shots-current') {
const started = await storyboardApi.regenerateEpisodeShots(projectId, targetEpisode) const started = await storyboardApi.regenerateEpisodeShots(projectId, targetEpisode)
await executions[0]!.observer.track(started.executionId, projectId) await executions[0]!.observer.track(started.executionId, projectId)
@@ -246,6 +260,8 @@ export function useStoryboard() {
repairsValid, repairsValid,
blocked, blocked,
directionComplete, directionComplete,
approval,
approved,
visualStateComplete, visualStateComplete,
hasCurrentEpisodeShots, hasCurrentEpisodeShots,
executions, executions,
@@ -29,6 +29,20 @@ const props = withDefaults(
const emit = defineEmits<{ refresh: []; dismiss: [] }>() const emit = defineEmits<{ refresh: []; dismiss: [] }>()
const percentage = computed(() => executionPercentage(props.execution?.current ?? 0, props.execution?.total ?? 0)) const percentage = computed(() => executionPercentage(props.execution?.current ?? 0, props.execution?.total ?? 0))
const result = computed(() => props.execution?.result ?? {}) const result = computed(() => props.execution?.result ?? {})
/** 动作诊断执行结束仅表示分析完成,不能套用素材生成的通过文案。 */
const diagnosisTask = computed(() => props.execution?.workflowName === 'storyboard-legacy-action-diagnosis')
/** 服务中断后必须由用户核对记录和费用,不根据未匹配数量自动重试。 */
const diagnosisRecovery = computed(() => diagnosisTask.value && result.value.recoveryRequired === true && result.value.retryAutomatically === false)
/**
* 恢复数量缺失时不补零,避免把未知范围描述为没有待核查镜头。
* @param name 服务返回的统计名称
* @returns 有效非负整数或未知
*/
function diagnosisCount(name: string): number | null {
const value = result.value[name]
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null
}
/** 拆解任务的单位和结果文案与镜头素材任务分开。 */ /** 拆解任务的单位和结果文案与镜头素材任务分开。 */
const breakdownTask = computed(() => props.execution?.workflowName === 'breakdown') const breakdownTask = computed(() => props.execution?.workflowName === 'breakdown')
/** 只采用后端明确返回的校验结果,缺失时保留待确认状态。 */ /** 只采用后端明确返回的校验结果,缺失时保留待确认状态。 */
@@ -88,6 +102,7 @@ const staleMotionPlanCount = computed(() => {
}) })
/** 业务未通过或结果未知时,不把任务执行结束展示为全成功。 */ /** 业务未通过或结果未知时,不把任务执行结束展示为全成功。 */
const statusType = computed(() => { const statusType = computed(() => {
if (diagnosisTask.value) return props.execution?.status === 'failed' ? 'error' : props.execution?.status === 'completed' ? 'default' : 'warning'
if (breakdownTask.value) if (breakdownTask.value)
return breakdownState.value === 'success' return breakdownState.value === 'success'
? 'success' ? 'success'
@@ -231,7 +246,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
</div> </div>
</dl> </dl>
<NProgress <NProgress
v-if="execution.total > 0 && (!breakdownTask || !finished)" v-if="execution.total > 0 && ((!breakdownTask && !diagnosisTask) || !finished)"
type="line" type="line"
:percentage="percentage" :percentage="percentage"
:height="5" :height="5"
@@ -268,7 +283,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
<ContextNotice <ContextNotice
v-else-if="execution.status === 'completed' && showStatusHint" v-else-if="execution.status === 'completed' && showStatusHint"
:type=" :type="
breakdownInvalid diagnosisTask ? 'info' : breakdownInvalid
? 'warning' ? 'warning'
: keyframeEdit : keyframeEdit
? result.passed === true ? result.passed === true
@@ -288,7 +303,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
> >
<p> <p>
{{ {{
breakdownTask diagnosisTask ? '动作诊断已结束,请查看最新结果;执行结束不代表动作全部通过。' : breakdownTask
? '剧本拆解已结束,请查看候选与校验结果。' ? '剧本拆解已结束,请查看候选与校验结果。'
: scriptCreation : scriptCreation
? '剧本创作任务已结束,可查看最新剧本内容。' ? '剧本创作任务已结束,可查看最新剧本内容。'
@@ -326,6 +341,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
> >
<template v-else>首帧检查结果尚不完整,请刷新任务详情后核对。</template> <template v-else>首帧检查结果尚不完整,请刷新任务详情后核对。</template>
</p> </p>
<p v-else-if="diagnosisTask" class="mt-2 text-xs">具体冲突与证据情况以最新诊断列表为准。</p>
<p v-else-if="!videoQuality && !scriptCreation && !breakdownTask" class="mt-2 text-xs"> <p v-else-if="!videoQuality && !scriptCreation && !breakdownTask" class="mt-2 text-xs">
共 {{ result.total ?? execution.total }} · 生成 {{ result.generated ?? execution.current }} · 跳过 共 {{ result.total ?? execution.total }} · 生成 {{ result.generated ?? execution.current }} · 跳过
{{ result.skipped ?? 0 }} · 阻塞 {{ result.blocked ?? 0 }} · 失败 {{ result.failed ?? 0 }} {{ result.skipped ?? 0 }} · 阻塞 {{ result.blocked ?? 0 }} · 失败 {{ result.failed ?? 0 }}
@@ -340,12 +356,21 @@ function isInputMode(value: unknown, inputMode: string): boolean {
<p>{{ userFacingText(execution.error) || '制作任务执行失败。' }}</p> <p>{{ userFacingText(execution.error) || '制作任务执行失败。' }}</p>
<p class="mt-2 text-xs"> <p class="mt-2 text-xs">
{{ {{
scriptCreation diagnosisTask
? '请先核对最新诊断记录。服务中断时还需确认费用,再决定是否手动重新诊断。'
: scriptCreation
? '请先核对已保存的剧本内容,处理报错原因后从当前阶段恢复生成或改写。' ? '请先核对已保存的剧本内容,处理报错原因后从当前阶段恢复生成或改写。'
: '请先刷新相关资产状态,确认已成功的镜头;处理报错原因后,只对仍处于“可执行”的镜头重新提交。' : '请先刷新相关资产状态,确认已成功的镜头;处理报错原因后,只对仍处于“可执行”的镜头重新提交。'
}} }}
</p> </p>
</ContextNotice> </ContextNotice>
<!-- 以下是诊断中断恢复摘要,未知费用与人工核查直接显示 -->
<div v-if="diagnosisTask && finished" class="mt-3 space-y-2 text-xs" aria-label="动作诊断任务统计">
<p v-if="diagnosisRecovery">需要人工核查:中断时的模型请求可能已产生费用,系统不会自动重新诊断。</p>
<p v-if="diagnosisRecovery"><span v-if="diagnosisCount('reusableShotCount') !== null">可复用 {{ diagnosisCount('reusableShotCount') }} 镜 · </span><span v-if="diagnosisCount('manualReviewShotCount') !== null">待核查 {{ diagnosisCount('manualReviewShotCount') }} 镜</span></p>
<p v-if="diagnosisRecovery && result.qualityPolicyVerified !== true">质量规则来源尚未确认,请先核对最新分镜。</p>
<p v-else-if="!diagnosisRecovery">本次处理 {{ diagnosisCount('completed') ?? diagnosisCount('total') ?? '待确认' }} 镜 · 复用 {{ diagnosisCount('skipped') ?? '待确认' }} 镜 · 调用失败 {{ diagnosisCount('failed') ?? '待确认' }} 镜。</p>
</div>
<!-- 以下是非拆解任务的 Naive 详情折叠模块 --> <!-- 以下是非拆解任务的 Naive 详情折叠模块 -->
<NCollapse v-if="!breakdownTask" class="mt-3 text-xs text-muted"> <NCollapse v-if="!breakdownTask" class="mt-3 text-xs text-muted">
<NCollapseItem name="task-details" title="任务详情"> <NCollapseItem name="task-details" title="任务详情">
+5 -2
View File
@@ -1,4 +1,4 @@
import { businessErrorMessages, userFacingText } from './user-facing-text' import { businessErrorMessages, configurationErrorText, userFacingText } from './user-facing-text'
/** HTTP 错误携带状态码与后端细节,供页面区别空数据、校验错误与网络故障。 */ /** HTTP 错误携带状态码与后端细节,供页面区别空数据、校验错误与网络故障。 */
export class ApiError extends Error { export class ApiError extends Error {
@@ -101,7 +101,10 @@ export async function optionalResource<T>(promise: Promise<T>): Promise<T | null
*/ */
export function errorMessage(error: unknown): string { export function errorMessage(error: unknown): string {
const fallback = '操作失败,请刷新后重试。' const fallback = '操作失败,请刷新后重试。'
if (error instanceof ApiError) if (error instanceof ApiError) {
const configurationMessage = configurationErrorText(error.code) ?? configurationErrorText(isRecord(error.details) ? error.details.code : undefined)
if (configurationMessage) return configurationMessage
return [...new Set([userFacingText(error.message, fallback), ...businessErrorMessages(error.details)].filter(Boolean))].join(';') || fallback return [...new Set([userFacingText(error.message, fallback), ...businessErrorMessages(error.details)].filter(Boolean))].join(';') || fallback
}
return error instanceof Error ? userFacingText(error.message, fallback) || fallback : fallback return error instanceof Error ? userFacingText(error.message, fallback) || fallback : fallback
} }
+31
View File
@@ -1,5 +1,23 @@
/** 项目配置的确定性业务状态说明,不将配置限制显示为系统故障。 */
const configurationErrorLabels: Record<string, string> = {
CREATIVE_PROFILE_REQUIRED: '请先保存项目生成配置,再重新检查制作计划。',
CANVAS_CHANGE_REQUIRES_REVALIDATION: '已有分镜,暂时不能直接修改作品画幅。需要先重新核对镜头设计和相关素材,当前配置未保存。',
CREATIVE_PROFILE_ACTIVE_WORKFLOW: '项目仍有任务进行中,请等待任务结束后再保存生成配置。',
GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION: '已有首帧或视频,暂时不能直接修改相关模型或参数。需要先处理现有素材的更新关系,当前配置未保存。'
}
/**
* 识别项目配置的公开业务码;未知状态仍保留原有错误处理。
* @param code 原始顶层错误码或详情中的业务码
* @returns 对应中文操作说明,非配置业务码时返回 null
*/
export function configurationErrorText(code: unknown): string | null {
return typeof code === 'string' ? configurationErrorLabels[code] ?? null : null
}
/** 系统说明中允许统一翻译的术语;不处理剧本、提示词正文、文件名或请求字段。 */ /** 系统说明中允许统一翻译的术语;不处理剧本、提示词正文、文件名或请求字段。 */
const terms: [RegExp, string][] = [ const terms: [RegExp, string][] = [
[/\bneeds_review\b/g, '需人工核对'], [/\binsufficient_evidence\b/g, '证据尚不完整'], [/\bblocked\b/g, '存在待处理问题'],
[/由项目 Creative Profile Canvas 决定;单次图片或视频生成不可覆盖。/g, '使用项目配置中的画面比例,单次生成时不能单独更改。'], [/由项目 Creative Profile Canvas 决定;单次图片或视频生成不可覆盖。/g, '使用项目配置中的画面比例,单次生成时不能单独更改。'],
[/业务层必须显式选择,不能依赖 Provider 默认值。/g, '请明确选择是否开启。'], [/业务层必须显式选择,不能依赖 Provider 默认值。/g, '请明确选择是否开启。'],
[/业务默认关闭/g, '默认关闭'], [/业务参考图/g, '参考图'], [/业务默认关闭/g, '默认关闭'], [/业务参考图/g, '参考图'],
@@ -33,6 +51,19 @@ const terms: [RegExp, string][] = [
*/ */
export function userFacingText(value: string | null | undefined, fallback = '暂无可读说明,请查看相关状态。'): string { export function userFacingText(value: string | null | undefined, fallback = '暂无可读说明,请查看相关状态。'): string {
let text = value?.trim() ?? '' let text = value?.trim() ?? ''
const codeLabels: Record<string, string> = {
...configurationErrorLabels,
QUALITY_POLICY_RECONFIRM_REQUIRED: '质量规则或正式分镜来源需要重新核对并确认。',
QUALITY_POLICY_NOT_CONFIRMED: '请先核对并确认项目质量规则。',
QUALITY_POLICY_VERSION_CONFLICT: '质量规则已更新,请重新核对后操作。',
QUALITY_POLICY_SNAPSHOT_UNKNOWN: '分镜缺少可信的质量规则记录,请重新生成拆解候选。',
QUALITY_POLICY_SNAPSHOT_INVALID: '分镜的质量规则记录不完整,请重新生成拆解候选。',
QUALITY_POLICY_SNAPSHOT_STALE: '分镜与质量规则版本不一致,请核对最新拆解结果。',
STORYBOARD_SOURCE_MISMATCH: '镜头与已提交分镜不一致,请刷新后核对。'
}
const code = Object.keys(codeLabels).find(key => text === key || text.startsWith(`${key}:`) || text.startsWith(`${key}:`))
if (code) text = text.slice(code.length).replace(/^[::]\s*/, '').trim() || codeLabels[code]!
if (!text) return '' if (!text) return ''
if (/fetch failed|failed to fetch|network error|ECONNREFUSED|ETIMEDOUT/i.test(text)) if (/fetch failed|failed to fetch|network error|ECONNREFUSED|ETIMEDOUT/i.test(text))
return '暂时无法连接服务,请检查网络后重试;已提交的任务可能仍在运行。' return '暂时无法连接服务,请检查网络后重试;已提交的任务可能仍在运行。'
+23
View File
@@ -769,3 +769,26 @@ body {
.workspace-tabs.n-tabs .n-tabs-nav .n-tabs-tab:hover { .workspace-tabs.n-tabs .n-tabs-nav .n-tabs-tab:hover {
background: transparent; background: transparent;
} }
/* 卡片内的辅助操作用独立中性底面区分,不添加边框;颜色共用深浅主题变量。 */
.n-button.workspace-action-button,
.workspace-action-group .n-button {
min-height: 34px;
padding-inline: 14px;
border: 0;
background: var(--app-surface);
color: var(--app-ink);
}
.n-button.workspace-action-button:not(:disabled):hover,
.workspace-action-group .n-button:not(:disabled):hover {
background: var(--app-control-hover);
color: var(--app-ink);
}
.n-button.workspace-action-button:focus-visible,
.workspace-action-group .n-button:focus-visible {
outline: 2px solid var(--app-ink);
outline-offset: 2px;
}
/* 项目顶部的相邻辅助入口统一使用中性底色,深浅主题保持一致。 */
.n-button.workspace-action-button { background: var(--app-control); }
+1 -1
View File
@@ -301,7 +301,7 @@ describe('全站平面主题', () => {
.filter(([, , declarations]) => .filter(([, , declarations]) =>
/border(?:-[\w]+)?:\s*1px (?:solid|dashed) var\(--(?:app-border|color-line)\)/.test(declarations!) /border(?:-[\w]+)?:\s*1px (?:solid|dashed) var\(--(?:app-border|color-line)\)/.test(declarations!)
) )
.map(([, selector]) => selector!.trim()) .map(([, selector]) => selector!.replace(/\/\*[\s\S]*?\*\//g, '').trim())
expect(separators).toEqual(['.identity-next-action']) expect(separators).toEqual(['.identity-next-action'])
expect(css).toMatch(/\.surface-inset\s*\{[^}]*background:\s*var\(--app-subtle\)/) expect(css).toMatch(/\.surface-inset\s*\{[^}]*background:\s*var\(--app-subtle\)/)
expect(css).toMatch(/\.record-list > article:nth-child\(even\)\s*\{\s*background:/) expect(css).toMatch(/\.record-list > article:nth-child\(even\)\s*\{\s*background:/)
+2 -2
View File
@@ -442,7 +442,7 @@ describe('管理后台组件边界', () => {
expect(document.querySelector('.n-modal-container')).toBeNull() expect(document.querySelector('.n-modal-container')).toBeNull()
}) })
it('服务端制作阶段就绪后解锁全部左侧链接,标题只保留项目配置入口', async () => { it('服务端制作阶段就绪后解锁全部左侧链接,标题保留制作前检查与项目配置入口', async () => {
const detail = vi.spyOn(projectsApi, 'detail').mockResolvedValue({ const detail = vi.spyOn(projectsApi, 'detail').mockResolvedValue({
id: 'navigation-test', id: 'navigation-test',
durationMode: 'auto', durationMode: 'auto',
@@ -506,7 +506,7 @@ describe('管理后台组件边界', () => {
expect(wrapper.get('.project-view .workspace-page').text()).toBe(path) expect(wrapper.get('.project-view .workspace-page').text()).toBe(path)
} }
expect(detail).toHaveBeenCalledOnce() expect(detail).toHaveBeenCalledOnce()
expect(wrapper.get('.project-header .n-button').text()).toBe('项目配置') expect(wrapper.findAll('.project-header .n-button').map(button => button.text())).toEqual(['制作前检查', '项目配置'])
expect(wrapper.find('.project-header [aria-label="刷新项目"]').exists()).toBe(false) expect(wrapper.find('.project-header [aria-label="刷新项目"]').exists()).toBe(false)
expect(wrapper.find('.project-header .n-tag').exists()).toBe(false) expect(wrapper.find('.project-header .n-tag').exists()).toBe(false)
}) })
+19 -19
View File
@@ -1,3 +1,4 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -22,10 +23,7 @@ import { getOperation } from '@/features/workflows/operations'
let wrapper: VueWrapper | undefined let wrapper: VueWrapper | undefined
it('首次点击生成先读取并确认质量规则,不直接打开模型启动确认', async () => { it('首次点击生成先读取并确认质量规则,不直接打开模型启动确认', async () => {
const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('breakdown-scroll-test', { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }))
projectId: 'breakdown-scroll-test',
policy: { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
})
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({ vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3, episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }] groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
@@ -45,9 +43,11 @@ it('首次点击生成先读取并确认质量规则,不直接打开模型启
}) })
it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => { it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ const result = policyReceipt('breakdown-scroll-test', { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] })
projectId: 'breakdown-scroll-test', vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(result))
policy: { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] } vi.spyOn(projectsApi, 'confirmQualityPolicy').mockImplementation(async () => {
Object.assign(result, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-17T15:00:00Z' })
return structuredClone(result)
}) })
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({ vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3, episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
@@ -84,12 +84,12 @@ it('规则确认保留分组预览,隐藏空白例外,确认不调用模型
it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定关闭且保存后仍需审核', async () => { it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定关闭且保存后仍需审核', async () => {
let policy: ProjectQualityPolicy = { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] } let policy: ProjectQualityPolicy = { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'breakdown-scroll-test', policy })) vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => policyReceipt('breakdown-scroll-test', policy))
let finish!: () => void let finish!: () => void
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => { const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => {
await new Promise<void>(resolve => { finish = resolve }) await new Promise<void>(resolve => { finish = resolve })
policy = input policy = input
return { projectId: id, policy: input } return policyReceipt(id, input)
}) })
vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(candidateReview({ vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(candidateReview({
projectId: 'breakdown-scroll-test', actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1] projectId: 'breakdown-scroll-test', actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1]
@@ -400,7 +400,7 @@ function handDiagnosticsResponse(evidenceShotCount: number) {
* @returns 当前动作诊断弹窗 * @returns 当前动作诊断弹窗
*/ */
function qualityDialog() { function qualityDialog() {
const panel = document.querySelector<HTMLElement>('.app-dialog[aria-label="动作诊断"]') const panel = document.querySelector<HTMLElement>('.app-drawer[aria-label="动作诊断"]')
if (!panel) throw new Error('动作诊断弹窗未打开') if (!panel) throw new Error('动作诊断弹窗未打开')
return new DOMWrapper(panel) return new DOMWrapper(panel)
} }
@@ -751,7 +751,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input) const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse() if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) return handDiagnosticsResponse(0) if (url.endsWith('storyboard-action-resource-diagnostics')) return handDiagnosticsResponse(0)
throw new Error(`未预期的诊断请求:${url}`) throw new Error(`未预期的诊断请求:${url}`)
}) })
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
@@ -765,7 +765,7 @@ describe('拆解页内容滚动', () => {
const panel = qualityDialog() const panel = qualityDialog()
expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false) expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false)
expect(panel.get('.storyboard-diagnosis-dialog').attributes('aria-busy')).toBe('false') expect(panel.get('.storyboard-diagnosis-dialog').attributes('aria-busy')).toBe('false')
const footer = panel.get('.n-card__footer') const footer = panel.get('.n-drawer-footer')
expect(footer.text()).toContain('预览诊断范围') expect(footer.text()).toContain('预览诊断范围')
expect(footer.text()).toContain('启动 AI 诊断') expect(footer.text()).toContain('启动 AI 诊断')
expect(footer.text()).toContain('关闭') expect(footer.text()).toContain('关闭')
@@ -778,7 +778,7 @@ describe('拆解页内容滚动', () => {
await flushPromises() await flushPromises()
expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false) expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false)
expect( expect(
fetcher.mock.calls.filter(([input]) => String(input).endsWith('storyboard-hand-occupancy-diagnostics')) fetcher.mock.calls.filter(([input]) => String(input).endsWith('storyboard-action-resource-diagnostics'))
).toHaveLength(1) ).toHaveLength(1)
}) })
@@ -795,7 +795,7 @@ describe('拆解页内容滚动', () => {
}) })
return diagnosisResultsResponse() return diagnosisResultsResponse()
} }
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) return handDiagnosticsResponse(0) if (url.endsWith('storyboard-action-resource-diagnostics')) return handDiagnosticsResponse(0)
throw new Error(`未预期的诊断请求:${url}`) throw new Error(`未预期的诊断请求:${url}`)
}) })
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
@@ -807,7 +807,7 @@ describe('拆解页内容滚动', () => {
await panel.findAll('.n-collapse-item__header-main')[1]!.trigger('click') await panel.findAll('.n-collapse-item__header-main')[1]!.trigger('click')
await flushPromises() await flushPromises()
const content = panel.get('.diagnosis-dialog-content').element const content = panel.get('.diagnosis-dialog-content').element
const scroll = panel.get<HTMLElement>('.dialog-body-scroll .n-scrollbar-container').element const scroll = panel.get<HTMLElement>('.n-drawer-body .n-scrollbar-container').element
scroll.scrollTop = 80 scroll.scrollTop = 80
const refreshButton = panel.findAll('button').find(button => button.text() === '刷新结果')! const refreshButton = panel.findAll('button').find(button => button.text() === '刷新结果')!
const refreshIcon = refreshButton.get('.n-button__icon').element const refreshIcon = refreshButton.get('.n-button__icon').element
@@ -838,7 +838,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input) const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse() if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) { if (url.endsWith('storyboard-action-resource-diagnostics')) {
handRequests++ handRequests++
if (handRequests > 1) if (handRequests > 1)
return new Promise<Response>(resolve => { return new Promise<Response>(resolve => {
@@ -886,7 +886,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input) const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse() if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) { if (url.endsWith('storyboard-action-resource-diagnostics')) {
handRequests++ handRequests++
if (handRequests === 1) if (handRequests === 1)
return new Promise<Response>(resolve => { return new Promise<Response>(resolve => {
@@ -906,13 +906,13 @@ describe('拆解页内容滚动', () => {
expect(qualityDialog().text()).not.toContain('诊断结果') expect(qualityDialog().text()).not.toContain('诊断结果')
expect( expect(
qualityDialog() qualityDialog()
.get('.n-card__footer') .get('.n-drawer-footer')
.findAll('button') .findAll('button')
.filter(button => button.text() !== '关闭') .filter(button => button.text() !== '关闭')
.every(button => (button.element as HTMLButtonElement).disabled) .every(button => (button.element as HTMLButtonElement).disabled)
).toBe(true) ).toBe(true)
const close = qualityDialog() const close = qualityDialog()
.get('.n-card__footer') .get('.n-drawer-footer')
.findAll('button') .findAll('button')
.find(button => button.text() === '关闭')! .find(button => button.text() === '关闭')!
expect((close.element as HTMLButtonElement).disabled).toBe(false) expect((close.element as HTMLButtonElement).disabled).toBe(false)
@@ -1,3 +1,4 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { actionExceptionTargets } from '@/features/breakdown/action-exceptions' import { actionExceptionTargets } from '@/features/breakdown/action-exceptions'
@@ -68,8 +69,8 @@ describe('从实际问题建立动作例外', () => {
it('用户仅填写原因,保存前重读并合并已有例外,不改全局规则或自动放行质量', async () => { it('用户仅填写原因,保存前重读并合并已有例外,不改全局规则或自动放行质量', async () => {
const { state, quality } = conflict() const { state, quality } = conflict()
const latest = { ...policy, customRules: ['其他入口刚保存的新规则'] } const latest = { ...policy, customRules: ['其他入口刚保存的新规则'] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValueOnce({ projectId: 'candidate-project', policy }).mockResolvedValue({ projectId: 'candidate-project', policy: latest }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValueOnce(policyReceipt('candidate-project', policy)).mockResolvedValue(policyReceipt('candidate-project', latest))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => ({ projectId: id, policy: input })) const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => (policyReceipt(id, input)))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } }) wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises() await flushPromises()
expect(wrapper.text()).toContain('左手握住铜铃') expect(wrapper.text()).toContain('左手握住铜铃')
@@ -87,7 +88,7 @@ describe('从实际问题建立动作例外', () => {
expect(save).toHaveBeenCalledExactlyOnceWith('candidate-project', { ...latest, actionExceptions: [ expect(save).toHaveBeenCalledExactlyOnceWith('candidate-project', { ...latest, actionExceptions: [
policy.actionExceptions![0], policy.actionExceptions![0],
{ code: 'action_resource_conflict', ownerRef: '@CH0001', resource: 'left_hand', reason: '剧本明确允许左手同时挥动持物' } { code: 'action_resource_conflict', ownerRef: '@CH0001', resource: 'left_hand', reason: '剧本明确允许左手同时挥动持物' }
] }) ] }, 2)
expect(wrapper.emitted('refresh')).toHaveLength(1) expect(wrapper.emitted('refresh')).toHaveLength(1)
expect(quality.actionStatus).toBe('blocked') expect(quality.actionStatus).toBe('blocked')
expect(wrapper.find('textarea').exists()).toBe(false) expect(wrapper.find('textarea').exists()).toBe(false)
@@ -95,8 +96,8 @@ describe('从实际问题建立动作例外', () => {
it('保存前出现活动任务或切换检查点时,不提交旧问题的例外', async () => { it('保存前出现活动任务或切换检查点时,不提交旧问题的例外', async () => {
const { state, quality } = conflict() const { state, quality } = conflict()
let finish!: (value: { projectId: string; policy: ProjectQualityPolicy }) => void let finish!: (value: ReturnType<typeof policyReceipt>) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy }) const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', policy))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy') const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } }) wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises() await flushPromises()
@@ -105,7 +106,7 @@ describe('从实际问题建立动作例外', () => {
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click') await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper.setProps({ disabled: true }) await wrapper.setProps({ disabled: true })
finish({ projectId: 'candidate-project', policy }) finish(policyReceipt('candidate-project', policy))
await flushPromises() await flushPromises()
expect(save).not.toHaveBeenCalled() expect(save).not.toHaveBeenCalled()
expect(wrapper.find('textarea').element.value).toBe('允许原因') expect(wrapper.find('textarea').element.value).toBe('允许原因')
@@ -117,7 +118,7 @@ describe('从实际问题建立动作例外', () => {
it('已有同一角色部位的例外不重复添加,其他例外保持可见', async () => { it('已有同一角色部位的例外不重复添加,其他例外保持可见', async () => {
const { state, quality } = conflict() const { state, quality } = conflict()
const existing = { ...policy, actionExceptions: [...policy.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0001', resource: 'left_hand' as const, reason: '已确认的同类例外' }] } const existing = { ...policy, actionExceptions: [...policy.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0001', resource: 'left_hand' as const, reason: '已确认的同类例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy: existing }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', existing))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy') const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } }) wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises() await flushPromises()
@@ -129,7 +130,7 @@ describe('从实际问题建立动作例外', () => {
it('保存失败保留原因供修正,不增加本地例外或宣称已通过', async () => { it('保存失败保留原因供修正,不增加本地例外或宣称已通过', async () => {
const { state, quality } = conflict() const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', policy))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockRejectedValue(new Error('后端拒绝修改')) vi.spyOn(projectsApi, 'saveQualityPolicy').mockRejectedValue(new Error('后端拒绝修改'))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } }) wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises() await flushPromises()
@@ -146,7 +147,7 @@ describe('从实际问题建立动作例外', () => {
it('读取失败或项目不符时不使用默认规则、不开放添加', async () => { it('读取失败或项目不符时不使用默认规则、不开放添加', async () => {
const { state, quality } = conflict() const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'other', policy }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('other', policy))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy') const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } }) wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises() await flushPromises()
@@ -0,0 +1,83 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, DOMWrapper, type VueWrapper } from '@vue/test-utils'
import StoryboardDiagnosis from '@/features/breakdown/components/StoryboardDiagnosis.vue'
import DiagnosisShotDetails from '@/features/breakdown/components/DiagnosisShotDetails.vue'
import { preparationApi } from '@/features/storyboard-preparation/api'
import { breakdownApi } from '@/features/breakdown/api'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import { diagnosisCanStart } from '@/features/breakdown/diagnosis'
import type { DiagnosisPreflight } from '@/features/breakdown/diagnosis.types'
/** 当前正式镜头的免费来源检查。 */
const checked = (): DiagnosisPreflight => ({ projectId: 'diag-p', shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, policyRevision: 3, policyFingerprint: 'a'.repeat(64), existingDiagnosisId: null, existingValid: false, eligibleForFurtherValidation: true, errors: [], requiresExecutionValidation: true, shouldDiagnose: true, willCallModel: false, willModifyAssets: false })
let wrapper: VueWrapper | undefined
/** 最近范围的真实形状,不包含可用于编辑的完整动作字段。 */
const preview = () => ({ projectId: 'diag-p', episodeNo: 1, candidateCount: 1, needsEvidenceCount: 1, invalidSnapshotCount: 0, candidates: [{ shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '当前镜头', description: '原始描述', durationSeconds: 4, requiredActionCount: 2, hasDurationPlanning: true, hasHandOccupancy: true, status: 'has_evidence' as const }], willCallModel: false as const, willModifyAssets: false as const })
/** 只读接口全部隔离,任何未授权模型请求均由测试捕获。 */
function mocks() {
vi.spyOn(workflowExecutionApi, 'latest').mockResolvedValue(null)
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-p', episodeNo: 1, counts: { total: 0, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 0 }, shots: [] })
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({ projectId: 'diag-p', shotCount: 0, diagnostics: [] } as never)
vi.spyOn(breakdownApi, 'legacyActionDiagnosisPreview').mockImplementation(async () => preview())
return vi.spyOn(breakdownApi, 'startLegacyActionDiagnosis')
}
beforeEach(() => { vi.spyOn(preparationApi, 'revisions').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', count: 0, revisions: [] }) })
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
describe('单镜头诊断收费前来源检查', () => {
it('规则缺失、跨项目、已可复用和不完整检查都不能进入新诊断', () => {
expect(diagnosisCanStart(checked(), 'diag-p', 'db-shot')).toBe(true)
for (const invalid of [{ projectId: 'other' }, { shotId: 'other' }, { existingValid: true }, { shouldDiagnose: false }, { policyRevision: null }, { policyFingerprint: null }, { errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN'] }, { eligibleForFurtherValidation: false }])
expect(diagnosisCanStart({ ...checked(), ...invalid }, 'diag-p', 'db-shot')).toBe(false)
})
it('正式单镜头入口先预检查,缺少规则快照显示中文原因且不发收费请求', async () => {
const start = mocks()
const read = vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue({ ...checked(), shouldDiagnose: false, eligibleForFurtherValidation: false, errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN'] })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
expect(read).toHaveBeenCalledWith('diag-p', 'db-shot')
const drawer = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(drawer.text()).toContain('缺少可信的质量规则记录')
expect(drawer.get('[aria-label="启动 AI 诊断"]').attributes('disabled')).toBeDefined()
expect(start).not.toHaveBeenCalled()
})
it('费用确认后再次检查,规则变化时保留只读结果并撤销启动', async () => {
const start = mocks()
vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValueOnce(checked()).mockResolvedValue({ ...checked(), policyRevision: 4, policyFingerprint: 'b'.repeat(64) })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 诊断"]').trigger('click')
await flushPromises()
const confirmation = new DOMWrapper(document.querySelector('.app-dialog')!)
await confirmation.findAll('button').find(button => button.text() === '确认启动 AI 诊断')!.trigger('click')
await flushPromises()
expect(start).not.toHaveBeenCalled()
expect(new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 诊断"]').attributes('disabled')).toBeDefined()
})
it('镜头描述在费用确认期间变化时必须重新预览,不能直接诊断新内容', async () => {
const start = mocks()
vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue(checked())
vi.mocked(breakdownApi.legacyActionDiagnosisPreview).mockResolvedValueOnce(preview()).mockResolvedValue({ ...preview(), candidates: [{ ...preview().candidates[0]!, description: '已更改的新镜头' }] })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 诊断"]').trigger('click'); await flushPromises()
await new DOMWrapper(document.querySelector('.app-dialog')!).findAll('button').find(button => button.text() === '确认启动 AI 诊断')!.trigger('click'); await flushPromises()
expect(start).not.toHaveBeenCalled()
})
it('修订条件与历史按需读取,跨项目响应不显示为可修订', async () => {
const history = vi.spyOn(breakdownApi, 'diagnosisHistory').mockResolvedValue({ projectId: 'other', shotId: 'db-shot', count: 0, revisions: [] })
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({ projectId: 'other', shotId: 'db-shot', diagnosisId: 'd', eligible: true, repairCandidates: [], blockingReasons: [], requiresManualReview: true, canApplyDirectly: false, willCallModel: false, willModifyAssets: false })
wrapper = mount(DiagnosisShotDetails, { props: { projectId: 'diag-p', shot: { shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '镜头', diagnosisId: 'd', status: 'conflict_found', issues: [], createdAt: null } } })
expect(history).not.toHaveBeenCalled()
await wrapper.get('button').trigger('click'); await flushPromises()
expect(wrapper.text()).toContain('记录与当前镜头不一致')
expect(wrapper.text()).not.toContain('已满足人工修订')
})
it('旧诊断即使只读资格返回 eligible,也不能显示成当前可修订', async () => {
vi.spyOn(breakdownApi, 'diagnosisHistory').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', count: 0, revisions: [] })
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', diagnosisId: 'd', eligible: true, repairCandidates: [], blockingReasons: [], requiresManualReview: true, canApplyDirectly: false, willCallModel: false, willModifyAssets: false })
wrapper = mount(DiagnosisShotDetails, { props: { projectId: 'diag-p', shot: { shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '镜头', diagnosisId: 'd', status: 'stale', policyStatus: 'stale', shotStale: false, issues: [], createdAt: null } } })
await wrapper.get('button').trigger('click'); await flushPromises()
expect(wrapper.text()).not.toContain('已满足人工修订')
})
})
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, DOMWrapper, type VueWrapper } from '@vue/test-utils'
import StoryboardDiagnosis from '@/features/breakdown/components/StoryboardDiagnosis.vue'
import WorkflowExecutionPanel from '@/features/workflows/WorkflowExecutionPanel.vue'
import { breakdownApi } from '@/features/breakdown/api'
import type { LegacyActionDiagnosisResults } from '@/features/breakdown/types'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
/** 页面回执同时包含修订完成、局部证据不足和 AI 待复查。 */
const shot: LegacyActionDiagnosisResults['shots'][number] = { shotId: 'shot-1', episodeNo: 1, beatNo: 1, shotNo: 1, title: '捂耳取铃', diagnosisId: 'diag-1', status: 'stale' as const, issues: [], createdAt: null,
policyStatus: 'stale', shotStale: true, repairStatus: 'repaired', requiresPostRepairDiagnosis: true,
handAudit: { status: 'partial_evidence', evidenceCount: 1, expectedActionCount: 2, coveredActionCount: 1, issueCount: 0, coverage: 0.5 },
bodyMotionFindings: [{ dimension: 'balance', status: 'needs_review', description: '重心需要核对', quote: '单脚站立' }] }
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
describe('诊断版本及复查展示', () => {
it('修订完成不显示全部通过,展示规则和镜头过期、手部覆盖及全身疑点', async () => {
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-update', episodeNo: 1, counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 1, pending: 0 }, shots: [shot] })
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({ projectId: 'diag-update', shotCount: 1, evidenceShotCount: 0, diagnostics: [] } as never)
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] } })
await flushPromises(); await wrapper.get('button').trigger('click'); await flushPromises()
const dialog = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(dialog.text()).toContain('镜头已修订,AI 待复查')
expect(dialog.text()).toContain('镜头内容已变化')
expect(dialog.text()).toContain('质量规则已变化')
expect(dialog.text()).toContain('手部动作证据 1 / 2')
expect(dialog.text()).toContain('重心需要核对')
expect(dialog.text()).not.toContain('全部通过')
})
it('中断诊断显示人工核查与可复用数量,不把未匹配镜头描述为未计费', () => {
const execution = { id: 'task', projectId: 'p', workflowName: 'storyboard-legacy-action-diagnosis', status: 'failed', current: 1, total: 3,
result: { recoveryRequired: true, retryAutomatically: false, requiresManualReview: true, resumeMode: 'manual', reusableShotCount: 1, manualReviewShotCount: 2, scopedShotCount: 3, qualityPolicyVerified: true }, metadata: null, stage: 'interrupted', currentResourceId: null, error: '诊断中断', startedAt: null, completedAt: null, createdAt: '', updatedAt: '' } satisfies WorkflowExecution
wrapper = mount(WorkflowExecutionPanel, { props: { execution, loading: false, error: '' } })
expect(wrapper.text()).toContain('需要人工核查')
expect(wrapper.text()).toContain('可复用 1 镜')
expect(wrapper.text()).toContain('待核查 2 镜')
expect(wrapper.text()).toContain('可能已产生费用')
expect(wrapper.text()).not.toContain('未计费')
})
})
@@ -0,0 +1,43 @@
import { effectScope, ref } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { projectsApi } from '@/features/projects/api'
import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy'
import { candidatePreviewReady } from '@/features/breakdown/candidate'
import { policyReceipt } from '../../fixtures/quality-policy'
import { commitPreview } from '../../fixtures/breakdown-candidate'
/** 当前规则;格式版本不能代替服务修订版本。 */
const policy = { version: 1 as const, physicsMode: 'realistic' as const, allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.clear() })
describe('服务端规则确认契约', () => {
it('保存发送规则和期望修订,明确确认使用独立接口', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: policyReceipt('p', policy) })))
vi.stubGlobal('fetch', fetcher)
await projectsApi.saveQualityPolicy('p', policy, 2)
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ policy, expectedRevision: 2 })
await projectsApi.confirmQualityPolicy('p', 2)
expect(fetcher.mock.calls[1]?.[0]).toBe('/api/projects/p/quality-policy/confirm')
expect(JSON.parse(String(fetcher.mock.calls[1]?.[1]?.body))).toEqual({ expectedRevision: 2 })
})
it('服务已确认的规则跨浏览器直接进入费用确认,启动携带真实修订版本', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', policy, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-17T15:00:00Z' }))
const scope = effectScope()
try {
const flow = scope.run(() => useBreakdownStartPolicy(ref('p'), ref('scope'), ref(true)))!
await flow.prepare()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(true)
expect(await flow.verifyStart()).toBe(true)
expect(flow.consumePermit()).toEqual({ expectedRevision: 2 })
expect(flow.consumePermit()).toBeNull()
} finally { scope.stop() }
})
it('候选安全检查必须包含规则匹配,缺失或 false 均不可提交', () => {
const preview = commitPreview()
expect(candidatePreviewReady({ ...preview, checks: { ...preview.checks, qualityPolicyMatches: false } }, preview.projectId, preview.checkpointId)).toBe(false)
const missing = structuredClone(preview)
delete (missing.checks as Partial<typeof missing.checks>).qualityPolicyMatches
expect(candidatePreviewReady(missing, preview.projectId, preview.checkpointId)).toBe(false)
})
})
+105 -232
View File
@@ -1,261 +1,134 @@
import { effectScope, ref, type EffectScope } from 'vue' import { effectScope, ref, type EffectScope } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import { projectsApi } from '@/features/projects/api' import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '@/features/projects/types' import type { ProjectQualityPolicyResult } from '@/features/projects/types'
import { policyDraft } from '@/features/projects/quality-policy' import { policyDraft } from '@/features/projects/quality-policy'
import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy' import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy'
import { import { qualityPolicySignature } from '@/features/projects/quality-policy-confirmation'
invalidateQualityPolicyConfirmation, qualityPolicySignature, import { policyReceipt } from '../../fixtures/quality-policy'
readQualityPolicyConfirmation, rememberQualityPolicyConfirmation
} from '@/features/projects/quality-policy-confirmation'
/** /** 真实规则回执,旧项目初始修订也必须明确确认。 */
* 使用真实接口形状的独立规则,不连接服务或调用模型。 const initial = () => policyReceipt('policy-project', {
* @returns 独立项目规则回执 version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false,
*/ allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
function receipt(): ProjectQualityPolicyResult { }, { revision: 0 })
return { projectId: 'policy-project', policy: { /** 测试结束释放全部流程观察器。 */
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, const scopes: EffectScope[] = []
allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] /** 创建独立流程,不访问真实模型。 */
} }
}
/** 每个测试释放组合函数观察器。 */
let scope: EffectScope | undefined
/**
* 创建可切换项目、预览和活动锁的测试观察器。
* @returns 流程及其响应式输入
*/
function setup() { function setup() {
const id = ref('policy-project') const id = ref('policy-project'), input = ref('preview-1'), allowed = ref(true)
const input = ref('preview-1') const scope = effectScope(); scopes.push(scope)
const allowed = ref(true) return { id, input, allowed, flow: scope.run(() => useBreakdownStartPolicy(id, input, allowed))! }
scope = effectScope()
const flow = scope.run(() => useBreakdownStartPolicy(id, input, allowed))!
return { id, input, allowed, flow }
} }
afterEach(() => { /** 模拟服务端 CAS 保存及独立明确确认,复制回执避免测试污染。 */
scope?.stop() function server() {
vi.unstubAllGlobals() let saved = initial()
localStorage.clear() const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
vi.restoreAllMocks() const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (_id, policy, expected) => {
}) if (expected !== saved.revision) throw new Error('版本冲突')
saved = policyReceipt(saved.projectId, policyDraft(policy), { revision: saved.revision + 1, fingerprint: 'b'.repeat(64) })
return structuredClone(saved)
})
const confirm = vi.spyOn(projectsApi, 'confirmQualityPolicy').mockImplementation(async (_id, expected) => {
if (expected !== saved.revision) throw new Error('版本冲突')
saved = { ...saved, confirmed: true, confirmedRevision: expected, confirmedAt: '2026-10-17T15:00:00Z' }
return structuredClone(saved)
})
return { read, save, confirm, get: () => saved, change: (value: Partial<ProjectQualityPolicyResult>) => { saved = { ...saved, ...value } } }
}
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.clear() })
describe('拆解质量规则内容与当前浏览器确认', () => { describe('规则内容比较与服务端确认', () => {
it('忽略属性顺序、首尾空格和空例外表示,但识别许可、规则和例外的实际变化', () => { it('格式版本不代替修订,比较内容时保留许可、规则和例外变化', () => {
const base = receipt().policy const base = initial().policy
expect(qualityPolicySignature({ ...base, actionExceptions: [] })).toBe(qualityPolicySignature(base)) expect(qualityPolicySignature({ ...base, actionExceptions: [] })).toBe(qualityPolicySignature(base))
const reversed = Object.fromEntries(Object.entries({ ...base, customRules: ['规则'] }).toReversed()) as unknown as ProjectQualityPolicy expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(qualityPolicySignature({ ...base, customRules: ['规则'] }))
expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(qualityPolicySignature(reversed)) for (const change of [{ physicsMode: 'fantasy' as const }, { allowExaggeratedMotion: true }, { allowNonPhysicalActions: true }, { allowSupernaturalAbilities: true }, { customRules: ['新规则'] }, { actionExceptions: [{ code: 'action_resource_conflict' as const, ownerRef: '@CH1', resource: 'left_hand' as const, reason: '许可' }] }])
for (const changed of [ expect(qualityPolicySignature({ ...base, ...change })).not.toBe(qualityPolicySignature(base))
{ ...base, physicsMode: 'fantasy' as const },
{ ...base, allowExaggeratedMotion: true },
{ ...base, allowNonPhysicalActions: true },
{ ...base, allowSupernaturalAbilities: true },
{ ...base, customRules: ['新规则'] },
{ ...base, actionExceptions: [{ code: 'action_resource_conflict' as const, ownerRef: '@CH1', resource: 'left_hand' as const, reason: '剧本许可' }] }
]) expect(qualityPolicySignature(changed)).not.toBe(qualityPolicySignature(base))
expect(() => qualityPolicySignature({ ...base, customRules: null } as unknown as ProjectQualityPolicy)).toThrow('质量规则响应不完整')
}) })
it('旧浏览器确认记录不能跳过服务未确认规则;取消不写入确认', async () => {
it('确认按项目隔离,损坏存储或存储权限失败不会被当作已确认', () => { const api = server()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull() localStorage.setItem('short-drama:breakdown-quality-confirmation:v1:policy-project', JSON.stringify({ formatVersion: 1, signature: qualityPolicySignature(initial().policy) }))
rememberQualityPolicyConfirmation('policy-project', 'signature') const { flow } = setup(); await flow.prepare()
expect(readQualityPolicyConfirmation('other')).toBeNull() expect(flow.reviewOpen.value).toBe(true); expect(flow.startOpen.value).toBe(false)
localStorage.setItem('short-drama:breakdown-quality-confirmation:v1:policy-project', '{') flow.cancel(); expect(api.confirm).not.toHaveBeenCalled(); expect(flow.consumePermit()).toBeNull()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => { throw new Error('storage blocked') } })
expect(rememberQualityPolicyConfirmation('policy-project', 'new')).toBe(false)
}) })
}) it('未改规则也独立明确确认,修订零可启动,其他页面重进不重复提醒', async () => {
const api = server(); const { flow } = setup()
describe('拆解前规则确认流程', () => { await flow.prepare(); expect(await flow.confirmRules(initial().policy)).toBe(true)
it('首次读取失败不展示默认规则,重试后才能进入确认', async () => { expect(api.save).not.toHaveBeenCalled(); expect(api.confirm).toHaveBeenCalledExactlyOnceWith('policy-project', 0)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockRejectedValueOnce(new Error('读取不可用')).mockResolvedValue(receipt()) flow.cancel(); const next = setup().flow; await next.prepare()
const { flow } = setup() expect(next.reviewOpen.value).toBe(false); expect(next.startOpen.value).toBe(true)
await flow.prepare()
expect(flow.policy.value).toBeNull()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.error.value).toBe('读取不可用')
expect(flow.consumePermit()).toBe(false)
await flow.prepare()
expect(read).toHaveBeenCalledTimes(2)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.error.value).toBe('')
})
it('首次读取真实规则,取消不记录确认,也不允许绕过确认直接启动', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
expect(read).not.toHaveBeenCalled()
await flow.prepare()
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
flow.cancel()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
expect(save).not.toHaveBeenCalled()
})
it('明确确认未改规则不重复保存,刷新会话后直接进入普通启动确认', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(receipt().policy)).toBe(true)
expect(flow.startOpen.value).toBe(true)
expect(save).not.toHaveBeenCalled()
expect(flow.consumePermit()).toBe(false)
flow.cancel()
scope!.stop()
const next = setup().flow
await next.prepare()
expect(next.reviewOpen.value).toBe(false)
expect(next.startOpen.value).toBe(true)
expect(await next.verifyStart()).toBe(true) expect(await next.verifyStart()).toBe(true)
expect(next.consumePermit()).toBe(true) expect(next.consumePermit()).toEqual({ expectedRevision: 0 }); expect(next.consumePermit()).toBeNull()
expect(next.consumePermit()).toBe(false)
}) })
it('修改规则先携带旧修订保存,再确认新修订,最后重读确认', async () => {
it('编辑的完整草稿先保存并重读,保存后的内容才记作已确认', async () => { const api = server(); const { flow } = setup(); await flow.prepare()
const saved = receipt() const draft = { ...initial().policy, allowExaggeratedMotion: true }
const draft = { ...saved.policy, allowExaggeratedMotion: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => {
saved.policy = policyDraft(policy)
return { projectId: id, policy: policyDraft(policy) }
})
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(draft)).toBe(true) expect(await flow.confirmRules(draft)).toBe(true)
expect(save).toHaveBeenCalledWith('policy-project', draft) expect(api.save).toHaveBeenCalledExactlyOnceWith('policy-project', draft, 0)
expect(read).toHaveBeenCalledTimes(3) expect(api.confirm).toHaveBeenCalledExactlyOnceWith('policy-project', 1)
expect(readQualityPolicyConfirmation('policy-project')).toBe(qualityPolicySignature(draft)) expect(api.read).toHaveBeenCalledTimes(3)
expect(await flow.verifyStart()).toBe(true); expect(flow.consumePermit()).toEqual({ expectedRevision: 1 })
}) })
it('同内容被修改后又恢复但修订增加时仍重新确认,不能覆盖更新', async () => {
it('规则在其他位置更新后重新确认,不覆盖服务端较新规则', async () => { const api = server(); const { flow } = setup(); await flow.prepare()
let saved = receipt() api.change({ revision: 4 })
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved)) expect(await flow.confirmRules(initial().policy)).toBe(false)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy') expect(flow.policy.value?.revision).toBe(4); expect(api.save).not.toHaveBeenCalled(); expect(api.confirm).not.toHaveBeenCalled()
const { flow } = setup()
await flow.prepare()
saved = { ...saved, policy: { ...saved.policy, allowNonPhysicalActions: true } }
expect(await flow.confirmRules(receipt().policy)).toBe(false)
expect(flow.policy.value?.policy.allowNonPhysicalActions).toBe(true)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(save).not.toHaveBeenCalled()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
}) })
it.each(['读取失败', '项目不符', '元数据缺失', '保存失败', '确认失败', '回执不符', '确认后变化'])('拦截%s且不取得启动许可', async kind => {
it('真实保存期间锁定取消,保存后的只读回查可取消,迟到回查不记录确认', async () => { const api = server(); const { flow } = setup(); await flow.prepare()
const initial = receipt() const draft = { ...initial().policy, allowNonPhysicalActions: true }
const draft = { ...initial.policy, allowNonPhysicalActions: true } if (kind === '读取失败') api.read.mockRejectedValueOnce(new Error('读取失败'))
let finishSave!: (value: ProjectQualityPolicyResult) => void if (kind === '项目不符') api.read.mockResolvedValueOnce({ ...initial(), projectId: 'other' })
let finishRead!: (value: ProjectQualityPolicyResult) => void if (kind === '元数据缺失') api.read.mockResolvedValueOnce({ ...initial(), revision: undefined } as unknown as ProjectQualityPolicyResult)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial) if (kind === '保存失败') api.save.mockRejectedValueOnce(new Error('保存失败'))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(() => new Promise(resolve => { finishSave = resolve })) if (kind === '确认失败') api.confirm.mockRejectedValueOnce(new Error('确认失败'))
const { flow } = setup() if (kind === '回执不符') api.confirm.mockResolvedValueOnce(initial())
await flow.prepare() if (kind === '确认后变化') api.confirm.mockImplementationOnce(async () => {
const pending = flow.confirmRules(draft) const confirmed = { ...api.get(), confirmed: true, confirmedRevision: api.get().revision, confirmedAt: '2026-10-17T15:00:00Z' }
await Promise.resolve() api.change({ revision: api.get().revision + 1 }); return confirmed
await Promise.resolve() })
expect(save).toHaveBeenCalledOnce() expect(await flow.confirmRules(draft)).toBe(false); expect(flow.startOpen.value).toBe(false); expect(flow.consumePermit()).toBeNull()
expect(flow.saving.value).toBe(true)
flow.cancel()
expect(flow.reviewOpen.value).toBe(true)
read.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve }))
finishSave({ ...initial, policy: draft })
await Promise.resolve()
await Promise.resolve()
expect(flow.saving.value).toBe(false)
expect(flow.reading.value).toBe(true)
flow.cancel()
finishRead({ ...initial, policy: draft })
expect(await pending).toBe(false)
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).toBeNull()
}) })
it.each(['cancel', 'project', 'scope', 'locked'])('%s 后丢弃迟到读取,重复点击不重复读取', async cause => {
it('最终启动确认期间规则变化,返回规则界面并撤销启动许可', async () => {
const saved = receipt()
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
rememberQualityPolicyConfirmation(saved.projectId, qualityPolicySignature(saved.policy))
const { flow } = setup()
await flow.prepare()
saved.policy.customRules = ['新规则']
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it.each(['读取失败', '项目不符', '保存失败', '回执不符', '保存后变化'])('安全拦截%s,不记住确认', async kind => {
const initial = receipt()
const changed = { ...initial.policy, allowNonPhysicalActions: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockResolvedValue({ ...initial, policy: changed })
const { flow } = setup()
await flow.prepare()
if (kind === '读取失败') read.mockRejectedValueOnce(new Error('读取失败'))
if (kind === '项目不符') read.mockResolvedValueOnce({ ...initial, projectId: 'other' })
if (kind === '保存失败') save.mockRejectedValueOnce(new Error('保存失败'))
if (kind === '回执不符') save.mockResolvedValueOnce(initial)
expect(await flow.confirmRules(changed)).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).toBeNull()
})
it.each(['cancel', 'project', 'scope', 'locked'])('重复点击只读一次,%s 后丢弃迟到读取', async cause => {
let finish!: (value: ProjectQualityPolicyResult) => void let finish!: (value: ProjectQualityPolicyResult) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(() => new Promise(resolve => { finish = resolve })) const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(() => new Promise(resolve => { finish = resolve }))
const { flow, id, input, allowed } = setup() const { flow, id, input, allowed } = setup(); const pending = flow.prepare(); await flow.prepare()
const pending = flow.prepare()
await flow.prepare()
expect(read).toHaveBeenCalledTimes(1) expect(read).toHaveBeenCalledTimes(1)
if (cause === 'cancel') flow.cancel() if (cause === 'cancel') flow.cancel()
if (cause === 'project') id.value = 'other' if (cause === 'project') id.value = 'other'
if (cause === 'scope') input.value = 'preview-2' if (cause === 'scope') input.value = 'new'
if (cause === 'locked') allowed.value = false if (cause === 'locked') allowed.value = false
finish(receipt()) finish(initial()); await pending
await pending expect(flow.reviewOpen.value).toBe(false); expect(flow.startOpen.value).toBe(false); expect(flow.consumePermit()).toBeNull()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
}) })
it('确认写入时锁定取消,写入后的只读回查仍可关闭且迟到响应不启动', async () => {
it('最终重读失败不能启动,取消后迟到成功也不能启动', async () => { const api = server(); const { flow } = setup(); await flow.prepare()
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
rememberQualityPolicyConfirmation('policy-project', qualityPolicySignature(receipt().policy))
const { flow } = setup()
await flow.prepare()
read.mockRejectedValueOnce(new Error('重读失败'))
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
let finish!: (value: ProjectQualityPolicyResult) => void let finish!: (value: ProjectQualityPolicyResult) => void
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve })) api.confirm.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
const pending = flow.verifyStart() const pending = flow.confirmRules(initial().policy)
flow.cancel() await Promise.resolve(); await Promise.resolve(); expect(flow.saving.value).toBe(true)
finish(receipt()) flow.cancel(); expect(flow.reviewOpen.value).toBe(true)
expect(await pending).toBe(false) let finishRead!: (value: ProjectQualityPolicyResult) => void
expect(flow.consumePermit()).toBe(false) api.read.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve }))
const confirmed = { ...initial(), confirmed: true, confirmedRevision: 0, confirmedAt: '2026-10-17T15:00:00Z' }
finish(confirmed); await Promise.resolve(); await Promise.resolve()
expect(flow.reading.value).toBe(true); expect(flow.saving.value).toBe(false)
flow.cancel(); finishRead(confirmed); expect(await pending).toBe(false); expect(flow.consumePermit()).toBeNull()
}) })
it('最终费用确认期间规则更新或确认撤销均返回规则核对', async () => {
it('存储受限时仅在本次会话跳过确认,实际规则保存会撤销临时确认', async () => { const api = server(); const { flow } = setup(); await flow.prepare(); await flow.confirmRules(initial().policy)
vi.stubGlobal('localStorage', { getItem: () => null, removeItem: () => {}, setItem: () => { throw new Error('blocked') } }) api.change({ confirmed: false, confirmedRevision: null, confirmedAt: null })
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt()) expect(await flow.verifyStart()).toBe(false); expect(flow.reviewOpen.value).toBe(true); expect(flow.consumePermit()).toBeNull()
const { flow } = setup() })
await flow.prepare() it('最终重读失败不能启动,取消后迟到成功也不能启动', async () => {
expect(await flow.confirmRules(receipt().policy)).toBe(true) const api = server(); const { flow } = setup(); await flow.prepare(); await flow.confirmRules(initial().policy)
flow.cancel() api.read.mockRejectedValueOnce(new Error('重读失败')); expect(await flow.verifyStart()).toBe(false)
await flow.prepare() let finish!: (value: ProjectQualityPolicyResult) => void
expect(flow.startOpen.value).toBe(true) api.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
invalidateQualityPolicyConfirmation('policy-project') const pending = flow.verifyStart(); flow.cancel(); finish(api.get())
expect(await flow.verifyStart()).toBe(false) expect(await pending).toBe(false); expect(flow.consumePermit()).toBeNull()
expect(flow.reviewOpen.value).toBe(true)
}) })
}) })
@@ -32,7 +32,10 @@ afterEach(() => {
vi.unstubAllGlobals() vi.unstubAllGlobals()
}) })
/** happy-dom 不计算排版;注入明确的容器几何,但保持真实 NScrollbar 和原生 scroll 事件路径。 */ /**
* 注入容器几何与浏览器滚动取整规则,保持真实 NScrollbar 和原生 scroll 事件路径。
* @returns 正文与目录容器、章节原始位置及滚动调用记录
*/
async function mountReader() { async function mountReader() {
wrapper = mount(EpisodeReader, { props: { episodes } }) wrapper = mount(EpisodeReader, { props: { episodes } })
const reader = wrapper.get<HTMLElement>('.reader-scroll .n-scrollbar-container').element const reader = wrapper.get<HTMLElement>('.reader-scroll .n-scrollbar-container').element
@@ -45,7 +48,9 @@ async function mountReader() {
if (this === reader) return new DOMRect(0, 100, 600, reader.clientHeight) if (this === reader) return new DOMRect(0, 100, 600, reader.clientHeight)
if (this === directory) return new DOMRect(0, 50, 200, directory.clientHeight) if (this === directory) return new DOMRect(0, 50, 200, directory.clientHeight)
if (this.matches('.reader-chapter')) { if (this.matches('.reader-chapter')) {
return new DOMRect(0, 100 + tops[Number(this.dataset.episode)]! - reader.scrollTop, 600, 600) // 模拟章节平移后的可见位置,保留真实组件负责的像素对齐行为。
const translation = parseFloat(this.style.getPropertyValue('--reader-chapter-offset')) || 0
return new DOMRect(0, 100 + tops[Number(this.dataset.episode)]! + translation - reader.scrollTop, 600, 600)
} }
if (this.matches('.reader-episode-link')) { if (this.matches('.reader-episode-link')) {
return new DOMRect(0, 58 + (Number(this.dataset.episode) - 1) * 72 - directory.scrollTop, 180, 64) return new DOMRect(0, 58 + (Number(this.dataset.episode) - 1) * 72 - directory.scrollTop, 180, 64)
@@ -55,7 +60,7 @@ async function mountReader() {
const readerScroll = vi.spyOn(reader, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => { const readerScroll = vi.spyOn(reader, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => {
if (typeof options !== 'object') return if (typeof options !== 'object') return
// 模拟浏览器边界:末集最小高度及上下留白让其标题能抵达阅读线。 // 模拟浏览器边界:末集最小高度及上下留白让其标题能抵达阅读线。
reader.scrollTop = Math.max(0, Math.min(options.top ?? 0, Math.max(...Object.values(tops)) - 32)) reader.scrollTop = Math.round(Math.max(0, Math.min(options.top ?? 0, Math.max(...Object.values(tops)) - 32)))
reader.dispatchEvent(new Event('scroll')) reader.dispatchEvent(new Event('scroll'))
}) })
const directoryScroll = vi.spyOn(directory, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => { const directoryScroll = vi.spyOn(directory, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => {
@@ -131,6 +136,18 @@ describe('连续剧本阅读器', () => {
expect(pageScroll).not.toHaveBeenCalled() expect(pageScroll).not.toHaveBeenCalled()
}) })
it('章节高度含小数时,反复切换各集仍与首集顶部精确对齐', async () => {
const { reader, tops } = await mountReader()
tops[2] = 700.625
tops[3] = 1480.84375
for (const episode of [1, 2, 3, 2, 1, 3, 2]) {
await wrapper!.get(`.reader-episode-link[data-episode="${episode}"]`).trigger('click')
const chapter = wrapper!.get(`.reader-chapter[data-episode="${episode}"]`).element
expect(chapter.getBoundingClientRect().top - reader.getBoundingClientRect().top).toBe(32)
expect(currentEpisode()).toBe(episode)
}
})
it('手机上下集按目录顺序切换,跳过缺号并禁用首尾边界', async () => { it('手机上下集按目录顺序切换,跳过缺号并禁用首尾边界', async () => {
const { reader } = await mountReader() const { reader } = await mountReader()
await wrapper!.setProps({ episodes: [episodes[0]!, episodes[2]!] }) await wrapper!.setProps({ episodes: [episodes[0]!, episodes[2]!] })
@@ -16,6 +16,15 @@ function mountFields(schemas: GenerationOptionSchema[]) {
} }
describe('生成模型参数字段', () => { describe('生成模型参数字段', () => {
it('只有目录声明支持的模型才提供智能时长,不按模型品牌补造 -1', () => {
for (const supported of [false, true]) {
const wrapper = mountFields([{ key: 'durationSeconds', label: '生成时长', type: 'integer', required: true,
min: 4, max: 6, ...(supported ? { specialValues: [{ label: '智能时长', value: -1 }] } : {}) }])
const options = wrapper.getComponent(NSelect).props('options') as { value: number }[]
expect(options.some(item => item.value === -1)).toBe(supported)
wrapper.unmount()
}
})
it('图片尺寸只保留当前 Provider 枚举、默认值与当前值', () => { it('图片尺寸只保留当前 Provider 枚举、默认值与当前值', () => {
const wrapper = mountFields([ const wrapper = mountFields([
{ {
@@ -86,6 +86,14 @@ const catalog: GenerationModelCatalog = {
} }
describe('项目配置保存前校验', () => { describe('项目配置保存前校验', () => {
it('项目竖屏画布允许目录支持的方形参考图尺寸,不把两者强制绑定', () => {
const draft = creativeProfileDraft(saved)
const squareCatalog = structuredClone(catalog)
squareCatalog.images[0]!.generationOptions[0]!.options = [{ label: '方形参考图', value: '2048*2048' }]
draft.imageOptions.size = '2048*2048'
expect(draft.aspectRatio).toBe('9:16')
expect(creativeProfileIssues(draft, squareCatalog)).toEqual([])
})
it('保留但提示不再支持的历史尺寸,选择有效尺寸后可保存', () => { it('保留但提示不再支持的历史尺寸,选择有效尺寸后可保存', () => {
const draft = creativeProfileDraft(saved) const draft = creativeProfileDraft(saved)
expect(creativeProfileIssues(draft, catalog)).toHaveLength(1) expect(creativeProfileIssues(draft, catalog)).toHaveLength(1)
@@ -0,0 +1,67 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { NSelect, type MessageApi } from 'naive-ui'
import { ref } from 'vue'
import CreativeProfileSettings from '@/features/generation-config/components/CreativeProfileSettings.vue'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectGenerationRevisionKey } from '@/features/generation-config/context'
import { actionMessageKey } from '@/components/ui/useActionMessage'
import { ApiError } from '@/lib/http'
import { generationProfile, imageCatalog } from '../../fixtures/generation'
/** 当前配置表单实例,测试后释放观察器。 */
let wrapper: VueWrapper | undefined
afterEach(() => wrapper?.unmount())
/**
* 使用真实表单和隔离消息层,不请求真实服务或保存项目数据。
* @returns 草稿原值、保存接口、消息及配置修订号
*/
async function settings() {
const saved = generationProfile('config-contract')
const catalog = { ...imageCatalog, videos: [{ ...imageCatalog.images[0]!, type: 'video' as const, provider: 'seedance', model: 'seedance', generationOptions: [], defaults: {} }] }
vi.spyOn(generationConfigApi, 'catalog').mockResolvedValue(catalog)
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(saved)
const save = vi.spyOn(generationConfigApi, 'saveProfile').mockResolvedValue(saved)
const messages = { success: vi.fn<MessageApi['success']>(), warning: vi.fn<MessageApi['warning']>(), error: vi.fn<MessageApi['error']>(), info: vi.fn<MessageApi['info']>() }
const revision = ref(0)
wrapper = mount(CreativeProfileSettings, {
props: { projectId: saved.projectId },
global: { provide: { [actionMessageKey as symbol]: messages as unknown as MessageApi, [projectGenerationRevisionKey as symbol]: revision } }
})
await flushPromises()
return { saved, save, messages, revision }
}
describe('项目配置的业务冲突反馈', () => {
it.each([
['CANVAS_CHANGE_REQUIRES_REVALIDATION', '画幅'],
['CREATIVE_PROFILE_ACTIVE_WORKFLOW', '任务'],
['GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION', '模型']
])('保存遇到 %s 时只提示业务原因、保留草稿且不重试', async (code, label) => {
const { saved, save, messages, revision } = await settings()
await wrapper!.findAllComponents(NSelect)[0]!.vm.$emit('update:value', '9:16')
save.mockRejectedValue(new ApiError('请求失败(409)', 409, { code, keyframeCount: 1 }))
await wrapper!.find('button').trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledTimes(1)
expect(messages.warning).toHaveBeenCalledWith(expect.stringContaining(label), expect.any(Object))
expect(messages.error).not.toHaveBeenCalled()
expect(messages.success).not.toHaveBeenCalled()
expect(wrapper!.findAllComponents(NSelect)[0]!.props('value')).toBe('9:16')
expect(wrapper!.emitted('saved')).toBeUndefined()
expect(revision.value).toBe(0)
expect(saved.aspectRatio).toBe('1:1')
expect(wrapper!.text()).not.toContain('请求失败')
})
it('保存成功使用统一消息,不遗留重复的常驻成功提示', async () => {
const { save, messages, revision } = await settings()
await wrapper!.find('button').trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledTimes(1)
expect(messages.success).toHaveBeenCalledTimes(1)
expect(wrapper!.find('.context-notice-success').exists()).toBe(false)
expect(revision.value).toBe(1)
})
})
@@ -6,7 +6,7 @@ import type { ProductionStartInput } from '@/features/production/types'
afterEach(() => vi.unstubAllGlobals()) afterEach(() => vi.unstubAllGlobals())
describe('生产后端真实请求契约', () => { describe('生产后端真实请求契约', () => {
it('计划使用 POST JSON 并将图片参数与启动保持同源', async () => { it('计划保持 POST 且只发送支持的模型参数,启动另外携带执行范围和视频参数', async () => {
const fetchMock = vi const fetchMock = vi
.fn<typeof fetch>() .fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p' } }))) .mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p' } })))
@@ -15,6 +15,7 @@ describe('生产后端真实请求契约', () => {
imageProvider: 'qwen-image', imageProvider: 'qwen-image',
imageGenerationOptions: { size: '1024*1024', seed: 3 }, imageGenerationOptions: { size: '1024*1024', seed: 3 },
videoProvider: 'wan', videoProvider: 'wan',
videoGenerationOptions: { duration: -1, resolution: '720p' },
startFrom: 'subjectImages', startFrom: 'subjectImages',
stopAfter: 'videoPrompts', stopAfter: 'videoPrompts',
stableIdentityAnchorLimit: 1, stableIdentityAnchorLimit: 1,
@@ -27,10 +28,13 @@ describe('生产后端真实请求契约', () => {
await productionApi.startPipeline('p', input) await productionApi.startPipeline('p', input)
expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/projects/p/production/plan') expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/projects/p/production/plan')
expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/projects/p/production/start') expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/projects/p/production/start')
for (const [, request] of fetchMock.mock.calls) { expect(fetchMock.mock.calls.every(([, request]) => request?.method === 'POST')).toBe(true)
expect(request?.method).toBe('POST') expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
expect(JSON.parse(String(request?.body))).toEqual(input) imageProvider: input.imageProvider,
} imageGenerationOptions: input.imageGenerationOptions,
videoProvider: input.videoProvider
})
expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual(input)
expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal) expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal)
}) })
+51 -1
View File
@@ -8,6 +8,9 @@ import { getOperation } from '@/features/workflows/operations'
import { formFixture } from '@/features/subject-images/testing/fixtures' import { formFixture } from '@/features/subject-images/testing/fixtures'
import { directionsResult } from '@/features/storyboard/testing/fixtures' import { directionsResult } from '@/features/storyboard/testing/fixtures'
import { checkPipeline, useAdvancedProduction } from '@/features/production/useAdvancedProduction' import { checkPipeline, useAdvancedProduction } from '@/features/production/useAdvancedProduction'
import { productionApi } from '@/features/production/api'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectSettingsOpenKey } from '@/features/generation-config/context'
import { useProduction } from '@/features/production/useProduction' import { useProduction } from '@/features/production/useProduction'
import { getProductionSession } from '@/features/production/model' import { getProductionSession } from '@/features/production/model'
import AdvancedProduction from '@/features/production/components/AdvancedProduction.vue' import AdvancedProduction from '@/features/production/components/AdvancedProduction.vue'
@@ -146,10 +149,12 @@ function server() {
} }
else if (path.endsWith('/checkpoints')) data = context.checkpoints.value else if (path.endsWith('/checkpoints')) data = context.checkpoints.value
else if (path.endsWith('/subject-forms')) data = [form] else if (path.endsWith('/subject-forms')) data = [form]
else if (path.endsWith('/production/entry-readiness')) data = { ready: true, derivedAssets: { shotCount: 1 } }
else if (path.includes('/storyboard-visual-states')) data = { ...directionsResult('capability-test', Number(new URL(String(url), 'http://localhost').searchParams.get('episodeNo') || 1)), shotCount: 1, visualStateCount: 1, staleCount: 0 }
else if (path.endsWith('/production/plan')) data = plan else if (path.endsWith('/production/plan')) data = plan
else if (path.endsWith('/production/status')) data = status else if (path.endsWith('/production/status')) data = status
else if (path.includes('/readiness')) data = readiness else if (path.includes('/readiness')) data = readiness
else if (path.includes('/storyboard-directions')) data = directionsResult('capability-test') else if (path.includes('/storyboard-directions')) data = { ...directionsResult('capability-test'), shotCount: 1, directionCount: 1 }
else if (path.endsWith('/videos/status')) else if (path.endsWith('/videos/status'))
data = { data = {
total: 1, total: 1,
@@ -205,6 +210,51 @@ async function advanced() {
} }
describe('高级串联生产的安全边界', () => { describe('高级串联生产的安全边界', () => {
it('缺少配置时在计划位置提供已有配置入口,不创建配置或允许启动', async () => {
const { context, posts } = server()
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(null)
const openSettings = vi.fn<() => void>()
wrapper = mount(AdvancedProduction, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context, [projectSettingsOpenKey as symbol]: openSettings } }
})
await flushPromises()
await expandSections()
button('检查串联生产条件').click()
await flushPromises()
const configure = wrapper.findAll('button').find(item => item.text() === '前往项目配置')
expect(configure?.exists()).toBe(true)
await configure!.trigger('click')
expect(openSettings).toHaveBeenCalledTimes(1)
expect(button('启动串联生产').disabled).toBe(true)
expect(posts()).toHaveLength(0)
})
it('配置在预检期间缺失时显示明确阻断,不读取空阶段或允许启动', async () => {
const { service, posts } = await advanced()
vi.spyOn(productionApi, 'plan').mockResolvedValue({ projectId: 'capability-test', canStart: false, canAutoRun: false, hasManualBlockers: true, manualBlocked: 1, configuration: { status: 'blocked', code: 'CREATIVE_PROFILE_REQUIRED', reason: '项目尚未配置 Creative Profile,请先保存项目生成配置' }, entryReadiness: { ready: true }, providers: null, generationConfig: null, completed: false, stage: 'configuration_required', characterIdentity: null, stableIdentityAnchors: null, subjectImages: null, keyframes: null, videoPrompts: null, videos: null, details: null })
await service.preflight()
expect(service.check.value).toBeNull()
expect(service.error.value).toContain('请先保存项目生成配置')
expect(service.error.value).not.toContain('TypeError')
expect(service.configurationRequired.value).toBe(true)
expect(posts()).toHaveLength(0)
})
it('尚无配置时不请求阶段计划,保存配置后重新预检恢复正常流程', async () => {
const { service, fetcher, posts } = await advanced()
const original = fetcher.getMockImplementation()!
let missing = true
fetcher.mockImplementation((url, init) => missing && String(url).endsWith('/creative-profile')
? Promise.resolve(new Response('{"data":null}')) : original(url, init))
await service.preflight()
expect(service.configurationRequired.value).toBe(true)
expect(service.check.value).toBeNull()
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/production/plan'))).toBe(false)
missing = false
await service.preflight()
expect(service.configurationRequired.value).toBe(false)
expect(service.check.value?.issues).toEqual([])
expect(posts()).toHaveLength(0)
})
it('挂载不查询或生成,通过预检仍需显式启动,再次预检后提交安全范围与项目模型参数', async () => { it('挂载不查询或生成,通过预检仍需显式启动,再次预检后提交安全范围与项目模型参数', async () => {
const { service, fetcher, posts } = await advanced() const { service, fetcher, posts } = await advanced()
expect(fetcher).not.toHaveBeenCalled() expect(fetcher).not.toHaveBeenCalled()
+23
View File
@@ -114,6 +114,29 @@ async function openProject(initialPath: string) {
} }
describe('剧本完成前的下游访问限制', () => { describe('剧本完成前的下游访问限制', () => {
it('导航使用当前阶段结果,旧待审标记不盖过已审核状态,下游素材仍独立限制', async () => {
const id = 'current-review-navigation'
const state = readiness(id, false)
state.script = { ready: true, reason: null }
state.breakdown = { ready: true, reason: null }
state.storyboard = { ready: true, reason: null }
vi.mocked(projectsApi.stageReadiness).mockImplementation(async () => structuredClone(state))
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project(id, 'completed'))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([{
checkpointId: 'old-pending-review', workflowName: 'breakdown', createdAt: '2026-10-01T00:00:00Z',
state: { storyboardNeedsManualReview: true, storyboardShotValidation: { valid: true, issues: [] } }
}])
const { mounted } = await openProject(`/projects/${id}/visual-style`)
expect(mounted).toHaveBeenCalledExactlyOnceWith('visual-style')
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/visual-style"]`).exists()).toBe(true)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/subject-identity"]`).exists()).toBe(false)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/production"]`).exists()).toBe(false)
state.breakdown = { ready: false, reason: '当前分镜审核已失效,请重新核对。' }
await wrapper!.get('.probe-refresh').trigger('click')
await flushPromises()
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('当前分镜审核已失效')
})
it('身份请求不使用全局加载消息,完成和失败使用临时消息且不遗留横幅', async () => { it('身份请求不使用全局加载消息,完成和失败使用临时消息且不遗留横幅', async () => {
vi.useFakeTimers() vi.useFakeTimers()
const id = 'identity-message-test' const id = 'identity-message-test'
+17 -19
View File
@@ -1,10 +1,10 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { policyDraft, policyIssue } from '@/features/projects/quality-policy' import { policyDraft, policyIssue } from '@/features/projects/quality-policy'
import { projectsApi } from '@/features/projects/api' import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types' import type { ProjectQualityPolicy } from '@/features/projects/types'
import QualityPolicySettings from '@/features/generation-config/components/QualityPolicySettings.vue' import QualityPolicySettings from '@/features/generation-config/components/QualityPolicySettings.vue'
import { qualityPolicySignature, readQualityPolicyConfirmation, rememberQualityPolicyConfirmation } from '@/features/projects/quality-policy-confirmation'
/** 保留已有精确例外的服务端完整策略。 */ /** 保留已有精确例外的服务端完整策略。 */
const saved: ProjectQualityPolicy = { const saved: ProjectQualityPolicy = {
@@ -29,7 +29,7 @@ afterEach(() => {
}) })
describe('项目质量策略', () => { describe('项目质量策略', () => {
it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => { it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => {
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } }) const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
settings = wrapper settings = wrapper
await flushPromises() await flushPromises()
expect(wrapper.findAll('button').some(button => button.text() === '添加例外')).toBe(false) expect(wrapper.findAll('button').some(button => button.text() === '添加例外')).toBe(false)
@@ -37,41 +37,39 @@ describe('项目质量策略', () => {
expect(wrapper.text()).toContain('已有动作例外 · 1 项') expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(saved.actionExceptions) expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(saved.actionExceptions)
}) })
it('启动入口复用真实回执,不重复读取,无变化保存保留确认,修改后撤销确认', async () => { it('启动入口复用真实回执,保存前重读版本,不把保存当作明确确认', async () => {
let currentPolicy = policyDraft(saved) let currentPolicy = policyDraft(saved)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'p', policy: policyDraft(currentPolicy) })) const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => (policyReceipt('p', policyDraft(currentPolicy))))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => { currentPolicy = policyDraft(policy); return { projectId: id, policy: policyDraft(policy) } }) vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => { currentPolicy = policyDraft(policy); return policyReceipt(id, policyDraft(policy)) })
const signature = qualityPolicySignature(saved) const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
rememberQualityPolicyConfirmation('p', signature)
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper settings = wrapper
await flushPromises() await flushPromises()
expect(read).not.toHaveBeenCalled() expect(read).not.toHaveBeenCalled()
expect(wrapper.vm.validatedDraft()).toEqual(saved) expect(wrapper.vm.validatedDraft()).toEqual(saved)
await wrapper.vm.save() await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBe(signature) expect(read).toHaveBeenCalledTimes(1)
await wrapper.get('#quality-custom-rules').setValue('新规则') await wrapper.get('#quality-custom-rules').setValue('新规则')
await wrapper.vm.save() await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBeNull() expect(read).toHaveBeenCalledTimes(2)
}) })
it('保存基础规则时合并后来新增的例外,不覆盖隐藏的服务端最新例外', async () => { it('保存基础规则时合并后来新增的例外,不覆盖隐藏的服务端最新例外', async () => {
const latest = { ...saved, actionExceptions: [...saved.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0002', resource: 'right_hand' as const, reason: '另一处刚添加的例外' }] } const latest = { ...saved, actionExceptions: [...saved.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0002', resource: 'right_hand' as const, reason: '另一处刚添加的例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'p', policy: latest }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', latest))
const write = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => ({ projectId: id, policy: policyDraft(policy) })) const write = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => (policyReceipt(id, policyDraft(policy))))
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } }) const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
settings = wrapper settings = wrapper
await flushPromises() await flushPromises()
expect(wrapper.find('.text-danger').exists()).toBe(false) expect(wrapper.find('.text-danger').exists()).toBe(false)
await wrapper.get('#quality-custom-rules').setValue('新的整体规则') await wrapper.get('#quality-custom-rules').setValue('新的整体规则')
await wrapper.vm.save() await wrapper.vm.save()
expect(write).toHaveBeenCalledExactlyOnceWith('p', { ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions }) expect(write).toHaveBeenCalledExactlyOnceWith('p', { ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions }, 2)
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(latest.actionExceptions) expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(latest.actionExceptions)
expect(wrapper.text()).toContain('已有动作例外 · 2 项') expect(wrapper.text()).toContain('已有动作例外 · 2 项')
}) })
it('基础规则已被其他位置修改时拒绝覆盖,保留用户草稿', async () => { it('基础规则已被其他位置修改时拒绝覆盖,保留用户草稿', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'p', policy: { ...saved, physicsMode: 'fantasy' } }) vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', { ...saved, physicsMode: 'fantasy' }))
const write = vi.spyOn(projectsApi, 'saveQualityPolicy') const write = vi.spyOn(projectsApi, 'saveQualityPolicy')
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } }) const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
settings = wrapper settings = wrapper
await flushPromises() await flushPromises()
await wrapper.get('#quality-custom-rules').setValue('不能丢失的用户草稿') await wrapper.get('#quality-custom-rules').setValue('不能丢失的用户草稿')
@@ -98,11 +96,11 @@ describe('项目质量策略', () => {
it('完整提交正式质量策略接口,保留用户明确的权限选择', async () => { it('完整提交正式质量策略接口,保留用户明确的权限选择', async () => {
const fetcher = vi const fetcher = vi
.fn<typeof fetch>() .fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p', policy: saved } }))) .mockImplementation(async () => new Response(JSON.stringify({ data: policyReceipt('p', saved) })))
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
await projectsApi.saveQualityPolicy('p', saved) await projectsApi.saveQualityPolicy('p', saved, 2)
expect(fetcher.mock.calls[0]![0]).toContain('/projects/p/quality-policy') expect(fetcher.mock.calls[0]![0]).toContain('/projects/p/quality-policy')
expect(fetcher.mock.calls[0]![1]!.method).toBe('PUT') expect(fetcher.mock.calls[0]![1]!.method).toBe('PUT')
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual(saved) expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ policy: saved, expectedRevision: 2 })
}) })
}) })
@@ -0,0 +1,17 @@
import type { StoryboardRecheck, ReviewBaselinePreview, StoryboardApprovalState, StoryboardApproval, ProductionEntryReadiness } from '@/features/storyboard-preparation/types'
import { policyReceipt } from '../../fixtures/quality-policy'
/**
* 创建符合真实路由形状的独立复检数据,canConfirm 始终为 false。
* @param projectId 当前测试项目
* @returns 可变化的只读回执与确认记录
*/
export function preparationFixture(projectId = 'p') {
const policy = policyReceipt(projectId, { version: 1, physicsMode: 'stylized', allowExaggeratedMotion: true, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-19T01:00:00Z' })
const quality: StoryboardRecheck = { projectId, status: 'insufficient_evidence', structure: { hasValidation: true, valid: true, reason: null }, coverage: { episodeCount: 1, beatCount: 1, shotCount: 1, issueCount: 0 }, issues: [], actionAudit: { projectId, shotCount: 1, issueCount: 0, blockedCount: 0, needsReviewCount: 0, issues: [] }, sourceAudit: { projectId, checkpointId: 'cp', shotCount: 1, valid: true, issues: [] }, provenance: { checkpointId: 'cp', sourceCommitted: true, qualityPolicyConsistent: true, qualityPolicyChecks: { projectConfirmed: true, checkpointSnapshotPresent: true }, baselineConsistent: false, shotCountsConsistent: true, checkpointConsistent: true }, preflightEligible: true, canConfirm: false }
const record: StoryboardApproval = { id: 'approval', projectId, checkpointId: 'cp', qualityPolicyRevision: 2, qualityPolicyFingerprint: 'a'.repeat(64), shotCount: 1, shotFingerprint: 'b'.repeat(64), reviewer: '复核人', reviewNote: '已逐镜核对动作与主体', confirmedAt: '2026-10-19T01:00:00Z' }
const approval: StoryboardApprovalState = { valid: false, confirmation: null, evidence: { valid: true, checkpointId: 'cp', qualityPolicyRevision: 2, qualityPolicyFingerprint: 'a'.repeat(64), shotCount: 1, shotFingerprint: 'b'.repeat(64) } }
const baseline: ReviewBaselinePreview = { eligible: false, reasons: ['当前记录已有规则来源'], checkpointId: 'cp', shotCount: 1, shotFingerprint: 'b'.repeat(64) }
const entry: ProductionEntryReadiness = { ready: false, hasStoryboardValidation: true, storyboardValid: true, reason: '请先完成分镜审核', derivedAssets: { shotCount: 1, directionCount: 0, directionCoverage: 0, visualStateCount: 0, visualStateCoverage: 0 } }
return { policy, quality, approval, baseline, entry, record }
}
@@ -0,0 +1,31 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { checkPipeline } from '@/features/production/useAdvancedProduction'
import { productionApi } from '@/features/production/api'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectsApi } from '@/features/projects/api'
import { subjectImagesApi } from '@/features/subject-images/api'
import { storyboardApi } from '@/features/storyboard/api'
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
describe('制作计划之前的正式分镜检查', () => {
it('入口未通过时不查询制作计划,也不调用生成接口', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: { ready: false, reason: '请先完成分镜审核', hasStoryboardValidation: true, storyboardValid: true, derivedAssets: { shotCount: 1, directionCount: 0, directionCoverage: 0, visualStateCount: 0, visualStateCoverage: 0 } } }))))
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(null)
vi.spyOn(projectsApi, 'detail').mockResolvedValue({ id: 'p' } as never)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.spyOn(subjectImagesApi, 'listForms').mockResolvedValue([])
vi.spyOn(productionApi, 'status').mockResolvedValue({ projectId: 'p' } as never)
const plan = vi.spyOn(productionApi, 'plan').mockRejectedValue(new Error('不应该进入制作计划'))
await expect(checkPipeline('p')).rejects.toThrow('请先完成分镜审核')
expect(plan).not.toHaveBeenCalled()
})
it('设计覆盖完整但已经过期时仍不进入制作计划', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: { ready: true, derivedAssets: { shotCount: 1 } } }))))
vi.spyOn(projectsApi, 'detail').mockResolvedValue({ id: 'p', episodes: [{ episode: 1 }] } as never)
vi.spyOn(storyboardApi, 'directions').mockResolvedValue({ projectId: 'p', episodeNo: 1, shotCount: 1, directionCount: 1, staleCount: 1, coverage: 1, beats: [] })
vi.spyOn(storyboardApi, 'visualStates').mockResolvedValue({ projectId: 'p', episodeNo: 1, shotCount: 1, visualStateCount: 1, staleCount: 0, coverage: 1, beats: [] })
const plan = vi.spyOn(productionApi, 'plan')
await expect(checkPipeline('p')).rejects.toThrow('过期')
expect(plan).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import FormalRepairEditor from '@/features/storyboard-preparation/FormalRepairEditor.vue'
import { preparationApi } from '@/features/storyboard-preparation/api'
import type { FormalShotRepairPreview, BeatSubjectPreview } from '@/features/storyboard-preparation/types'
/** 当前正式镜头有明确可补齐的动作关联,全部旧证据必须保留。 */
const preview = (): FormalShotRepairPreview => ({ projectId: 'p', shotId: 's', expectedFingerprint: 'a'.repeat(64), written: false, willCallModel: false, requiredActions: [{ id: 'a', kind: 'action', description: '左手持铃', mustPerformInShot: true }], durationPlanning: { complexity: 'low', phases: [{ action: '持铃', actionIds: ['a'], estimatedSeconds: 4, resourceOccupancy: [{ actionId: 'a', ownerRef: '@CH1', resource: 'left_hand', usage: 'hold', shareable: false, continuityRef: '@PR1' }] }], transitionSeconds: 0, recommendedDurationSeconds: 4, reason: '原动作时长' }, classification: { status: 'candidate', beforeFingerprint: 'a'.repeat(64), proposed: null, semanticIssues: [], originalIssues: [] } })
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); vi.restoreAllMocks() })
describe('正式镜头版本化修订', () => {
it('读取当前正式数据,不调用模型;人工确认后保存真实指纹和完整占用证据', async () => {
vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const model = vi.spyOn(preparationApi, 'repairCandidate')
const save = vi.spyOn(preparationApi, 'repair').mockResolvedValue({ projectId: 'p', shotId: 's', written: true, beforeFingerprint: 'a'.repeat(64), afterFingerprint: 'b'.repeat(64) })
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' }, disabled: false } })
await flushPromises()
expect(model).not.toHaveBeenCalled(); expect(save).not.toHaveBeenCalled()
await wrapper.get('[aria-label="修订原因"] textarea').setValue('逐项核对并调整动作关联')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(save).toHaveBeenCalledWith('p', expect.objectContaining({ shotId: 's', expectedFingerprint: 'a'.repeat(64), confirmed: true, reason: '逐项核对并调整动作关联', durationPlanning: expect.objectContaining({ phases: [expect.objectContaining({ resourceOccupancy: [expect.objectContaining({ continuityRef: '@PR1' })] })] }) }))
expect(wrapper.emitted('saved')).toHaveLength(1)
})
it('打开时不校验,保存前版本变化不得覆盖新镜头', async () => {
const read = vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const save = vi.spyOn(preparationApi, 'repair')
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' }, disabled: false } })
await flushPromises(); expect(wrapper.text()).not.toContain('请填写修订原因')
await wrapper.get('[aria-label="修订原因"] textarea').setValue('明确原因')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
read.mockResolvedValue({ ...preview(), expectedFingerprint: 'c'.repeat(64) })
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(save).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('已变化')
})
it('主体遗漏先保存段落的真实版本,不把段落指纹当作镜头指纹或自动追加镜头', async () => {
vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const upstream: BeatSubjectPreview = { projectId: 'p', shotId: 's', beatId: 'beat', checkpointId: 'cp', subjectRef: '@PR1', subjectName: '铜铃', subjectDescription: '项目已有铜铃', beat: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃', subjectRefs: ['@CH1'] }, shot: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃' }, status: 'upstream-missing', written: false, candidate: { checkpointId: 'cp', beatId: 'beat', subjectRef: '@PR1', expectedFingerprint: 'c'.repeat(64), proposed: { upstreamRefs: ['@CH1', '@PR1'], persistedRefs: ['@CH1', '@PR1'] }, requiresHumanReview: true } }
vi.spyOn(preparationApi, 'beatSubjectPreview').mockResolvedValue(upstream)
const beatWrite = vi.spyOn(preparationApi, 'repairBeatSubject').mockResolvedValue({ projectId: 'p', shotId: 's', beatId: 'beat', checkpointId: 'cp', resultFingerprint: 'd'.repeat(64), written: true })
const shotWrite = vi.spyOn(preparationApi, 'repairSubject')
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', subjectRef: '@PR1', message: '缺少铜铃' }, disabled: false } })
await flushPromises()
expect(beatWrite).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('剧情段落')
await wrapper.get('[aria-label="修订原因"] textarea').setValue('正文明确出现铜铃,补齐段落来源')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(beatWrite).toHaveBeenCalledExactlyOnceWith('p', { shotId: 's', subjectRef: '@PR1', expectedFingerprint: 'c'.repeat(64), confirmed: true, reason: '正文明确出现铜铃,补齐段落来源' })
expect(shotWrite).not.toHaveBeenCalled(); expect(wrapper.emitted('saved')).toHaveLength(1)
})
})
@@ -0,0 +1,82 @@
import { effectScope, ref } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { preparationApi } from '@/features/storyboard-preparation/api'
import { projectsApi } from '@/features/projects/api'
import { useStoryboardPreparation } from '@/features/storyboard-preparation/useStoryboardPreparation'
import { currentStoryboardApproval } from '@/features/storyboard-preparation/model'
import { preparationFixture } from './fixtures'
/** 当前作用域,避免项目切换测试遗留响应式观察器。 */
const scopes: ReturnType<typeof effectScope>[] = []
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks() })
/** 测试只读回执保留当前已确认规则,所有写入独立模拟。 */
function setup() {
const data = preparationFixture()
vi.spyOn(preparationApi, 'recheck').mockImplementation(async () => structuredClone(data.quality))
vi.spyOn(preparationApi, 'approval').mockImplementation(async () => structuredClone(data.approval))
vi.spyOn(preparationApi, 'baseline').mockImplementation(async () => structuredClone(data.baseline))
vi.spyOn(preparationApi, 'entry').mockImplementation(async () => structuredClone(data.entry))
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(data.policy))
const scope = effectScope(); scopes.push(scope)
const id = ref('p'), locked = ref(false)
const flow = scope.run(() => useStoryboardPreparation(id, locked))!
return { data, id, locked, flow }
}
describe('正式分镜审核绑定当前内容', () => {
it('有效标志也必须有同项目同版本的实际审核凭据', () => {
const data = preparationFixture()
const current = { ...data.approval, valid: true, confirmation: data.record }
expect(currentStoryboardApproval(current, 'p')).toBe(true)
expect(currentStoryboardApproval({ ...current, confirmation: null }, 'p')).toBe(false)
expect(currentStoryboardApproval(current, 'other')).toBe(false)
expect(currentStoryboardApproval({ ...current, evidence: { ...current.evidence, shotFingerprint: 'f'.repeat(64) } }, 'p')).toBe(false)
expect(currentStoryboardApproval({ ...current, evidence: { ...current.evidence, qualityPolicyRevision: 3 } }, 'p')).toBe(false)
})
it('只读 canConfirm=false 不代替人工确认;满足实际预检后提交真实版本', async () => {
const { data, flow } = setup()
const confirm = vi.spyOn(preparationApi, 'confirmApproval').mockResolvedValue(data.record)
await flow.load()
expect(flow.reviewable.value).toBe(true)
expect(confirm).not.toHaveBeenCalled()
expect(await flow.confirm('approval', '复核人', '已逐镜核对动作与主体')).toBe(true)
expect(confirm).toHaveBeenCalledExactlyOnceWith('p', { reviewer: '复核人', reviewNote: '已逐镜核对动作与主体', expectedCheckpointId: 'cp', expectedShotFingerprint: 'b'.repeat(64) })
})
it('确认期间镜头版本变化时撤销确认,不自动提交新版本', async () => {
const { data, flow } = setup()
const confirm = vi.spyOn(preparationApi, 'confirmApproval')
await flow.load(); data.approval.evidence.shotFingerprint = 'c'.repeat(64)
expect(await flow.confirm('approval', '复核人', '已核对')).toBe(false)
expect(confirm).not.toHaveBeenCalled()
expect(flow.error.value).toContain('已变化')
})
it('结构通过但动作问题、来源不一致或缺规则确认均不能人工放行', async () => {
const { data, flow } = setup()
data.quality.preflightEligible = false; await flow.load()
expect(flow.reviewable.value).toBe(false)
data.quality.preflightEligible = true; data.quality.actionAudit.issueCount = 1; await flow.load()
expect(flow.reviewable.value).toBe(false)
data.quality.actionAudit.issueCount = 0; data.policy.confirmed = false; await flow.load()
expect(flow.reviewable.value).toBe(false)
})
it('旧分镜来源确认与整体审核分开提交,使用真实镜头内容版本', async () => {
const { data, flow } = setup()
data.quality.provenance.qualityPolicyConsistent = false
data.quality.preflightEligible = false
data.baseline.eligible = true; data.baseline.reasons = []
const baseline = vi.spyOn(preparationApi, 'confirmBaseline').mockResolvedValue(data.record)
const approval = vi.spyOn(preparationApi, 'confirmApproval')
await flow.load(); expect(flow.baselineAllowed.value).toBe(true); expect(flow.reviewable.value).toBe(false)
expect(await flow.confirm('baseline', '复核人', '明确采用当前规则重新核对旧分镜')).toBe(true)
expect(baseline).toHaveBeenCalledExactlyOnceWith('p', { reviewer: '复核人', reviewNote: '明确采用当前规则重新核对旧分镜', expectedCheckpointId: 'cp', expectedShotFingerprint: 'b'.repeat(64) })
expect(approval).not.toHaveBeenCalled()
})
it('确认失败保留可读原因,不能把历史确认存在当作当前有效', async () => {
const { data, flow } = setup()
data.approval.confirmation = data.record
const confirm = vi.spyOn(preparationApi, 'confirmApproval').mockRejectedValue(new Error('版本冲突,请重新核对'))
await flow.load(); expect(flow.approved.value).toBe(false)
expect(await flow.confirm('approval', '复核人', '已核对')).toBe(false)
expect(confirm).toHaveBeenCalledTimes(1); expect(flow.error.value).toContain('版本冲突')
expect(flow.approved.value).toBe(false)
})
})
+10 -4
View File
@@ -1,3 +1,4 @@
import { preparationFixture } from '../storyboard-preparation/fixtures'
import { generationProfile, imageCatalog } from '../../fixtures/generation' import { generationProfile, imageCatalog } from '../../fixtures/generation'
import { routerLinkStubs } from '../../fixtures/router' import { routerLinkStubs } from '../../fixtures/router'
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
@@ -99,6 +100,7 @@ function stubFetch(fetcher: Mock<typeof fetch>) {
let executionCount = 0 let executionCount = 0
fetcher.mockImplementation(async (url, init) => { fetcher.mockImplementation(async (url, init) => {
const path = String(url) const path = String(url)
if (path.endsWith('/storyboard/quality-confirmation')) { const current = preparationFixture(fixture.id); return jsonResponse({ ...current.approval, valid: true, confirmation: current.record }) }
if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog) if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id)) if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
if (path.endsWith('/duration-budget')) if (path.endsWith('/duration-budget'))
@@ -1816,7 +1818,7 @@ describe('工作台页面交互', () => {
expect(drawerPanel().text()).toContain('本集新镜头已保存') expect(drawerPanel().text()).toContain('本集新镜头已保存')
expect(drawerPanel().text()).toContain('2 个镜头') expect(drawerPanel().text()).toContain('2 个镜头')
/** Duration Budget 新增一次只读 GET;镜头重生成不应增加额外写入。 */ /** Duration Budget 新增一次只读 GET;镜头重生成不应增加额外写入。 */
expect(fetcher.mock.calls.filter(([, init]) => !init?.method || init.method === 'GET')).toHaveLength(12) expect(fetcher.mock.calls.filter(([url, init]) => (!init?.method || init.method === 'GET') && !String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(12)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(2) expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(2)
expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe( expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe(
true true
@@ -1913,7 +1915,8 @@ describe('工作台页面交互', () => {
expect(wrapper!.text()).toContain('第2集镜头1') expect(wrapper!.text()).toContain('第2集镜头1')
expect(wrapper!.text()).not.toContain('第1集镜头1') expect(wrapper!.text()).not.toContain('第1集镜头1')
/** 切换剧集只增加当前集查询,项目时长预算只在挂载时读取一次。 */ /** 切换剧集只增加当前集查询,项目时长预算只在挂载时读取一次。 */
expect(fetcher.mock.calls).toHaveLength(6) expect(fetcher.mock.calls.filter(([url]) => !String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(6)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(1)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(1) expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(1)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true) expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
}) })
@@ -2076,12 +2079,14 @@ describe('工作台页面交互', () => {
}) })
it('修改每组集数会废弃预览,重新预览并确认后才能启动', async () => { it('修改每组集数会废弃预览,重新预览并确认后才能启动', async () => {
let rulesConfirmed = false
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).includes('breakdown-preview')) if (String(url).includes('breakdown-preview'))
return new Response( return new Response(
'{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}' '{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}'
) )
if (String(url).includes('quality-policy')) return new Response(JSON.stringify({ data: { projectId: 'page-test-project', policy: { if (String(url).endsWith('quality-policy/confirm')) rulesConfirmed = true
if (String(url).includes('quality-policy')) return new Response(JSON.stringify({ data: { projectId: 'page-test-project', revision: 3, fingerprint: 'a'.repeat(64), confirmed: rulesConfirmed, confirmedRevision: rulesConfirmed ? 3 : null, confirmedAt: rulesConfirmed ? '2026-10-17T15:00:00Z' : null, policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} } })) } } }))
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}') return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
@@ -2109,9 +2114,10 @@ describe('工作台页面交互', () => {
await flushPromises() await flushPromises()
button('确认生成拆解候选').click() button('确认生成拆解候选').click()
await flushPromises() await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST') const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST' && String(call[0]).endsWith('/breakdown/start'))
expect(post?.[0]).toBe('/api/projects/page-test-project/breakdown/start') expect(post?.[0]).toBe('/api/projects/page-test-project/breakdown/start')
expect(JSON.parse(post![1]!.body as string)).toEqual({ expect(JSON.parse(post![1]!.body as string)).toEqual({
expectedRevision: 3,
groupSize: 2, groupSize: 2,
modules: ['character', 'scene', 'prop'], modules: ['character', 'scene', 'prop'],
candidateOnly: true candidateOnly: true
+1 -1
View File
@@ -82,5 +82,5 @@ export function candidateReview(overrides: Partial<CandidateRevalidation> = {}):
* @returns 只读安全检查 * @returns 只读安全检查
*/ */
export function commitPreview(overrides: Partial<CandidateCommitPreview> = {}): CandidateCommitPreview { export function commitPreview(overrides: Partial<CandidateCommitPreview> = {}): CandidateCommitPreview {
return { projectId: 'candidate-project', checkpointId: 'candidate-current', ready: true, readOnly: true, checks: { episodeNumbersMatch: true, episodeFingerprintsMatch: true, noActiveExecutions: true, noActiveVideos: true, noSubjectIdentities: true, noSubjectImages: true, noProtectedShots: true }, counts: { episodes: 1, existingStoryboards: 0, activeExecutions: 0, activeVideos: 0, subjectIdentities: 0, subjectImages: 0, protectedShots: 0 }, ...overrides } return { projectId: 'candidate-project', checkpointId: 'candidate-current', ready: true, readOnly: true, checks: { qualityPolicyMatches: true, episodeNumbersMatch: true, episodeFingerprintsMatch: true, noActiveExecutions: true, noActiveVideos: true, noSubjectIdentities: true, noSubjectImages: true, noProtectedShots: true }, counts: { episodes: 1, existingStoryboards: 0, activeExecutions: 0, activeVideos: 0, subjectIdentities: 0, subjectImages: 0, protectedShots: 0 }, ...overrides }
} }
+12
View File
@@ -0,0 +1,12 @@
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '@/features/projects/types'
/**
* 构造带服务端修订及明确确认状态的规则回执,测试不访问真实服务。
* @param projectId 所属项目
* @param policy 规则内容
* @param overrides 修订和确认状态差异
* @returns 独立的接口回执
*/
export function policyReceipt(projectId: string, policy: ProjectQualityPolicy, overrides: Partial<ProjectQualityPolicyResult> = {}): ProjectQualityPolicyResult {
return { projectId, policy, revision: 2, fingerprint: 'a'.repeat(64), confirmed: false, confirmedRevision: null, confirmedAt: null, ...overrides }
}
+13
View File
@@ -3,6 +3,11 @@ import { ApiError, errorMessage } from '@/lib/http'
import { getOperation, operationErrorText, runOperation } from '@/features/workflows/operations' import { getOperation, operationErrorText, runOperation } from '@/features/workflows/operations'
describe('面向普通用户的系统提示', () => { describe('面向普通用户的系统提示', () => {
it('规则版本冲突显示操作指引,保留原始错误码供流程恢复', () => {
const cause = new ApiError('QUALITY_POLICY_VERSION_CONFLICT: 质量规则已更新', 409, undefined, 'QUALITY_POLICY_VERSION_CONFLICT')
expect(errorMessage(cause)).not.toContain('QUALITY_POLICY_VERSION_CONFLICT')
expect(cause.code).toBe('QUALITY_POLICY_VERSION_CONFLICT')
})
it('错误展示使用中文说明,不把技术字段和调试对象直接输出给用户', () => { it('错误展示使用中文说明,不把技术字段和调试对象直接输出给用户', () => {
const details = { issues: [{ message: 'Shot 主体引用缺失:@CH0001' }], debug: { executionId: 'internal-id', sql: 'SELECT secret' } } const details = { issues: [{ message: 'Shot 主体引用缺失:@CH0001' }], debug: { executionId: 'internal-id', sql: 'SELECT secret' } }
const error = new ApiError('后端 Storyboard 校验失败', 400, details) const error = new ApiError('后端 Storyboard 校验失败', 400, details)
@@ -28,3 +33,11 @@ describe('面向普通用户的系统提示', () => {
expect(operationErrorText(operation)).toBe('新的操作原因') expect(operationErrorText(operation)).toBe('新的操作原因')
}) })
}) })
it.each(['CANVAS_CHANGE_REQUIRES_REVALIDATION', 'CREATIVE_PROFILE_ACTIVE_WORKFLOW', 'GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION'])('配置冲突 %s 从真实 details.code 或顶层 code 转成中文原因', code => {
for (const cause of [new ApiError('请求失败(409)', 409, { code }), new ApiError('服务器内部错误', 409, undefined, code)]) {
expect(errorMessage(cause)).not.toMatch(/请求失败|服务器内部错误|REQUIRES|WORKFLOW/)
expect(errorMessage(cause)).toMatch(/画幅|任务|模型/)
expect(cause.status).toBe(409)
}
})