diff --git a/docs/api-contract-sync.md b/docs/api-contract-sync.md
index 7615aa5..94603bb 100644
--- a/docs/api-contract-sync.md
+++ b/docs/api-contract-sync.md
@@ -1,5 +1,24 @@
# 接口数据同步说明
+## 2026-10-28 剧本审核人工确认、延期验证与改写预检
+
+按同级后端 `dev@b26aa94e` 的正式审核路由、人工确认事务、质量问题 Schema 和改写预检接入,前端仅修改根目录 `dev`。
+
+- “审核记录”按需读取 `GET /projects/:id/reviews/latest`、`reviews/confirm-issues/preview` 与现有 `resume-rewrite/preview`。最新审核和预检必须属于同项目、同审核编号;预检失败保留只读审核,异常结构、来源过期、活动任务及剩余列表缺失均不开放确认。只读查询可关闭、取消,切项目或卸载后的旧响应不回填。
+- 待审核项目首次进入直接定位“审核记录”;失败项目保留当前未通过审核时也定位此处。仅引导阅读,不自动弹出写入确认或启动改写;用户切换内容后,刷新不抢回标签。当前有效改写预检存在剧集、角色或世界观改写范围时提示先检查改写,否则引导人工核对。推荐延期仅在对应单选旁标注“建议”,仍默认保留待处理,不能把人工核对自动转换为接受。
+- 两种处理入口独立按实际内容显示:剩余待确认问题或不确定项为空时隐藏“人工确认”;真实改写预检的剧集、角色、世界观均不需改写时隐藏“改写预检”。两种操作并存时都保留;审核通过或预检缺失时不保留空入口。“刷新审核”始终保留。不能只按 confirmedRewriteEpisodes 判断改写是否存在;角色或世界观单独改写也必须正常显示。改写读取沿用公共校验方法,保存记录与当前审核预检不一致时隐藏旧范围并提示刷新。
+- 当前有效预检只强调一个主按钮:改写已就绪时突出“改写预检”,否则待人工处理时突出“人工确认”;刷新、读取失败、来源失效、活动任务及审核通过时均不强调处理入口。配色和入口显示不代替服务端操作权限或确认流程。
+- “人工确认”复用全屏 `AppDrawer`,按集分组核对错误、警告及不确定项,并提供当前正式正文和人工补充证据。人工补充仅提交已明确核对的 Error、逐字原文、真实集号及说明;首次打开和增加空行不立即报错。处理建议展示推荐原因、全部候选剧集及置信度;默认全部保留待处理,用户明确选择后才展开延期字段。低置信度或要求人工选集时集号留空,候选优先但可选择其它正式剧集;阶段和预填验证标准可编辑,延期不等于后续核验通过。
+- 完整原文桌面默认展开,手机按需展开;从问题点击原文入口会选择该集并定位核对区。窄屏操作保留完整名称并自然换行,长内容仅正文滚动,底栏保持可见。
+- POST `reviews/confirm-issues` 始终发送 `confirmed: true`、当前 `reviewId` 和 `issueIndexes` 数组;三种选择分别使用原始待确认列表或原始 uncertainty 数组索引,过滤、排序和多轮处理不重编号。提交前重新 GET 核对审核、保存记录、剩余项和正式正文;建议按当前剩余项生成,按完整原文映射回原始审核索引。接受与延期互斥,延期必须填写真实集号、拆解/分镜阶段与非空标准;请求使用 deferredUncertainties。来源变化后旧选择保留为只读草稿,禁止套用旧索引;同来源提交失败保留当前输入,409 只重读,不自动重试写入。
+- 确认成功后读取项目详情、当前保存记录、阶段状态和最新审核。尚未生成新 Review 时,已保存裁决优先读取本次预检绑定的保存记录;剩余问题仍可继续处理。只按服务端 `finalized` 表达本次审核是否完成,不按 `remainingBlockers` 推断通过,不自动调用改写模型。审核结果更新时清除旧人工回执;已完成审核仍能只读核对正式正文,旧任务的失败或待修订回执标为历史执行记录。
+- 审核页和创作任务弹窗共用改写范围确认入口。GET `/projects/:id/resume-rewrite/preview` 展示真实集数及角色/世界观范围;未就绪只读说明原因。明确确认费用后再次预检,保存记录或范围变化即撤销旧确认;只有同一有效范围才 POST `resume-rewrite`,请求体包含 `confirmed: true`。保留项目活动锁与真实任务句柄,网络不确定不自动重复提交。
+- 人工处理后可主动查看改写范围,先等待抽屉离场和焦点释放再打开预检。普通读取不锁定关闭,实际写入期间防止重复操作。运行、失败、完成和未知状态分别展示,不把历史通过或执行结束当作当前制作许可。
+
+接口及页面测试隔离模型与数据库写入。Chrome 使用 `localhost` 验证,确认及改写启动的浏览器验收使用 `/tmp` 内存样例服务,不对正式审核发送裁决,不触发真实付费改写。未修改后端;Git 交付按用户明确要求提交并推送至 `dev`。
+
+验证:82 个测试文件、626 项测试通过;静态检查、格式检查、类型检查及生产构建通过。复用本地 Chrome,桌面只读核对 `cmvrk799a0000k6nd3udc1wow` 的三项真实建议及原文,均保持待处理;隔离样例验证部分延期保存、原始索引请求、提交后重新读取审核与项目阶段、未选剧集阻止提交,以及 390×600 视口的长内容滚动与固定底栏。另验证首次刷新自动进入审核记录、切换世界观后只读刷新仍保留当前标签、手机端引导与入口换行,以及建议标签不默认接受任何问题。入口显隐覆盖仅人工确认、仅改写、两者并存、无可处理事项、审核通过及预检读取失败;额外验证世界观单独改写无集号仍保留入口,保存记录不一致时隐藏旧范围。旧 Review、活动任务、失败保留草稿及改写二次预检由自动化回归覆盖。开发验收日志出现两次 ResizeObserver 布局提示,来源尚未定位,可见交互正常;未为此修改无关公共布局。验收后恢复真实项目审核记录并停止隔离服务。
+
## 2026-10-28 Story Plan 创作流程适配
核对同级后端 `dev@c6ad973c` 的项目创建路由、创作 Graph、节点保存中间件、恢复服务和任务订阅;只修改前端根目录 `dev`。
diff --git a/src/features/create-drama/CreateDramaPage.vue b/src/features/create-drama/CreateDramaPage.vue
index 555cd4a..e00fd9c 100644
--- a/src/features/create-drama/CreateDramaPage.vue
+++ b/src/features/create-drama/CreateDramaPage.vue
@@ -17,6 +17,8 @@ import EpisodeReader from './EpisodeReader.vue'
import { executionStageLabel, useWorkflowExecution } from '../workflows/execution'
import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
import { dramaStages } from './progress'
+import DramaReviewPanel from './review/DramaReviewPanel.vue'
+import DramaRewriteAction from './review/DramaRewriteAction.vue'
/** 剧本创作工作区,正式数据库内容为准,checkpoint 只补充计划与恢复信息。 */
const { project, checkpoints, refresh, refreshStageReadiness, error } = useProjectContext()
@@ -40,6 +42,22 @@ const targetMinutes = computed(() =>
)
/** 当前任务与操作的项目归属。 */
const projectId = computed(() => project.value?.id ?? '')
+/** 仅记住本次进入已定位的项目,后续刷新不抢走用户正在阅读的标签。 */
+const initialTabProject = ref('')
+/** 首次进入按正式项目和当前审核记录定位;这里只引导阅读,不决定审核或改写权限。 */
+watch(
+ [projectId, () => project.value?.status, () => state.value?.reviewPassed],
+ () => {
+ const current = project.value
+ if (!current || initialTabProject.value === current.id) return
+ initialTabProject.value = current.id
+ const needsReview =
+ current.status === 'need_review' ||
+ (current.status === 'failed' && state.value?.reviewPassed === false && !!state.value.review)
+ tab.value = needsReview ? 'review' : 'episodes'
+ },
+ { immediate: true }
+)
/** 复用项目级操作互斥。 */
const operation = computed(() => getOperation(projectId.value))
/** 项目布局发现任务,页面共享同一持久化记录。 */
@@ -75,6 +93,16 @@ watch(
)
/** 正式项目完成状态独立于任务结束与审核执行状态。 */
const complete = computed(() => project.value?.status === 'completed')
+/** 人工处理已完成项目时,旧失败或待修订任务不能覆盖当前正式结果。 */
+const historicalTask = computed(() => {
+ const record = backgroundExecution.query.data.value
+ return (
+ complete.value &&
+ !!record &&
+ ['completed', 'failed'].includes(record.status) &&
+ record.result?.projectStatus !== 'completed'
+ )
+})
/** 当前记录是否包含服务端保存的规划,不在页面验证或重建规划。 */
const hasStoryPlan = computed(() => !!state.value?.storyPlan)
/** 恢复生成只接受连续的正式剧集前缀,允许进入尚未完成的派生设定阶段。 */
@@ -90,15 +118,6 @@ const hasEpisodePrefix = computed(
const hasReview = computed(() => typeof state.value?.reviewPassed === 'boolean')
/** 生成恢复不再以 Character 或 World 为前置条件,最终仍由服务端复核。 */
const canGenerate = computed(() => !complete.value && hasStoryPlan.value && hasEpisodePrefix.value && !hasReview.value)
-/** 只有当前保存记录明确审核未通过,才能恢复改写。 */
-const canRewrite = computed(
- () =>
- !complete.value &&
- !!state.value?.review &&
- state.value.reviewPassed === false &&
- hasEpisodePrefix.value &&
- episodes.value.length === total.value
-)
/** 任务发现或状态读取异常时,先核对真实状态,禁止重复恢复。 */
const recoveryBlocked = computed(
() =>
@@ -113,28 +132,14 @@ const recoveryBlocked = computed(
const stages = computed(() =>
dramaStages(project.value, dramaRecords.value.at(-1), backgroundExecution.query.data.value)
)
-/** 恢复中不展示旧审核结论,等当前保存记录确认结果。 */
-const reviewPassed = computed(() =>
- stages.value.find(stage => stage.node === 'reviewDrama')?.status === 'completed'
- ? state.value?.reviewPassed
- : undefined
-)
-/**
- * 确认后提交恢复请求,并继续观察真实任务。
- * @param action 后端支持的生成或改写恢复动作
- */
-async function resume(action: 'resume-generation' | 'resume-rewrite') {
- if (
- !project.value ||
- recoveryBlocked.value ||
- !(action === 'resume-generation' ? canGenerate.value : canRewrite.value)
- )
- return
+/** 用户明确确认后恢复未完成的生成,改写单独执行范围预检。 */
+async function resumeGeneration() {
+ if (!project.value || recoveryBlocked.value || !canGenerate.value) return
const id = project.value.id
- await runOperation(id, action === 'resume-generation' ? '恢复剧集生成' : '恢复剧本改写', async () => {
- const started = await projectsApi.resume(id, action)
- await backgroundExecution.track(started.executionId)
+ await runOperation(id, '恢复剧集生成', async () => {
+ const started = await projectsApi.resume(id, 'resume-generation')
+ await backgroundExecution.track(started.executionId, id)
return started
})
await refresh()
@@ -309,33 +314,14 @@ function exportScript() {
+
-
- {{ reviewPassed ? '最近工作流审核通过' : '最近工作流审核未通过' }}
-
-
查看改写建议原文
-
- {{
- JSON.stringify(state.rewriteSuggestion, null, 2)
- }}
-
-
+
-
-
+
+ 当前结果已更新;下方保留的是最近一次任务的执行记录。
@@ -407,14 +397,13 @@ function exportScript() {
description="从已保存的故事规划继续编写剧集,再生成角色设定、世界观并审核。已有完整剧集时会核对来源并继续未完成的设定。可能产生模型调用费用。"
acknowledgement
:disabled="!canGenerate || recoveryBlocked"
- @confirm="resume('resume-generation')"
- />
+
diff --git a/src/features/create-drama/review/DramaReviewPanel.vue b/src/features/create-drama/review/DramaReviewPanel.vue
new file mode 100644
index 0000000..d556aa9
--- /dev/null
+++ b/src/features/create-drama/review/DramaReviewPanel.vue
@@ -0,0 +1,850 @@
+
+
+
+
+
+
+
+
+
+ 人工确认
+
+
+
+
+
{{
+ flow.query.error.value
+ }}
+
{{
+ rewriteQuery.error.value
+ }}
+
正在读取最新审核…
+
+
+
+ {{
+ reviewUncertain ? '审核状态待核对' : latest.passed ? '当前审核已通过' : '当前审核尚未通过'
+ }}
+
+
+ {{ nextStep.description }}
+ {{ flow.blockedReason.value }}
+ {{ receiptSummary }}
+
+
+
+
- 待确认问题
+ -
+ {{ preview.remainingPendingQualityIssues?.length ?? '待核对'
+ }} 项
+
+
+
+
- 待核对说明
+ -
+ {{ preview.remainingUncertainty?.length ?? '待核对'
+ }} 项
+
+
+
+
- 待改写剧集
+ - {{ rewriteEpisodeSummary }}
+
+
+
+
+
+
+ 第 {{ issue.episode }} 集 · {{ categoryLabel(issue) }}
+ {{ issue.message }}
+ {{ issue.sourceQuote }}
+ 修改方向:{{ issue.suggestion }}
+
+
+
+
+ {{ userFacingText(latest.message) }}
+
+
+ -
+ {{
+ decision.disposition === 'accepted'
+ ? '已接受'
+ : decision.disposition === 'verified'
+ ? '已核验'
+ : '留待后续核验'
+ }}
+ · {{ decision.description }}
+
+ 第 {{ decision.episode }} 集 ·
+ {{ decision.verificationTarget === 'breakdown' ? '拆解' : '分镜' }}阶段 · 核验标准:{{ decision.verificationCriteria }}
+
+
+
+
+ - 审核编号
+ - {{ latest.id }}
+ - 保存记录
+ - {{ preview.checkpointId }}
+
+
+
+
+
+
+
+
+
{{
+ flow.blockedReason.value
+ }}
+
{{
+ flow.actionError.value
+ }}
+
+
+
+
+
以下选择属于旧审核,仅供重新核对,尚未保存为当前判断。
+
+ 原选择接受:{{ flow.preservedDraft.value.descriptions[index] }}
+
+
+
原选择延期:{{ flow.preservedDraft.value.descriptions[draft.index] }}
+
+ 第 {{ draft.episode ?? '未选' }} 集 ·
+ {{
+ draft.verificationTarget === 'breakdown'
+ ? '拆解'
+ : draft.verificationTarget === 'storyboard'
+ ? '分镜'
+ : '未选阶段'
+ }}
+ · {{ draft.verificationCriteria }}
+
+
+
+
{{ draft.message }}
+
{{ draft.sourceQuote }}
+
{{ draft.suggestion }}
+
+
+ 原错误与警告选择已撤销,请对照当前问题重新选择。
+
+
+
+
+
{{ receiptSummary }}
+
+
+
+
+
+
+
+
+
+
+
+
+
{{ categoryLabel(row.issue) }}
+ {{
+ row.issue.policyException
+ ? '策略允许'
+ : row.issue.severity === 'error'
+ ? '错误待核对'
+ : '警告待核对'
+ }}
+
+ {{ row.issue.message }}
+
+ {{ row.issue.sourceQuote }}
+
+
+ 修改方向:{{ row.issue.suggestion }}
+
+
+ 已核实错误,记录为改写依据
+ 已核对原文,接受保留此警告
+
+ {{
+ row.issue.policyException
+ ? '该项属于已允许的表现方式,不能强制确认改写。'
+ : '当前证据尚不能直接确认,可补充经核对的真实原文。'
+ }}
+
+
+
+
+
+
+ {{
+ latest?.passed
+ ? '当前审核已通过,无需再次确认问题。'
+ : '当前没有待人工确认的结构化问题。已有审核问题仍需以改写预检为准。'
+ }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 引用必须逐字出现在所选剧集中,不能用事件编号代替。
+
+
+
+ {{
+ sourceContent ||
+ (sourceEpisodes.length
+ ? '请选择需要核对的剧集。'
+ : '当前没有可核对的正式正文。')
+ }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/features/create-drama/review/DramaRewriteAction.vue b/src/features/create-drama/review/DramaRewriteAction.vue
new file mode 100644
index 0000000..0eb6d08
--- /dev/null
+++ b/src/features/create-drama/review/DramaRewriteAction.vue
@@ -0,0 +1,221 @@
+
+
+
+
+
+
+ {{ label }}
+
+
+
+
正在检查改写范围…
+
{{
+ blockedReason
+ }}
+
+
+
只读检查不会产生生成费用。确认后将改写上述内容并重新审核,请勿重复提交。
+
我已核对本次范围,确认当前没有同项目任务运行,并同意本次模型调用费用。
+
{{
+ actionError
+ }}
+
+
+
+
+
+
+
+
+
+
diff --git a/src/features/create-drama/review/ManualReviewIssueEditor.vue b/src/features/create-drama/review/ManualReviewIssueEditor.vue
new file mode 100644
index 0000000..e4edfdd
--- /dev/null
+++ b/src/features/create-drama/review/ManualReviewIssueEditor.vue
@@ -0,0 +1,115 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ error }}
+
+
+
+
diff --git a/src/features/create-drama/review/ReviewUncertaintyCard.vue b/src/features/create-drama/review/ReviewUncertaintyCard.vue
new file mode 100644
index 0000000..1a945af
--- /dev/null
+++ b/src/features/create-drama/review/ReviewUncertaintyCard.vue
@@ -0,0 +1,186 @@
+
+
+
+
+
+
+
+
问题 {{ row.originalIndex + 1 }}
+ {{
+ suggestion
+ ? suggestion.suggestedAction === 'defer'
+ ? '建议延期验证'
+ : '建议人工核对'
+ : '尚无处理建议'
+ }}
+
+
{{ row.text }}
+
推荐原因:{{ suggestion.reason }}
+
+
涉及剧集:{{ candidateLabel }}
+
建议依据:{{ confidenceLabel }}
+
+ 验证阶段:{{ suggestion.verificationTarget === 'breakdown' ? '拆解' : '分镜' }}
+
+
验证标准:{{ suggestion.verificationCriteria }}
+
+
+
+
+
+
+
+ 保留待处理
+ 接受为合理创作安排
+ 延期验证(建议)
+
+
+
+ 此项需要补充真实原文证据,不能直接接受或延期。
+
+
+
+
+
+ 请明确选择负责验证的剧集;建议候选之外的正式剧集也可选择。
+
+
+
+
+
+
+
+
+
+
+ {{ error }}
+
+
+
diff --git a/src/features/create-drama/review/api.ts b/src/features/create-drama/review/api.ts
new file mode 100644
index 0000000..5b28bb4
--- /dev/null
+++ b/src/features/create-drama/review/api.ts
@@ -0,0 +1,200 @@
+import { errorMessage, optionalResource, request } from '../../../lib/http'
+import type {
+ ConfirmDramaIssuesInput,
+ ConfirmDramaIssuesResult,
+ DramaReviewPreview,
+ DramaReviewSnapshot,
+ DramaRewritePreview,
+ LatestDramaReview
+} from './types'
+
+/**
+ * 校验需要展示和定位的最小问题结构,不在页面重新判断业务质量。
+ * @param value 接口原始问题列表
+ * @returns 是否具备完整可展示字段
+ */
+function validIssues(value: unknown): boolean {
+ return (
+ Array.isArray(value) &&
+ value.every(
+ item =>
+ item &&
+ typeof item === 'object' &&
+ Number.isSafeInteger(item.episode) &&
+ item.episode > 0 &&
+ ['warning', 'error'].includes(item.severity) &&
+ ['category', 'code', 'sourceQuote', 'message', 'suggestion'].every(
+ key => typeof item[key] === 'string'
+ ) &&
+ (item.subjectRef === undefined || typeof item.subjectRef === 'string') &&
+ (item.policyException === undefined || typeof item.policyException === 'boolean') &&
+ (item.evidenceConfidence === undefined ||
+ ['explicit', 'inferred', 'unknown'].includes(item.evidenceConfidence))
+ )
+ )
+}
+
+/**
+ * 历史回执或格式异常只能只读提示,不伪造成空问题列表并开放提交。
+ * @param preview 原始确认预检
+ * @returns 是否具备完整的来源与正文结构
+ */
+function validPreview(preview: DramaReviewPreview): boolean {
+ return (
+ preview.readOnly === true &&
+ !!preview.checkpointId &&
+ [preview.ready, preview.sourceValid, preview.reviewSourceValid, preview.hasActiveExecution].every(
+ value => typeof value === 'boolean'
+ ) &&
+ validIssues(preview.pendingQualityIssues) &&
+ validTextList(preview.uncertainty) &&
+ (preview.remainingPendingQualityIssues === undefined || validIssues(preview.remainingPendingQualityIssues)) &&
+ (preview.remainingUncertainty === undefined || validTextList(preview.remainingUncertainty)) &&
+ (preview.resolutionSuggestions === undefined || validSuggestions(preview.resolutionSuggestions)) &&
+ Array.isArray(preview.episodes) &&
+ preview.episodes.every(
+ item => item && Number.isSafeInteger(item.episode) && item.episode > 0 && typeof item.content === 'string'
+ )
+ )
+}
+
+/**
+ * 校验原始不确定项列表。
+ * @param value 原始字段
+ * @returns 是否为完整的文字数组
+ */
+function validTextList(value: unknown): boolean {
+ return Array.isArray(value) && value.every(item => typeof item === 'string')
+}
+
+/**
+ * 校验建议的展示字段,不据建议置信度推导审核是否通过。
+ * @param value 原始建议列表
+ * @returns 是否具备完整的建议结构
+ */
+function validSuggestions(value: unknown): boolean {
+ return (
+ Array.isArray(value) &&
+ value.every(
+ item =>
+ item &&
+ typeof item === 'object' &&
+ Number.isSafeInteger(item.index) &&
+ item.index >= 0 &&
+ typeof item.description === 'string' &&
+ ['defer', 'manual_review'].includes(item.suggestedAction) &&
+ typeof item.requiresEpisodeSelection === 'boolean' &&
+ typeof item.requiresManualConfirmation === 'boolean' &&
+ (item.episode === null || (Number.isSafeInteger(item.episode) && item.episode > 0)) &&
+ Array.isArray(item.episodeCandidates) &&
+ item.episodeCandidates.every(
+ (episode: unknown) => typeof episode === 'number' && Number.isSafeInteger(episode) && episode > 0
+ ) &&
+ ['high', 'low', 'none'].includes(item.confidence) &&
+ [null, 'breakdown', 'storyboard'].includes(item.verificationTarget) &&
+ (item.verificationCriteria === null || typeof item.verificationCriteria === 'string') &&
+ typeof item.reason === 'string'
+ )
+ )
+}
+
+/** 真实剧本审核接口;只读预检和人工确认均不调用模型。 */
+export const dramaReviewApi = {
+ /**
+ * 读取最新正式审核,尚无审核时返回空值。
+ * @param id 正式项目编号
+ * @param signal 取消旧查询
+ * @returns 最新审核或空值
+ */
+ latest: (id: string, signal?: AbortSignal) =>
+ optionalResource(request(`/projects/${encodeURIComponent(id)}/reviews/latest`, { signal })),
+ /**
+ * 读取人工确认来源、稳定索引、当前剩余项与正式正文。
+ * @param id 正式项目编号
+ * @param signal 取消旧查询
+ * @returns 只读确认预检
+ */
+ preview: (id: string, signal?: AbortSignal) =>
+ request(`/projects/${encodeURIComponent(id)}/reviews/confirm-issues/preview`, { signal }),
+ /**
+ * 保存明确确认的人工裁决,不能以请求成功代替审核通过。
+ * @param id 正式项目编号
+ * @param input 用户核对的裁决
+ * @returns 本次裁决回执
+ */
+ confirm: (id: string, input: ConfirmDramaIssuesInput) =>
+ request(`/projects/${encodeURIComponent(id)}/reviews/confirm-issues`, {
+ method: 'POST',
+ body: input
+ }),
+ /**
+ * 只读查询当前改写范围,不创建任务。
+ * @param id 正式项目编号
+ * @param signal 取消旧查询
+ * @returns 真实改写预检
+ */
+ rewritePreview: (id: string, signal?: AbortSignal) =>
+ request(`/projects/${encodeURIComponent(id)}/resume-rewrite/preview`, { signal })
+}
+
+/**
+ * 读取并校验真实改写预检,角色、世界观和剧集范围均由服务端提供。
+ * @param id 正式项目编号
+ * @param signal 取消旧读取
+ * @returns 已核对归属与结构的改写预检
+ */
+export async function loadDramaRewritePreview(id: string, signal?: AbortSignal): Promise {
+ const preview = await dramaReviewApi.rewritePreview(id, signal)
+ if (
+ preview.projectId !== id ||
+ !preview.checkpointId ||
+ preview.readOnly !== true ||
+ preview.requiresConfirmation !== true ||
+ typeof preview.ready !== 'boolean' ||
+ !['stale', 'blocked', 'needs_review', 'ready'].includes(preview.status) ||
+ !Array.isArray(preview.episodeNumbers) ||
+ !preview.episodeNumbers.every(number => Number.isSafeInteger(number) && number > 0) ||
+ ![preview.rewriteCharacters, preview.rewriteWorld, preview.rewriteEpisodes].every(
+ value => typeof value === 'boolean'
+ )
+ )
+ throw new Error('改写预检返回的数据不完整或不属于当前项目,请重新读取。')
+ return preview
+}
+
+/**
+ * 最新审核与处理预检分别核对身份,预检失败仍保留正式审核供只读查看。
+ * @param id 正式项目编号
+ * @param signal 取消旧查询
+ * @returns 当前审核及其对应预检
+ */
+export async function loadDramaReview(id: string, signal?: AbortSignal): Promise {
+ if (!id) return { latest: null, preview: null }
+ const latest = await dramaReviewApi.latest(id, signal)
+ if (!latest) return { latest: null, preview: null }
+ if (latest.projectId !== id || !latest.id || typeof latest.passed !== 'boolean')
+ throw new Error('审核记录与当前项目不一致,请重新读取。')
+ if (
+ !validIssues(latest.pendingQualityIssues) ||
+ !Array.isArray(latest.affectedEpisodes) ||
+ !validTextList(latest.hitWords) ||
+ !Array.isArray(latest.manualUncertaintyDecisions) ||
+ latest.manualUncertaintyDecisions.some(item => !item || typeof item.description !== 'string') ||
+ (latest.qualityReview !== null &&
+ (!latest.qualityReview ||
+ !validIssues(latest.qualityReview.issues) ||
+ !validTextList(latest.qualityReview.uncertainty)))
+ )
+ throw new Error('正式审核数据不完整,请重新读取后核对。')
+ if (latest.passed) return { latest, preview: null }
+ try {
+ const preview = await dramaReviewApi.preview(id, signal)
+ if (preview.projectId !== id || preview.reviewId !== latest.id)
+ throw new Error('审核版本已变化,请重新读取后核对。')
+ if (!validPreview(preview)) throw new Error('审核预检的数据不完整,请重新读取后核对。')
+ return { latest, preview }
+ } catch (cause) {
+ if (signal?.aborted) throw cause
+ return { latest, preview: null, previewError: errorMessage(cause) }
+ }
+}
diff --git a/src/features/create-drama/review/model.ts b/src/features/create-drama/review/model.ts
new file mode 100644
index 0000000..a386d09
--- /dev/null
+++ b/src/features/create-drama/review/model.ts
@@ -0,0 +1,248 @@
+import type {
+ DramaReviewIssue,
+ DramaReviewPreview,
+ DramaReviewSnapshot,
+ DramaRewritePreview,
+ ManualReviewDraft,
+ DeferredUncertaintyDraft,
+ ReviewResolutionSuggestion,
+ ManualReviewDecision
+} from './types'
+
+/**
+ * 读取当前预检绑定保存记录中的裁决,兼容人工处理尚未生成新 Review 的情况。
+ * @param review 保存记录中的原始审核字段
+ * @param reviewId 本次预检对应的正式审核编号
+ * @returns 结构完整且属于本次审核的裁决,字段缺失时回退正式审核记录
+ */
+export function savedReviewDecisions(review: unknown, reviewId: string): ManualReviewDecision[] | null {
+ if (!review || typeof review !== 'object' || !('manualUncertaintyDecisions' in review)) return null
+ const decisions = review.manualUncertaintyDecisions
+ if (!Array.isArray(decisions)) return null
+ return decisions.filter(
+ (item): item is ManualReviewDecision =>
+ !!item &&
+ typeof item === 'object' &&
+ item.reviewId === reviewId &&
+ Number.isSafeInteger(item.originalIndex) &&
+ typeof item.description === 'string' &&
+ ['accepted', 'deferred', 'verified'].includes(item.disposition) &&
+ (item.episode === undefined || (Number.isSafeInteger(item.episode) && item.episode > 0)) &&
+ (item.verificationTarget === undefined || ['breakdown', 'storyboard'].includes(item.verificationTarget)) &&
+ (item.verificationCriteria === undefined || typeof item.verificationCriteria === 'string')
+ )
+}
+
+/** 原始审核中的问题位置,不能用排序后的页面位置替代。 */
+export interface IndexedReviewIssue {
+ /** 原始待确认数组索引。 */ originalIndex: number
+ /** 真实问题内容。 */ issue: DramaReviewIssue
+}
+
+/** 原始审核中的不确定项位置。 */
+export interface IndexedReviewUncertainty {
+ /** 原始不确定项数组索引。 */ originalIndex: number
+ /** 原始文字。 */ text: string
+}
+
+/** 质量维度只翻译展示名称,提交仍使用原始枚举。 */
+export const reviewCategoryOptions = [
+ { label: '动作衔接', value: 'action_continuity' },
+ { label: '手部占用', value: 'hand_occupancy' },
+ { label: '姿态', value: 'pose' },
+ { label: '视线', value: 'gaze' },
+ { label: '道具交互', value: 'prop_interaction' },
+ { label: '时长', value: 'duration' },
+ { label: '主体一致性', value: 'subject_consistency' },
+ { label: '空间衔接', value: 'spatial_continuity' }
+]
+
+/**
+ * 沿用服务端识别当前待处理问题的字段,不把同集不同问题合并。
+ * @param left 原始问题
+ * @param right 当前问题
+ * @returns 是否为同一原始条目
+ */
+function sameIssue(left: DramaReviewIssue, right: DramaReviewIssue) {
+ return left.episode === right.episode && left.code === right.code && left.sourceQuote === right.sourceQuote
+}
+
+/**
+ * 展示当前剩余问题,始终保留原数组索引。
+ * @param preview 当前预检
+ * @returns 可按剧集展示的原始条目
+ */
+export function indexedPendingIssues(preview: DramaReviewPreview | null): IndexedReviewIssue[] {
+ if (!preview) return []
+ return preview.pendingQualityIssues
+ .map((issue, originalIndex) => ({ issue, originalIndex }))
+ .filter(
+ row =>
+ !preview.remainingPendingQualityIssues ||
+ preview.remainingPendingQualityIssues.some(issue => sameIssue(row.issue, issue))
+ )
+ .toSorted((left, right) => left.issue.episode - right.issue.episode || left.originalIndex - right.originalIndex)
+}
+
+/**
+ * 原始索引独立于页面过滤,并与后端的文字匹配规则保持一致。
+ * @param preview 当前预检
+ * @returns 尚未裁决的不确定项
+ */
+export function indexedUncertainties(preview: DramaReviewPreview | null): IndexedReviewUncertainty[] {
+ if (!preview) return []
+ return preview.uncertainty
+ .map((text, originalIndex) => ({ text, originalIndex }))
+ .filter(row => !preview.remainingUncertainty || preview.remainingUncertainty.includes(row.text))
+}
+
+/**
+ * 只比较用户已核对的服务端来源,任何变更都要求重新选择。
+ * @param previous 用户已核对的版本
+ * @param current 提交前重新读取的版本
+ * @returns 审核、保存记录与正文是否完全相同
+ */
+export function sameReviewSource(previous: DramaReviewPreview, current: DramaReviewPreview): boolean {
+ return (
+ previous.projectId === current.projectId &&
+ previous.reviewId === current.reviewId &&
+ previous.checkpointId === current.checkpointId &&
+ JSON.stringify(previous.episodes) === JSON.stringify(current.episodes) &&
+ JSON.stringify(previous.pendingQualityIssues) === JSON.stringify(current.pendingQualityIssues) &&
+ JSON.stringify(previous.uncertainty) === JSON.stringify(current.uncertainty) &&
+ JSON.stringify(previous.remainingPendingQualityIssues) ===
+ JSON.stringify(current.remainingPendingQualityIssues) &&
+ JSON.stringify(previous.remainingUncertainty) === JSON.stringify(current.remainingUncertainty) &&
+ JSON.stringify(previous.resolutionSuggestions) === JSON.stringify(current.resolutionSuggestions)
+ )
+}
+
+/**
+ * 改写范围或来源变化后撤销旧费用确认。
+ * @param previous 已展示的改写预检
+ * @param current 提交前的新预检
+ * @returns 是否仍是用户核对的同一范围
+ */
+export function sameRewriteScope(previous: DramaRewritePreview, current: DramaRewritePreview): boolean {
+ return (
+ previous.projectId === current.projectId &&
+ previous.checkpointId === current.checkpointId &&
+ previous.rewriteCharacters === current.rewriteCharacters &&
+ previous.rewriteWorld === current.rewriteWorld &&
+ previous.rewriteEpisodes === current.rewriteEpisodes &&
+ JSON.stringify(previous.episodeNumbers.toSorted((a, b) => a - b)) ===
+ JSON.stringify(current.episodeNumbers.toSorted((a, b) => a - b))
+ )
+}
+
+/**
+ * 只有正式预检明确允许,且当前剩余数据完整时,才开放人工确认。
+ * @param snapshot 已读取的审核及预检
+ * @returns 不可提交的可读原因,空字符串表示可继续核对
+ */
+export function reviewBlockReason(snapshot: DramaReviewSnapshot | null): string {
+ if (!snapshot?.latest) return '当前尚无审核记录。'
+ if (snapshot.latest.passed) return '当前审核已通过,无需再次确认。'
+ if (snapshot.previewError) return snapshot.previewError
+ const preview = snapshot.preview
+ if (!preview) return '尚未取得问题处理预检,请重新读取。'
+ if (preview.hasActiveExecution) return '剧本任务仍在运行,请结束后再处理审核问题。'
+ if (!preview.sourceValid || !preview.reviewSourceValid || preview.reviewId !== snapshot.latest.id)
+ return '审核与当前剧本来源不一致,请刷新并核对保存记录。'
+ if (
+ !preview.ready ||
+ preview.readOnly !== true ||
+ !Array.isArray(preview.remainingPendingQualityIssues) ||
+ !Array.isArray(preview.remainingUncertainty)
+ )
+ return '当前预检尚不允许确认,请刷新后核对。'
+ return ''
+}
+
+/**
+ * 表单提交前检查必填项与逐字引用;最终事实仍由服务端核验。
+ * @param draft 人工补充的草稿
+ * @param episodes 当前预检返回的正式正文
+ * @returns 可读字段问题,空字符串表示表单完整
+ */
+export function manualIssueError(draft: ManualReviewDraft, episodes: DramaReviewPreview['episodes']): string {
+ const episode = episodes.find(item => item.episode === draft.episode)
+ if (!episode) return '请选择当前正式剧集。'
+ if (![draft.code, draft.sourceQuote, draft.message, draft.suggestion].every(value => value.trim()))
+ return '请填写问题名称、原文片段、问题说明和修改建议。'
+ if (!episode.content.includes(draft.sourceQuote.trim())) return '引用片段必须逐字出现在所选剧集原文中。'
+ if (draft.subjectRef.trim() && !episode.content.includes(draft.subjectRef.trim()))
+ return '所选角色必须出现在引用所属的剧集原文中。'
+ return ''
+}
+
+/**
+ * 无效模型结构或无法核实的证据不能通过接受不确定项绕过。
+ * @param text 原始不确定项
+ * @returns 是否允许请求人工接受
+ */
+export function uncertaintyAcceptable(text: string): boolean {
+ return !/引用原文或主体无法核实|模型返回不符合审核结构/.test(text)
+}
+
+/**
+ * 建议位置可能来自剩余项列表;按完整原文对应,提交仍使用原始审核索引。
+ * @param preview 当前预检
+ * @param originalIndex 原始不确定项索引
+ * @returns 唯一对应的建议,无法对应时为空
+ */
+export function suggestionForUncertainty(
+ preview: DramaReviewPreview | null,
+ originalIndex: number
+): ReviewResolutionSuggestion | null {
+ const text = preview?.uncertainty[originalIndex]
+ if (
+ !preview ||
+ typeof text !== 'string' ||
+ (preview.remainingUncertainty && !preview.remainingUncertainty.includes(text))
+ )
+ return null
+ const matches = preview.resolutionSuggestions?.filter(item => item.description === text) ?? []
+ return matches.length === 1 ? matches[0]! : null
+}
+
+/**
+ * 只有用户主动选择延期时创建草稿;低置信度或要求选集的建议不绑定默认集号。
+ * @param index 原始不确定项索引
+ * @param suggestion 当前原文对应的建议
+ * @param episodes 正式剧集列表
+ * @returns 尚未确认的延期表单
+ */
+export function newDeferredDraft(
+ index: number,
+ suggestion: ReviewResolutionSuggestion | null,
+ episodes: DramaReviewPreview['episodes']
+): DeferredUncertaintyDraft {
+ const episode =
+ suggestion?.confidence === 'high' &&
+ !suggestion.requiresEpisodeSelection &&
+ episodes.some(item => item.episode === suggestion.episode)
+ ? suggestion.episode
+ : null
+ return {
+ index,
+ episode,
+ verificationTarget: suggestion?.verificationTarget ?? null,
+ verificationCriteria: suggestion?.verificationCriteria ?? ''
+ }
+}
+
+/**
+ * 校验用户编辑后的延期要求,不限制为候选集,也不把建议当作已确认。
+ * @param draft 当前延期草稿
+ * @param episodes 当前正式剧集
+ * @returns 需要用户修正的字段问题
+ */
+export function deferredDraftError(draft: DeferredUncertaintyDraft, episodes: DramaReviewPreview['episodes']): string {
+ if (!Number.isSafeInteger(draft.episode) || !episodes.some(item => item.episode === draft.episode))
+ return '请明确选择负责核验的正式剧集。'
+ if (!['breakdown', 'storyboard'].includes(draft.verificationTarget ?? '')) return '请选择核验阶段。'
+ if (!draft.verificationCriteria.trim()) return '请填写核验标准。'
+ if (draft.verificationCriteria.trim().length > 2000) return '核验标准不能超过 2000 个字符。'
+ return ''
+}
diff --git a/src/features/create-drama/review/types.ts b/src/features/create-drama/review/types.ts
new file mode 100644
index 0000000..cc93318
--- /dev/null
+++ b/src/features/create-drama/review/types.ts
@@ -0,0 +1,186 @@
+/** 剧本审核使用的真实质量维度。 */
+export type DramaReviewCategory =
+ | 'hand_occupancy'
+ | 'pose'
+ | 'gaze'
+ | 'prop_interaction'
+ | 'action_continuity'
+ | 'duration'
+ | 'subject_consistency'
+ | 'spatial_continuity'
+
+/** 剧本审核问题,引用与事件标识保持服务端原值。 */
+export interface DramaReviewIssue {
+ /** 正式集号。 */ episode: number
+ /** 质量维度。 */ category: DramaReviewCategory
+ /** 原始问题代码。 */ code: string
+ /** 服务端严重程度。 */ severity: 'warning' | 'error'
+ /** 逐字原文引用。 */ sourceQuote: string
+ /** 问题说明。 */ message: string
+ /** 局部修改建议。 */ suggestion: string
+ /** 是否属于已允许的策略例外。 */ policyException?: boolean
+ /** 原文证据的确定程度。 */ evidenceConfidence?: 'explicit' | 'inferred' | 'unknown'
+ /** 正文明确出现的主体名称。 */ subjectRef?: string
+ /** 事件追踪标识,并非原文引用。 */ eventKey?: string
+}
+
+/** 已保存的人工不确定性裁决,延期记录仅供追溯。 */
+export interface ManualReviewDecision {
+ /** 原审核编号。 */ reviewId: string
+ /** 原始不确定项索引。 */ originalIndex: number
+ /** 原始问题说明。 */ description: string
+ /** 服务端记录的处理方式。 */ disposition: 'accepted' | 'deferred' | 'verified'
+ /** 涉及的正式集号。 */ episode?: number
+ /** 后续核验阶段。 */ verificationTarget?: 'breakdown' | 'storyboard'
+ /** 已保存的后续核验标准。 */ verificationCriteria?: string
+}
+
+/** 最新正式审核,不从保存记录的布尔值虚构明细。 */
+export interface LatestDramaReview {
+ /** 正式审核编号。 */ id: string
+ /** 所属项目。 */ projectId: string
+ /** 审核是否明确通过。 */ passed: boolean
+ /** 审核摘要。 */ message: string | null
+ /** 审核时间。 */ createdAt: string
+ /** 原始结构化质量审核。 */ qualityReview: {
+ /** 原审核结构化问题。 */ issues: DramaReviewIssue[]
+ /** 原审核不确定项,保留稳定索引。 */ uncertainty: string[]
+ } | null
+ /** 原始待人工确认的问题。 */ pendingQualityIssues: DramaReviewIssue[]
+ /** 已保存的人工裁决。 */ manualUncertaintyDecisions: ManualReviewDecision[]
+ /** 已有改写目标集数。 */ affectedEpisodes: number[]
+ /** 敏感词审核结果。 */ hitWords: string[]
+}
+
+/** 人工确认前的真实只读预检,兼容来源过期时的精简回执。 */
+export interface DramaReviewPreview {
+ /** 所属项目。 */ projectId: string
+ /** 当前最新正式审核。 */ reviewId: string
+ /** 当前创作保存记录。 */ checkpointId: string
+ /** 只读操作。 */ readOnly: true
+ /** 服务端是否允许处理。 */ ready: boolean
+ /** 保存记录与正式正文一致。 */ sourceValid: boolean
+ /** 最新审核与正式正文一致。 */ reviewSourceValid: boolean
+ /** 是否存在活动创作任务。 */ hasActiveExecution: boolean
+ /** 原始待确认问题,索引来源。 */ pendingQualityIssues: DramaReviewIssue[]
+ /** 原始不确定项,索引来源。 */ uncertainty: string[]
+ /** 当前仍待处理的问题;缺失时仅展示原列表,不开放提交。 */ remainingPendingQualityIssues?: DramaReviewIssue[]
+ /** 当前仍待处理的不确定项。 */ remainingUncertainty?: string[]
+ /** 当前剩余项的只读处理建议,不等同于已确认的决定。 */ resolutionSuggestions?: ReviewResolutionSuggestion[]
+ /** 当前保存的改写目标集数。 */ confirmedRewriteEpisodes?: number[]
+ /** 供逐字核对的正式正文。 */ episodes: Array<{
+ /** 正式集号。 */ episode: number
+ /** 完整正文。 */ content: string
+ }>
+ /** 服务端附加的来源状态。 */ status?: string
+ /** 来源失效原因。 */ reason?: string
+}
+
+/** 用户逐项核对后的人工确认请求,不包含任何模型生成参数。 */
+export interface ConfirmDramaIssuesInput {
+ /** 必须明确确认。 */ confirmed: true
+ /** 已核对的最新审核编号。 */ reviewId: string
+ /** 原始待确认列表中的错误索引,始终发送数组。 */ issueIndexes: number[]
+ /** 接受保留的警告原始索引。 */ acceptedWarningIndexes?: number[]
+ /** 接受保留的不确定项原始索引。 */ acceptedUncertaintyIndexes?: number[]
+ /** 用户补充、具有真实原文的错误证据。 */ manualIssues?: DramaReviewIssue[]
+ /** 用户明确选择并编辑的延期核验要求。 */ deferredUncertainties?: DeferredReviewUncertainty[]
+}
+
+/** 人工确认回执,只有 finalized 才代表服务端已完成审核收敛。 */
+export interface ConfirmDramaIssuesResult {
+ /** 所属项目。 */ projectId: string
+ /** 本次生成的保存记录。 */ checkpointId: string
+ /** 本次处理的原审核编号。 */ reviewId: string
+ /** 本次确认的改写集数。 */ confirmedEpisodes: number[]
+ /** 本次接受的不确定项。 */ acceptedUncertaintyIndexes: number[]
+ /** 本次接受的警告。 */ acceptedWarningIndexes: number[]
+ /** 诊断合计,不能作为审核通过依据。 */ remainingBlockers: number
+ /** 分类统计可能重叠,不相加作为独立问题数。 */ blockers: {
+ /** 待确认问题。 */ pendingIssues: number
+ /** 不确定项。 */ uncertainty: number
+ /** 确认错误。 */ confirmedErrors: number
+ /** 改写剧集。 */ affectedEpisodes: number
+ /** 安全问题。 */ contentSafety: number
+ }
+ /** 服务端是否已原子完成审核与项目状态。 */ finalized: boolean
+}
+
+/** 恢复改写前的只读范围预检。 */
+export interface DramaRewritePreview {
+ /** 所属项目。 */ projectId: string
+ /** 本次核对的保存记录。 */ checkpointId: string
+ /** 不启动任务。 */ readOnly: true
+ /** 服务端是否允许启动改写。 */ ready: boolean
+ /** 服务端原始预检状态。 */ status: 'stale' | 'blocked' | 'needs_review' | 'ready'
+ /** 本次改写的正式集号。 */ episodeNumbers: number[]
+ /** 是否改写角色设定。 */ rewriteCharacters: boolean
+ /** 是否改写世界观。 */ rewriteWorld: boolean
+ /** 是否改写剧集。 */ rewriteEpisodes: boolean
+ /** 必须由用户明确确认。 */ requiresConfirmation: true
+}
+
+/** 一次审核读取,正式审核与预检必须属于同一版本。 */
+export interface DramaReviewSnapshot {
+ /** 最新审核,没有审核时为空。 */ latest: LatestDramaReview | null
+ /** 待处理审核的只读预检。 */ preview: DramaReviewPreview | null
+ /** 预检单独失败时仍保留正式审核供只读查看。 */ previewError?: string
+}
+
+/** 待人工补充的表单草稿,不等同于已保存的审核事实。 */
+export interface ManualReviewDraft {
+ /** 当前表单行标识。 */ id: string
+ /** 从正式剧集选择的集号。 */ episode: number | null
+ /** 后端支持的质量维度。 */ category: DramaReviewCategory
+ /** 用户填写的问题名称,作为自由格式问题标识提交。 */ code: string
+ /** 用户核对的逐字原文。 */ sourceQuote: string
+ /** 用户核对的问题说明。 */ message: string
+ /** 用户提出的修改方向。 */ suggestion: string
+ /** 用户明确指定的角色,未指定时留空。 */ subjectRef: string
+}
+
+/** 后端根据当前审核原文提供的建议,只用于辅助人工判断。 */
+export interface ReviewResolutionSuggestion {
+ /** 当前建议列表中的位置,提交仍对应原始审核索引。 */ index: number
+ /** 对应不确定项的原始描述。 */ description: string
+ /** 推荐处理方式,不能据此自动提交。 */ suggestedAction: 'defer' | 'manual_review'
+ /** 是否必须由用户明确选择负责核验的剧集。 */ requiresEpisodeSelection: boolean
+ /** 建议是否要求人工确认。 */ requiresManualConfirmation: boolean
+ /** 推荐的唯一集号,没有明确归属时为空。 */ episode: number | null
+ /** 推荐候选集号,不限制选择其它正式剧集。 */ episodeCandidates: number[]
+ /** 建议置信度,低置信度不能自动绑定集号。 */ confidence: 'high' | 'low' | 'none'
+ /** 建议的后续核验阶段。 */ verificationTarget: 'breakdown' | 'storyboard' | null
+ /** 建议的核验标准,用户可编辑。 */ verificationCriteria: string | null
+ /** 推荐原因。 */ reason: string
+}
+
+/** 尚未提交的延期核验表单,允许保留未填写字段。 */
+export interface DeferredUncertaintyDraft {
+ /** 原始审核中的不确定项索引。 */ index: number
+ /** 由用户核对的正式集号。 */ episode: number | null
+ /** 用户核对的验证阶段。 */ verificationTarget: 'breakdown' | 'storyboard' | null
+ /** 用户核对或编辑后的核验标准。 */ verificationCriteria: string
+}
+
+/** 人工明确确认后提交的延期核验请求。 */
+export interface DeferredReviewUncertainty {
+ /** 原始审核索引。 */ index: number
+ /** 正式存在的集号。 */ episode: number
+ /** 真实支持的核验阶段。 */ verificationTarget: 'breakdown' | 'storyboard'
+ /** 非空且不超过后端限制的核验标准。 */ verificationCriteria: string
+}
+
+/** 未提交的人工选择,保留并不代表已接受问题。 */
+export type UncertaintyDisposition = 'pending' | 'accept' | 'defer'
+
+/** 来源变化后保留的只读草稿,不能直接提交到新版本。 */
+export interface ReviewDraftBackup {
+ /** 草稿对应的正式审核。 */ reviewId: string
+ /** 草稿对应的保存记录。 */ checkpointId: string
+ /** 原始错误索引。 */ issueIndexes: number[]
+ /** 原始警告索引。 */ acceptedWarningIndexes: number[]
+ /** 原始不确定项索引。 */ acceptedUncertaintyIndexes: number[]
+ /** 当时的问题描述,方便重新核对。 */ descriptions: string[]
+ /** 用户填写的延期核验草稿。 */ deferredUncertainties: DeferredUncertaintyDraft[]
+ /** 用户填写的人工原文证据。 */ manualIssues: ManualReviewDraft[]
+}
diff --git a/src/features/create-drama/review/useDramaReview.ts b/src/features/create-drama/review/useDramaReview.ts
new file mode 100644
index 0000000..2ebe9db
--- /dev/null
+++ b/src/features/create-drama/review/useDramaReview.ts
@@ -0,0 +1,447 @@
+import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
+import { useQuery } from '../../../composables/useQuery'
+import { ApiError, errorMessage } from '../../../lib/http'
+import { useActionMessage } from '../../../components/ui/useActionMessage'
+import { getOperation, runOperation } from '../../workflows/operations'
+import { dramaReviewApi, loadDramaReview } from './api'
+import {
+ deferredDraftError,
+ newDeferredDraft,
+ suggestionForUncertainty,
+ indexedPendingIssues,
+ indexedUncertainties,
+ manualIssueError,
+ reviewBlockReason,
+ sameReviewSource,
+ uncertaintyAcceptable,
+ type IndexedReviewIssue
+} from './model'
+import type {
+ ConfirmDramaIssuesInput,
+ ConfirmDramaIssuesResult,
+ DramaReviewIssue,
+ ManualReviewDraft,
+ DeferredUncertaintyDraft,
+ ReviewDraftBackup,
+ UncertaintyDisposition
+} from './types'
+
+/**
+ * 审核问题处理只保存人工裁决;当前权限与终态始终读取服务端。
+ * @param projectId 正式项目编号
+ * @param changed 写入后刷新项目、保存记录及阶段状态
+ * @param disabled 外部项目读取或操作限制
+ * @returns 查询、原始索引选择与明确提交入口
+ */
+export function useDramaReview(
+ projectId: Ref,
+ changed: () => Promise,
+ disabled: Ref = ref(false)
+) {
+ /** 正式审核与当前预检,不自动轮询。 */
+ const query = useQuery(projectId, (id, signal) => loadDramaReview(id, signal))
+ /** 复杂原文核对与人工补充使用同一个全屏抽屉。 */
+ const editorOpen = ref(false)
+ /** 本次人工确认请求状态,普通读取不锁定关闭。 */
+ const writing = ref(false)
+ /** 用户对本次处理的明确确认。 */
+ const acknowledged = ref(false)
+ /** 当前已尝试提交表单,首次打开不显示字段错误。 */
+ const attempted = ref(false)
+ /** 当前操作的可读错误,不改变原始业务错误。 */
+ const actionError = ref('')
+ /** 服务端本次真实回执,不在页面推算 finalized。 */
+ const receipt = ref(null)
+ /** 原始待确认列表中的错误索引。 */
+ const selectedErrors = ref([])
+ /** 原始待确认列表中的警告索引。 */
+ const selectedWarnings = ref([])
+ /** 原始不确定项数组索引。 */
+ const selectedUncertainty = ref([])
+ /** 用户主动选择的延期草稿;读取建议不会新增任何条目。 */
+ const deferredDrafts = ref>({})
+ /** 来源变化后保留的只读草稿,不能直接套用到新审核。 */
+ const preservedDraft = ref(null)
+ /** 字段验证反馈复用应用 NMessage,不重复发送后台错误通知。 */
+ const message = useActionMessage()
+ /** 用户补充的原文证据草稿。 */
+ const manualDrafts = ref([])
+ /** 项目级活动锁与其它生成入口保持一致。 */
+ const operation = computed(() => getOperation(projectId.value))
+ /** 剩余问题保留原始索引,分组不会影响请求。 */
+ const pendingRows = computed(() => indexedPendingIssues(query.data.value?.preview ?? null))
+ /** 剩余不确定项保留原始索引。 */
+ const uncertaintyRows = computed(() => indexedUncertainties(query.data.value?.preview ?? null))
+ /** 服务端明确给出的不可处理原因。 */
+ const blockedReason = computed(() => query.error.value || reviewBlockReason(query.data.value))
+ /** 普通读取、来源不完整或后台运行时只读查看。 */
+ const locked = computed(
+ () => disabled.value || writing.value || query.loading.value || !!blockedReason.value || operation.value.pending
+ )
+ /** 用户实际选择的处理数量,不混算服务端阻断分类。 */
+ const selectionCount = computed(
+ () =>
+ selectedErrors.value.length +
+ selectedWarnings.value.length +
+ selectedUncertainty.value.length +
+ Object.keys(deferredDrafts.value).length +
+ manualDrafts.value.length
+ )
+ /** 只有用户明确勾选后才允许执行表单提交。 */
+ const canConfirm = computed(
+ () => editorOpen.value && acknowledged.value && selectionCount.value > 0 && !locked.value
+ )
+ /** 提交后才逐行展示人工补充表单错误。 */
+ const manualErrors = computed(() =>
+ attempted.value
+ ? manualDrafts.value.map(draft => manualIssueError(draft, query.data.value?.preview?.episodes ?? []))
+ : []
+ )
+ /** 用户尝试提交后才显示延期字段错误。 */
+ const deferredErrors = computed>(() =>
+ attempted.value
+ ? Object.fromEntries(
+ Object.entries(deferredDrafts.value).map(([key, draft]) => [
+ Number(key),
+ draft.index !== Number(key) ||
+ !uncertaintyRows.value.some(row => row.originalIndex === draft.index)
+ ? '原审核项已变化,请重新读取。'
+ : deferredDraftError(draft, query.data.value?.preview?.episodes ?? [])
+ ])
+ )
+ : {}
+ )
+ /** 草稿行编号只用于界面,不作为业务标识提交。 */
+ let nextDraftId = 0
+ /** 项目版本,防止旧项目预检或回执回填。 */
+ let revision = 0
+ /** 提交前只读核对的取消控制器。 */
+ let controller: AbortController | undefined
+ onScopeDispose(() => {
+ revision++
+ controller?.abort()
+ })
+
+ /** 清除当前选择与证据草稿,来源变化时要求重新核对。 */
+ function resetChoices() {
+ selectedErrors.value = []
+ selectedWarnings.value = []
+ selectedUncertainty.value = []
+ deferredDrafts.value = {}
+ manualDrafts.value = []
+ acknowledged.value = false
+ attempted.value = false
+ }
+ watch(projectId, () => {
+ revision++
+ controller?.abort()
+ editorOpen.value = false
+ resetChoices()
+ receipt.value = null
+ preservedDraft.value = null
+ actionError.value = ''
+ })
+ watch(editorOpen, () => {
+ acknowledged.value = false
+ attempted.value = false
+ })
+ watch(
+ [selectedErrors, selectedWarnings, selectedUncertainty, deferredDrafts, manualDrafts],
+ () => {
+ acknowledged.value = false
+ attempted.value = false
+ if (!writing.value && selectionCount.value > 0) actionError.value = ''
+ },
+ { deep: true }
+ )
+ watch(
+ () => query.data.value,
+ (current, previous) => {
+ const before = previous?.preview
+ const after = current?.preview
+ const sourceChanged =
+ (before && (!after || !sameReviewSource(before, after))) ||
+ (!!previous?.latest && previous.latest.id !== current?.latest?.id)
+ if (sourceChanged) {
+ const hadChoices = selectionCount.value > 0
+ if (!writing.value) receipt.value = null
+ if (before && hadChoices) preserveChoices(before)
+ resetChoices()
+ if (hadChoices && !writing.value)
+ actionError.value = '审核来源或建议已变化,旧选择已保留为草稿,请按当前版本重新核对。'
+ }
+ },
+ { flush: 'sync' }
+ )
+
+ /** 打开处理界面时重新核对当前版本,不自动提交。 */
+ async function openEditor() {
+ editorOpen.value = true
+ actionError.value = ''
+ await query.refresh()
+ }
+
+ /**
+ * 已有结构化问题可带入补充表单,纯文本疑点不能自动升级为错误。
+ * @param issue 用户选择补充证据的原问题
+ */
+ function addManual(issue?: DramaReviewIssue) {
+ if (locked.value || issue?.policyException) return
+ manualDrafts.value.push({
+ id: `manual-${++nextDraftId}`,
+ episode: issue?.episode ?? query.data.value?.preview?.episodes[0]?.episode ?? null,
+ category: issue?.category ?? 'action_continuity',
+ code: issue?.code ?? '',
+ sourceQuote: issue?.sourceQuote ?? '',
+ message: issue?.message ?? '',
+ suggestion: issue?.suggestion ?? '',
+ subjectRef: issue?.subjectRef ?? ''
+ })
+ }
+
+ /**
+ * 移除尚未保存的证据行,不修改正式审核。
+ * @param id 草稿行编号
+ */
+ function removeManual(id: string) {
+ manualDrafts.value = manualDrafts.value.filter(draft => draft.id !== id)
+ actionError.value = ''
+ attempted.value = false
+ }
+
+ /**
+ * 界面仅开放接口明确支持的操作,最终证据与权限仍由服务端复核。
+ * @param row 原始问题及索引
+ * @returns 可选择的确认或接受方式,无法核实时为空
+ */
+ function issueAction(row: IndexedReviewIssue): 'error' | 'warning' | null {
+ const issue = row.issue
+ const content = query.data.value?.preview?.episodes.find(item => item.episode === issue.episode)?.content
+ if (issue.policyException || !content?.includes(issue.sourceQuote)) return null
+ if (issue.severity === 'warning') return 'warning'
+ return issue.evidenceConfidence === 'explicit' ? 'error' : null
+ }
+
+ /**
+ * 来源变化时保留用户输入供核对,不自动复用旧索引。
+ * @param source 原草稿绑定的预检
+ */
+ function preserveChoices(source: NonNullable['preview']) {
+ if (!source || selectionCount.value === 0) return
+ preservedDraft.value = JSON.parse(
+ JSON.stringify({
+ reviewId: source.reviewId,
+ checkpointId: source.checkpointId,
+ issueIndexes: selectedErrors.value,
+ acceptedWarningIndexes: selectedWarnings.value,
+ acceptedUncertaintyIndexes: selectedUncertainty.value,
+ descriptions: source.uncertainty,
+ deferredUncertainties: Object.values(deferredDrafts.value),
+ manualIssues: manualDrafts.value
+ })
+ ) as ReviewDraftBackup
+ }
+
+ /**
+ * 人工选择是唯一创建延期草稿的入口,接受与延期始终互斥。
+ * @param index 原始不确定项索引
+ * @param action 用户明确选择的处理方式
+ */
+ function setUncertaintyAction(index: number, action: UncertaintyDisposition) {
+ if (locked.value) return
+ const row = uncertaintyRows.value.find(item => item.originalIndex === index)
+ if (!row || (action !== 'pending' && !uncertaintyAcceptable(row.text))) return
+ selectedUncertainty.value = selectedUncertainty.value.filter(value => value !== index)
+ if (action === 'accept') {
+ delete deferredDrafts.value[index]
+ selectedUncertainty.value.push(index)
+ } else if (action === 'defer') {
+ if (!deferredDrafts.value[index])
+ deferredDrafts.value[index] = newDeferredDraft(
+ index,
+ suggestionForUncertainty(query.data.value?.preview ?? null, index),
+ query.data.value?.preview?.episodes ?? []
+ )
+ } else delete deferredDrafts.value[index]
+ acknowledged.value = false
+ attempted.value = false
+ actionError.value = ''
+ }
+
+ /**
+ * 不确定说明只能带入尚未核实的表单草稿,原文与建议仍需人工填写。
+ * @param index 原始不确定项索引
+ */
+ function addUncertaintyEvidence(index: number) {
+ const row = uncertaintyRows.value.find(item => item.originalIndex === index)
+ if (locked.value || !row) return
+ addManual()
+ const draft = manualDrafts.value.at(-1)
+ const suggestion = suggestionForUncertainty(query.data.value?.preview ?? null, index)
+ if (draft) {
+ draft.episode =
+ suggestion?.confidence === 'high' && !suggestion.requiresEpisodeSelection ? suggestion.episode : null
+ draft.message = row.text
+ }
+ }
+
+ /** 在明确确认后重新预检并保存裁决,成功或冲突后重读真实结果,不自动改写。 */
+ async function confirm() {
+ if (!canConfirm.value || !query.data.value?.preview) return
+ attempted.value = true
+ const overlap = Object.values(deferredDrafts.value).some(draft =>
+ selectedUncertainty.value.includes(draft.index)
+ )
+ if (overlap) {
+ actionError.value = '同一问题不能同时接受和延期验证。'
+ message?.warning(actionError.value)
+ return
+ }
+ const unresolved = [
+ ...selectedUncertainty.value,
+ ...Object.values(deferredDrafts.value).map(draft => draft.index)
+ ].some(index => {
+ const row = uncertaintyRows.value.find(item => item.originalIndex === index)
+ return !row || !uncertaintyAcceptable(row.text)
+ })
+ if (unresolved) {
+ actionError.value = '所选问题已变化或需要补充原文证据,请重新核对。'
+ message?.warning(actionError.value)
+ return
+ }
+ if (Object.values(deferredErrors.value).some(Boolean)) {
+ actionError.value = '请先完善延期验证的剧集、阶段和验证标准。'
+ message?.warning(actionError.value)
+ return
+ }
+ if (manualErrors.value.some(Boolean)) {
+ actionError.value = '请先修正人工补充中的原文与必填内容。'
+ message?.warning(actionError.value)
+ return
+ }
+ const expected = query.data.value.preview
+ const id = projectId.value
+ const version = revision
+ const input: ConfirmDramaIssuesInput = {
+ confirmed: true,
+ reviewId: expected.reviewId,
+ issueIndexes: [...selectedErrors.value],
+ acceptedWarningIndexes: [...selectedWarnings.value],
+ acceptedUncertaintyIndexes: [...selectedUncertainty.value],
+ ...(Object.keys(deferredDrafts.value).length
+ ? {
+ deferredUncertainties: Object.values(deferredDrafts.value)
+ .toSorted((a, b) => a.index - b.index)
+ .map(draft => ({
+ index: draft.index,
+ episode: draft.episode!,
+ verificationTarget: draft.verificationTarget!,
+ verificationCriteria: draft.verificationCriteria.trim()
+ }))
+ }
+ : {}),
+ ...(manualDrafts.value.length
+ ? {
+ manualIssues: manualDrafts.value.map(draft => ({
+ episode: draft.episode!,
+ category: draft.category,
+ code: draft.code.trim(),
+ severity: 'error' as const,
+ sourceQuote: draft.sourceQuote.trim(),
+ message: draft.message.trim(),
+ suggestion: draft.suggestion.trim(),
+ evidenceConfidence: 'explicit' as const,
+ policyException: false,
+ ...(draft.subjectRef.trim() ? { subjectRef: draft.subjectRef.trim() } : {})
+ }))
+ }
+ : {})
+ }
+ writing.value = true
+ actionError.value = ''
+ controller = new AbortController()
+ try {
+ const succeeded = await runOperation(
+ id,
+ '确认审核问题',
+ async () => {
+ const current = await loadDramaReview(id, controller!.signal)
+ if (disabled.value || version !== revision || projectId.value !== id)
+ throw new Error('查看的项目已变化,请重新核对。')
+ if (!current.preview || !sameReviewSource(expected, current.preview)) {
+ preserveChoices(expected)
+ query.data.value = current
+ resetChoices()
+ throw new Error('审核记录或建议来源已变化,旧选择已保留为草稿,请重新核对并选择问题。')
+ }
+ const block = reviewBlockReason(current)
+ if (block) {
+ query.data.value = current
+ throw new Error(block)
+ }
+ const result = await dramaReviewApi.confirm(id, input)
+ if (
+ result.projectId !== id ||
+ result.reviewId !== expected.reviewId ||
+ !result.checkpointId ||
+ typeof result.finalized !== 'boolean' ||
+ !Array.isArray(result.confirmedEpisodes)
+ )
+ throw new Error('处理回执来源尚未确认,请刷新审核记录,不要重复提交。')
+ if (version === revision && projectId.value === id) receipt.value = result
+ return result
+ },
+ result => ({
+ type: result.finalized ? 'success' : 'info',
+ content: result.finalized
+ ? '人工处理已完成,当前审核已通过。'
+ : '本次处理已保存,请继续核对剩余问题与改写范围。'
+ })
+ )
+ if (version !== revision || projectId.value !== id) return
+ acknowledged.value = false
+ if (succeeded) {
+ resetChoices()
+ await Promise.all([query.refresh(), changed()])
+ } else {
+ actionError.value = getOperation(id).error
+ if (getOperation(id).cause instanceof ApiError && (getOperation(id).cause as ApiError).status === 409)
+ await query.refresh()
+ }
+ } catch (cause) {
+ if (version === revision && projectId.value === id) actionError.value = errorMessage(cause)
+ } finally {
+ writing.value = false
+ }
+ }
+ return {
+ query,
+ editorOpen,
+ writing,
+ acknowledged,
+ actionError,
+ receipt,
+ selectedErrors,
+ selectedWarnings,
+ selectedUncertainty,
+ deferredDrafts,
+ deferredErrors,
+ preservedDraft,
+ setUncertaintyAction,
+ addUncertaintyEvidence,
+ manualDrafts,
+ manualErrors,
+ pendingRows,
+ uncertaintyRows,
+ blockedReason,
+ locked,
+ selectionCount,
+ canConfirm,
+ openEditor,
+ addManual,
+ removeManual,
+ issueAction,
+ uncertaintyAcceptable,
+ confirm
+ }
+}
diff --git a/src/features/projects/api.ts b/src/features/projects/api.ts
index 1e979e8..7a902cb 100644
--- a/src/features/projects/api.ts
+++ b/src/features/projects/api.ts
@@ -73,6 +73,15 @@ export const projectsApi = {
optionalResource(request(`/projects/${encodeURIComponent(id)}/state`, { signal })),
checkpoints: (id: string, signal?: AbortSignal) =>
request(`/projects/${encodeURIComponent(id)}/checkpoints`, { signal }),
+ /**
+ * 用户确认后恢复创作;改写明确携带服务端要求的确认标记。
+ * @param id 当前项目编号
+ * @param action 已确认的恢复动作
+ * @returns 后台任务句柄
+ */
resume: (id: string, action: 'resume-generation' | 'resume-rewrite') =>
- request(`/projects/${encodeURIComponent(id)}/${action}`, { method: 'POST' })
+ request(`/projects/${encodeURIComponent(id)}/${action}`, {
+ method: 'POST',
+ body: action === 'resume-rewrite' ? { confirmed: true } : undefined
+ })
}
diff --git a/src/features/workflows/WorkflowExecutionPanel.vue b/src/features/workflows/WorkflowExecutionPanel.vue
index de90679..c819537 100644
--- a/src/features/workflows/WorkflowExecutionPanel.vue
+++ b/src/features/workflows/WorkflowExecutionPanel.vue
@@ -25,13 +25,22 @@ const props = withDefaults(
showStatusHint?: boolean
/** 嵌入弹窗时使用扁平正文,标题、关闭及刷新操作由外层统一提供。 */
embedded?: boolean
+ /** 当前项目结果已更新时,旧创作任务只作为历史执行记录展示。 */
+ resultIsHistorical?: boolean
}>(),
- { title: '制作任务', showStatusHint: true, embedded: false }
+ { title: '制作任务', showStatusHint: true, embedded: false, resultIsHistorical: false }
)
/** 刷新状态与隐藏任务记录事件。 */
const emit = defineEmits<{ refresh: []; dismiss: [] }>()
const percentage = computed(() => executionPercentage(props.execution?.current ?? 0, props.execution?.total ?? 0))
const result = computed(() => props.execution?.result ?? {})
+/** 只改变旧记录的展示语义,不改写原始任务或审核结果。 */
+const historical = computed(
+ () =>
+ props.resultIsHistorical &&
+ props.execution?.workflowName === 'create-drama' &&
+ ['completed', 'failed'].includes(props.execution.status)
+)
/** 动作诊断执行结束仅表示分析完成,不能套用素材生成的通过文案。 */
const diagnosisTask = computed(() => props.execution?.workflowName === 'storyboard-legacy-action-diagnosis')
/** 服务中断后必须由用户核对记录和费用,不根据未匹配数量自动重试。 */
@@ -85,6 +94,7 @@ const progressLabel = computed(() =>
const statusLabel = computed(() => {
const labels = { pending: '等待开始', running: '执行中', completed: '已完成', failed: '失败' }
if (!props.execution) return ''
+ if (historical.value) return '历史执行记录'
if (scriptCreation.value && props.execution.status === 'completed') {
if (result.value.projectStatus === 'need_review') return '执行结束 · 待修订'
if (result.value.projectStatus !== 'completed') return '执行结束 · 结果待确认'
@@ -111,6 +121,7 @@ const staleMotionPlanCount = computed(() => {
})
/** 业务未通过或结果未知时,不把任务执行结束展示为全成功。 */
const statusType = computed(() => {
+ if (historical.value) return 'default'
if (scriptCreation.value && props.execution?.status === 'completed')
return result.value.projectStatus === 'completed'
? 'success'
@@ -332,7 +343,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
}}可以离开或刷新页面,返回后会继续显示本次任务进度,请勿重复提交。
{
+ wrapper?.unmount()
+ wrapper = undefined
+ document.body.innerHTML = ''
+ localStorage.clear()
+})
+
+/**
+ * 挂载实际创作页面,隔离审核查询以只验证首次导航。
+ * @param context 当前正式项目上下文
+ * @returns 当前创作页面
+ */
+async function openGuidance(context: ReturnType) {
+ wrapper = mount(CreateDramaPage, {
+ attachTo: document.body,
+ global: { provide: { [projectContextKey as symbol]: context }, stubs: { DramaReviewPanel: true } }
+ })
+ await flushPromises()
+ return wrapper
+}
+
+describe('首次进入剧本创作的审核引导', () => {
+ it('待审核项目首次进入直接显示审核记录,不自动打开确认或启动任务', async () => {
+ const context = testProjectContext('guide-pending')
+ context.data.value!.project.status = 'need_review'
+ const page = await openGuidance(context)
+ expect(page.getComponent(NTabs).props('value')).toBe('review')
+ expect(page.find('drama-review-panel-stub').exists()).toBe(true)
+ expect(document.querySelector('.app-drawer, .app-dialog')).toBeNull()
+ })
+ it('失败项目保留当前未通过审核时,引导到审核和改写入口', async () => {
+ const context = testProjectContext('guide-rewrite')
+ context.data.value!.project.status = 'failed'
+ context.data.value!.checkpoints = [
+ {
+ checkpointId: 'rewrite-source',
+ workflowName: 'create-drama',
+ createdAt: '2026-10-28T00:00:00Z',
+ state: { reviewPassed: false, review: { passed: false } }
+ }
+ ]
+ const page = await openGuidance(context)
+ expect(page.getComponent(NTabs).props('value')).toBe('review')
+ })
+ it('用户切换到其它内容后,项目刷新不再次切回审核记录', async () => {
+ const context = testProjectContext('guide-no-steal')
+ context.data.value!.project.status = 'need_review'
+ const page = await openGuidance(context)
+ await page.getComponent(NTabs).vm.$emit('update:value', 'world')
+ context.data.value = { ...context.data.value!, project: { ...context.project.value! } }
+ await flushPromises()
+ expect(page.getComponent(NTabs).props('value')).toBe('world')
+ })
+ it('完成或尚未进入审核的项目保留正文,切换项目时按新项目重新定位', async () => {
+ const context = testProjectContext('guide-completed')
+ const page = await openGuidance(context)
+ expect(page.getComponent(NTabs).props('value')).toBe('episodes')
+ context.data.value = {
+ ...context.data.value!,
+ project: { ...context.project.value!, id: 'guide-other-project', status: 'need_review' }
+ }
+ await flushPromises()
+ expect(page.getComponent(NTabs).props('value')).toBe('review')
+ })
+})
diff --git a/tests/features/create-drama/progress.test.ts b/tests/features/create-drama/progress.test.ts
index 5d5cd0e..3e1929e 100644
--- a/tests/features/create-drama/progress.test.ts
+++ b/tests/features/create-drama/progress.test.ts
@@ -83,7 +83,7 @@ async function open(task: WorkflowExecution | null) {
}
wrapper = mount(CreateDramaPage, {
attachTo: document.body,
- global: { provide: { [projectContextKey as symbol]: context } }
+ global: { provide: { [projectContextKey as symbol]: context }, stubs: { DramaReviewPanel: true } }
})
await flushPromises()
return wrapper
@@ -109,6 +109,24 @@ afterEach(() => {
})
describe('故事规划创作进度与恢复', () => {
+ it('人工审核已完成时,旧任务的待修订回执只作为历史记录展示', async () => {
+ context = testProjectContext('manual-review-current-complete')
+ context.data.value!.checkpoints = [
+ checkpoint({ reviewPassed: true, review: { passed: true } }, 'manual-confirm')
+ ]
+ const page = await open(
+ execution(context.project.value!.id, {
+ status: 'completed',
+ stage: 'completed',
+ result: { projectStatus: 'need_review' }
+ })
+ )
+ const dialog = await openTask(page)
+ expect(dialog.text()).toContain('当前剧本已完成审核')
+ expect(dialog.text()).not.toContain('审核仍需处理')
+ expect(dialog.text()).not.toContain('执行结束 · 待修订')
+ expect(dialog.text()).toContain('历史执行记录')
+ })
it('页面仅保留摘要和入口,任务与恢复说明按需进入弹窗且操作都在固定底栏', async () => {
context = testProjectContext('compact-task')
context.data.value!.project.status = 'failed'
@@ -240,10 +258,10 @@ describe('故事规划创作进度与恢复', () => {
expect(page.get('[data-stage="generateStoryPlan"]').attributes('data-status')).toBe('completed')
expect(page.get('[data-stage="generateEpisode"]').attributes('data-status')).toBeUndefined()
expect(dialog.get('button[aria-label="恢复生成"]').attributes('disabled')).toBeUndefined()
- expect(dialog.get('button[aria-label="恢复改写"]').attributes('disabled')).toBeDefined()
+ expect(dialog.get('button[aria-label="恢复改写"]').attributes('aria-haspopup')).toBe('dialog')
})
- it('派生设定失败且正式剧集已齐全时仍允许恢复生成,不误开恢复改写', async () => {
+ it('派生设定失败仍允许恢复生成,改写入口先打开只读预检', async () => {
context = testProjectContext('derive-failed')
context.data.value!.project.status = 'failed'
context.data.value!.checkpoints = [
@@ -254,7 +272,7 @@ describe('故事规划创作进度与恢复', () => {
expect(page.get('[data-stage="generateEpisode"]').attributes('data-status')).toBe('completed')
expect(page.get('[data-stage="generateCharacter"]').attributes('data-status')).toBeUndefined()
expect(dialog.get('button[aria-label="恢复生成"]').attributes('disabled')).toBeUndefined()
- expect(dialog.get('button[aria-label="恢复改写"]').attributes('disabled')).toBeDefined()
+ expect(dialog.get('button[aria-label="恢复改写"]').attributes('aria-haspopup')).toBe('dialog')
})
it('恢复期间不以旧保存记录或数据库设定把当前节点及审核标为完成', async () => {
diff --git a/tests/features/create-drama/review/api.test.ts b/tests/features/create-drama/review/api.test.ts
new file mode 100644
index 0000000..7673c0a
--- /dev/null
+++ b/tests/features/create-drama/review/api.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi } from 'vitest'
+import { projectsApi } from '@/features/projects/api'
+import { dramaReviewApi, loadDramaReview } from '@/features/create-drama/review/api'
+import { confirmationPreview, latestReview } from './fixtures'
+import type { DramaReviewPreview } from '@/features/create-drama/review/types'
+
+describe('剧本恢复的明确确认契约', () => {
+ it('正式审核的问题格式损坏时显示读取错误,不让页面因空问题对象崩溃', async () => {
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue({
+ ...latestReview(),
+ qualityReview: { issues: [null], uncertainty: [] }
+ } as unknown as ReturnType)
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview())
+ await expect(loadDramaReview('review-project')).rejects.toThrow('不完整')
+ })
+ it('预检数据格式异常时保留正式审核并阻止确认,不把原始错误当作问题列表', async () => {
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview())
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(),
+ pendingQualityIssues: [null]
+ } as unknown as DramaReviewPreview)
+ const snapshot = await loadDramaReview('review-project')
+ expect(snapshot.latest?.id).toBe('review-1')
+ expect(snapshot.preview).toBeNull()
+ expect(snapshot.previewError).toContain('不完整')
+ })
+ it('最新审核与预检版本不同不混合展示为可确认状态', async () => {
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview())
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({ ...confirmationPreview(), reviewId: 'another-review' })
+ const snapshot = await loadDramaReview('review-project')
+ expect(snapshot.preview).toBeNull()
+ expect(snapshot.previewError).toContain('版本已变化')
+ })
+ it('恢复改写携带 confirmed,恢复生成不新增未约定参数', async () => {
+ const fetcher = vi
+ .fn()
+ .mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ data: { executionId: 'task', status: 'running' } }), { status: 202 })
+ )
+ vi.stubGlobal('fetch', fetcher)
+ await projectsApi.resume('project/id', 'resume-rewrite')
+ await projectsApi.resume('project/id', 'resume-generation')
+ expect(fetcher.mock.calls[0]![0]).toBe('/api/projects/project%2Fid/resume-rewrite')
+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body ?? 'null'))).toEqual({ confirmed: true })
+ expect(fetcher.mock.calls[1]![1]!.body).toBeUndefined()
+ })
+})
diff --git a/tests/features/create-drama/review/confirmation.test.ts b/tests/features/create-drama/review/confirmation.test.ts
new file mode 100644
index 0000000..9030e0b
--- /dev/null
+++ b/tests/features/create-drama/review/confirmation.test.ts
@@ -0,0 +1,203 @@
+import { effectScope, ref } from 'vue'
+import { flushPromises } from '@vue/test-utils'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { dramaReviewApi } from '@/features/create-drama/review/api'
+import { useDramaReview } from '@/features/create-drama/review/useDramaReview'
+import { confirmationPreview, latestReview } from './fixtures'
+import type { ConfirmDramaIssuesResult } from '@/features/create-drama/review/types'
+
+/** 当前测试拥有的组件作用域。 */
+let scope: ReturnType | undefined
+afterEach(() => {
+ scope?.stop()
+ scope = undefined
+})
+
+/**
+ * 为真实裁决流程提供隔离的接口响应。
+ * @param id 当前项目
+ * @returns 流程与刷新回调
+ */
+async function createFlow(id: string) {
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview(id))
+ const changed = vi.fn<() => Promise>().mockResolvedValue()
+ scope = effectScope()
+ const flow = scope.run(() => useDramaReview(ref(id), changed))!
+ await flushPromises()
+ return { flow, changed }
+}
+
+/**
+ * 构造仍有改写问题的真实回执。
+ * @param id 当前项目
+ * @returns 裁决回执
+ */
+function receipt(id: string): ConfirmDramaIssuesResult {
+ return {
+ projectId: id,
+ reviewId: 'review-1',
+ checkpointId: 'confirmed-cp',
+ confirmedEpisodes: [1],
+ acceptedWarningIndexes: [2],
+ acceptedUncertaintyIndexes: [1],
+ remainingBlockers: 3,
+ blockers: { pendingIssues: 1, uncertainty: 0, confirmedErrors: 1, affectedEpisodes: 1, contentSafety: 0 },
+ finalized: false
+ }
+}
+
+describe('人工确认审核问题', () => {
+ it('项目切换发生在二次预检期间时,不把旧项目选择提交到任何项目', async () => {
+ const id = 'review-project-switch'
+ const project = ref(id)
+ vi.spyOn(dramaReviewApi, 'latest').mockImplementation(async value => latestReview(value))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview(id))
+ scope = effectScope()
+ const flow = scope.run(() => useDramaReview(project, vi.fn<() => Promise>().mockResolvedValue()))!
+ await flushPromises()
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ let resolve!: (value: ReturnType) => void
+ vi.mocked(dramaReviewApi.preview)
+ .mockImplementationOnce(
+ () =>
+ new Promise(done => {
+ resolve = done
+ })
+ )
+ .mockResolvedValue(confirmationPreview('another-project'))
+ flow.editorOpen.value = true
+ flow.selectedErrors.value = [1]
+ await flushPromises()
+ flow.acknowledged.value = true
+ const action = flow.confirm()
+ await flushPromises()
+ project.value = 'another-project'
+ await flushPromises()
+ resolve(confirmationPreview(id))
+ await action
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.editorOpen.value).toBe(false)
+ })
+ it('新的正式审核到达后不保留上一轮人工完成的成功回执', async () => {
+ const id = 'review-receipt-stale'
+ const { flow } = await createFlow(id)
+ flow.receipt.value = { ...receipt(id), finalized: true }
+ vi.mocked(dramaReviewApi.latest).mockResolvedValue({ ...latestReview(id), id: 'review-2' })
+ vi.mocked(dramaReviewApi.preview).mockResolvedValue({
+ ...confirmationPreview(id),
+ reviewId: 'review-2',
+ checkpointId: 'cp-new'
+ })
+ await flow.query.refresh()
+ expect(flow.receipt.value).toBeNull()
+ })
+ it('人工核实的补充证据按完整错误结构提交,不丢失严重程度或原文', async () => {
+ const id = 'review-manual-complete'
+ const { flow } = await createFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm').mockResolvedValue(receipt(id))
+ flow.editorOpen.value = true
+ flow.addManual()
+ Object.assign(flow.manualDrafts.value[0]!, {
+ code: '动作衔接',
+ sourceQuote: '林夏放下信件后打开房门。',
+ message: '缺少动作过程',
+ suggestion: '补齐动作'
+ })
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(confirm.mock.calls[0]![1].manualIssues).toEqual([
+ {
+ episode: 1,
+ category: 'action_continuity',
+ code: '动作衔接',
+ severity: 'error',
+ sourceQuote: '林夏放下信件后打开房门。',
+ message: '缺少动作过程',
+ suggestion: '补齐动作',
+ evidenceConfidence: 'explicit',
+ policyException: false
+ }
+ ])
+ })
+ it('提交原始索引、明确确认和当前审核编号,成功后重读且不自动改写或放行', async () => {
+ const id = 'review-confirm-source'
+ const { flow, changed } = await createFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm').mockResolvedValue(receipt(id))
+ flow.editorOpen.value = true
+ flow.selectedErrors.value = [1]
+ flow.selectedWarnings.value = [2]
+ flow.selectedUncertainty.value = [1]
+ await flushPromises()
+ expect(confirm).not.toHaveBeenCalled()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(confirm).toHaveBeenCalledWith(id, {
+ confirmed: true,
+ reviewId: 'review-1',
+ issueIndexes: [1],
+ acceptedWarningIndexes: [2],
+ acceptedUncertaintyIndexes: [1]
+ })
+ expect(changed).toHaveBeenCalledOnce()
+ expect(flow.receipt.value?.finalized).toBe(false)
+ expect(flow.acknowledged.value).toBe(false)
+ })
+
+ it('预检来源变化后清除旧选择,不提交过期裁决', async () => {
+ const id = 'review-source-change'
+ const { flow } = await createFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ flow.editorOpen.value = true
+ flow.selectedErrors.value = [1]
+ await flushPromises()
+ flow.acknowledged.value = true
+ vi.mocked(dramaReviewApi.preview).mockResolvedValue({ ...confirmationPreview(id), checkpointId: 'new-cp' })
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.actionError.value).toContain('已变化')
+ expect(flow.selectedErrors.value).toEqual([])
+ expect(flow.acknowledged.value).toBe(false)
+ })
+
+ it('没有人工勾选或原文不匹配时不发送任何确认', async () => {
+ const id = 'review-manual-validation'
+ const { flow } = await createFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ flow.editorOpen.value = true
+ flow.addManual()
+ Object.assign(flow.manualDrafts.value[0]!, {
+ code: '动作衔接',
+ sourceQuote: '不存在的原文',
+ message: '缺少动作',
+ suggestion: '补齐动作'
+ })
+ await flushPromises()
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.manualErrors.value[0]).toContain('原文')
+ flow.removeManual(flow.manualDrafts.value[0]!.id)
+ await flushPromises()
+ expect(flow.actionError.value).toBe('')
+ })
+
+ it('后端明确 finalized 才展示完成,不凭阻断计数归零自行通过', async () => {
+ const id = 'review-finalized'
+ const { flow } = await createFlow(id)
+ vi.spyOn(dramaReviewApi, 'confirm').mockResolvedValue({
+ ...receipt(id),
+ remainingBlockers: 0,
+ finalized: false
+ })
+ flow.editorOpen.value = true
+ flow.selectedUncertainty.value = [1]
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(flow.receipt.value?.finalized).toBe(false)
+ })
+})
diff --git a/tests/features/create-drama/review/deferred.test.ts b/tests/features/create-drama/review/deferred.test.ts
new file mode 100644
index 0000000..26e3a13
--- /dev/null
+++ b/tests/features/create-drama/review/deferred.test.ts
@@ -0,0 +1,172 @@
+import { effectScope, ref } from 'vue'
+import { flushPromises } from '@vue/test-utils'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { dramaReviewApi } from '@/features/create-drama/review/api'
+import { useDramaReview } from '@/features/create-drama/review/useDramaReview'
+import { ApiError } from '@/lib/http'
+import { latestReview, suggestedPreview } from './fixtures'
+import type { ConfirmDramaIssuesResult } from '@/features/create-drama/review/types'
+
+/** 当前测试作用域,不连接真实数据。 */
+let scope: ReturnType | undefined
+afterEach(() => {
+ scope?.stop()
+ scope = undefined
+})
+
+/**
+ * 为真实人工选择逻辑提供包含建议的隔离预检。
+ * @param id 正式测试项目
+ * @returns 当前人工确认流程
+ */
+async function resolutionFlow(id: string) {
+ const preview = suggestedPreview(id)
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue({
+ ...latestReview(id),
+ pendingQualityIssues: [],
+ qualityReview: { issues: [], uncertainty: preview.uncertainty }
+ })
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(preview)
+ scope = effectScope()
+ const flow = scope.run(() => useDramaReview(ref(id), vi.fn<() => Promise>().mockResolvedValue()))!
+ await flushPromises()
+ flow.editorOpen.value = true
+ await flushPromises()
+ return flow
+}
+
+/**
+ * 返回仍有待处理事项的正式结构回执。
+ * @param id 正式测试项目
+ * @returns 人工确认回执
+ */
+function result(id: string): ConfirmDramaIssuesResult {
+ return {
+ projectId: id,
+ reviewId: 'review-1',
+ checkpointId: 'cp-saved',
+ confirmedEpisodes: [],
+ acceptedWarningIndexes: [],
+ acceptedUncertaintyIndexes: [2],
+ remainingBlockers: 1,
+ blockers: { pendingIssues: 0, uncertainty: 1, confirmedErrors: 0, affectedEpisodes: 0, contentSafety: 0 },
+ finalized: false
+ }
+}
+
+describe('延期验证的明确人工选择', () => {
+ it('读取建议不会自动接受或创建延期草稿,manual_review 默认保留待处理', async () => {
+ const flow = await resolutionFlow('defer-no-auto')
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ expect(flow.deferredDrafts.value).toEqual({})
+ expect(flow.selectedUncertainty.value).toEqual([])
+ expect(flow.selectionCount.value).toBe(0)
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ })
+ it('明确选集后可同时提交接受和延期,使用原始索引与用户修改的要求', async () => {
+ const id = 'defer-payload'
+ const flow = await resolutionFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm').mockResolvedValue(result(id))
+ flow.setUncertaintyAction(0, 'defer')
+ flow.setUncertaintyAction(1, 'defer')
+ flow.setUncertaintyAction(2, 'accept')
+ expect(flow.deferredDrafts.value[0]!.episode).toBeNull()
+ flow.deferredDrafts.value[0]!.episode = 2
+ flow.deferredDrafts.value[0]!.verificationCriteria = '用户核对后的空间要求。'
+ flow.deferredDrafts.value[1]!.episode = 3
+ flow.deferredDrafts.value[1]!.verificationTarget = 'breakdown'
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(confirm.mock.calls[0]![1]).toEqual({
+ confirmed: true,
+ reviewId: 'review-1',
+ issueIndexes: [],
+ acceptedWarningIndexes: [],
+ acceptedUncertaintyIndexes: [2],
+ deferredUncertainties: [
+ {
+ index: 0,
+ episode: 2,
+ verificationTarget: 'storyboard',
+ verificationCriteria: '用户核对后的空间要求。'
+ },
+ {
+ index: 1,
+ episode: 3,
+ verificationTarget: 'breakdown',
+ verificationCriteria: '核对空间关系与动作连续性。'
+ }
+ ]
+ })
+ })
+ it('必须选集且标准非空,不完整时不发送请求并保留当前草稿', async () => {
+ const flow = await resolutionFlow('defer-required')
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ flow.setUncertaintyAction(0, 'defer')
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(flow.deferredErrors.value[0]).toContain('剧集')
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.deferredDrafts.value[0]!.verificationCriteria).toBe('核对空间关系与动作连续性。')
+ flow.deferredDrafts.value[0]!.episode = 2
+ flow.deferredDrafts.value[0]!.verificationCriteria = ' '
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(flow.deferredErrors.value[0]).toContain('标准')
+ expect(confirm).not.toHaveBeenCalled()
+ })
+ it('同一原始问题不能同时接受和延期', async () => {
+ const flow = await resolutionFlow('defer-overlap')
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ flow.setUncertaintyAction(0, 'defer')
+ flow.deferredDrafts.value[0]!.episode = 2
+ flow.selectedUncertainty.value = [0]
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.actionError.value).toContain('不能同时')
+ })
+ it('提交失败且来源未变时保留选项、集号、阶段和编辑标准', async () => {
+ const id = 'defer-retained'
+ const flow = await resolutionFlow(id)
+ vi.spyOn(dramaReviewApi, 'confirm').mockRejectedValue(new ApiError('核验要求需修正', 409))
+ flow.setUncertaintyAction(0, 'defer')
+ Object.assign(flow.deferredDrafts.value[0]!, {
+ episode: 3,
+ verificationTarget: 'breakdown',
+ verificationCriteria: '保留用户编辑的标准。'
+ })
+ flow.setUncertaintyAction(2, 'accept')
+ await flushPromises()
+ flow.acknowledged.value = true
+ await flow.confirm()
+ expect(flow.deferredDrafts.value[0]).toEqual({
+ index: 0,
+ episode: 3,
+ verificationTarget: 'breakdown',
+ verificationCriteria: '保留用户编辑的标准。'
+ })
+ expect(flow.selectedUncertainty.value).toEqual([2])
+ expect(flow.acknowledged.value).toBe(false)
+ })
+ it('来源变化不提交旧选择,并保留旧草稿供重新核对', async () => {
+ const id = 'defer-new-source'
+ const flow = await resolutionFlow(id)
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ flow.setUncertaintyAction(0, 'defer')
+ flow.deferredDrafts.value[0]!.episode = 2
+ await flushPromises()
+ flow.acknowledged.value = true
+ vi.mocked(dramaReviewApi.preview).mockResolvedValue({ ...suggestedPreview(id), checkpointId: 'changed' })
+ await flow.confirm()
+ expect(confirm).not.toHaveBeenCalled()
+ expect(flow.deferredDrafts.value).toEqual({})
+ expect(flow.preservedDraft.value?.reviewId).toBe('review-1')
+ expect(flow.preservedDraft.value?.deferredUncertainties[0]?.episode).toBe(2)
+ })
+})
diff --git a/tests/features/create-drama/review/fixtures.ts b/tests/features/create-drama/review/fixtures.ts
new file mode 100644
index 0000000..03aac5b
--- /dev/null
+++ b/tests/features/create-drama/review/fixtures.ts
@@ -0,0 +1,132 @@
+import type {
+ DramaReviewIssue,
+ DramaReviewPreview,
+ DramaRewritePreview,
+ LatestDramaReview
+} from '@/features/create-drama/review/types'
+
+/**
+ * 构造真实结构化问题字段。
+ * @param overrides 当前问题差异
+ * @returns 完整问题
+ */
+export function reviewIssue(overrides: Partial = {}): DramaReviewIssue {
+ return {
+ episode: 1,
+ category: 'action_continuity',
+ code: 'fall_support',
+ severity: 'error',
+ sourceQuote: '林夏放下信件后打开房门。',
+ message: '动作承接需要核对',
+ suggestion: '补齐必要的动作过程',
+ policyException: false,
+ evidenceConfidence: 'explicit',
+ ...overrides
+ }
+}
+
+/**
+ * 构造最新审核。
+ * @param id 正式项目编号
+ * @returns 真实最新审核回执
+ */
+export function latestReview(id = 'review-project'): LatestDramaReview {
+ return {
+ id: 'review-1',
+ projectId: id,
+ passed: false,
+ message: '有待核对的剧本问题。',
+ createdAt: '2026-10-28T00:00:00Z',
+ qualityReview: { issues: [], uncertainty: ['空间信息尚未说明', '动作过程尚待核对'] },
+ pendingQualityIssues: [
+ reviewIssue({ severity: 'warning', code: 'warning-old' }),
+ reviewIssue(),
+ reviewIssue({ episode: 2, severity: 'warning', code: 'warning-current' })
+ ],
+ manualUncertaintyDecisions: [],
+ affectedEpisodes: [],
+ hitWords: []
+ }
+}
+
+/**
+ * 构造多轮裁决后的预检,保留原始索引。
+ * @param id 正式项目编号
+ * @returns 完整只读预检
+ */
+export function confirmationPreview(id = 'review-project'): DramaReviewPreview {
+ const review = latestReview(id)
+ return {
+ projectId: id,
+ reviewId: review.id,
+ checkpointId: 'cp-1',
+ readOnly: true,
+ ready: true,
+ sourceValid: true,
+ reviewSourceValid: true,
+ hasActiveExecution: false,
+ pendingQualityIssues: review.pendingQualityIssues,
+ uncertainty: review.qualityReview!.uncertainty,
+ remainingPendingQualityIssues: review.pendingQualityIssues.slice(1),
+ remainingUncertainty: ['动作过程尚待核对'],
+ confirmedRewriteEpisodes: [],
+ episodes: [
+ { episode: 1, content: '林夏放下信件后打开房门。随后走入院中。' },
+ { episode: 2, content: '林夏放下信件后打开房门。另一人走来。' }
+ ]
+ }
+}
+
+/**
+ * 构造真实改写范围。
+ * @param id 正式项目编号
+ * @returns 只读改写预检
+ */
+export function rewritePreview(id = 'review-project'): DramaRewritePreview {
+ return {
+ projectId: id,
+ checkpointId: 'cp-1',
+ readOnly: true,
+ ready: true,
+ status: 'ready',
+ episodeNumbers: [1, 2],
+ rewriteCharacters: false,
+ rewriteWorld: false,
+ rewriteEpisodes: true,
+ requiresConfirmation: true
+ }
+}
+
+/**
+ * 构造带多集候选的建议预检,所有建议尚未被人工采用。
+ * @param id 正式项目编号
+ * @returns 包含三种待处理说明与建议的预检
+ */
+export function suggestedPreview(id = 'suggestion-project'): DramaReviewPreview {
+ const descriptions = [
+ '铜铃与木凳的空间关系需要在画面中核对',
+ '人物站位与动作接触关系需要核对',
+ '第二、三集的重复对白需人工确认'
+ ]
+ return {
+ ...confirmationPreview(id),
+ pendingQualityIssues: [],
+ remainingPendingQualityIssues: [],
+ uncertainty: descriptions,
+ remainingUncertainty: descriptions,
+ episodes: [1, 2, 3].map(episode => ({ episode, content: `第${episode}集正式正文。` })),
+ resolutionSuggestions: descriptions.map((description, index) => ({
+ index,
+ description,
+ suggestedAction: index < 2 ? 'defer' : 'manual_review',
+ requiresEpisodeSelection: index < 2,
+ requiresManualConfirmation: true,
+ episode: null,
+ episodeCandidates: index === 0 ? [1, 2, 3] : [2, 3],
+ confidence: 'none',
+ verificationTarget: index < 2 ? 'storyboard' : null,
+ verificationCriteria: index < 2 ? '核对空间关系与动作连续性。' : null,
+ reason: index < 2 ? '涉及多集视觉问题,需人工选集' : '需人工核对跨集叙事'
+ }))
+ }
+}
diff --git a/tests/features/create-drama/review/model.test.ts b/tests/features/create-drama/review/model.test.ts
new file mode 100644
index 0000000..c2546ec
--- /dev/null
+++ b/tests/features/create-drama/review/model.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest'
+import {
+ indexedPendingIssues,
+ indexedUncertainties,
+ sameReviewSource,
+ sameRewriteScope,
+ manualIssueError
+} from '@/features/create-drama/review/model'
+import { confirmationPreview, rewritePreview } from './fixtures'
+
+describe('审核原始索引与来源保护', () => {
+ it('已接受第一项后,分组排序仍提交原始问题和不确定项索引', () => {
+ const preview = confirmationPreview()
+ expect(indexedPendingIssues(preview).map(row => row.originalIndex)).toEqual([1, 2])
+ expect(indexedUncertainties(preview).map(row => row.originalIndex)).toEqual([1])
+ })
+ it('剩余列表缺失时不伪造已处理结果', () => {
+ const preview = confirmationPreview()
+ delete preview.remainingPendingQualityIssues
+ delete preview.remainingUncertainty
+ expect(indexedPendingIssues(preview).map(row => row.originalIndex)).toEqual([0, 1, 2])
+ expect(indexedUncertainties(preview).map(row => row.originalIndex)).toEqual([0, 1])
+ })
+ it('审核、保存记录或正式正文变化都使本次选择失效', () => {
+ const preview = confirmationPreview()
+ expect(sameReviewSource(preview, structuredClone(preview))).toBe(true)
+ expect(sameReviewSource(preview, { ...preview, checkpointId: 'cp-new' })).toBe(false)
+ expect(sameReviewSource(preview, { ...preview, reviewId: 'review-new' })).toBe(false)
+ expect(sameReviewSource(preview, { ...preview, episodes: [{ episode: 1, content: '正文已变化' }] })).toBe(false)
+ })
+ it('保存记录或改写范围变化必须重新确认,集号顺序变化不视为范围变化', () => {
+ const preview = rewritePreview()
+ expect(sameRewriteScope(preview, { ...preview, episodeNumbers: [2, 1] })).toBe(true)
+ expect(sameRewriteScope(preview, { ...preview, checkpointId: 'new' })).toBe(false)
+ expect(sameRewriteScope(preview, { ...preview, rewriteWorld: true })).toBe(false)
+ expect(sameRewriteScope(preview, { ...preview, episodeNumbers: [1] })).toBe(false)
+ })
+ it('人工补充必须填写真实集号、逐字引用、说明和建议', () => {
+ const draft = {
+ id: 'draft',
+ episode: 1,
+ category: 'action_continuity' as const,
+ code: '动作衔接',
+ sourceQuote: '不存在的引用',
+ message: '核对动作',
+ suggestion: '补齐动作',
+ subjectRef: ''
+ }
+ expect(manualIssueError(draft, confirmationPreview().episodes)).toContain('原文')
+ expect(
+ manualIssueError({ ...draft, sourceQuote: '林夏放下信件后打开房门。' }, confirmationPreview().episodes)
+ ).toBe('')
+ expect(manualIssueError({ ...draft, episode: 9 }, confirmationPreview().episodes)).toContain('剧集')
+ })
+})
diff --git a/tests/features/create-drama/review/panel.test.ts b/tests/features/create-drama/review/panel.test.ts
new file mode 100644
index 0000000..fdfc69c
--- /dev/null
+++ b/tests/features/create-drama/review/panel.test.ts
@@ -0,0 +1,400 @@
+import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { NButton, NCheckbox, NTag } from 'naive-ui'
+import DramaReviewPanel from '@/features/create-drama/review/DramaReviewPanel.vue'
+import { dramaReviewApi } from '@/features/create-drama/review/api'
+import { projectContextKey } from '@/features/projects/context'
+import { testProjectContext } from '@/testing/project-context'
+import { confirmationPreview, latestReview, rewritePreview } from './fixtures'
+
+/** 当前审核页面。 */
+let wrapper: VueWrapper | undefined
+beforeEach(() => {
+ vi.spyOn(dramaReviewApi, 'rewritePreview').mockImplementation(async id => ({
+ ...rewritePreview(id),
+ ready: false,
+ status: 'needs_review',
+ episodeNumbers: [],
+ rewriteEpisodes: false
+ }))
+})
+afterEach(() => {
+ wrapper?.unmount()
+ wrapper = undefined
+ document.body.innerHTML = ''
+ localStorage.clear()
+})
+
+describe('审核记录中的人工问题处理', () => {
+ it.each([
+ {
+ episodes: [],
+ title: '请先核对审核问题',
+ description: '点击“人工确认”对照原文逐项处理',
+ actions: [['人工确认', 'primary']]
+ },
+ {
+ episodes: [2],
+ title: '已有改写依据,请检查改写范围',
+ description: '第 2 集已有改写依据',
+ actions: [
+ ['人工确认', 'default'],
+ ['改写预检', 'primary']
+ ]
+ }
+ ])('显示当前审核的下一步引导:$title', async ({ episodes, title, description, actions }) => {
+ const id = `review-guidance-${episodes.length}`
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(id),
+ confirmedRewriteEpisodes: episodes
+ })
+ vi.mocked(dramaReviewApi.rewritePreview).mockResolvedValue({
+ ...rewritePreview(id),
+ ready: episodes.length > 0,
+ status: episodes.length ? 'ready' : 'needs_review',
+ episodeNumbers: episodes,
+ rewriteEpisodes: episodes.length > 0
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ expect(wrapper.text()).toContain(title)
+ expect(wrapper.text()).toContain(description)
+ const entries = wrapper
+ .findAllComponents(NButton)
+ .filter(button => ['人工确认', '改写预检'].includes(button.attributes('aria-label') ?? ''))
+ const refresh = wrapper.findAllComponents(NButton).find(button => button.text() === '刷新审核')!
+ expect(entries.map(button => [button.attributes('aria-label'), button.props('type')])).toEqual(actions)
+ expect(refresh.props('type')).toBe('default')
+ expect(document.querySelector('.app-drawer, .app-dialog')).toBeNull()
+ })
+ it.each([
+ { name: '仅需改写', targets: [2], passed: false, actions: ['改写预检'] },
+ { name: '没有可处理事项', targets: [], passed: false, actions: [] },
+ { name: '审核已通过', targets: [], passed: true, actions: [] }
+ ])('$name 时只显示实际存在的入口', async ({ name, targets, passed, actions }) => {
+ const id = `review-visible-${name}`
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue({ ...latestReview(id), passed })
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(id),
+ confirmedRewriteEpisodes: targets,
+ remainingPendingQualityIssues: [],
+ remainingUncertainty: []
+ })
+ vi.mocked(dramaReviewApi.rewritePreview).mockResolvedValue({
+ ...rewritePreview(id),
+ ready: targets.length > 0,
+ status: targets.length ? 'ready' : 'needs_review',
+ episodeNumbers: targets,
+ rewriteEpisodes: targets.length > 0
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ const entries = wrapper
+ .findAllComponents(NButton)
+ .map(button => button.attributes('aria-label'))
+ .filter(label => ['人工确认', '改写预检'].includes(label ?? ''))
+ expect(entries).toEqual(actions)
+ expect(wrapper.findAllComponents(NButton).some(button => button.text() === '刷新审核')).toBe(true)
+ expect(wrapper.text()).not.toContain('待确认问题仍可继续人工处理')
+ })
+ it('角色或世界观单独改写没有集号时,仍按真实改写预检显示入口', async () => {
+ const id = 'review-visible-world-rewrite'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(id),
+ confirmedRewriteEpisodes: [],
+ remainingPendingQualityIssues: [],
+ remainingUncertainty: []
+ })
+ vi.mocked(dramaReviewApi.rewritePreview).mockResolvedValue({
+ ...rewritePreview(id),
+ episodeNumbers: [],
+ rewriteEpisodes: false,
+ rewriteWorld: true
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ const entries = wrapper
+ .findAllComponents(NButton)
+ .filter(button => ['人工确认', '改写预检'].includes(button.attributes('aria-label') ?? ''))
+ expect(entries.map(button => [button.attributes('aria-label'), button.props('type')])).toEqual([
+ ['改写预检', 'primary']
+ ])
+ expect(wrapper.text()).toContain('世界观')
+ })
+ it('改写预检与当前审核保存记录不一致时隐藏旧范围并允许刷新', async () => {
+ const id = 'review-visible-stale-rewrite'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview(id))
+ vi.mocked(dramaReviewApi.rewritePreview).mockResolvedValue({
+ ...rewritePreview(id),
+ checkpointId: 'another-checkpoint'
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ expect(wrapper.find('button[aria-label="改写预检"]').exists()).toBe(false)
+ expect(wrapper.text()).toContain('保存记录已变化')
+ expect(
+ wrapper
+ .findAllComponents(NButton)
+ .find(button => button.text() === '刷新审核')!
+ .props('disabled')
+ ).toBe(false)
+ })
+ it('预检读取失败时不展示没有当前依据的处理入口', async () => {
+ const id = 'review-visible-preview-error'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockRejectedValue(new Error('预检读取失败'))
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ expect(wrapper.find('button[aria-label="人工确认"]').exists()).toBe(false)
+ expect(wrapper.find('button[aria-label="改写预检"]').exists()).toBe(false)
+ expect(wrapper.text()).toContain('预检读取失败')
+ })
+ it.each([
+ { name: '来源失效', sourceValid: false, hasActiveExecution: false },
+ { name: '活动任务', sourceValid: true, hasActiveExecution: true }
+ ])('$name 时保留只读入口,不强调人工确认或改写', async ({ name, sourceValid, hasActiveExecution }) => {
+ const id = `review-primary-blocked-${name}`
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(id),
+ confirmedRewriteEpisodes: [2],
+ ready: false,
+ sourceValid,
+ hasActiveExecution
+ })
+ vi.mocked(dramaReviewApi.rewritePreview).mockResolvedValue({
+ ...rewritePreview(id),
+ ready: false,
+ status: hasActiveExecution ? 'blocked' : 'stale',
+ rewriteEpisodes: hasActiveExecution
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ const entryButtons = wrapper
+ .findAllComponents(NButton)
+ .filter(button => ['人工确认', '改写预检'].includes(button.attributes('aria-label') ?? ''))
+ expect(entryButtons.map(button => button.props('type'))).toEqual(
+ hasActiveExecution ? ['default', 'default'] : ['default']
+ )
+ })
+ it('手机默认收起完整正文,点击查看本集原文后展开核对区', async () => {
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
+ matches: false,
+ media: '(min-width: 1024px)',
+ onchange: null,
+ addEventListener: vi.fn<() => void>(),
+ removeEventListener: vi.fn<() => void>(),
+ addListener: vi.fn<() => void>(),
+ removeListener: vi.fn<() => void>(),
+ dispatchEvent: () => true
+ })
+ vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(() => {})
+ const id = 'review-mobile-source'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview(id))
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ await wrapper.get('button[aria-label="人工确认"]').trigger('click')
+ await flushPromises()
+ const drawer = new DOMWrapper(document.querySelector('.app-drawer')!)
+ expect(drawer.find('.review-source-content').exists()).toBe(false)
+ await drawer
+ .get('[data-review-issue="1"]')
+ .findAll('button')
+ .find(item => item.text() === '查看本集原文')!
+ .trigger('click')
+ await flushPromises()
+ expect(drawer.get('.review-source-content').text()).toContain('林夏放下信件后打开房门。')
+ })
+ it('人工处理完成审核后仍可只读核对正式正文,不再显示可提交表单', async () => {
+ const id = 'review-panel-finalized'
+ const preview = confirmationPreview(id)
+ preview.pendingQualityIssues = [preview.pendingQualityIssues[2]!]
+ preview.remainingPendingQualityIssues = preview.pendingQualityIssues
+ preview.uncertainty = []
+ preview.remainingUncertainty = []
+ const initial = {
+ ...latestReview(id),
+ pendingQualityIssues: preview.pendingQualityIssues,
+ qualityReview: { issues: [], uncertainty: [] }
+ }
+ const latest = vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(initial)
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(preview)
+ const context = testProjectContext(id)
+ context.data.value!.project.status = 'need_review'
+ context.data.value!.project.episodes = confirmationPreview(id).episodes.map(item => ({
+ ...item,
+ title: `第${item.episode}集`,
+ targetDurationSeconds: null
+ }))
+ vi.spyOn(dramaReviewApi, 'confirm').mockImplementation(async () => {
+ latest.mockResolvedValue({ ...initial, id: 'review-passed', passed: true, pendingQualityIssues: [] })
+ context.data.value!.project.status = 'completed'
+ return {
+ projectId: id,
+ reviewId: 'review-1',
+ checkpointId: 'final-cp',
+ confirmedEpisodes: [],
+ acceptedWarningIndexes: [0],
+ acceptedUncertaintyIndexes: [],
+ finalized: true,
+ remainingBlockers: 0,
+ blockers: {
+ pendingIssues: 0,
+ uncertainty: 0,
+ confirmedErrors: 0,
+ affectedEpisodes: 0,
+ contentSafety: 0
+ }
+ }
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: context } }
+ })
+ await flushPromises()
+ await wrapper.get('button[aria-label="人工确认"]').trigger('click')
+ await flushPromises()
+ const drawer = new DOMWrapper(document.querySelector('.app-drawer')!)
+ await drawer.get('[data-review-issue="0"] [role="checkbox"]').trigger('click')
+ await drawer.get('.app-drawer-footer [role="checkbox"]').trigger('click')
+ await drawer
+ .get('.app-drawer-footer')
+ .findAll('button')
+ .find(item => item.text() === '确认本次处理')!
+ .trigger('click')
+ await flushPromises()
+ expect(drawer.text()).toContain('本次处理已完成审核')
+ expect(drawer.text()).toContain('林夏放下信件后打开房门。')
+ expect(drawer.text()).not.toContain('当前没有可核对的正式正文')
+ expect(drawer.findAll('button').some(item => item.text() === '确认本次处理')).toBe(false)
+ })
+ it('刷新失败保留旧记录时不把旧通过结论继续标为当前成功', async () => {
+ const id = 'review-read-failed'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue({ ...latestReview(id), passed: true })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ vi.mocked(dramaReviewApi.latest).mockRejectedValue(new Error('审核读取中断'))
+ await wrapper
+ .findAll('button')
+ .find(button => button.text() === '刷新审核')!
+ .trigger('click')
+ await flushPromises()
+ expect(wrapper.getComponent(NTag).props('type')).toBe('default')
+ expect(wrapper.text()).not.toContain('当前审核已通过')
+ })
+ it('按集核对正式原文,默认不勾选,实际提交仍使用原始索引', async () => {
+ const id = 'review-panel-index'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(confirmationPreview(id))
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm').mockResolvedValue({
+ projectId: id,
+ reviewId: 'review-1',
+ checkpointId: 'saved-cp',
+ confirmedEpisodes: [1],
+ acceptedWarningIndexes: [],
+ acceptedUncertaintyIndexes: [],
+ finalized: false,
+ remainingBlockers: 2,
+ blockers: {
+ pendingIssues: 1,
+ uncertainty: 0,
+ confirmedErrors: 1,
+ affectedEpisodes: 0,
+ contentSafety: 0
+ }
+ })
+ const context = testProjectContext(id)
+ context.data.value!.project.status = 'need_review'
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: context } }
+ })
+ await flushPromises()
+ await wrapper.get('button[aria-label="人工确认"]').trigger('click')
+ await flushPromises()
+ const drawer = new DOMWrapper(document.querySelector('.app-drawer')!)
+ expect(drawer.text()).toContain('正式剧本原文')
+ const footer = drawer.get('.app-drawer-footer')
+ const submit = footer.findAll('button').find(item => item.text() === '确认本次处理')!
+ expect(submit.attributes('disabled')).toBeDefined()
+ expect(confirm).not.toHaveBeenCalled()
+ await drawer.get('[data-review-issue="1"] [role="checkbox"]').trigger('click')
+ await footer.get('[role="checkbox"]').trigger('click')
+ await submit.trigger('click')
+ await flushPromises()
+ expect(confirm.mock.calls[0]![1]).toMatchObject({ confirmed: true, reviewId: 'review-1', issueIndexes: [1] })
+ expect(context.refresh).toHaveBeenCalled()
+ expect(drawer.text()).not.toContain('当前审核已通过')
+ })
+ it('来源过期只读展示,界面不开放人工确认', async () => {
+ const id = 'review-panel-stale'
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue(latestReview(id))
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue({
+ ...confirmationPreview(id),
+ ready: false,
+ sourceValid: false
+ })
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ expect(wrapper.text()).toContain('来源不一致')
+ await wrapper.get('button[aria-label="人工确认"]').trigger('click')
+ await flushPromises()
+ const drawer = new DOMWrapper(document.querySelector('.app-drawer')!)
+ expect(drawer.get('[data-review-issue="1"] [role="checkbox"]').attributes('aria-disabled')).toBe('true')
+ expect(
+ wrapper
+ .findAllComponents(NCheckbox)
+ .find(item => item.element.closest('[data-review-issue="1"]'))!
+ .props('disabled')
+ ).toBe(true)
+ expect(
+ drawer
+ .get('.app-drawer-footer')
+ .findAll('button')
+ .find(item => item.text() === '确认本次处理')!
+ .attributes('disabled')
+ ).toBeDefined()
+ })
+})
diff --git a/tests/features/create-drama/review/resolutions.test.ts b/tests/features/create-drama/review/resolutions.test.ts
new file mode 100644
index 0000000..787da71
--- /dev/null
+++ b/tests/features/create-drama/review/resolutions.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest'
+import {
+ deferredDraftError,
+ newDeferredDraft,
+ suggestionForUncertainty,
+ savedReviewDecisions
+} from '@/features/create-drama/review/model'
+import { suggestedPreview } from './fixtures'
+
+describe('延期建议与原始索引', () => {
+ it('部分处理后从当前保存记录读取同一审核的裁决,不混入其它来源', () => {
+ const decision = {
+ reviewId: 'review-current',
+ originalIndex: 0,
+ description: '空间关系',
+ disposition: 'deferred',
+ episode: 2,
+ verificationTarget: 'storyboard',
+ verificationCriteria: '核对可达性。'
+ }
+ expect(
+ savedReviewDecisions(
+ { manualUncertaintyDecisions: [decision, { ...decision, reviewId: 'old' }] },
+ 'review-current'
+ )
+ ).toEqual([decision])
+ expect(savedReviewDecisions({}, 'review-current')).toBeNull()
+ })
+ it('建议按剩余项重编号后,仍通过原文对应原始审核问题', () => {
+ const preview = suggestedPreview()
+ preview.remainingUncertainty = preview.uncertainty.slice(1)
+ preview.resolutionSuggestions = preview
+ .resolutionSuggestions!.slice(1)
+ .map((item, index) => ({ ...item, index }))
+ expect(suggestionForUncertainty(preview, 1)?.description).toBe(preview.uncertainty[1])
+ expect(suggestionForUncertainty(preview, 2)?.suggestedAction).toBe('manual_review')
+ expect(suggestionForUncertainty(preview, 0)).toBeNull()
+ })
+ it('低置信度或要求选集时不预选集号,但预填可编辑的阶段与标准', () => {
+ const preview = suggestedPreview()
+ const suggestion = { ...preview.resolutionSuggestions![0]!, episode: 2, confidence: 'low' as const }
+ expect(newDeferredDraft(0, suggestion, preview.episodes)).toEqual({
+ index: 0,
+ episode: null,
+ verificationTarget: 'storyboard',
+ verificationCriteria: '核对空间关系与动作连续性。'
+ })
+ expect(
+ newDeferredDraft(
+ 0,
+ { ...suggestion, confidence: 'high', requiresEpisodeSelection: false },
+ preview.episodes
+ ).episode
+ ).toBe(2)
+ })
+ it('允许选择候选之外的正式剧集,拒绝空标准、未知阶段与不存在集号', () => {
+ const preview = suggestedPreview()
+ const draft = {
+ index: 1,
+ episode: 1,
+ verificationTarget: 'breakdown' as const,
+ verificationCriteria: '核对动作。'
+ }
+ expect(deferredDraftError(draft, preview.episodes)).toBe('')
+ expect(deferredDraftError({ ...draft, episode: null }, preview.episodes)).toContain('剧集')
+ expect(deferredDraftError({ ...draft, episode: 9 }, preview.episodes)).toContain('剧集')
+ expect(deferredDraftError({ ...draft, verificationCriteria: ' ' }, preview.episodes)).toContain('标准')
+ expect(deferredDraftError({ ...draft, verificationTarget: null }, preview.episodes)).toContain('阶段')
+ })
+})
diff --git a/tests/features/create-drama/review/rewrite.test.ts b/tests/features/create-drama/review/rewrite.test.ts
new file mode 100644
index 0000000..28fb0dc
--- /dev/null
+++ b/tests/features/create-drama/review/rewrite.test.ts
@@ -0,0 +1,113 @@
+import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import DramaRewriteAction from '@/features/create-drama/review/DramaRewriteAction.vue'
+import { dramaReviewApi } from '@/features/create-drama/review/api'
+import { workflowExecutionApi } from '@/features/workflows/execution-api'
+import { rewritePreview } from './fixtures'
+
+/** 当前挂载的改写入口。 */
+let wrapper: VueWrapper | undefined
+
+/**
+ * 从实际入口打开改写预检。
+ * @param id 当前测试项目
+ * @returns 当前确认弹窗
+ */
+async function openRewrite(id: string) {
+ wrapper = mount(DramaRewriteAction, { attachTo: document.body, props: { projectId: id } })
+ await wrapper.get('button').trigger('click')
+ await flushPromises()
+ return new DOMWrapper(document.querySelector('.app-dialog[aria-label="恢复改写"]')!)
+}
+
+afterEach(() => {
+ wrapper?.unmount()
+ wrapper = undefined
+ document.body.innerHTML = ''
+ localStorage.clear()
+})
+
+describe('恢复改写前的范围与费用确认', () => {
+ it('打开和关闭只做预检,明确确认后才提交 confirmed 并跟踪后台任务', async () => {
+ const id = 'rewrite-confirmed'
+ vi.spyOn(dramaReviewApi, 'rewritePreview').mockResolvedValue(rewritePreview(id))
+ vi.spyOn(workflowExecutionApi, 'get').mockResolvedValue({
+ id: 'rewrite-task',
+ projectId: id,
+ workflowName: 'create-drama',
+ status: 'running',
+ stage: 'resumeRewrite',
+ current: 0,
+ total: 0,
+ currentResourceId: null,
+ metadata: null,
+ result: null,
+ error: null,
+ startedAt: null,
+ completedAt: null,
+ createdAt: '2026-10-28T00:00:00Z',
+ updatedAt: '2026-10-28T00:00:00Z'
+ })
+ const fetcher = vi.fn().mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ data: { executionId: 'rewrite-task', status: 'running' } }), {
+ status: 202
+ })
+ )
+ vi.stubGlobal('fetch', fetcher)
+ const dialog = await openRewrite(id)
+ expect(dialog.text()).toContain('第 1、2 集')
+ expect(fetcher).not.toHaveBeenCalled()
+ const confirm = dialog.findAll('button').find(button => button.text() === '确认恢复改写')!
+ expect(confirm.attributes('disabled')).toBeDefined()
+ await dialog.get('[role="checkbox"]').trigger('click')
+ await confirm.trigger('click')
+ await flushPromises()
+ expect(fetcher).toHaveBeenCalledTimes(1)
+ expect(fetcher.mock.calls[0]![0]).toBe(`/api/projects/${id}/resume-rewrite`)
+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ confirmed: true })
+ expect(localStorage.getItem(`short-drama:workflow-execution:${id}:create-drama`)).toBe('rewrite-task')
+ })
+
+ it('二次预检发现保存记录或集数变化时撤销旧确认,不发送改写请求', async () => {
+ const id = 'rewrite-changed'
+ vi.spyOn(dramaReviewApi, 'rewritePreview')
+ .mockResolvedValueOnce(rewritePreview(id))
+ .mockResolvedValue({ ...rewritePreview(id), checkpointId: 'cp-new', episodeNumbers: [2] })
+ const fetcher = vi.fn()
+ vi.stubGlobal('fetch', fetcher)
+ const dialog = await openRewrite(id)
+ await dialog.get('[role="checkbox"]').trigger('click')
+ await dialog
+ .findAll('button')
+ .find(button => button.text() === '确认恢复改写')!
+ .trigger('click')
+ await flushPromises()
+ expect(fetcher).not.toHaveBeenCalled()
+ expect(dialog.text()).toContain('已变化')
+ expect(dialog.get('[role="checkbox"]').attributes('aria-checked')).toBe('false')
+ })
+
+ it('服务端未就绪时可关闭和重新读取,但不能启动改写', async () => {
+ const id = 'rewrite-blocked'
+ vi.spyOn(dramaReviewApi, 'rewritePreview').mockResolvedValue({
+ ...rewritePreview(id),
+ ready: false,
+ status: 'needs_review'
+ })
+ const dialog = await openRewrite(id)
+ expect(dialog.text()).toContain('没有可执行的改写目标')
+ expect(
+ dialog
+ .findAll('button')
+ .find(button => button.text() === '确认恢复改写')!
+ .attributes('disabled')
+ ).toBeDefined()
+ expect(
+ dialog
+ .findAll('button')
+ .find(button => button.text() === '取消')!
+ .attributes('disabled')
+ ).toBeUndefined()
+ })
+})
diff --git a/tests/features/create-drama/review/suggestions-panel.test.ts b/tests/features/create-drama/review/suggestions-panel.test.ts
new file mode 100644
index 0000000..15edcc9
--- /dev/null
+++ b/tests/features/create-drama/review/suggestions-panel.test.ts
@@ -0,0 +1,90 @@
+import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
+import { NSelect } from 'naive-ui'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import DramaReviewPanel from '@/features/create-drama/review/DramaReviewPanel.vue'
+import { dramaReviewApi } from '@/features/create-drama/review/api'
+import { projectContextKey } from '@/features/projects/context'
+import { testProjectContext } from '@/testing/project-context'
+import { latestReview, suggestedPreview, rewritePreview } from './fixtures'
+
+/** 当前挂载页面。 */
+let wrapper: VueWrapper | undefined
+beforeEach(() => {
+ vi.spyOn(dramaReviewApi, 'rewritePreview').mockImplementation(async id => ({
+ ...rewritePreview(id),
+ ready: false,
+ status: 'needs_review',
+ episodeNumbers: [],
+ rewriteEpisodes: false
+ }))
+})
+afterEach(() => {
+ wrapper?.unmount()
+ wrapper = undefined
+ document.body.innerHTML = ''
+})
+
+/**
+ * 通过真实审核入口打开含建议的处理抽屉。
+ * @param id 测试项目编号
+ * @returns 当前抽屉
+ */
+async function openSuggestions(id: string) {
+ const preview = suggestedPreview(id)
+ preview.resolutionSuggestions![0]!.episodeCandidates = [2, 3]
+ vi.spyOn(dramaReviewApi, 'latest').mockResolvedValue({
+ ...latestReview(id),
+ pendingQualityIssues: [],
+ qualityReview: { issues: [], uncertainty: preview.uncertainty }
+ })
+ vi.spyOn(dramaReviewApi, 'preview').mockResolvedValue(preview)
+ wrapper = mount(DramaReviewPanel, {
+ attachTo: document.body,
+ props: { projectId: id },
+ global: { provide: { [projectContextKey as symbol]: testProjectContext(id) } }
+ })
+ await flushPromises()
+ await wrapper.get('button[aria-label="人工确认"]').trigger('click')
+ await flushPromises()
+ return new DOMWrapper(document.querySelector('.app-drawer')!)
+}
+
+describe('审核建议卡片', () => {
+ it('低置信度延期建议展示候选但不默认采用,选择延期后预填标准且剧集留空', async () => {
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ const drawer = await openSuggestions('suggestion-ui-defer')
+ const card = drawer.get('[data-review-uncertainty="0"]')
+ expect(card.text()).toContain('延期验证')
+ expect(card.text()).toContain('第 2、3 集')
+ expect(card.get('[data-resolution-action="defer"]').text()).toContain('建议')
+ expect((card.get('[data-resolution-action="pending"] input').element as HTMLInputElement).checked).toBe(true)
+ await card.get('[data-resolution-action="defer"] input').setValue(true)
+ await flushPromises()
+ const episode = wrapper!
+ .findAllComponents(NSelect)
+ .find(item => item.attributes('aria-label') === '问题 1 负责验证的剧集')!
+ expect(episode.props('value')).toBeNull()
+ expect(episode.props('options')!.map(item => ('value' in item ? item.value : undefined))).toEqual([2, 3, 1])
+ expect((card.get('textarea[aria-label="问题 1 验证标准"]').element as HTMLTextAreaElement).value).toBe(
+ '核对空间关系与动作连续性。'
+ )
+ expect(confirm).not.toHaveBeenCalled()
+ expect(
+ drawer
+ .get('.app-drawer-footer')
+ .findAll('button')
+ .find(item => item.text() === '确认本次处理')!
+ .attributes('disabled')
+ ).toBeDefined()
+ })
+ it('人工核对建议仍默认保留,不能由 manual_review 自动接受', async () => {
+ const confirm = vi.spyOn(dramaReviewApi, 'confirm')
+ const drawer = await openSuggestions('suggestion-ui-manual')
+ const card = drawer.get('[data-review-uncertainty="2"]')
+ expect(card.text()).toContain('人工核对')
+ expect((card.get('[data-resolution-action="pending"] input').element as HTMLInputElement).checked).toBe(true)
+ expect((card.get('[data-resolution-action="accept"] input').element as HTMLInputElement).checked).toBe(false)
+ expect(card.find('textarea').exists()).toBe(false)
+ expect(confirm).not.toHaveBeenCalled()
+ })
+})