feat(short-drama-agent-front): 接入审核人工确认与延期验证

This commit is contained in:
GJ committed 2026-10-28 16:32:47 +08:00
1 parent 5836b90934
commit c6ef595a8e
23 files changed
+3923 -67

No files matched your search

@@ -0,0 +1,850 @@
<script setup lang="ts">
import { computed, nextTick, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NForm, NScrollbar, NSelect, NTag } from 'naive-ui'
import { FileCheck2, FileSearch, Plus } from '@lucide/vue'
import { AppDrawer, EmptyState, WorkspaceRefreshButton, WorkspaceSectionHeading } from '../../../components/ui'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { formatDate } from '../../../lib/format'
import { userFacingText } from '../../../lib/user-facing-text'
import { useQuery } from '../../../composables/useQuery'
import { useProjectContext } from '../../projects/context'
import { workflowCheckpoints } from '../../workflows/selectors'
import DramaRewriteAction from './DramaRewriteAction.vue'
import ManualReviewIssueEditor from './ManualReviewIssueEditor.vue'
import ReviewUncertaintyCard from './ReviewUncertaintyCard.vue'
import { reviewCategoryOptions, suggestionForUncertainty, savedReviewDecisions } from './model'
import { useDramaReview } from './useDramaReview'
import { loadDramaRewritePreview } from './api'
import type { DramaReviewIssue, DramaReviewPreview, DeferredUncertaintyDraft } from './types'
/** 审核记录只在用户切到当前标签时挂载,不为其它页面额外查询。 */
const props = withDefaults(
defineProps<{
/** 当前正式项目。 */ projectId: string
/** 项目查询失败等外部限制。 */ disabled?: boolean
}>(),
{ disabled: false }
)
/** 正式项目、保存记录与导航状态共用同一个数据源。 */
const context = useProjectContext()
/** 当前入口绑定的项目,异步响应必须核对归属。 */
const projectId = computed(() => props.projectId)
/** 外部项目错误只限制写入,仍可只读查看。 */
const disabled = computed(() => props.disabled || !!context.error.value)
/** 人工确认与稳定原始索引选择。 */
const flow = useDramaReview(projectId, context.refresh, disabled)
/** 最新正式审核。 */
const latest = computed(() => flow.query.data.value?.latest ?? null)
/** 当前已核对的处理预检。 */
const preview = computed(() => flow.query.data.value?.preview ?? null)
/** 当前审核每次重读后同步查询改写范围,不从集号数量推断角色或世界观能否改写。 */
const rewriteKey = computed(() =>
latest.value?.passed === false
? JSON.stringify([projectId.value, latest.value.id, preview.value?.checkpointId, flow.query.updatedAt.value])
: ''
)
/**
* 查询当前真实改写范围,并拒绝与人工确认来源不同的保存记录。
* @param key 当前审核查询版本,空值时不发送请求
* @param signal 取消过期查询
* @returns 当前改写预检或空值
*/
async function readRewriteAvailability(key: string, signal: AbortSignal) {
if (!key) return null
const id = projectId.value
const checkpointId = preview.value?.checkpointId
const result = await loadDramaRewritePreview(id, signal)
if (checkpointId && result.checkpointId !== checkpointId)
throw new Error('审核与改写范围的保存记录已变化,请刷新审核后重新核对。')
return result
}
/** 改写预检只读查询,项目和保存记录变化时自动取消旧结果。 */
const rewriteQuery = useQuery(rewriteKey, readRewriteAvailability)
/** 只展示与当前项目及当前保存记录一致的真实改写范围。 */
const currentRewrite = computed(() => {
const result = rewriteQuery.data.value
return result?.projectId === projectId.value &&
(!preview.value || result.checkpointId === preview.value.checkpointId)
? result
: null
})
/** 只在预检确有剩余待处理项时显示人工确认入口,不为已处理完的审核保留空操作。 */
const hasManualIssues = computed(
() =>
latest.value?.passed === false &&
!!preview.value &&
!!(flow.pendingRows.value.length || flow.uncertaintyRows.value.length)
)
/** 任一真实改写模块存在时保留入口,支持没有集号的角色或世界观单独改写。 */
const hasRewriteTargets = computed(
() =>
latest.value?.passed === false &&
!rewriteQuery.error.value &&
!!(
currentRewrite.value?.rewriteEpisodes ||
currentRewrite.value?.rewriteCharacters ||
currentRewrite.value?.rewriteWorld
)
)
/** 当前有效预检只强调一个下一步入口,配色不代替服务端操作权限。 */
const primaryAction = computed<'confirm' | 'rewrite' | null>(() => {
if (flow.locked.value || rewriteQuery.loading.value || rewriteQuery.error.value || latest.value?.passed !== false)
return null
if (currentRewrite.value?.status === 'blocked' || currentRewrite.value?.status === 'stale') return null
if (hasRewriteTargets.value) return currentRewrite.value?.ready === true ? 'rewrite' : null
return hasManualIssues.value ? 'confirm' : null
})
/** 剧集范围同样读取真实改写预检,设定单独改写不伪造成剧集任务。 */
const rewriteEpisodeSummary = computed(() => {
const result = currentRewrite.value
if (rewriteQuery.loading.value || rewriteQuery.error.value || !result) return '待确认'
if (result.rewriteEpisodes && result.episodeNumbers.length) return `第 ${result.episodeNumbers.join('、')} 集`
return result.rewriteCharacters || result.rewriteWorld ? '仅涉及设定' : '暂无剧集改写'
})
/** 下一步说明只读取服务端已有的改写依据,不预先接受问题或启动模型。 */
const nextStep = computed(() => {
const result = currentRewrite.value
const scope = [
result?.rewriteEpisodes ? `第 ${result.episodeNumbers.join('、')} 集` : '',
result?.rewriteCharacters ? '角色设定' : '',
result?.rewriteWorld ? '世界观' : ''
]
.filter(Boolean)
.join('、')
return hasRewriteTargets.value
? {
title: '已有改写依据,请检查改写范围',
description: `${scope}已有改写依据。点击“改写预检”核对范围${hasManualIssues.value ? ';待确认问题仍可继续人工处理' : ''}。开始改写前会再次确认费用。`
}
: {
title: '请先核对审核问题',
description:
'点击“人工确认”对照原文逐项处理。确认后如需改写,会显示“改写预检”入口;所有处理都需要你确认。'
}
})
/** 正式正文的当前阅读集号。 */
const sourceEpisode = ref<number | null>(null)
/** 原文容器用于抽屉内定位,不切换到另一个主界面。 */
const sourceElement = ref<HTMLElement | null>(null)
/** 人工补充证据区用于用户主动操作后的抽屉内定位。 */
const manualElement = ref<HTMLElement | null>(null)
/** 完整正文桌面展开、手机按需展开,避免短屏首次进入被原文占满。 */
const sourceMedia = window.matchMedia('(min-width: 1024px)')
/** 当前只读正文折叠状态,不影响任何审核选择。 */
const sourceExpanded = ref<string[]>(sourceMedia.matches ? ['source'] : [])
/**
* 屏幕断点变化时同步适合当前尺寸的正文展示方式。
* @param event 当前桌面断点
*/
function syncSourceMedia(event: MediaQueryListEvent) {
sourceExpanded.value = event.matches ? ['source'] : []
}
sourceMedia.addEventListener('change', syncSourceMedia)
onScopeDispose(() => sourceMedia.removeEventListener('change', syncSourceMedia))
/** 改写预检复用页面上的唯一入口。 */
const rewriteAction = ref<InstanceType<typeof DramaRewriteAction> | null>(null)
/** 仅记录用户主动的界面交接意图,避免同时叠加抽屉和预检弹窗。 */
const queuedRewriteProject = ref('')
/** 读取中或失败时不把上次通过结果显示为当前成功。 */
const reviewUncertain = computed(() => flow.query.loading.value || !!flow.query.error.value)
/** 服务端回执说明下一步,不根据分类计数推断已经通过。 */
const receiptSummary = computed(() => {
const result = flow.receipt.value
if (!result) return ''
if (result.finalized) return '本次人工处理已由系统确认完成,请以最新审核与阶段状态为准。'
return result.confirmedEpisodes.length
? `本次已记录第 ${result.confirmedEpisodes.join('、')} 集的改写依据。请核对改写范围后再决定是否继续。`
: '本次人工处理已保存,请继续核对剩余问题和改写范围。'
})
watch(projectId, () => {
queuedRewriteProject.value = ''
})
/** 待处理正文来自预检,通过后仍可只读查看当前项目已保存的正式正文。 */
const sourceEpisodes = computed<DramaReviewPreview['episodes']>(
() =>
preview.value?.episodes ??
(latest.value?.passed && context.project.value?.id === projectId.value
? context.project.value.episodes.map(({ episode, content }) => ({ episode, content }))
: [])
)
/** 正文选项来自实际保存的剧集,不根据计划数量补造内容。 */
const episodeOptions = computed(() =>
sourceEpisodes.value.map(item => ({ label: `第 ${item.episode} 集`, value: item.episode }))
)
/** 当前完整正文以纯文本展示。 */
const sourceContent = computed(
() => sourceEpisodes.value.find(item => item.episode === sourceEpisode.value)?.content ?? ''
)
/** 角色选项沿用正式项目数据,用户不能填写猜测的角色名。 */
const characters = computed(() => context.project.value?.characters.map(item => item.name) ?? [])
/** 仍待处理的问题按正式集号分组,原始索引不变。 */
const groups = computed(() =>
[...new Set(flow.pendingRows.value.map(row => row.issue.episode))]
.toSorted((a, b) => a - b)
.map(episode => ({ episode, rows: flow.pendingRows.value.filter(row => row.issue.episode === episode) }))
)
/** 原始已记录问题只读展示,不用它覆盖当前剩余裁决。 */
const recordedIssues = computed(() => latest.value?.qualityReview?.issues ?? [])
/** 现有延期等裁决只作追溯,不能把接受视为已完成后续核验。 */
const decisions = computed(() => {
const checkpoint = workflowCheckpoints(context.checkpoints.value, 'create-drama').at(-1)
return preview.value && checkpoint?.checkpointId === preview.value.checkpointId
? (savedReviewDecisions(checkpoint.state.review, preview.value.reviewId) ??
latest.value?.manualUncertaintyDecisions ??
[])
: (latest.value?.manualUncertaintyDecisions ?? [])
})
watch(sourceEpisodes, value => {
if (!value.some(item => item.episode === sourceEpisode.value)) sourceEpisode.value = value[0]?.episode ?? null
})
/** 其它入口改写结束时,保存记录变化会触发一次重读,不定时查询。 */
watch(
() => workflowCheckpoints(context.checkpoints.value, 'create-drama').at(-1)?.checkpointId,
(id, previous) => {
if (id && id !== previous && !flow.writing.value) void flow.query.refresh()
}
)
/**
* 仅切换当前抽屉中的正式正文,不发送写入请求。
* @param episode 用户核对的集号
*/
async function viewEpisode(episode: number | null) {
sourceEpisode.value = episode
sourceExpanded.value = ['source']
await nextTick()
sourceElement.value?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}
/**
* 更新用户已创建的延期表单,建议读取不会触发此操作。
* @param draft 本次人工编辑的延期草稿
*/
function updateDeferred(draft: DeferredUncertaintyDraft) {
flow.deferredDrafts.value[draft.index] = draft
}
/**
* 带入待核对的说明后定位证据表单,仍由用户填写真实原文。
* @param index 原始不确定项索引
*/
async function addUncertaintyEvidence(index: number) {
flow.addUncertaintyEvidence(index)
await nextTick()
manualElement.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
/**
* 中文分类只用于展示,原始枚举保留在请求中。
* @param issue 当前审核问题
* @returns 中文分类名称
*/
function categoryLabel(issue: DramaReviewIssue) {
return reviewCategoryOptions.find(option => option.value === issue.category)?.label ?? '待核对问题'
}
/**
* 多种处理方式共用原始索引选择,不使用分组后的页面位置。
* @param kind 当前处理方式
* @param index 原始审核数组索引
* @param checked 用户是否选择
*/
function toggleChoice(kind: 'error' | 'warning' | 'uncertainty', index: number, checked: boolean) {
const target =
kind === 'error' ? flow.selectedErrors : kind === 'warning' ? flow.selectedWarnings : flow.selectedUncertainty
target.value = checked ? [...new Set([...target.value, index])] : target.value.filter(value => value !== index)
}
/** 用户明确请求下一步时,先关闭核对抽屉。 */
function requestRewritePreview() {
if (flow.writing.value || disabled.value || !hasRewriteTargets.value) return
queuedRewriteProject.value = projectId.value
flow.editorOpen.value = false
}
/** 抽屉离场和焦点约束释放后,再打开预检;不自动启动改写。 */
function editorClosed() {
const id = queuedRewriteProject.value
queuedRewriteProject.value = ''
if (id && id === projectId.value) rewriteAction.value?.openPreview()
}
</script>
<template>
<div class="drama-review-panel grid gap-6">
<!-- 以下是最新审核摘要与只读刷新、处理及改写预检入口 -->
<WorkspaceSectionHeading
title="审核记录"
:description="latest ? `最近审核 · ${formatDate(latest.createdAt)}` : '查看当前正式审核与可处理的问题。'"
>
<template #actions>
<WorkspaceRefreshButton
label="刷新审核"
:loading="flow.query.loading.value"
:disabled="flow.writing.value"
@refresh="flow.query.refresh"
/>
<NButton
v-if="hasManualIssues"
:class="{ 'workspace-action-button': primaryAction !== 'confirm' }"
:type="primaryAction === 'confirm' ? 'primary' : 'default'"
aria-label="人工确认"
:disabled="!latest || latest.passed || flow.writing.value"
@click="flow.openEditor"
>
<template #icon><FileCheck2 :size="15" aria-hidden="true" /></template>人工确认
</NButton>
<DramaRewriteAction
v-if="hasRewriteTargets"
ref="rewriteAction"
:project-id="projectId"
:primary="primaryAction === 'rewrite'"
:disabled="disabled || flow.writing.value || latest?.passed === true"
@started="context.refresh"
/>
</template>
</WorkspaceSectionHeading>
<ContextNotice v-if="flow.query.error.value" type="error" title="审核读取失败" emphasized>{{
flow.query.error.value
}}</ContextNotice>
<ContextNotice v-if="rewriteQuery.error.value" type="error" title="改写范围读取失败" emphasized>{{
rewriteQuery.error.value
}}</ContextNotice>
<p v-if="flow.query.loading.value && !latest" class="text-sm text-muted">正在读取最新审核…</p>
<EmptyState
v-else-if="!latest && !flow.query.error.value"
title="暂无审核记录"
description="正式审核完成后会显示结果;刷新不会重新启动审核。"
/>
<template v-if="latest">
<div class="flex flex-wrap items-center gap-3">
<NTag :type="reviewUncertain ? 'default' : latest.passed ? 'success' : 'warning'" :bordered="false">{{
reviewUncertain ? '审核状态待核对' : latest.passed ? '当前审核已通过' : '当前审核尚未通过'
}}</NTag>
</div>
<!-- 以下是当前审核的下一步引导,仅在来源有效且读取完成后显示 -->
<ContextNotice
v-if="
(hasManualIssues || hasRewriteTargets) &&
!flow.blockedReason.value &&
!reviewUncertain &&
!rewriteQuery.loading.value &&
!rewriteQuery.error.value
"
type="info"
:title="nextStep.title"
emphasized
>{{ nextStep.description }}</ContextNotice
>
<ContextNotice
v-if="!latest.passed && flow.blockedReason.value"
type="warning"
title="当前仅可查看"
emphasized
>{{ flow.blockedReason.value }}</ContextNotice
>
<ContextNotice
v-if="flow.receipt.value && !reviewUncertain"
:type="flow.receipt.value.finalized ? 'success' : 'info'"
:title="flow.receipt.value.finalized ? '本次处理已完成审核' : '本次处理已保存'"
emphasized
>{{ receiptSummary }}</ContextNotice
>
<!-- 以下是当前剩余问题与已记录改写范围,统计不合并为总阻断数 -->
<dl v-if="preview && !latest.passed" class="grid gap-5 sm:grid-cols-3">
<div>
<dt class="text-xs text-muted">待确认问题</dt>
<dd class="mt-2 text-sm">
{{ preview.remainingPendingQualityIssues?.length ?? '待核对'
}}<span v-if="preview.remainingPendingQualityIssues"> 项</span>
</dd>
</div>
<div>
<dt class="text-xs text-muted">待核对说明</dt>
<dd class="mt-2 text-sm">
{{ preview.remainingUncertainty?.length ?? '待核对'
}}<span v-if="preview.remainingUncertainty"> 项</span>
</dd>
</div>
<div>
<dt class="text-xs text-muted">待改写剧集</dt>
<dd class="mt-2 text-sm">{{ rewriteEpisodeSummary }}</dd>
</div>
</dl>
<NCollapse>
<NCollapseItem
v-if="recordedIssues.length"
name="recorded-issues"
:title="`已记录的审核问题(${recordedIssues.length})`"
>
<div class="grid gap-5 pt-2">
<article v-for="(issue, index) in recordedIssues" :key="index" class="grid gap-2">
<h4 class="text-sm font-medium">第 {{ issue.episode }} 集 · {{ categoryLabel(issue) }}</h4>
<p class="text-sm leading-7">{{ issue.message }}</p>
<blockquote class="review-source-quote">{{ issue.sourceQuote }}</blockquote>
<p class="text-xs leading-6 text-muted">修改方向:{{ issue.suggestion }}</p>
</article>
</div>
</NCollapseItem>
<NCollapseItem v-if="latest.message" name="review-message" title="审核说明"
><p class="whitespace-pre-wrap text-sm leading-7">
{{ userFacingText(latest.message) }}
</p></NCollapseItem
>
<NCollapseItem v-if="decisions.length" name="decisions" title="已保存的人工判断"
><ul class="space-y-3 text-sm leading-7">
<li v-for="(decision, index) in decisions" :key="index">
{{
decision.disposition === 'accepted'
? '已接受'
: decision.disposition === 'verified'
? '已核验'
: '留待后续核验'
}}
· {{ decision.description }}
<p v-if="decision.verificationCriteria" class="text-xs text-muted">
<span v-if="decision.episode">第 {{ decision.episode }} 集 · </span>
<span v-if="decision.verificationTarget"
>{{ decision.verificationTarget === 'breakdown' ? '拆解' : '分镜' }}阶段 · </span
>核验标准:{{ decision.verificationCriteria }}
</p>
</li>
</ul></NCollapseItem
>
<NCollapseItem name="review-details" title="高级详情"
><dl class="grid gap-2 text-xs">
<dt class="text-muted">审核编号</dt>
<dd class="break-all font-mono">{{ latest.id }}</dd>
<template v-if="preview"
><dt class="mt-2 text-muted">保存记录</dt>
<dd class="break-all font-mono">{{ preview.checkpointId }}</dd></template
>
</dl></NCollapseItem
>
</NCollapse>
</template>
</div>
<!-- 以下是全屏人工核对抽屉,正文与表单独立于固定底栏 -->
<AppDrawer
v-model:open="flow.editorOpen.value"
class="review-confirm-drawer"
title="审核人工确认"
description="对照正式正文逐项核对。本次确认不调用模型,也不会自动改写。"
:busy="flow.writing.value"
@closed="editorClosed"
>
<div v-if="flow.editorOpen.value" class="review-editor-content grid gap-6">
<ContextNotice v-if="flow.blockedReason.value" type="warning" title="当前仅可查看" emphasized>{{
flow.blockedReason.value
}}</ContextNotice>
<ContextNotice v-if="flow.actionError.value" type="error" title="请核对本次处理" emphasized>{{
flow.actionError.value
}}</ContextNotice>
<!-- 以下是来源变化时保留的只读草稿,不将旧索引套用到新版本 -->
<NCollapse v-if="flow.preservedDraft.value">
<NCollapseItem name="preserved-draft" title="查看来源变化前的草稿">
<div class="grid gap-4 text-sm leading-7">
<p class="text-muted">以下选择属于旧审核,仅供重新核对,尚未保存为当前判断。</p>
<p
v-for="index in flow.preservedDraft.value.acceptedUncertaintyIndexes"
:key="`accepted-${index}`"
>
原选择接受:{{ flow.preservedDraft.value.descriptions[index] }}
</p>
<div v-for="draft in flow.preservedDraft.value.deferredUncertainties" :key="draft.index">
<p>原选择延期:{{ flow.preservedDraft.value.descriptions[draft.index] }}</p>
<p class="text-muted">
第 {{ draft.episode ?? '未选' }} 集 ·
{{
draft.verificationTarget === 'breakdown'
? '拆解'
: draft.verificationTarget === 'storyboard'
? '分镜'
: '未选阶段'
}}
· {{ draft.verificationCriteria }}
</p>
</div>
<div v-for="draft in flow.preservedDraft.value.manualIssues" :key="draft.id">
<p>{{ draft.message }}</p>
<blockquote class="review-source-quote">{{ draft.sourceQuote }}</blockquote>
<p>{{ draft.suggestion }}</p>
</div>
<p
v-if="
flow.preservedDraft.value.issueIndexes.length ||
flow.preservedDraft.value.acceptedWarningIndexes.length
"
class="text-muted"
>
原错误与警告选择已撤销,请对照当前问题重新选择。
</p>
</div>
</NCollapseItem>
</NCollapse>
<ContextNotice
v-if="flow.receipt.value && !reviewUncertain"
:type="flow.receipt.value.finalized ? 'success' : 'info'"
:title="flow.receipt.value.finalized ? '本次处理已完成审核' : '本次处理已保存'"
emphasized
>{{ receiptSummary }}</ContextNotice
>
<div class="review-editor-layout">
<!-- 以下是桌面独立滚动的问题区,手机沿用抽屉正文滚动 -->
<NScrollbar class="review-issues-scroll">
<div class="grid min-w-0 content-start gap-8">
<!-- 以下是按剧集分组的待确认问题,原始索引与展示位置分离 -->
<section v-if="groups.length || !flow.uncertaintyRows.value.length">
<WorkspaceSectionHeading
title="待确认问题"
description="确认错误用于后续改写;接受警告表示保留当前处理。未选择的条目继续保留。"
/>
<NCollapse
v-if="groups.length"
class="mt-4"
:default-expanded-names="groups.map(group => group.episode)"
>
<NCollapseItem
v-for="group in groups"
:key="group.episode"
:name="group.episode"
:title="`第 ${group.episode} 集 · ${group.rows.length} 项`"
>
<div class="grid gap-4">
<article
v-for="row in group.rows"
:key="row.originalIndex"
:data-review-issue="row.originalIndex"
class="review-issue-card"
:class="{
'review-issue-error':
row.issue.severity === 'error' && !row.issue.policyException
}"
>
<div class="flex flex-wrap items-center gap-3">
<h4 class="text-sm font-semibold">{{ categoryLabel(row.issue) }}</h4>
<NTag size="small" :bordered="false">{{
row.issue.policyException
? '策略允许'
: row.issue.severity === 'error'
? '错误待核对'
: '警告待核对'
}}</NTag>
</div>
<p class="mt-3 text-sm leading-7">{{ row.issue.message }}</p>
<blockquote class="review-source-quote mt-3">
{{ row.issue.sourceQuote }}
</blockquote>
<p class="mt-3 text-xs leading-6 text-muted">
修改方向:{{ row.issue.suggestion }}
</p>
<div class="workspace-action-group mt-4 flex flex-wrap items-center gap-3">
<NButton size="small" @click="viewEpisode(row.issue.episode)"
><template #icon
><FileSearch :size="14" aria-hidden="true" /></template
>查看本集原文</NButton
>
<NButton
v-if="!row.issue.policyException"
size="small"
:disabled="flow.locked.value"
@click="flow.addManual(row.issue)"
><template #icon><Plus :size="14" aria-hidden="true" /></template
>补充原文证据</NButton
>
</div>
<NCheckbox
v-if="row.issue.severity === 'error'"
class="mt-4"
:checked="flow.selectedErrors.value.includes(row.originalIndex)"
:disabled="flow.locked.value || flow.issueAction(row) !== 'error'"
:aria-disabled="flow.locked.value || flow.issueAction(row) !== 'error'"
@update:checked="toggleChoice('error', row.originalIndex, $event)"
>已核实错误,记录为改写依据</NCheckbox
>
<NCheckbox
v-else
class="mt-4"
:checked="flow.selectedWarnings.value.includes(row.originalIndex)"
:disabled="flow.locked.value || flow.issueAction(row) !== 'warning'"
:aria-disabled="
flow.locked.value || flow.issueAction(row) !== 'warning'
"
@update:checked="toggleChoice('warning', row.originalIndex, $event)"
>已核对原文,接受保留此警告</NCheckbox
>
<p
v-if="flow.issueAction(row) === null"
class="mt-2 text-xs leading-6 text-muted"
>
{{
row.issue.policyException
? '该项属于已允许的表现方式,不能强制确认改写。'
: '当前证据尚不能直接确认,可补充经核对的真实原文。'
}}
</p>
</article>
</div>
</NCollapseItem>
</NCollapse>
<p v-else class="mt-4 text-sm text-muted">
{{
latest?.passed
? '当前审核已通过,无需再次确认问题。'
: '当前没有待人工确认的结构化问题。已有审核问题仍需以改写预检为准。'
}}
</p>
</section>
<!-- 以下是不确定项,禁止将无效原文或模型格式问题直接接受 -->
<section>
<WorkspaceSectionHeading
title="待核对说明"
description="默认保留待处理。可选择标有“建议”的处理方式,也可核对原文后另行决定;确认保存后才会生效。"
/>
<div v-if="flow.uncertaintyRows.value.length" class="mt-4 grid gap-4">
<ReviewUncertaintyCard
v-for="row in flow.uncertaintyRows.value"
:key="row.originalIndex"
:row="row"
:suggestion="suggestionForUncertainty(preview, row.originalIndex)"
:episodes="preview?.episodes ?? []"
:accepted="flow.selectedUncertainty.value.includes(row.originalIndex)"
:deferred="flow.deferredDrafts.value[row.originalIndex]"
:error="flow.deferredErrors.value[row.originalIndex]"
:locked="flow.locked.value"
@action="flow.setUncertaintyAction(row.originalIndex, $event)"
@update:deferred="updateDeferred"
@view="viewEpisode"
@evidence="addUncertaintyEvidence(row.originalIndex)"
/>
</div>
<p v-else class="mt-4 text-sm text-muted">当前没有待核对说明。</p>
</section>
<!-- 以下是人工补充表单,首次打开和新增空行不立即报错 -->
<section v-if="!latest?.passed" ref="manualElement">
<WorkspaceSectionHeading
title="人工补充证据"
description="仅补充你已核实的真实错误,不自动将不确定说明转换为错误。"
>
<template #actions
><NButton
:disabled="flow.locked.value || !preview?.episodes.length"
@click="flow.addManual()"
><template #icon><Plus :size="15" aria-hidden="true" /></template
>补充原文证据</NButton
></template
>
</WorkspaceSectionHeading>
<NForm
v-if="flow.manualDrafts.value.length"
label-placement="top"
class="mt-5 grid gap-8"
@submit.prevent
>
<ManualReviewIssueEditor
v-for="(draft, index) in flow.manualDrafts.value"
:key="draft.id"
:model-value="draft"
:order="index + 1"
:episodes="preview?.episodes ?? []"
:characters="characters"
:disabled="flow.locked.value"
:error="flow.manualErrors.value[index]"
@update:model-value="flow.manualDrafts.value[index] = $event"
@remove="flow.removeManual(draft.id)"
/>
</NForm>
</section>
</div>
</NScrollbar>
<!-- 以下是当前正式剧本的纯文本核对区,窄屏先显示原文 -->
<section ref="sourceElement" class="review-source-pane">
<NCollapse v-model:expanded-names="sourceExpanded">
<NCollapseItem name="source" title="正式剧本原文">
<div class="review-source-fields grid gap-4">
<p class="text-xs leading-6 text-muted">
引用必须逐字出现在所选剧集中,不能用事件编号代替。
</p>
<NSelect
v-model:value="sourceEpisode"
:options="episodeOptions"
aria-label="选择核对剧集"
:disabled="!episodeOptions.length"
/>
<NScrollbar class="review-source-scroll">
<pre class="review-source-content">{{
sourceContent ||
(sourceEpisodes.length
? '请选择需要核对的剧集。'
: '当前没有可核对的正式正文。')
}}</pre>
</NScrollbar>
</div>
</NCollapseItem>
</NCollapse>
</section>
</div>
</div>
<!-- 以下是固定的关闭、只读刷新与明确确认操作,不自动启动改写 -->
<template #footer>
<div class="review-editor-footer">
<NCheckbox
v-if="!latest?.passed"
v-model:checked="flow.acknowledged.value"
:disabled="flow.locked.value || !flow.selectionCount.value"
:aria-disabled="flow.locked.value || !flow.selectionCount.value"
class="review-confirm-ack"
>我已逐项核对所选问题、引用原文和本次处理方式,确认保存人工判断。</NCheckbox
>
<div class="review-editor-actions">
<NButton :disabled="flow.writing.value" @click="flow.editorOpen.value = false">关闭</NButton>
<NButton
v-if="
hasRewriteTargets &&
flow.receipt.value?.confirmedEpisodes.length &&
!flow.receipt.value.finalized
"
:disabled="flow.writing.value || disabled"
@click="requestRewritePreview"
><template #icon><FileSearch :size="15" aria-hidden="true" /></template>查看改写范围</NButton
>
<WorkspaceRefreshButton
label="重新读取"
:loading="flow.query.loading.value"
:disabled="flow.writing.value"
@refresh="flow.query.refresh"
/>
<NButton
v-if="!latest?.passed"
type="primary"
:loading="flow.writing.value"
:disabled="!flow.canConfirm.value"
@click="flow.confirm"
>确认本次处理</NButton
>
</div>
</div>
</template>
</AppDrawer>
</template>
<style>
@reference "../../../styles/styles.css";
.drama-review-panel {
min-width: 0;
}
/* 审核入口文字在手机保留,限制操作组宽度后自动换行,避免按钮被裁切。 */
.drama-review-panel > .workspace-section-heading .workspace-section-heading-actions {
max-width: 100%;
}
/* 此抽屉由固定底栏提供上下留白,正文不再叠加底部内边距。 */
.review-confirm-drawer.app-drawer.n-drawer .n-drawer-content .n-drawer-body-content-wrapper {
padding-bottom: 0;
}
.review-editor-layout {
@apply grid min-w-0 items-start gap-8 lg:grid-cols-[minmax(0,1.2fr)_minmax(300px,1fr)];
}
.review-issues-scroll {
height: auto;
}
.review-issue-card {
@apply min-w-0;
padding: var(--app-content-gap);
background: var(--app-subtle);
}
.review-issue-card.review-issue-error {
background: var(--app-danger-soft);
}
.review-source-quote {
@apply whitespace-pre-wrap wrap-anywhere text-sm leading-7;
padding: var(--app-content-gap);
background: var(--app-control);
}
.review-source-pane {
@apply order-first grid min-w-0 gap-4 lg:sticky lg:top-0 lg:order-last;
}
.review-source-scroll {
height: min(42dvh, 380px);
background: var(--app-subtle);
}
.review-source-content {
@apply whitespace-pre-wrap wrap-anywhere text-sm leading-8;
padding: var(--app-content-gap);
}
.review-editor-footer {
@apply flex w-full flex-wrap items-center justify-between gap-4;
}
.review-confirm-ack {
@apply min-w-0 text-sm leading-6;
flex: 1 1 360px;
}
.review-editor-actions {
@apply ml-auto flex flex-wrap items-center justify-end gap-2;
}
@media (max-width: 1023px) {
/* 窄屏取消内层滚动,桌面继续使用 Naive 滚动容器自身的默认行为。 */
.review-issues-scroll,
.review-issues-scroll > .n-scrollbar-container {
height: auto;
overflow: visible;
}
}
@media (min-width: 1024px) {
/* 正文按抽屉实际剩余高度分配,两列各自滚动,不以视口比例截断原文。 */
.review-confirm-drawer.app-drawer.n-drawer .n-drawer-content .n-drawer-body-content-wrapper {
height: 100%;
}
.review-editor-content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.review-editor-content > :not(.review-editor-layout) {
flex-shrink: 0;
}
.review-editor-layout {
flex: 1;
min-height: 0;
align-items: stretch;
overflow: hidden;
}
.review-issues-scroll {
height: 100%;
min-height: 0;
}
.review-source-pane {
position: static;
height: 100%;
min-height: 0;
}
.review-source-pane > .n-collapse,
.review-source-pane > .n-collapse > .n-collapse-item {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.review-source-pane .n-collapse-item__header {
flex-shrink: 0;
}
.review-source-pane .n-collapse-item__content-wrapper {
flex: 1;
min-height: 0;
}
.review-source-pane .n-collapse-item__content-inner {
box-sizing: border-box;
height: 100%;
min-height: 0;
}
.review-source-fields {
height: 100%;
min-height: 0;
grid-template-rows: auto auto minmax(0, 1fr);
}
.review-source-scroll {
height: 100%;
min-height: 0;
}
}
</style>
@@ -0,0 +1,221 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox } from 'naive-ui'
import { FilePenLine } from '@lucide/vue'
import { AppDialog, WorkspaceRefreshButton, WorkspaceSectionHeading } from '../../../components/ui'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { useQuery } from '../../../composables/useQuery'
import { errorMessage } from '../../../lib/http'
import { projectsApi } from '../../projects/api'
import { getOperation, runOperation } from '../../workflows/operations'
import { useWorkflowExecution } from '../../workflows/execution'
import { loadDramaRewritePreview } from './api'
import { sameRewriteScope } from './model'
/** 复用同一个范围预检与费用确认流程的入口参数。 */
const props = withDefaults(
defineProps<{
/** 当前正式项目。 */ projectId: string
/** 外部读取失败或操作锁。 */ disabled?: boolean
/** 页面与任务弹窗可使用不同入口文案。 */ label?: string
/** 当前明确以改写预检为下一步时,入口使用主题主按钮。 */ primary?: boolean
}>(),
{ disabled: false, label: '改写预检', primary: false }
)
/** 后台已接受改写时通知上层刷新,不能将受理视为审核通过。 */
const emit = defineEmits<{ started: [executionId: string, projectId: string] }>()
/** 预检弹窗开关。 */
const open = ref(false)
/** 本次实际启动请求进行中,普通读取不锁定关闭。 */
const writing = ref(false)
/** 用户确认本次范围、费用及活动任务情况。 */
const acknowledged = ref(false)
/** 本次提交或来源变化的可读提示。 */
const actionError = ref('')
/** 项目级互斥与其它生成入口共享。 */
const operation = computed(() => getOperation(props.projectId))
/** 只在弹窗打开时读取预检。 */
const queryKey = computed(() => (open.value ? props.projectId : ''))
/** 项目布局负责观察任务,本入口只保存真实句柄,不额外轮询。 */
const trackerProject = ref('')
/** 复用原持久化句柄与活动锁写入能力。 */
const tracker = useWorkflowExecution(trackerProject, 'create-drama')
/** 切项目或离开后取消尚未提交的二次预检。 */
let revision = 0
/** 二次预检取消控制器,不取消已经受理的后台任务。 */
let controller: AbortController | undefined
onScopeDispose(() => {
revision++
controller?.abort()
})
/** 关闭、切换项目时取消预检,不能沿用旧费用确认。 */
const query = useQuery(queryKey, (id, signal) => (id ? loadDramaRewritePreview(id, signal) : Promise.resolve(null)))
watch([open, () => props.projectId], () => {
revision++
controller?.abort()
acknowledged.value = false
actionError.value = ''
})
watch(
() => query.data.value,
() => {
acknowledged.value = false
}
)
/** 只有服务端明确就绪且无读取错误时才允许开始。 */
const ready = computed(
() =>
query.data.value?.ready === true &&
query.data.value.status === 'ready' &&
!query.error.value &&
!query.loading.value
)
/** 服务端预检状态转换为可操作中文,保留真实状态作为判断来源。 */
const blockedReason = computed(() => {
if (query.error.value) return query.error.value
if (!query.data.value || ready.value) return ''
return query.data.value.status === 'stale'
? '审核与当前正文来源不一致,请先刷新审核记录。'
: query.data.value.status === 'blocked'
? '当前仍有剧本任务运行,请结束后再改写。'
: '当前审核没有可执行的改写目标,请先核对并处理审核问题。'
})
/** 从服务端范围生成说明,不自行扩展到整剧。 */
const scope = computed(() => {
const preview = query.data.value
if (!preview) return []
return [
preview.rewriteEpisodes ? `第 ${preview.episodeNumbers.join('、')} 集剧本` : '',
preview.rewriteCharacters ? '角色设定' : '',
preview.rewriteWorld ? '世界观' : ''
].filter(Boolean)
})
/** 当前确认操作是否允许提交。 */
const canSubmit = computed(
() => ready.value && acknowledged.value && !props.disabled && !operation.value.pending && !writing.value
)
/** 二次预检后才启动改写;范围变化或网络不确定时不自动重试。 */
async function confirm() {
if (!canSubmit.value || !query.data.value) return
const expected = query.data.value
const id = props.projectId
const version = revision
writing.value = true
actionError.value = ''
controller = new AbortController()
try {
await runOperation(
id,
'恢复剧本改写',
async () => {
const current = await loadDramaRewritePreview(id, controller!.signal)
if (version !== revision || props.projectId !== id) throw new Error('查看的项目已变化,请重新核对。')
if (!current.ready || current.status !== 'ready' || !sameRewriteScope(expected, current)) {
query.data.value = current
acknowledged.value = false
throw new Error('改写范围或保存记录已变化,请重新核对并确认。')
}
const started = await projectsApi.resume(id, 'resume-rewrite')
await tracker.track(started.executionId, id)
if (version === revision && props.projectId === id) {
emit('started', started.executionId, id)
open.value = false
}
return started
},
{ type: 'info', content: '改写任务已提交,请查看真实任务进度。' }
)
if (version === revision && props.projectId === id && getOperation(id).error)
actionError.value = getOperation(id).error
} catch (cause) {
if (version === revision && props.projectId === id) actionError.value = errorMessage(cause)
} finally {
writing.value = false
}
}
/** 用户主动打开范围预检,供审核抽屉离场后交接焦点。 */
function openPreview() {
if (!props.disabled && !operation.value.pending && !writing.value) open.value = true
}
/** 外层可在抽屉关闭动画结束后打开同一个只读预检。 */
defineExpose({ openPreview })
</script>
<template>
<span class="drama-rewrite-action">
<!-- 以下是只读预检入口,打开不会提交改写 -->
<NButton
:type="primary ? 'primary' : 'default'"
:disabled="disabled || operation.pending || writing"
:aria-label="label"
aria-haspopup="dialog"
:aria-expanded="open"
@click="openPreview"
>
<template #icon><FilePenLine :size="15" aria-hidden="true" /></template>{{ label }}
</NButton>
<AppDialog
v-model:open="open"
title="恢复改写"
description="先核对本次改写范围,确认费用后才会开始生成。"
:busy="writing"
:width="720"
>
<div class="grid gap-6">
<p v-if="query.loading.value" class="text-sm text-muted">正在检查改写范围…</p>
<ContextNotice v-if="blockedReason" type="warning" title="暂不能开始改写" emphasized>{{
blockedReason
}}</ContextNotice>
<!-- 以下是服务端明确返回的剧集与设定范围 -->
<section v-if="query.data.value">
<WorkspaceSectionHeading title="本次改写范围" />
<ul v-if="scope.length" class="mt-3 space-y-2 text-sm">
<li v-for="item in scope" :key="item">{{ item }}</li>
</ul>
<p v-else class="mt-3 text-sm text-muted">当前没有可执行的改写范围。</p>
</section>
<ContextNotice v-if="ready" type="info" title="本次操作会调用模型" emphasized
>只读检查不会产生生成费用。确认后将改写上述内容并重新审核,请勿重复提交。</ContextNotice
>
<NCheckbox
v-if="ready"
v-model:checked="acknowledged"
:disabled="writing || disabled || operation.pending"
:aria-disabled="writing || disabled || operation.pending"
aria-label="确认改写范围与费用"
>我已核对本次范围,确认当前没有同项目任务运行,并同意本次模型调用费用。</NCheckbox
>
<ContextNotice v-if="actionError" type="error" title="请核对操作状态" emphasized>{{
actionError
}}</ContextNotice>
</div>
<!-- 以下是固定取消、重读与明确确认操作 -->
<template #footer>
<div class="drama-rewrite-footer">
<NButton :disabled="writing" @click="open = false">取消</NButton>
<WorkspaceRefreshButton
label="重新检查"
:loading="query.loading.value"
:disabled="writing"
@refresh="query.refresh"
/>
<NButton type="primary" :loading="writing" :disabled="!canSubmit" @click="confirm"
>确认恢复改写</NButton
>
</div>
</template>
</AppDialog>
</span>
</template>
<style scoped>
@reference "../../../styles/styles.css";
.drama-rewrite-action {
@apply inline-flex;
}
.drama-rewrite-footer {
@apply flex w-full flex-wrap items-center justify-end gap-2;
}
</style>
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NButton, NFormItem, NInput, NSelect } from 'naive-ui'
import { Trash2 } from '@lucide/vue'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import WorkspaceActionTooltip from '../../../components/ui/WorkspaceActionTooltip.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { reviewCategoryOptions } from './model'
import type { DramaReviewPreview, ManualReviewDraft } from './types'
/** 人工补充表单只使用正式剧集和当前角色选项。 */
const props = defineProps<{
/** 表单行显示序号。 */ order: number
/** 当前正式正文。 */ episodes: DramaReviewPreview['episodes']
/** 当前正式角色名称。 */ characters: string[]
/** 读取或写入期间只读。 */ disabled: boolean
/** 用户尝试提交后才提供的错误。 */ error?: string
}>()
/** 尚未保存的证据草稿,确认前不转换为审核事实。 */
const draft = defineModel<ManualReviewDraft>({ required: true })
/** 删除只影响当前草稿。 */
const emit = defineEmits<{ remove: [] }>()
/** 集数选项直接来自预检,不伪造缺少的集号。 */
const episodeOptions = computed(() =>
props.episodes.map(episode => ({ label: `第 ${episode.episode} 集`, value: episode.episode }))
)
/** 角色名称来自正式项目,提交保留原值。 */
const characterOptions = computed(() => props.characters.map(name => ({ label: name, value: name })))
</script>
<template>
<!-- 以下是单条人工补充的标题与删除入口 -->
<section class="manual-review-editor">
<WorkspaceSectionHeading :title="`补充证据 ${order}`">
<template #actions>
<WorkspaceActionTooltip :label="`删除第 ${order} 条补充证据`">
<NButton
class="workspace-action-button icon-button"
:disabled="disabled"
:aria-label="`删除第 ${order} 条补充证据`"
@click="emit('remove')"
>
<template #icon><Trash2 :size="16" aria-hidden="true" /></template>
</NButton>
</WorkspaceActionTooltip>
</template>
</WorkspaceSectionHeading>
<!-- 以下是逐行填写的真实原文与错误说明,不自动把模型推断升级为事实 -->
<div class="mt-4 grid gap-4">
<NFormItem label="所属剧集" required
><NSelect
v-model:value="draft.episode"
:options="episodeOptions"
:disabled="disabled"
:aria-label="`补充证据 ${order} 所属剧集`"
/></NFormItem>
<NFormItem label="问题分类" required
><NSelect
v-model:value="draft.category"
:options="reviewCategoryOptions"
:disabled="disabled"
:aria-label="`补充证据 ${order} 问题分类`"
/></NFormItem>
<NFormItem label="问题名称" required
><NInput
v-model:value="draft.code"
:disabled="disabled"
placeholder="例如:坠落前缺少支撑变化"
:input-props="{ 'aria-label': `补充证据 ${order} 问题名称` }"
/></NFormItem>
<NFormItem label="引用原文" required
><NInput
v-model:value="draft.sourceQuote"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
:disabled="disabled"
placeholder="粘贴所选剧集中的逐字原文,不能填写事件编号或自行改写的内容"
:input-props="{ 'aria-label': `补充证据 ${order} 引用原文` }"
/></NFormItem>
<NFormItem label="问题说明" required
><NInput
v-model:value="draft.message"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="disabled"
:input-props="{ 'aria-label': `补充证据 ${order} 问题说明` }"
/></NFormItem>
<NFormItem label="修改建议" required
><NInput
v-model:value="draft.suggestion"
type="textarea"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="disabled"
:input-props="{ 'aria-label': `补充证据 ${order} 修改建议` }"
/></NFormItem>
<NFormItem label="涉及角色(可选)"
><NSelect
:value="draft.subjectRef || null"
:options="characterOptions"
clearable
:disabled="disabled"
:aria-label="`补充证据 ${order} 涉及角色`"
@update:value="draft.subjectRef = $event ?? ''"
/></NFormItem>
</div>
<ContextNotice v-if="error" type="error" title="请核对这条补充证据" emphasized>{{ error }}</ContextNotice>
</section>
</template>
<style scoped>
@reference "../../../styles/styles.css";
.manual-review-editor {
@apply min-w-0;
}
</style>
@@ -0,0 +1,186 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NButton, NForm, NFormItem, NInput, NRadio, NRadioGroup, NSelect, NTag } from 'naive-ui'
import { FileSearch, PencilLine } from '@lucide/vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { uncertaintyAcceptable, type IndexedReviewUncertainty } from './model'
import type {
DeferredUncertaintyDraft,
DramaReviewPreview,
ReviewResolutionSuggestion,
UncertaintyDisposition
} from './types'
/** 每项人工处理始终绑定原审核索引,推荐内容仅供用户核对。 */
const props = defineProps<{
/** 原始不确定项。 */ row: IndexedReviewUncertainty
/** 当前版本的建议,缺失时不补造。 */ suggestion: ReviewResolutionSuggestion | null
/** 正式剧集列表。 */ episodes: DramaReviewPreview['episodes']
/** 用户已明确选择接受。 */ accepted: boolean
/** 用户已明确选择延期后创建的表单。 */ deferred?: DeferredUncertaintyDraft
/** 当前禁止编辑。 */ locked: boolean
/** 提交后才显示的字段错误。 */ error?: string
}>()
/** 显式处理选择、只读定位与补充证据交给统一流程。 */
const emit = defineEmits<{
/** 用户选择处理方式。 */ action: [action: UncertaintyDisposition]
/** 用户修改延期字段。 */ 'update:deferred': [draft: DeferredUncertaintyDraft]
/** 查看单集或主动选择多集原文。 */ view: [episode: number | null]
/** 补充经原文核实的改写证据。 */ evidence: []
}>()
/** 选择来源仅为用户操作,不由推荐方式推断。 */
const disposition = computed<UncertaintyDisposition>(() =>
props.deferred ? 'defer' : props.accepted ? 'accept' : 'pending'
)
/** 无法核实的原文或格式异常不能直接接受或延期。 */
const unavailable = computed(() => props.locked || !uncertaintyAcceptable(props.row.text))
/** 候选剧集优先排列,其余真实剧集仍可选择。 */
const episodeOptions = computed(() => {
const candidates = props.suggestion?.episodeCandidates ?? []
return props.episodes
.toSorted(
(a, b) =>
Number(candidates.includes(b.episode)) - Number(candidates.includes(a.episode)) || a.episode - b.episode
)
.map(item => ({
label: `第 ${item.episode} 集${candidates.includes(item.episode) ? '(建议)' : ''}`,
value: item.episode
}))
})
/** 建议涉及多集时展示全部候选,不擅自绑定其中一集。 */
const candidateLabel = computed(() =>
props.suggestion?.episodeCandidates.length
? `第 ${props.suggestion.episodeCandidates.join('、')} 集`
: '需对照正式正文确认'
)
/** 后端置信度只展示为中性说明,不代表核对通过。 */
const confidenceLabel = computed(() =>
props.suggestion?.confidence === 'high'
? '依据较明确'
: props.suggestion?.confidence === 'low'
? '依据有限,需人工核对'
: '尚无明确对应,需人工核对'
)
/** 只提交真实验证阶段枚举。 */
const targetOptions = [
{ label: '拆解阶段', value: 'breakdown' },
{ label: '分镜阶段', value: 'storyboard' }
]
/**
* 修改已有延期草稿,不通过渲染建议创建处理决定。
* @param patch 用户修改的字段
*/
function updateDeferred(patch: Partial<DeferredUncertaintyDraft>) {
if (props.deferred && !props.locked) emit('update:deferred', { ...props.deferred, ...patch })
}
/** 原文定位只使用已选择的集号或唯一明确建议,多集时留给用户选择。 */
function viewSource() {
const episode =
props.deferred?.episode ??
(props.suggestion?.confidence === 'high' && !props.suggestion.requiresEpisodeSelection
? props.suggestion.episode
: null)
emit('view', episode ?? null)
}
</script>
<template>
<article class="review-issue-card grid gap-5" :data-review-uncertainty="row.originalIndex">
<!-- 以下是问题、推荐原因及来源范围,推荐不等于已确认 -->
<div class="grid gap-3">
<div class="flex flex-wrap items-center gap-3">
<h4 class="text-sm font-semibold">问题 {{ row.originalIndex + 1 }}</h4>
<NTag :bordered="false" size="small">{{
suggestion
? suggestion.suggestedAction === 'defer'
? '建议延期验证'
: '建议人工核对'
: '尚无处理建议'
}}</NTag>
</div>
<p class="text-sm leading-7">{{ row.text }}</p>
<p v-if="suggestion?.reason" class="text-xs leading-6 text-muted">推荐原因:{{ suggestion.reason }}</p>
<div class="grid gap-2 text-xs leading-6 text-muted">
<div>涉及剧集:{{ candidateLabel }}</div>
<div v-if="suggestion">建议依据:{{ confidenceLabel }}</div>
<div v-if="suggestion?.verificationTarget">
验证阶段:{{ suggestion.verificationTarget === 'breakdown' ? '拆解' : '分镜' }}
</div>
<div v-if="suggestion?.verificationCriteria">验证标准:{{ suggestion.verificationCriteria }}</div>
</div>
<div class="workspace-action-group flex-wrap">
<NButton class="workspace-action-button" @click="viewSource"
><template #icon><FileSearch :size="15" aria-hidden="true" /></template>查看相关原文</NButton
>
<NButton class="workspace-action-button" :disabled="locked" @click="emit('evidence')"
><template #icon><PencilLine :size="15" aria-hidden="true" /></template>补充改写证据</NButton
>
</div>
</div>
<!-- 以下是人工选择,所有项目初始均为保留待处理 -->
<NRadioGroup
:value="disposition"
:disabled="locked"
:name="`uncertainty-${row.originalIndex}`"
:aria-label="`问题 ${row.originalIndex + 1} 处理方式`"
@update:value="emit('action', $event as UncertaintyDisposition)"
>
<div class="grid gap-3">
<NRadio value="pending" data-resolution-action="pending">保留待处理</NRadio>
<NRadio value="accept" data-resolution-action="accept" :disabled="unavailable"
>接受为合理创作安排</NRadio
>
<NRadio value="defer" data-resolution-action="defer" :disabled="unavailable"
>延期验证<span v-if="suggestion?.suggestedAction === 'defer'" class="ml-2 text-xs text-muted"
>(建议)</span
></NRadio
>
</div>
</NRadioGroup>
<p v-if="!uncertaintyAcceptable(row.text)" class="text-xs text-muted">
此项需要补充真实原文证据,不能直接接受或延期。
</p>
<!-- 以下是用户选择延期后展开的可编辑验证要求 -->
<NForm v-if="deferred" label-placement="top" :show-feedback="false" class="grid gap-5" @submit.prevent>
<p
v-if="suggestion?.requiresEpisodeSelection || suggestion?.confidence !== 'high'"
class="text-xs leading-6 text-muted"
>
请明确选择负责验证的剧集;建议候选之外的正式剧集也可选择。
</p>
<NFormItem label="负责验证的剧集" required>
<NSelect
:value="deferred.episode"
:options="episodeOptions"
:disabled="locked"
placeholder="请选择正式剧集"
:aria-label="`问题 ${row.originalIndex + 1} 负责验证的剧集`"
@update:value="updateDeferred({ episode: $event })"
/>
</NFormItem>
<NFormItem label="验证阶段" required>
<NSelect
:value="deferred.verificationTarget"
:options="targetOptions"
:disabled="locked"
:aria-label="`问题 ${row.originalIndex + 1} 验证阶段`"
@update:value="updateDeferred({ verificationTarget: $event })"
/>
</NFormItem>
<NFormItem label="验证标准" required>
<NInput
:value="deferred.verificationCriteria"
type="textarea"
:maxlength="2000"
:autosize="{ minRows: 3, maxRows: 8 }"
:disabled="locked"
:input-props="{ 'aria-label': `问题 ${row.originalIndex + 1} 验证标准` }"
@update:value="updateDeferred({ verificationCriteria: $event })"
/>
</NFormItem>
<ContextNotice v-if="error" type="error" title="请完善延期验证">{{ error }}</ContextNotice>
</NForm>
</article>
</template>
+200
View File
@@ -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<LatestDramaReview>(`/projects/${encodeURIComponent(id)}/reviews/latest`, { signal })),
/**
* 读取人工确认来源、稳定索引、当前剩余项与正式正文。
* @param id 正式项目编号
* @param signal 取消旧查询
* @returns 只读确认预检
*/
preview: (id: string, signal?: AbortSignal) =>
request<DramaReviewPreview>(`/projects/${encodeURIComponent(id)}/reviews/confirm-issues/preview`, { signal }),
/**
* 保存明确确认的人工裁决,不能以请求成功代替审核通过。
* @param id 正式项目编号
* @param input 用户核对的裁决
* @returns 本次裁决回执
*/
confirm: (id: string, input: ConfirmDramaIssuesInput) =>
request<ConfirmDramaIssuesResult>(`/projects/${encodeURIComponent(id)}/reviews/confirm-issues`, {
method: 'POST',
body: input
}),
/**
* 只读查询当前改写范围,不创建任务。
* @param id 正式项目编号
* @param signal 取消旧查询
* @returns 真实改写预检
*/
rewritePreview: (id: string, signal?: AbortSignal) =>
request<DramaRewritePreview>(`/projects/${encodeURIComponent(id)}/resume-rewrite/preview`, { signal })
}
/**
* 读取并校验真实改写预检,角色、世界观和剧集范围均由服务端提供。
* @param id 正式项目编号
* @param signal 取消旧读取
* @returns 已核对归属与结构的改写预检
*/
export async function loadDramaRewritePreview(id: string, signal?: AbortSignal): Promise<DramaRewritePreview> {
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<DramaReviewSnapshot> {
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) }
}
}
+248
View File
@@ -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 ''
}
+186
View File
@@ -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[]
}
@@ -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<string>,
changed: () => Promise<void>,
disabled: Ref<boolean> = 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<ConfirmDramaIssuesResult | null>(null)
/** 原始待确认列表中的错误索引。 */
const selectedErrors = ref<number[]>([])
/** 原始待确认列表中的警告索引。 */
const selectedWarnings = ref<number[]>([])
/** 原始不确定项数组索引。 */
const selectedUncertainty = ref<number[]>([])
/** 用户主动选择的延期草稿;读取建议不会新增任何条目。 */
const deferredDrafts = ref<Record<number, DeferredUncertaintyDraft>>({})
/** 来源变化后保留的只读草稿,不能直接套用到新审核。 */
const preservedDraft = ref<ReviewDraftBackup | null>(null)
/** 字段验证反馈复用应用 NMessage,不重复发送后台错误通知。 */
const message = useActionMessage()
/** 用户补充的原文证据草稿。 */
const manualDrafts = ref<ManualReviewDraft[]>([])
/** 项目级活动锁与其它生成入口保持一致。 */
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<Record<number, string>>(() =>
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<typeof query.data.value>['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
}
}