feat(short-drama-agent-front): 完善质量规则确认与中文交互

This commit is contained in:
GJ committed 2026-10-17 22:09:28 +08:00
1 parent 190333d4f9
commit c4b43b9725
85 files changed
+2059 -480

No files matched your search

+11
View File
@@ -33,6 +33,15 @@
- 维持项目现有简洁、扁平的视觉风格。用标题、简短说明、留白和对齐区分普通功能区域,避免无意义的底色、边框和装饰线。
- 页面文案保持精简,说明应帮助用户理解当前操作;不把大量错误、技术细节和重复提示堆在设置页面。
### 面向普通用户的文案
- 默认使用者不了解软件开发。页面、弹窗、按钮、说明、校验、空状态和错误提示不得直接描述“前端做什么”“后端做什么”,应说明当前结果、影响和下一步操作。
- 英文技术术语优先改成易懂的中文,例如 `Checkpoint` 用“保存记录”、`Storyboard` 用“分镜”、`Prompt` 用“画面描述”或“提示词”、`Thinking` 用“深度思考”。不要把内部字段名、错误码、任务标识直接作为主要说明。
- 接口返回的系统提示也需要在展示层转换为可读中文;错误详情只提取有助于操作的业务原因,不把调试对象、堆栈或整段原始数据直接输出给用户。原始错误和错误码保留在数据层,不改动业务判断依据。
- 只调整展示文案,不翻译或改写请求字段、枚举值、接口地址、用户创作的剧本与提示词正文、文件名、自定义名称或模型品牌。分类等内部值使用中文选项展示,提交仍保留真实取值。
- 费用、覆盖、删除、适用范围与待审核限制必须保留并说清楚,不能为了简化文字改变功能含义。无法确认的能力不要用容易误解的描述代替。
- 必要的原始技术数据放在默认收起的“高级详情”或导出结果中,日常操作先展示中文摘要。同一弹窗的操作统一放入公共 `footer`,避免正文操作与默认关闭按钮重复。
### 全屏抽屉与关闭入口
- 新建剧本、项目全局配置、拆解设置、拆解问题等已确认使用全屏的界面统一复用 `AppDrawer`。后续同类复杂表单、设置和问题处理界面默认沿用全屏抽屉;简短确认或轻量提示仍可使用 `AppDialog`。
@@ -65,6 +74,8 @@
### 设置、问题处理与任务进度
- 拆解设置与问题处理分开:设置界面负责模块选择、分组预览、启动拆解、候选确认与提交;问题界面负责错误查看、分镜定位、人工修订、读取修复清单及阶段恢复。
- 首次拆解前只确认表现方式、动作许可和自定义规则,不显示精确动作例外的空白编辑行。已有例外可只读核对,隐藏输入不能清空已有规则或在保存时覆盖后来新增的例外。
- 新增精确动作例外统一放在拆解后的问题修订中,从当前版本的真实冲突证据自动带入角色、部位或物品及动作,用户填写允许原因。证据缺失时不能猜测或用其他镜头代替;按后端实际范围说明影响,保存例外不能直接标记质量通过。
- 不在拆解设置中重复堆放详细错误列表和修复说明;问题按剧集、节拍、镜头分组并去重,保留后端原始问题及可定位位置。
- 从问题界面定位正文时,先关闭抽屉,等离场和焦点约束释放后再定位,不能同时叠加两个主界面。
- 后端从其他入口启动或重新执行任务时,前端也应发现任务并显示真实运行阶段、进度、作用范围及更新时间;重新进入页面后能够恢复观察,不能只依赖前端本次点击形成的加载状态。
+1 -1
View File
@@ -273,7 +273,7 @@ const menuOptions = computed<MenuOption[]>(() => {
</div>
<AppDialog v-model:open="settingsOpen" title="连接设置" description="查看当前服务地址。">
<dl class="detail-grid mt-6">
<dt>API 地址</dt>
<dt>服务地址</dt>
<dd>
<code>{{ apiBase }}</code>
</dd>
+1
View File
@@ -161,6 +161,7 @@ onBeforeUnmount(() => {
.app-dialog .dialog-footer {
@apply flex justify-end gap-2;
width: 100%;
align-items: center;
padding-top: 0;
}
+4 -3
View File
@@ -3,6 +3,7 @@ import { ref } from 'vue'
import { NPopover } from 'naive-ui'
import type { PopoverProps } from 'naive-ui'
import { CircleHelp } from '@lucide/vue'
import { userFacingText } from '../../lib/user-facing-text'
/** 字段标签与按需打开的说明,适用于项目配置和各类生成表单。 */
withDefaults(
@@ -23,14 +24,14 @@ const open = ref(false)
<template>
<!-- 以下是字段标签与说明提示模块 -->
<span class="inline-flex min-w-0 items-center gap-1.5">
<span>{{ label }}</span>
<span>{{ userFacingText(label, label) }}</span>
<!-- 浮层挂到视口层,按字段指定位置并自动翻转,避免被弹窗滚动容器裁剪。 -->
<NPopover v-if="description" v-model:show="open" trigger="click" :placement="placement" :to="true" :flip="true">
<template #trigger>
<button
type="button"
class="inline-flex size-4 shrink-0 items-center justify-center text-muted hover:text-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current"
:aria-label="`${label}说明`"
:aria-label="`${userFacingText(label, label)}说明`"
:aria-expanded="open"
@click.stop
>
@@ -38,7 +39,7 @@ const open = ref(false)
</button>
</template>
<div class="max-w-[min(360px,calc(100vw-48px))] whitespace-pre-wrap break-words text-xs leading-5">
{{ description }}
{{ userFacingText(description) }}
</div>
</NPopover>
</span>
+2 -1
View File
@@ -2,6 +2,7 @@
import { h } from 'vue'
import { NButton } from 'naive-ui'
import { useActionMessage } from './useActionMessage'
import { userFacingText } from '../../lib/user-facing-text'
/** 问题说明按需查看,页面不长期堆叠错误段落。 */
const props = withDefaults(
@@ -22,7 +23,7 @@ const message = useActionMessage()
/** 点击后展示去重问题,不重新请求或生成内容。 */
function showReasons() {
const content = [...new Set(props.messages.map(item => item.trim()).filter(Boolean))].join(';')
const content = [...new Set(props.messages.map(item => userFacingText(item)).filter(Boolean))].join(';')
if (content)
message?.[props.type](() => h('div', { class: 'max-w-[min(600px,calc(100vw-48px))] break-words' }, content), {
duration: 7000,
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { NCollapse, NCollapseItem } from 'naive-ui'
/** 原始诊断与生成参数仅供高级核对,默认收起,不替代普通用户的中文摘要。 */
withDefaults(defineProps<{
/** 原始数据保持不变,便于核对技术问题。 */
value: unknown
/** 中文高级入口名称。 */
title?: string
}>(), { title: '高级详情(原始数据)' })
</script>
<template>
<!-- 以下是默认收起的高级数据模块,统一使用 Naive 折叠组件 -->
<NCollapse class="mt-3"><NCollapseItem name="raw-data" :title="title"><pre class="whitespace-pre-wrap break-words text-xs leading-6">{{ JSON.stringify(value, null, 2) }}</pre></NCollapseItem></NCollapse>
</template>
+5
View File
@@ -21,6 +21,8 @@ withDefaults(
pending?: boolean
/** 在操作入口原位置展示真实任务名称。 */
pendingLabel?: string
/** 真实提交期间锁定关闭,普通只读加载不锁定。 */
busy?: boolean
}>(),
{
label: '操作与回执',
@@ -57,11 +59,14 @@ const emit = defineEmits<{ closed: [] }>()
:is="fullscreen ? AppDrawer : AppDialog"
v-model:open="open"
:title="title"
:busy="busy"
description=""
v-bind="fullscreen ? {} : { wide: true }"
@closed="emit('closed')"
>
<div class="workspace-tools-body"><slot /></div>
<!-- 以下是业务确认操作底栏;未提供时保留公共容器的灰色关闭按钮 -->
<template v-if="$slots.footer" #footer><slot name="footer" /></template>
</component>
</template>
+2
View File
@@ -1,5 +1,6 @@
import { hasInjectionContext, inject, type InjectionKey } from 'vue'
import type { MessageApi } from 'naive-ui'
import { userFacingText } from '../../lib/user-facing-text'
/** 页面操作结果共用的 Naive Message 实例。 */
export const actionMessageKey: InjectionKey<MessageApi> = Symbol('action-message')
@@ -18,6 +19,7 @@ export function showActionFeedback(
type: 'success' | 'error' | 'warning' | 'info'
) {
if (!message || !content.trim()) return
content = userFacingText(content)
const history = recentMessages.get(message) ?? new Map<string, number>()
const now = Date.now()
const key = `${type}:${content}`
+112 -22
View File
@@ -7,8 +7,9 @@ import WorkspaceExportButton from '../../components/ui/WorkspaceExportButton.vue
import { NScrollbar, NButton, NCheckbox, NCollapse, NCollapseItem, NInputNumber, NTab, NTable, NTabs } from 'naive-ui'
import { computed, h, nextTick, onScopeDispose, ref, watch } from 'vue'
import { useActionMessage } from '../../components/ui/useActionMessage'
import { CircleAlert, Layers, LoaderCircle, Settings2 } from '@lucide/vue'
import { EmptyState, StatusBadge, WorkspaceTools } from '../../components/ui'
import { CircleAlert, Layers, LoaderCircle, Settings2, ShieldCheck } from '@lucide/vue'
import { AppDialog, EmptyState, StatusBadge, WorkspaceTools } from '../../components/ui'
import QualityPolicySettings from '../generation-config/components/QualityPolicySettings.vue'
import { useProjectContext } from '../projects/context'
import { breakdownApi } from './api'
import type { BreakdownAction, BreakdownInput, BreakdownModule, BreakdownPreview, ShotValidation } from './types'
@@ -24,7 +25,9 @@ import BreakdownCandidatePanel from './components/BreakdownCandidatePanel.vue'
import StoryboardQualityRepair from './components/StoryboardQualityRepair.vue'
import BreakdownIssuesDialog from './components/BreakdownIssuesDialog.vue'
import CandidateRepairs from './components/CandidateRepairs.vue'
import ActionExceptionRepair from './components/ActionExceptionRepair.vue'
import { useBreakdownQuality } from './useBreakdownQuality'
import { useBreakdownStartPolicy } from './useBreakdownStartPolicy'
import type { DiagnosisLocation } from './diagnosis'
import { errorMessage } from '../../lib/http'
import { downloadText } from '../../lib/format'
@@ -41,6 +44,8 @@ const tab = ref('character')
const toolsOpen = ref(false)
/** 问题查看、人工修订和阶段恢复共用独立窗口。 */
const issuesOpen = ref(false)
/** 动作例外真实写入期间锁定问题抽屉的关闭,普通查询不锁定。 */
const exceptionSaving = ref(false)
/** 从设置切换时等待关闭动画结束,避免两层弹窗同时显示。 */
const pendingIssues = ref(false)
/** 问题入口统一使用红色文字、图标和柔和底色,交互时保持错误语义。 */
@@ -343,6 +348,42 @@ const canStart = computed(
!error.value &&
(!records.value.length || taskStopped.value)
)
/** 质量确认始终绑定本次真实预览输入,修改设置后立即撤销未完成启动。 */
const startScope = computed(() => JSON.stringify(input.value))
/** 首次及规则变化时确认,已确认的相同内容不重复弹出规则表单。 */
const startPolicy = useBreakdownStartPolicy(projectId, startScope, canStart)
/** 复用全局质量表单的完整校验和独立草稿。 */
const qualityForm = ref<InstanceType<typeof QualityPolicySettings> | null>(null)
/** 仅由用户明确勾选形成规则确认,不能把默认配置当作已确认。 */
const rulesAcknowledged = ref(false)
/** 每次真实模型启动仍需核对后台任务是否停止。 */
const startAcknowledged = ref(false)
/** 规则、目标或步骤变化后重新确认,不沿用旧勾选。 */
watch([startPolicy.reviewOpen, startPolicy.editorKey, startScope], () => { rulesAcknowledged.value = false })
watch(startPolicy.startOpen, () => { startAcknowledged.value = false })
/** 关闭整个设置时中断只读确认,不能在关闭后打开迟到的弹窗。 */
watch(toolsOpen, shown => { if (!shown) startPolicy.cancel() }, { flush: 'sync' })
/** 校验用户编辑的规则,成功后进入普通启动确认;此步骤不运行模型。 */
async function confirmStartRules() {
if (!rulesAcknowledged.value) return
const draft = qualityForm.value?.validatedDraft()
if (draft) await startPolicy.confirmRules(draft)
}
/** 最终确认费用与任务范围后重新读取规则,再消费本次启动许可。 */
async function confirmStart() {
if (records.value.length > 0 && !startAcknowledged.value) return
if (await startPolicy.verifyStart()) await run('start')
}
/**
* 普通启动弹窗只读核对期间仍允许用户取消。
* @param shown 弹窗目标显隐状态
*/
function updateStartOpen(shown: boolean) {
if (!shown) startPolicy.cancel()
}
let previewController: AbortController | undefined
let previewVersion = 0
@@ -395,7 +436,7 @@ async function loadPreview() {
async function run(action: BreakdownAction) {
if (project.value?.status !== 'completed' || operation.value.pending || error.value) return
if (breakdownBusy.value || backgroundExecution.discovering.value || backgroundExecution.discoveryError.value) return
if (action === 'start' && !canStart.value) return
if (action === 'start' && (!canStart.value || !startPolicy.consumePermit())) return
const labels: Record<BreakdownAction, string> = {
start: '正在拆解剧本',
retry: '正在重试失败抽取',
@@ -477,12 +518,29 @@ const rules = {
:pending="operation.pending"
:pending-label="operation.label"
v-model:open="toolsOpen"
title="拆解设置"
:title="startPolicy.reviewOpen.value ? '拆解前确认质量规则' : '拆解设置'"
label="拆解设置"
:busy="startPolicy.saving.value"
fullscreen
@closed="finishOpeningIssues"
>
<section class="panel workspace-panel breakdown-settings-panel">
<!-- 以下是在同一全屏抽屉内核对真实质量规则的模块,不叠加第二个抽屉 -->
<div v-if="startPolicy.reviewOpen.value && startPolicy.policy.value" class="breakdown-policy-review">
<p class="text-sm leading-6 text-muted">请核对动作与物理规则,修改将在继续时保存。当前浏览器会记住确认,规则未变时不再重复提醒。</p>
<QualityPolicySettings
ref="qualityForm"
:key="startPolicy.editorKey.value"
:project-id="projectId"
:initial-policy="startPolicy.policy.value"
:disabled="!canStart || startPolicy.busy.value"
/>
<NCheckbox v-model:checked="rulesAcknowledged" :disabled="startPolicy.busy.value || !canStart" class="mt-5">
我已核对本次拆解使用的质量规则
</NCheckbox>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
</div>
<!-- 以下是拆解分组设置模块,规则确认时保留已有预览和草稿 -->
<section v-show="!startPolicy.reviewOpen.value" class="panel workspace-panel breakdown-settings-panel">
<p
v-if="backgroundExecution.discoveryError.value"
class="mb-4 text-xs leading-6 text-danger"
@@ -583,22 +641,16 @@ const rules = {
<span class="mx-2 text-faint">/</span>
<strong>{{ preview.estimatedTaskCount }}</strong> 个抽取任务
</p>
<ConfirmAction
<NButton
:loading="
startPolicy.reading.value ||
isOperationRunning(operation, '正在拆解剧本') ||
backgroundExecution.active.value
"
:label="candidateOnly ? '生成拆解候选' : '开始拆解'"
:description="
candidateOnly
? '将按当前分组调用模型生成主体、形态与分镜候选,可能产生模型费用。现有正式数据会保留,候选需经独立确认后才提交。'
: '将按当前预览配置启动完整的 剧本拆解流程。抽取结束后仍需完成主体整理、分镜生成与入库。'
"
:acknowledgement="records.length > 0"
primary
:disabled="!canStart"
@confirm="run('start')"
/>
type="primary"
:disabled="!canStart || startPolicy.busy.value"
@click="startPolicy.prepare"
><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>{{ candidateOnly ? '生成拆解候选' : '开始拆解' }}</NButton>
</div>
<div class="flex flex-wrap gap-2">
<div v-for="group in preview.groups" :key="group.groupId" class="group-chip">
@@ -607,6 +659,7 @@ const rules = {
</div>
</div>
</div>
<p v-if="startPolicy.error.value && !startPolicy.startOpen.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
<p v-if="project.status === 'generating'" class="mt-4 text-xs text-danger">
剧本仍在生成,暂不允许启动拆解,避免读取到不完整的剧集。
</p>
@@ -618,6 +671,7 @@ const rules = {
</p>
</section>
<BreakdownCandidatePanel
v-show="!startPolicy.reviewOpen.value"
:project-id="projectId"
:state="qualityObservation.source.value.state || undefined"
:quality="quality"
@@ -626,7 +680,7 @@ const rules = {
@refresh="refreshCandidate"
/>
<!-- 以下是明确标记的历史执行回执,旧任务结论不表示当前候选质量 -->
<component :is="executionHistorical ? NCollapse : 'div'" v-if="backgroundExecution.executionId.value" :class="{ 'breakdown-execution-history': executionHistorical }">
<component :is="executionHistorical ? NCollapse : 'div'" v-if="backgroundExecution.executionId.value" v-show="!startPolicy.reviewOpen.value" :class="{ 'breakdown-execution-history': executionHistorical }">
<component :is="executionHistorical ? NCollapseItem : 'div'" :name="executionHistorical ? 'history' : undefined" :title="executionHistorical ? '历史拆解执行记录(不代表当前质量)' : undefined">
<WorkflowExecutionPanel
v-if="backgroundExecution.executionId.value"
@@ -641,14 +695,34 @@ const rules = {
/>
</component>
</component>
<!-- 以下是固定的规则确认底栏,返回不记录确认,继续不会直接调用模型 -->
<template v-if="startPolicy.reviewOpen.value" #footer>
<NButton :disabled="startPolicy.saving.value" @click="startPolicy.cancel">取消</NButton>
<NButton type="primary" :loading="startPolicy.busy.value" :disabled="!rulesAcknowledged || !qualityForm?.canSave || startPolicy.busy.value || !canStart" @click="confirmStartRules"><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>确认规则并继续</NButton>
</template>
</WorkspaceTools>
<!-- 以下是每次真实模型调用前的费用与任务确认,规则未变时直接进入此步骤 -->
<AppDialog
:open="startPolicy.startOpen.value"
:title="candidateOnly ? '生成拆解候选' : '开始拆解'"
:description="candidateOnly ? '将按当前分组调用模型生成主体、形态与分镜候选,可能产生模型费用。现有正式数据会保留,候选需经独立确认后才提交。' : '将按当前预览启动完整拆解并调用模型,可能产生模型费用。抽取结束后仍需完成主体整理、分镜生成与入库。'"
:busy="operation.pending"
@update:open="updateStartOpen"
>
<NCheckbox v-if="records.length > 0" v-model:checked="startAcknowledged" :disabled="startPolicy.busy.value">我已确认后台任务停止,当前没有同项目的生成或拆解任务在运行。</NCheckbox>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
<template #footer>
<NButton :disabled="operation.pending" @click="startPolicy.cancel">取消</NButton>
<NButton type="primary" :loading="startPolicy.reading.value" :disabled="!canStart || startPolicy.busy.value || (records.length > 0 && !startAcknowledged)" @click="confirmStart"><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>确认{{ candidateOnly ? '生成拆解候选' : '开始拆解' }}</NButton>
</template>
</AppDialog>
</div>
</div>
</template>
<NScrollbar v-if="!project?.episodes.length" class="panel-scroll panel">
<EmptyState
title="还没有可拆解的剧集"
description="先完成剧本创作。拆解会读取数据库中的正式剧集,不需要上传 checkpoint。"
description="先完成剧本创作。拆解会使用已保存的正式剧集,无需重新上传。"
/>
</NScrollbar>
<template v-else>
@@ -799,6 +873,7 @@ const rules = {
v-model:open="issuesOpen"
:issues="storyboardIssues"
:quality="quality"
:busy="exceptionSaving"
:workflow-error="currentWorkflowError"
:locatable="!breakdownBusy && !!shots.length"
@locate="locateIssue"
@@ -816,6 +891,17 @@ const rules = {
>
任务状态或结果尚未确认,请先重新读取状态与结果。
</p>
<!-- 以下是从当前动作冲突带入角色和动作的例外入口,独立保存规则且保留旧例外 -->
<ActionExceptionRepair
v-if="issuesOpen && qualityObservation.source.value.state && quality.source !== 'history' && quality.actionBlocks.some(block => [...block.blockingCodes, ...block.warningCodes].includes('action_resource_conflict'))"
:project-id="projectId"
:checkpoint-id="latestCheckpoint?.checkpointId || ''"
:state="qualityObservation.source.value.state"
:quality="quality"
:disabled="issueActionsDisabled"
@busy="exceptionSaving = $event"
@refresh="refreshCandidate"
/>
<CandidateRepairs
v-if="issuesOpen && quality.isCandidate && snapshot"
:project-id="projectId"
@@ -840,21 +926,21 @@ const rules = {
<ConfirmAction
:loading="isOperationRunning(operation, '正在重试失败抽取')"
label="重试失败抽取"
description="只重试 character / scene / prop 抽取任务中的失败项。不能用于镜头阶段失败。"
description="只重新提取失败的人物、场景或道具,不重做已完成内容。镜头问题请使用对应修复操作。"
acknowledgement
:disabled="issueActionsDisabled || !recovery.retry"
@confirm="run('retry')"
/><ConfirmAction
:loading="isOperationRunning(operation, '正在补齐镜头')"
label="补齐缺失镜头"
description="复用已完成剧集的镜头,仅生成尚未完成的 Episode Shot,再进行校验与入库。"
description="保留已经完成的镜头,只补齐缺失的镜头,然后检查并保存。"
acknowledgement
:disabled="issueActionsDisabled || !recovery.shots"
@confirm="run('resume-shots')"
/><ConfirmAction
:loading="isOperationRunning(operation, '正在修复分镜绑定')"
label="修复分镜绑定"
description="复用已有镜头,修复 SubjectRef 与视觉 Form 绑定,再校验并保存。"
description="保留已有镜头,补齐人物、场景、道具及其形态的对应关系,然后检查并保存。"
acknowledgement
:disabled="issueActionsDisabled || !recovery.storyboard"
@confirm="run('resume-storyboard')"
@@ -891,6 +977,10 @@ const rules = {
.breakdown-settings-panel {
container: breakdown-settings / inline-size;
}
/* 同一抽屉切换步骤时首个可见模块不继承隐藏设置区域的兄弟间距。 */
.workspace-tools-body > .breakdown-policy-review + .breakdown-settings-panel {
margin-top: 0;
}
/* 说明与表单留出 16px,避免移除来源标签后紧贴首个字段。 */
.breakdown-settings-form {
margin-top: 16px;
@@ -0,0 +1,66 @@
import type { ActionResource } from '../projects/types'
import { actionResourceOptions } from '../projects/quality-policy'
import type { BreakdownState } from './types'
import type { BreakdownQuality } from './quality'
import type { CandidateShotLocation } from './candidate.types'
/** 从当前镜头真实占用证据带入的例外目标,不将自由文本当作角色或动作编号。 */
export interface ActionExceptionTarget extends CandidateShotLocation {
/** 镜头、阶段、主体与部位组成的稳定标识。 */
key: string
/** 实际冲突发生的阶段。 */
phaseNo: number
/** 当前镜头标题。 */
shotTitle: string
/** 后端镜头已有的主体引用。 */
ownerRef: string
/** 已有主体名称,缺失时直接显示真实编号。 */
ownerName: string
/** 同阶段重复占用的资源。 */
resource: ActionResource
/** 实际冲突动作的可读描述。 */
actions: string[]
}
/**
* 仅在当前审核明确指出资源冲突时,从同版本镜头证据提取角色与冲突动作。
* @param state 当前版本的完整镜头与主体
* @param quality 与当前检查点一致的审核
* @returns 可添加精确例外的真实目标;历史、缺失或无效证据不产生目标
*/
export function actionExceptionTargets(state: BreakdownState, quality: BreakdownQuality): ActionExceptionTarget[] {
if (!['candidate', 'formal'].includes(quality.source) || quality.loading || quality.needsRefresh || quality.error) return []
const targets = new Map<string, ActionExceptionTarget>()
for (const block of quality.actionBlocks) {
if (![...block.blockingCodes, ...block.warningCodes].includes('action_resource_conflict')) continue
const shot = state.storyboardEpisodeShots?.find(episode => episode.episodeNo === block.episodeNo)
?.beatShots.find(beat => beat.beatNo === block.beatNo)?.shots.find(item => item.shotNo === block.shotNo)
if (!shot?.requiredActions?.length || !shot.durationPlanning) continue
for (const [index, phase] of shot.durationPlanning.phases.entries()) {
// 与后端审计一致:只接受本阶段、已存在动作及镜头主体的明确占用证据。
const resources = (phase.resourceOccupancy ?? []).filter(item =>
shot.subjectRefs.includes(item.ownerRef) && phase.actionIds?.includes(item.actionId) &&
shot.requiredActions!.some(action => action.id === item.actionId) &&
actionResourceOptions.some(option => option.value === item.resource))
for (const [leftIndex, left] of resources.entries()) {
for (const right of resources.slice(leftIndex + 1)) {
if (left.ownerRef !== right.ownerRef || left.resource !== right.resource || left.actionId === right.actionId) continue
if (left.shareable && right.shareable && !['support', 'move'].includes(left.usage) && !['support', 'move'].includes(right.usage)) continue
const key = `${block.episodeNo}/${block.beatNo}/${block.shotNo}/${index + 1}/${left.ownerRef}/${left.resource}`
const target = targets.get(key) ?? {
key, episodeNo: block.episodeNo, beatNo: block.beatNo, shotNo: block.shotNo,
phaseNo: index + 1, shotTitle: shot.title, ownerRef: left.ownerRef, resource: left.resource,
ownerName: state.subjectCandidates?.find(subject => subject.ref === left.ownerRef)?.name || left.ownerRef,
actions: []
}
for (const actionId of [left.actionId, right.actionId]) {
const description = shot.requiredActions.find(action => action.id === actionId)!.description
if (!target.actions.includes(description)) target.actions.push(description)
}
targets.set(key, target)
}
}
}
}
return [...targets.values()]
}
@@ -0,0 +1,223 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NButton, NFormItem, NInput } from 'naive-ui'
import { Plus } from '@lucide/vue'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import QualityPolicyExceptions from '../../generation-config/components/QualityPolicyExceptions.vue'
import { projectsApi } from '../../projects/api'
import { actionResourceOptions, policyDraft } from '../../projects/quality-policy'
import { invalidateQualityPolicyConfirmation, qualityPolicySignature } from '../../projects/quality-policy-confirmation'
import type { ProjectQualityPolicyResult } from '../../projects/types'
import { getOperation, runOperation } from '../../workflows/operations'
import { actionExceptionTargets, type ActionExceptionTarget } from '../action-exceptions'
import type { BreakdownState } from '../types'
import type { BreakdownQuality } from '../quality'
import { errorMessage } from '../../../lib/http'
/** 例外仅从当前版本的具体动作问题添加,不修改镜头、不调用模型。 */
const props = defineProps<{
/** 当前正式项目。 */
projectId: string
/** 当前最新检查点,切换后撤销旧问题草稿。 */
checkpointId: string
/** 同一检查点中的完整主体与镜头。 */
state: BreakdownState
/** 当前审核,不能使用历史通过或历史问题。 */
quality: BreakdownQuality
/** 项目活动任务、读错或未确认状态下禁止写入。 */
disabled: boolean
}>()
/** 真实写入期间锁定父抽屉,保存后重新读取服务端审核。 */
const emit = defineEmits<{ busy: [value: boolean]; refresh: [] }>()
/** 当前后端保存的规则,失败时不使用默认值。 */
const receipt = ref<ProjectQualityPolicyResult | null>(null)
/** 只读加载允许关闭,不把查询当作不可取消提交。 */
const loading = ref(false)
/** 最终保存前的规则合并查询,阻止重复点击。 */
const checking = ref(false)
/** 真正写入规则的状态。 */
const writing = ref(false)
/** 用户当前选中的完整问题目标。 */
const selected = ref<ActionExceptionTarget | null>(null)
/** 用户明确填写的允许原因,不自动代填确认依据。 */
const reason = ref('')
/** 仅在用户点击保存时展示的字段校验。 */
const issue = ref('')
/** 实际接口错误,失败后保留草稿。 */
const error = ref('')
/** 保存成功仅说明规则已保存,不暗示质量已经通过。 */
const notice = ref('')
/** 项目级写操作锁。 */
const operation = computed(() => getOperation(props.projectId))
/** 当前审核与原始数据必须属于同一项目和最新检查点。 */
const current = computed(() => !!props.checkpointId && props.quality.checkpointId === props.checkpointId &&
(!props.state.projectId || props.state.projectId === props.projectId) && ['candidate', 'formal'].includes(props.quality.source))
/** 只从真实审核和阶段证据生成目标。 */
const targets = computed(() => current.value ? actionExceptionTargets(props.state, props.quality) : [])
/** 已有例外原样展示,保存新项不会删除或替换它们。 */
const exceptions = computed(() => receipt.value?.policy.actionExceptions ?? [])
/** 用户可以提交的时机,所有外部活动锁都需要满足。 */
const writable = computed(() => current.value && !!receipt.value && !props.disabled && !operation.value.pending && !loading.value && !checking.value && !writing.value)
/** 失效代次与可取消的只读请求。 */
let generation = 0
/** 当前规则查询的取消控制器。 */
let controller: AbortController | undefined
/**
* 使用真实项目规则,验证项目及完整性后创建独立副本。
* @param id 目标项目
* @param signal 只读请求的取消信号
* @returns 已验证的完整规则
*/
async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> {
const result = await projectsApi.qualityPolicy(id, signal)
if (result.projectId !== id) throw new Error('规则所属项目不一致,请重新读取。')
qualityPolicySignature(result.policy)
return { projectId: id, policy: policyDraft(result.policy) }
}
/** 按需读取已有规则;无真实拆解结果时不创建例外。 */
async function load() {
if (loading.value || !current.value) return
const version = ++generation
const id = props.projectId
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
try {
const result = await read(id, controller.signal)
if (version === generation) receipt.value = result
} catch (cause) { if (version === generation) error.value = errorMessage(cause) }
finally { if (version === generation) loading.value = false }
}
/**
* 同一角色及部位已有例外时禁止重复添加,适用范围遵循后端项目级契约。
* @param target 真实动作冲突目标
* @returns 是否已经保存对应例外
*/
function exists(target: ActionExceptionTarget): boolean {
return exceptions.value.some(item => item.code === 'action_resource_conflict' && item.ownerRef === target.ownerRef && item.resource === target.resource)
}
/**
* 带入只读角色、部位及动作,用户只填写允许原因。
* @param target 被用户选中的真实问题
*/
function select(target: ActionExceptionTarget) {
if (!writable.value || exists(target)) return
selected.value = target
reason.value = ''
issue.value = ''
error.value = ''
notice.value = ''
}
/** 取消当前例外草稿,同时撤销尚未完成的只读请求。 */
function cancel() {
if (writing.value) return
generation++
controller?.abort()
checking.value = false
selected.value = null
reason.value = ''
issue.value = ''
}
/** 最终提交前重读并追加到最新完整规则,绝不覆盖已有例外或伪造审核通过。 */
async function save() {
if (!writable.value || !selected.value) return
issue.value = reason.value.trim() ? '' : '请填写允许原因,说明剧本为什么允许这样做。'
if (issue.value) return
const target = selected.value
const targetSignature = JSON.stringify(target)
const id = props.projectId
const version = ++generation
controller?.abort()
controller = new AbortController()
checking.value = true
error.value = ''
try {
const latest = await read(id, controller.signal)
if (version !== generation || props.disabled || operation.value.pending || !current.value ||
!targets.value.some(item => JSON.stringify(item) === targetSignature)) return
receipt.value = latest
if (exists(target)) { notice.value = '这个角色的对应部位已有例外,已保留现有设置。'; selected.value = null; return }
if (exceptions.value.length >= 30) throw new Error('动作例外最多 30 项,当前不能继续添加。')
const input = policyDraft(latest.policy)
input.actionExceptions = [...(input.actionExceptions ?? []), {
code: 'action_resource_conflict', ownerRef: target.ownerRef, resource: target.resource, reason: reason.value.trim()
}]
const signature = qualityPolicySignature(input)
writing.value = true
const success = await runOperation(id, '正在保存动作例外', async () => {
const result = await projectsApi.saveQualityPolicy(id, input)
invalidateQualityPolicyConfirmation(id)
if (result.projectId !== id || qualityPolicySignature(result.policy) !== signature)
throw new Error('规则保存回执与提交内容不一致,请重新读取确认。')
if (version === generation) receipt.value = { projectId: id, policy: policyDraft(result.policy) }
}, { type: 'info', content: '动作例外已保存,当前分镜仍需审核,不会自动放行提交。' })
if (version !== generation) return
if (success) {
selected.value = null
reason.value = ''
notice.value = '动作例外已保存。当前分镜仍需审核,不会自动标记通过或修改正式结果。'
emit('refresh')
} else error.value = operation.value.error
} catch (cause) { if (version === generation) error.value = errorMessage(cause) }
finally { if (version === generation) { checking.value = false; writing.value = false } }
}
/** 修改原因时清除旧校验,打开空白草稿不提前报错。 */
watch(reason, () => { issue.value = '' })
/** 当前问题的动作证据变化后撤销旧草稿,不能把旧动作的确认套到新动作。 */
watch(targets, items => {
if (selected.value && !items.some(item => JSON.stringify(item) === JSON.stringify(selected.value))) cancel()
}, { flush: 'sync' })
/** 切换版本后清空旧草稿和读取,迟到响应不得回填或提交。 */
watch(() => [props.projectId, props.checkpointId], () => {
generation++
controller?.abort()
receipt.value = null
selected.value = null
reason.value = ''
issue.value = ''
notice.value = ''
error.value = ''
loading.value = false
checking.value = false
writing.value = false
void load()
}, { immediate: true, flush: 'sync' })
/** 父抽屉只在真实写入期间锁定,普通读取仍可关闭。 */
watch(writing, value => emit('busy', value), { flush: 'sync' })
onScopeDispose(() => { generation++; controller?.abort(); emit('busy', false) })
</script>
<template>
<!-- 以下是拆解后从具体冲突添加动作例外的模块,角色和动作均不可自由输入 -->
<section class="workspace-panel space-y-4" aria-label="动作例外修订">
<WorkspaceSectionHeading title="动作例外" description="只为剧本明确允许的特殊动作添加例外。角色、部位和动作从当前问题自动带入,你只需填写允许原因。" />
<p v-if="loading" role="status" class="text-xs text-muted">正在读取已有动作例外…</p>
<div v-if="error" role="alert" class="space-y-2 text-sm text-danger"><p>{{ error }}</p><NButton v-if="!receipt" :disabled="loading" @click="load">重新读取规则</NButton></div>
<QualityPolicyExceptions :exceptions="exceptions" />
<p v-if="!targets.length && !loading" class="text-xs leading-6 text-muted">当前没有能准确带入角色与动作的冲突。缺少动作证据或其他结构错误时,请先使用人工修订。</p>
<article v-for="target in targets" :key="target.key" class="space-y-3" :data-exception-target="target.key">
<div class="flex flex-wrap items-center justify-between gap-3">
<p class="text-sm">第 {{ target.episodeNo }} 集 · 节拍 {{ target.beatNo }} · 镜头 {{ target.shotNo }} · 阶段 {{ target.phaseNo }}</p>
<NButton v-if="selected?.key !== target.key" :disabled="!writable || exists(target)" @click="select(target)"><template #icon><Plus :size="15" aria-hidden="true" /></template>{{ exists(target) ? '已有例外' : '添加例外' }}</NButton>
</div>
<p class="text-sm">{{ target.ownerName }}({{ target.ownerRef }}) · {{ actionResourceOptions.find(option => option.value === target.resource)?.label }}</p>
<ul class="space-y-1 pl-5 text-xs leading-6 text-muted list-disc"><li v-for="action in target.actions" :key="action">{{ action }}</li></ul>
<!-- 以下是只填写原因的例外草稿,后端实际范围是同一角色的对应部位 -->
<div v-if="selected?.key === target.key" class="space-y-3">
<p class="text-xs leading-6 text-muted">此例外按项目保存,同一角色或物品在其他镜头中的同类占用冲突也会受影响;其他错误仍会检查。</p>
<NFormItem label="允许原因"><NInput v-model:value="reason" type="textarea" aria-label="动作例外允许原因" placeholder="填写剧本中明确允许这样做的设定" :autosize="{ minRows: 2, maxRows: 6 }" :disabled="disabled || checking || writing" /></NFormItem>
<p v-if="issue" role="alert" class="text-xs text-danger">{{ issue }}</p>
<div class="flex flex-wrap justify-end gap-2"><NButton :disabled="writing" @click="cancel">取消</NButton><NButton type="primary" :disabled="!writable" :loading="checking || writing" @click="save"><template #icon><Plus :size="15" aria-hidden="true" /></template>保存动作例外</NButton></div>
</div>
</article>
<p v-if="notice" role="status" class="text-xs leading-6 text-muted">{{ notice }}</p>
</section>
</template>
@@ -143,7 +143,7 @@ async function commit() {
<section v-if="failedChecks.length" class="problem-surface p-4" aria-label="未通过的提交安全检查"><p class="mb-2 text-sm">提交安全检查未通过</p><ul class="list-inside list-disc space-y-2 text-xs"><li v-for="label in failedChecks" :key="label">{{ label }}</li></ul></section>
<p v-if="checkError" class="text-xs text-danger" role="alert">{{ checkError }}</p>
<!-- 以下是通过只读预检查后才出现的最终确认,取消和关闭撤销确认 -->
<AppDialog v-model:open="confirmOpen" title="确认提交候选为正式结果" :busy="committing" description="将替换正式主体、形态与分镜。提交时后端仍会在事务内重新检查剧本版本和下游资产。">
<AppDialog v-model:open="confirmOpen" title="确认提交候选为正式结果" :busy="committing" description="将替换正式主体、形态与分镜。保存时还会检查剧本是否变化,以及已有制作成果是否受到影响。">
<p class="text-sm">本次候选:{{ counts.subjects }} 个主体、{{ counts.episodes }} 集、{{ counts.shots }} 个镜头。</p>
<NCheckbox v-model:checked="acknowledged" class="mt-5">我已确认替换正式结果,当前没有同项目的制作任务在运行。</NCheckbox>
<template #footer><NButton :disabled="committing" @click="confirmOpen = false; acknowledged = false">取消</NButton><NButton type="primary" :loading="committing" :disabled="!acknowledged || !ready || !canCheck" @click="commit">确认提交候选为正式结果</NButton></template>
@@ -1,4 +1,6 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { qualityIssueLabel } from '../repair'
import { computed, ref } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import { AppDrawer } from '../../../components/ui'
@@ -25,6 +27,8 @@ const props = defineProps<{
locatable: boolean
/** 当前版本统一审核,历史问题与当前问题分开。 */
quality?: BreakdownQuality
/** 真实写入例外期间禁止关闭和定位,普通读取不锁定。 */
busy?: boolean
}>()
/** 独立问题抽屉显隐。 */
const open = defineModel<boolean>('open', { default: false })
@@ -56,7 +60,7 @@ const pendingLocation = ref<ShotValidation['issues'][number] | null>(null)
* @param issue 后端提供的问题位置
*/
function locate(issue: ShotValidation['issues'][number]) {
if (!props.locatable) return
if (!props.locatable || props.busy) return
pendingLocation.value = { ...issue }
open.value = false
}
@@ -72,7 +76,7 @@ function finish() {
<template>
<!-- 以下是全屏展示的拆解执行错误与分镜校验问题模块 -->
<AppDrawer v-model:open="open" title="拆解问题" class="breakdown-issues-drawer" @closed="finish">
<AppDrawer v-model:open="open" title="拆解问题" :busy="busy" class="breakdown-issues-drawer" @closed="finish">
<template #description
><span v-if="quality">{{ quality.isCandidate ? '当前候选' : quality.source === 'history' ? '历史结果(当前质量未确认)' : '当前正式结果' }} · 结构 {{ quality.structuralCount }} 项 · 动作 {{ quality.actionBlocks.length }} 镜</span
><span v-else-if="count">{{ count }} 项校验问题 · {{ groups.length }} 个位置</span
@@ -87,18 +91,18 @@ function finish() {
<h3 class="text-sm font-medium">{{ group.label }} · {{ group.items.length }}</h3>
<article v-for="item in group.items" :key="item.key" class="workspace-panel problem-surface space-y-3 break-words" :data-problem-type="item.type">
<div v-if="item.location" class="flex flex-wrap items-center justify-between gap-3"><p class="text-sm">第 {{ item.location.episodeNo }} 集<span v-if="item.location.beatNo"> · 节拍 {{ item.location.beatNo }}</span><span v-if="item.location.shotNo"> · 镜头 {{ item.location.shotNo }}</span><span class="ml-3 text-xs text-muted">待处理</span></p><NButton v-if="locatable" text size="small" @click="locate(item.location)">{{ item.location.beatNo ? '定位分镜' : '查看本集' }}</NButton></div>
<p class="text-sm leading-6">{{ item.message }}</p><p v-if="item.codes.length" class="text-xs text-muted break-all">阻断代码:{{ item.codes.join('、') }}</p>
<p class="text-sm leading-6">{{ userFacingText(item.message) }}</p><p v-if="item.codes.length" class="text-xs text-muted break-all">需要处理:{{ item.codes.map(qualityIssueLabel).join('、') }}</p>
</article>
</section>
<p v-if="!quality.issueCount && !workflowError" class="text-sm text-muted">当前版本没有待处理的质量问题。</p>
<!-- 以下是使用 Naive 折叠组件的历史记录,默认收起且不计入当前问题 -->
<NCollapse v-if="quality.historyIssues.length" class="text-xs text-muted" data-history-issues><NCollapseItem name="history" :title="`历史审核记录 · ${quality.historyIssues.length} 项(不计入当前问题)`"><p v-for="(item, index) in quality.historyIssues" :key="index" class="mt-3 break-words">第 {{ item.episodeNo }} 集 · {{ item.message }}</p></NCollapseItem></NCollapse>
<NCollapse v-if="quality.historyIssues.length" class="text-xs text-muted" data-history-issues><NCollapseItem name="history" :title="`历史审核记录 · ${quality.historyIssues.length} 项(不计入当前问题)`"><p v-for="(item, index) in quality.historyIssues" :key="index" class="mt-3 break-words">第 {{ item.episodeNo }} 集 · {{ userFacingText(item.message) }}</p></NCollapseItem></NCollapse>
</template>
</div>
<div class="space-y-4">
<section v-if="workflowError" class="workspace-panel problem-surface space-y-3" aria-label="执行异常">
<h3 class="text-sm font-medium">执行异常</h3>
<p class="whitespace-pre-wrap break-words text-sm leading-6">{{ workflowError }}</p>
<p class="whitespace-pre-wrap break-words text-sm leading-6">{{ userFacingText(workflowError) }}</p>
</section>
<article
v-for="group in quality ? [] : groups"
@@ -116,7 +120,7 @@ function finish() {
}}</NButton>
</div>
<p v-for="message in group.messages" :key="message" class="break-words text-sm leading-6">
{{ message }}
{{ userFacingText(message) }}
</p>
</article>
<p v-if="!quality && !groups.length && !workflowError" class="py-5 text-sm text-muted">
@@ -126,7 +130,7 @@ function finish() {
<!-- 以下是独立的问题修订与阶段恢复模块,不承载生成配置或候选提交 -->
<div v-if="$slots.repair" class="mt-6 space-y-5" aria-label="问题修订与恢复"><slot name="repair" /></div>
<!-- 以下是灰底关闭操作,绿色主按钮仅用于提交或执行任务 -->
<template #footer><NButton type="default" @click="open = false">关闭</NButton></template>
<template #footer><NButton type="default" :disabled="busy" @click="open = false">关闭</NButton></template>
</AppDrawer>
</template>
@@ -173,7 +173,7 @@ async function repairActions() {
<article v-for="draft in actionDrafts" :key="draft.key" class="candidate-action-draft space-y-3 p-4" :data-action-id="draft.actionId">
<NCheckbox v-model:checked="draft.selected" :disabled="!writable">第 {{ draft.episodeNo }} 集 · 节拍 {{ draft.beatNo }} · 镜头 {{ draft.shotNo }} · {{ draft.title }} · {{ draft.actionId }}</NCheckbox>
<p class="text-xs leading-6 text-muted">原始状态:{{ draft.original }}</p>
<p v-if="draft.parallel" class="text-xs text-danger">该动作处于并行阶段,后端可能拒绝覆盖,需核对同阶段其他动作。</p>
<p v-if="draft.parallel" class="text-xs text-danger">这个动作与其他动作同时发生。请先核对它们的关系,避免修改后互相冲突。</p>
<NInput v-model:value="draft.description" type="textarea" :disabled="!writable || !draft.selected" :input-props="{ 'aria-label': `动作 ${draft.key} 修订描述` }" placeholder="请人工填写动作如何发生,不能只把结果状态改名" :autosize="{ minRows: 3, maxRows: 8 }" />
</article>
<p v-if="repairs.length" class="text-xs leading-6 text-muted break-words" aria-label="批量修复摘要">{{ actionSummary }}</p>
@@ -222,7 +222,7 @@ onScopeDispose(() => {
<AppDialog
v-model:open="open"
:title="targetLabel"
description="修订完整动作与阶段证据;保存前后端会重新审核当前镜头。此操作不调用模型。"
description="调整镜头中的动作和先后顺序,保存时会重新检查这个镜头。此操作不调用模型。"
:busy="operation.pending"
wide
>
@@ -245,7 +245,7 @@ onScopeDispose(() => {
><ConfirmAction
:key="draftVersion"
label="保存人工修订"
description="将保存当前完整动作与阶段证据。若版本变化或质量审核仍不通过,后端会拒绝保存。保存成功后仍需恢复拆解与正式提交。"
description="保存当前镜头的动作安排。如果内容版本已变化或检查仍未通过,需要先处理问题。保存后还需继续拆解并提交正式结果。"
:disabled="disabled || operation.pending || !current || !!issue"
@confirm="save"
/></template>
+1 -1
View File
@@ -27,7 +27,7 @@ export function qualityIssueLabel(code: string): string {
hand_action_not_in_phase: '手部动作不属于当前阶段',
invalid_hand_character_ref: '手部主体引用无效'
}
return labels[code] ?? `待复核问题(${code})`
return labels[code] ?? '其他待复核问题'
}
/**
@@ -0,0 +1,246 @@
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import { projectsApi } from '../projects/api'
import { policyDraft } from '../projects/quality-policy'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../projects/types'
import {
qualityPolicyConfirmationEpoch, qualityPolicySignature,
readQualityPolicyConfirmation, rememberQualityPolicyConfirmation
} from '../projects/quality-policy-confirmation'
import { errorMessage } from '../../lib/http'
import { showActionFeedback, useActionMessage } from '../../components/ui/useActionMessage'
/** 一次性启动许可只在前端内使用,不作为后端权限或提交参数。 */
interface StartPermit {
/** 当前项目。 */
projectId: string
/** 当前拆解输入。 */
scope: string
/** 本次重新读取并确认的质量规则。 */
signature: string
}
/** 存储受限时仅在当前页面有效的确认,规则变更后通过代次撤销。 */
interface SessionConfirmation extends StartPermit {
/** 当前项目在本页面的规则失效代次。 */
epoch: number
}
/**
* 读取真实规则并验证所属项目和内容完整性。
* @param id 请求项目
* @param signal 只读请求取消信号
* @returns 已验证的真实规则回执
*/
async function read(id: string, signal: AbortSignal): Promise<ProjectQualityPolicyResult> {
const result = await projectsApi.qualityPolicy(id, signal)
if (result.projectId !== id) throw new Error('质量规则所属项目不一致,请重新读取。')
qualityPolicySignature(result.policy)
return { projectId: id, policy: policyDraft(result.policy) }
}
/**
* 启动拆解前读取并确认规则,内容未变时跳过规则弹窗,保留每次模型启动确认。
* @param projectId 当前项目
* @param scope 当前预览对应的拆解配置
* @param allowed 当前是否允许启动
* @returns 规则确认、普通启动确认及一次性启动许可
*/
export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<string>, allowed: Ref<boolean>) {
/** 已读取的服务端规则,编辑器不能自行使用本地默认值代替。 */
const policy = ref<ProjectQualityPolicyResult | null>(null)
/** 在现有拆解抽屉中切换到规则确认,不叠加第二个全屏抽屉。 */
const reviewOpen = ref(false)
/** 普通模型启动确认,规则已确认时直接进入此步骤。 */
const startOpen = ref(false)
/** 只读请求加载状态,允许用户取消。 */
const reading = ref(false)
/** 真实保存期间禁止重复操作和意外关闭。 */
const saving = ref(false)
/** 当前按钮请求是否正在执行。 */
const busy = computed(() => reading.value || saving.value)
/** 用户可重试的错误反馈。 */
const error = ref('')
/** 编辑器只在服务端版本变化时重建,失败保留草稿。 */
const editorKey = computed(() => policy.value ? `${policy.value.projectId}:${qualityPolicySignature(policy.value.policy)}` : '')
/** 应用统一消息层。 */
const message = useActionMessage()
/** 取消项目或配置变更前的旧请求。 */
let controller: AbortController | undefined
/** 旧响应隔离代次。 */
let generation = 0
/** 普通启动弹窗对应的规则内容。 */
let preparedSignature = ''
/** 存储不可写时,仅本次页面会话使用的确认。 */
let fallback: SessionConfirmation | null = null
/** 成功重读后才能消费的一次性启动许可。 */
let permit: StartPermit | null = null
/**
* 判断规则内容是否经过本浏览器明确确认。
* @param id 当前项目
* @param signature 最新服务端内容
* @returns 是否允许跳过规则确认界面
*/
function confirmed(id: string, signature: string): boolean {
return readQualityPolicyConfirmation(id) === signature ||
(fallback?.projectId === id && fallback.signature === signature &&
fallback.epoch === qualityPolicyConfirmationEpoch(id))
}
/** 撤销未完成请求和启动许可,不撤销用户已经完成的规则确认。 */
function reset() {
generation++
controller?.abort()
reading.value = false
saving.value = false
reviewOpen.value = false
startOpen.value = false
policy.value = null
preparedSignature = ''
permit = null
error.value = ''
}
/** 用户点击生成时读取规则,不在页面进入或定时器中请求。 */
async function prepare() {
if (!allowed.value || busy.value) return
reset()
const current = generation
const id = projectId.value
controller = new AbortController()
reading.value = true
try {
const result = await read(id, controller.signal)
if (current !== generation || !allowed.value) return
policy.value = result
const signature = qualityPolicySignature(result.policy)
if (confirmed(id, signature)) {
preparedSignature = signature
startOpen.value = true
} else reviewOpen.value = true
} catch (cause) {
if (current === generation) {
error.value = errorMessage(cause)
showActionFeedback(message, error.value, 'error')
}
} finally { if (current === generation) reading.value = false }
}
/**
* 明确确认完整规则,修改过的草稿先保存并核对;无变化时不重复写入。
* @param draft 表单完整校验后的用户草稿
* @returns 是否已进入普通启动确认,不会自动执行模型任务
*/
async function confirmRules(draft: ProjectQualityPolicy): Promise<boolean> {
if (!allowed.value || busy.value || !reviewOpen.value || !policy.value) return false
const id = projectId.value
const current = ++generation
const expected = qualityPolicySignature(policy.value.policy)
controller?.abort()
controller = new AbortController()
const signal = controller.signal
reading.value = true
error.value = ''
try {
const draftSignature = qualityPolicySignature(draft)
let result = await read(id, signal)
if (current !== generation || !allowed.value) return false
if (qualityPolicySignature(result.policy) !== expected) {
policy.value = result
showActionFeedback(message, '质量规则已在其他位置更新,请重新核对后确认。', 'warning')
return false
}
if (draftSignature !== expected) {
reading.value = false
saving.value = true
const saved = await projectsApi.saveQualityPolicy(id, policyDraft(draft))
if (current !== generation || !allowed.value) return false
if (saved.projectId !== id || qualityPolicySignature(saved.policy) !== draftSignature)
throw new Error('质量规则保存结果与草稿不一致,请重新读取。')
saving.value = false
reading.value = true
result = await read(id, signal)
if (current !== generation || !allowed.value) return false
if (qualityPolicySignature(result.policy) !== draftSignature) {
policy.value = result
showActionFeedback(message, '质量规则保存后又有更新,请重新核对。', 'warning')
return false
}
}
const signature = qualityPolicySignature(result.policy)
const persisted = rememberQualityPolicyConfirmation(id, signature)
fallback = persisted ? null : { projectId: id, scope: scope.value, signature, epoch: qualityPolicyConfirmationEpoch(id) }
if (!persisted) showActionFeedback(message, '当前浏览器未能记住确认,下次进入时可能再次提醒。', 'info')
policy.value = result
preparedSignature = signature
reviewOpen.value = false
startOpen.value = true
return true
} catch (cause) {
if (current === generation) {
error.value = errorMessage(cause)
showActionFeedback(message, error.value, 'error')
}
return false
} finally {
if (current === generation) { reading.value = false; saving.value = false }
}
}
/**
* 最终启动前再次读取,弹窗期间规则变化时返回确认,绝不直接调用模型。
* @returns 是否取得本次启动许可
*/
async function verifyStart(): Promise<boolean> {
if (!allowed.value || busy.value || !startOpen.value || !preparedSignature) return false
const id = projectId.value
const current = ++generation
const currentScope = scope.value
controller?.abort()
controller = new AbortController()
reading.value = true
error.value = ''
try {
const result = await read(id, controller.signal)
if (current !== generation || !allowed.value) return false
const signature = qualityPolicySignature(result.policy)
if (signature !== preparedSignature || !confirmed(id, signature)) {
policy.value = result
preparedSignature = ''
startOpen.value = false
reviewOpen.value = true
showActionFeedback(message, '质量规则已变化,请重新确认后再启动拆解。', 'warning')
return false
}
permit = { projectId: id, scope: currentScope, signature }
startOpen.value = false
return true
} catch (cause) {
if (current === generation) {
error.value = errorMessage(cause)
showActionFeedback(message, error.value, 'error')
}
return false
} finally { if (current === generation) reading.value = false }
}
/**
* 消费同项目、同预览范围的本地一次性启动许可;后端仍需要独立门禁。
* @returns 是否允许本次提交
*/
function consumePermit(): boolean {
const current = permit
permit = null
return !!current && allowed.value && current.projectId === projectId.value &&
current.scope === scope.value && confirmed(current.projectId, current.signature)
}
/** 用户取消只读确认时撤销未完成请求,保存请求进行中禁止重复取消。 */
function cancel() {
if (!saving.value) reset()
}
watch([projectId, scope], reset, { flush: 'sync' })
watch(allowed, value => { if (!value) reset() }, { flush: 'sync' })
onScopeDispose(reset)
return { policy, reviewOpen, startOpen, reading, saving, busy, error, editorKey, prepare, confirmRules, verifyStart, consumePermit, cancel }
}
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { computed } from 'vue'
import { NFormItem, NInputNumber, NSelect, NSwitch, NTag } from 'naive-ui'
import FieldLabel from '../../../components/ui/FieldLabel.vue'
@@ -53,10 +54,15 @@ function updateOption(key: string, value: string | number | boolean | null) {
emit('update:options', next)
}
/**
* 为模型参数生成中文选项,保留真实取值和支持的时长范围。
* @param item 当前模型参数
* @returns 参数选项
*/
function choices(item: GenerationModelItem['generationOptions'][number]): SelectOption[] {
const options = [...(item.options ?? []), ...(item.specialValues ?? [])]
.filter(option => typeof option.value === 'string' || typeof option.value === 'number')
.map(option => ({ label: option.label, value: option.value as string | number }))
.map(option => ({ label: userFacingText(option.label, option.label), value: option.value as string | number }))
if (
/duration|时长/i.test(`${item.key} ${item.label}`) &&
Number.isInteger(item.min) &&
@@ -93,11 +99,11 @@ function selectValue(key: string): string | number | null {
v-for="item in model.generationOptions"
:key="item.key"
class="generation-model-field"
:label="item.label"
:label="userFacingText(item.label, item.label)"
:show-feedback="false"
>
<!-- 以下是生成参数标签与说明提示模块 -->
<template #label><FieldLabel :label="item.label" :description="item.description" /></template>
<template #label><FieldLabel :label="userFacingText(item.label, item.label)" :description="userFacingText(item.description)" /></template>
<div class="generation-model-field-control">
<div v-if="item.type === 'boolean'" class="generation-model-toggle">
<NSwitch
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { NCheckbox, NFormItem, NInput, NInputNumber, NSelect } from 'naive-ui'
import FieldLabel from '../../../components/ui/FieldLabel.vue'
import type { GenerationOptionSchema, GenerationOptions } from '../types'
@@ -26,10 +27,15 @@ function selectValue(value: string | number | boolean | undefined) {
return typeof value === 'string' || typeof value === 'number' ? value : null
}
/**
* 只翻译参数选项名称,模型要求的取值保持不变。
* @param schema 当前模型的参数定义
* @returns 可显示的中文选项及原始取值
*/
function selectOptions(schema: GenerationOptionSchema) {
return [...(schema.options || []), ...(schema.specialValues || [])].flatMap(option =>
typeof option.value === 'string' || typeof option.value === 'number'
? [{ label: option.label, value: option.value }]
? [{ label: userFacingText(option.label, option.label), value: option.value }]
: []
)
}
@@ -42,7 +48,12 @@ function optionKey(value: string | number) {
return `${typeof value}:${value}`
}
/** 尺寸和时长使用有限选项,避免用户输入 Provider 不支持的自由值。 */
/**
* 尺寸和时长使用模型支持的有限选项,只转换展示文字。
* @param schema 当前模型参数定义
* @param current 当前已保存取值
* @returns 保留原始值且去重的可选项
*/
function constrainedOptions(schema: GenerationOptionSchema, current: string | number | boolean | undefined) {
const options = selectOptions(schema)
if (schema.type === 'size') {
@@ -59,10 +70,10 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
}
}
if (typeof schema.providerDefault === 'string' || typeof schema.providerDefault === 'number') {
options.push({ label: String(schema.providerDefault), value: schema.providerDefault })
options.push({ label: userFacingText(String(schema.providerDefault), String(schema.providerDefault)), value: schema.providerDefault })
}
if (typeof current === 'string' || typeof current === 'number') {
options.push({ label: String(current), value: current })
options.push({ label: userFacingText(String(current), String(current)), value: current })
}
const seen = new Set<string>()
return options.filter(option => {
@@ -79,14 +90,14 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
<NFormItem
v-for="schema in schemas"
:key="schema.key"
:label="`${schema.label}${schema.required ? ' *' : ''}`"
:label="`${userFacingText(schema.label, schema.label)}${schema.required ? ' *' : ''}`"
:show-feedback="false"
>
<!-- 以下是参数标签与按需说明模块 -->
<template #label>
<FieldLabel
:label="`${schema.label}${schema.required ? ' *' : ''}`"
:description="schema.description"
:label="`${userFacingText(schema.label, schema.label)}${schema.required ? ' *' : ''}`"
:description="userFacingText(schema.description)"
/>
</template>
<NCheckbox
@@ -118,7 +129,7 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
v-else
:value="typeof modelValue[schema.key] === 'string' ? (modelValue[schema.key] as string) : ''"
:disabled="disabled"
placeholder="例如 2048x2048 或 auto"
placeholder="例如 2048x2048;也可使用当前模型的默认值"
clearable
@update:value="update(modelValue, schema.key, $event)"
/>
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { NCollapse, NCollapseItem } from 'naive-ui'
import type { ProjectQualityPolicy } from '../../projects/types'
import { actionResourceOptions } from '../../projects/quality-policy'
/** 已有例外仅供核对,基础配置不再创建没有镜头依据的空白行。 */
defineProps<{
/** 服务端实际保存的完整例外。 */
exceptions: NonNullable<ProjectQualityPolicy['actionExceptions']>
}>()
</script>
<template>
<!-- 以下是已有动作例外的只读核对模块,新增入口统一放在拆解问题修订中 -->
<NCollapse v-if="exceptions.length" class="quality-policy-exceptions">
<NCollapseItem name="existing" :title="`已有动作例外 · ${exceptions.length} 项`">
<p class="text-xs leading-6 text-muted">这些例外会继续保留。新增例外请在拆解后的具体动作问题中填写。</p>
<ul class="mt-3 space-y-3">
<li v-for="(item, index) in exceptions" :key="index" class="space-y-1 break-words text-sm">
<p>{{ item.ownerRef }} · {{ actionResourceOptions.find(option => option.value === item.resource)?.label || item.resource }}</p>
<p class="text-xs leading-6 text-muted">{{ item.reason }}</p>
</li>
</ul>
</NCollapseItem>
</NCollapse>
</template>
@@ -1,12 +1,14 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { computed, h, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCheckbox, NFormItem, NInput, NSelect } from 'naive-ui'
import { Trash2 } from '@lucide/vue'
import type { SelectRenderLabel, SelectRenderTag } from 'naive-ui'
import { projectsApi } from '../../projects/api'
import { actionResourceOptions, policyDraft, policyIssue } from '../../projects/quality-policy'
import type { ProjectQualityPolicy } from '../../projects/types'
import { policyDraft, policyIssue } from '../../projects/quality-policy'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../../projects/types'
import { invalidateQualityPolicyConfirmation, qualityPolicySignature } from '../../projects/quality-policy-confirmation'
import { errorMessage } from '../../../lib/http'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import QualityPolicyExceptions from './QualityPolicyExceptions.vue'
/** 项目质量策略独立编辑表单。 */
const props = defineProps<{
@@ -14,6 +16,8 @@ const props = defineProps<{
projectId: string
/** 项目有活动操作时禁止保存。 */
disabled: boolean
/** 启动入口已经读取的真实回执,复用时不重复请求或使用默认值。 */
initialPolicy?: ProjectQualityPolicyResult
}>()
/** 保存状态交给弹窗锁定关闭与标签切换。 */
const emit = defineEmits<{ busy: [value: boolean]; saved: [] }>()
@@ -27,11 +31,50 @@ const error = ref('')
const notice = ref('')
/** 服务端策略的独立草稿。 */
const policy = ref<ProjectQualityPolicy | null>(null)
/** 模式选择不自动修改允许范围。 */
/** 已保存内容用于区分真实规则变更与无变化保存。 */
let savedSignature = ''
/** 基础规则的原始内容,用于阻止覆盖其他入口并发修改的通用规则。 */
let savedGeneralSignature = ''
/** 整体表现方式及通俗示例,仅说明含义,不自动修改动作许可。 */
const physicsOptions = [
{ value: 'realistic', label: '写实物理' },
{ value: 'stylized', label: '风格化表现' },
{ value: 'fantasy', label: '幻想表现' }
{ value: 'realistic', label: '写实物理', description: '按现实生活中的规律设计动作,例如跳起需要借力,物品失去支撑会落下。' },
{ value: 'stylized', label: '风格化表现', description: '适合卡通、喜剧,让动作更有戏剧感;具体允许哪些夸张动作,还需在下方勾选。' },
{ value: 'fantasy', label: '幻想表现', description: '适合仙侠、魔法等故事,按故事设定设计动作;飞行、法术等能力仍需在下方明确允许。' }
]
/** 当前选择的说明始终显示,关闭下拉菜单后也能了解含义。 */
const physicsDescription = computed(() => physicsOptions.find(option => option.value === policy.value?.physicsMode)?.description ?? '')
/**
* 下拉选项同时展示名称与说明,窄屏可自然换行。
* @param option Naive UI 提供的当前选项
* @returns 包含通俗说明的选项内容
*/
const renderPhysicsLabel: SelectRenderLabel = option => h('div', { class: 'grid min-w-0 gap-1 py-1 whitespace-normal' }, [
h('span', { class: 'text-sm leading-6' }, String(option.label ?? '')),
h('span', { class: 'text-xs leading-5 text-muted' }, String(option.description ?? ''))
])
/**
* 选择框只显示简短名称,完整说明放在控件下方,避免撑高或截断控件。
* @param info 当前选择的信息
* @returns 当前表现方式的名称
*/
const renderPhysicsSelection: SelectRenderTag = info => String(info.option.label ?? '')
/** 动作许可选项共用同一种标题与说明布局,字段仍映射原有后端契约。 */
interface MotionPermissionOption {
/** 对应规则中的独立布尔字段。 */
field: 'allowExaggeratedMotion' | 'allowNonPhysicalActions' | 'allowSupernaturalAbilities'
/** 用户可见的动作许可名称。 */
label: string
/** 使用日常语言说明允许范围与例子。 */
description: string
}
/** 三类许可的区别直接展示,不依赖悬停或术语理解。 */
const motionPermissions: MotionPermissionOption[] = [
{ field: 'allowExaggeratedMotion', label: '允许夸张动作', description: '把正常动作做得更夸张,例如惊讶时大幅后仰、跑步时摆臂更大;不等于允许悬空或法术。' },
{ field: 'allowNonPhysicalActions', label: '允许非物理动作', description: '允许现实中做不到的动作,例如身体像橡皮一样拉长、没有支撑也能悬空。' },
{ field: 'allowSupernaturalAbilities', label: '允许超自然能力', description: '允许角色使用法术或特殊能力,例如瞬间移动、隔空移动物品、凭空变出火焰。' }
]
/** 仅在用户点击保存时产生校验反馈,不在读取或新增空白例外时提前报错。 */
const issue = ref('')
@@ -72,9 +115,11 @@ async function load() {
notice.value = ''
issue.value = ''
try {
const result = await projectsApi.qualityPolicy(id, controller.signal)
const result = props.initialPolicy ?? await projectsApi.qualityPolicy(id, controller.signal)
if (current !== version) return
if (result.projectId !== id) throw new Error('质量策略所属项目不一致,请重新读取。')
savedSignature = qualityPolicySignature(result.policy)
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
policy.value = policyDraft(result.policy)
rulesText.value = policy.value.customRules.join('\n')
} catch (cause) {
@@ -84,37 +129,46 @@ async function load() {
}
}
/** 新增一项精确例外,必须填写主体和依据后才可保存。 */
function addException() {
if (!policy.value || props.disabled || saving.value) return
const items = (policy.value.actionExceptions ??= [])
if (items.length < 30)
items.push({ code: 'action_resource_conflict', ownerRef: '', resource: 'left_hand', reason: '' })
}
/**
* 移除当前草稿中的精确例外,保存前不改变后端。
* @param index 例外在草稿中的位置
* 在用户明确提交时校验并返回独立草稿,不提前显示错误。
* @returns 完整草稿,未就绪或校验失败时为空
*/
function removeException(index: number) {
policy.value?.actionExceptions?.splice(index, 1)
function validatedDraft(): ProjectQualityPolicy | null {
if (!canSave.value || !policy.value) return null
issue.value = policyIssue(policy.value)
return issue.value ? null : policyDraft(policy.value)
}
/** 点击保存时校验完整策略,通过后再提交并核对项目归属。 */
async function save() {
if (!canSave.value || !policy.value) return
issue.value = policyIssue(policy.value)
if (issue.value) return
const input = validatedDraft()
if (!input) return
const id = props.projectId
const current = version
const input = policyDraft(policy.value)
saving.value = true
loading.value = true
controller?.abort()
controller = new AbortController()
error.value = ''
notice.value = ''
try {
const latest = await projectsApi.qualityPolicy(id, controller.signal)
if (current !== version || props.disabled) return
if (latest.projectId !== id) throw new Error('质量规则所属项目不一致,请重新读取。')
qualityPolicySignature(latest.policy)
if (qualityPolicySignature({ ...latest.policy, actionExceptions: [] }) !== savedGeneralSignature)
throw new Error('质量规则已在其他位置更新,请重新打开配置后再保存。')
// 例外由问题修订入口管理,基础配置永远合并服务端最新例外,不提交隐藏的旧副本。
if (latest.policy.actionExceptions) input.actionExceptions = latest.policy.actionExceptions.map(item => ({ ...item }))
else delete input.actionExceptions
loading.value = false
saving.value = true
const result = await projectsApi.saveQualityPolicy(id, input)
if (current !== version) return
if (result.projectId !== id) throw new Error('质量策略保存回执所属项目不一致。')
const signature = qualityPolicySignature(result.policy)
if (signature !== savedSignature) invalidateQualityPolicyConfirmation(id)
savedSignature = signature
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
policy.value = policyDraft(result.policy)
rulesText.value = policy.value.customRules.join('\n')
notice.value = '质量策略已保存,后续创作、拆解和生成使用此策略。'
@@ -122,7 +176,7 @@ async function save() {
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) saving.value = false
if (current === version) { saving.value = false; loading.value = false }
}
}
@@ -133,7 +187,7 @@ onScopeDispose(() => {
controller?.abort()
})
/** 弹窗底栏复用同一个保存入口。 */
defineExpose({ save, canSave })
defineExpose({ save, canSave, validatedDraft })
</script>
<template>
@@ -149,87 +203,47 @@ defineExpose({ save, canSave })
<section class="space-y-4" aria-label="动作与物理规则">
<WorkspaceSectionHeading
title="动作与物理规则"
description="选择表现方式后,仍需明确勾选允许的动作范围。保存不会重新生成已有资产。"
description="先选整体表现方式,再勾选故事中允许的动作。切换方式不会自动勾选,也不会自动添加剧情或重新生成已有内容。"
/>
<NFormItem label="物理表现方式" :label-props="{ id: 'quality-physics-mode-label' }">
<NSelect
v-model:value="policy.physicsMode"
aria-labelledby="quality-physics-mode-label"
:options="physicsOptions"
:disabled="disabled || saving"
/>
<div class="quality-policy-field">
<NSelect
v-model:value="policy.physicsMode"
aria-labelledby="quality-physics-mode-label"
aria-describedby="quality-physics-mode-help"
:options="physicsOptions"
:render-label="renderPhysicsLabel"
:render-tag="renderPhysicsSelection"
:virtual-scroll="false"
:disabled="disabled || saving"
/>
<p id="quality-physics-mode-help" class="text-xs leading-6 text-muted">{{ physicsDescription }}</p>
</div>
</NFormItem>
<!-- 以下是动作许可及其日常示例,桌面按列对齐,手机逐项展示 -->
<div class="grid gap-4 sm:grid-cols-3">
<NCheckbox v-model:checked="policy.allowExaggeratedMotion" :disabled="disabled || saving"
>允许夸张动作</NCheckbox
>
<NCheckbox v-model:checked="policy.allowNonPhysicalActions" :disabled="disabled || saving"
>允许非物理动作</NCheckbox
>
<NCheckbox v-model:checked="policy.allowSupernaturalAbilities" :disabled="disabled || saving"
>允许超自然能力</NCheckbox
>
<div v-for="permission in motionPermissions" :key="permission.field" class="min-w-0 space-y-2">
<NCheckbox v-model:checked="policy[permission.field]" :disabled="disabled || saving" :aria-describedby="`quality-${permission.field}-help`">{{ permission.label }}</NCheckbox>
<p :id="`quality-${permission.field}-help`" class="pl-6 text-xs leading-6 text-muted">{{ permission.description }}</p>
</div>
</div>
</section>
<!-- 以下是逐行声明的自定义规则模块 -->
<NFormItem label="自定义规则" :label-props="{ for: 'quality-custom-rules' }">
<NInput
v-model:value="rulesText"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
:input-props="{ id: 'quality-custom-rules' }"
placeholder="每行一条,最多 30 条;请写明具体允许的例外"
:disabled="disabled || saving"
/>
</NFormItem>
<!-- 以下是主体和具体动作资源的精确例外模块 -->
<section class="space-y-4" aria-label="精确动作例外">
<!-- 以下是与生成配置统一间距的模块标题、说明和操作模块 -->
<WorkspaceSectionHeading
title="精确动作例外"
description="仅对填写的主体与资源放宽动作资源冲突,需记录明确依据。"
>
<template #actions>
<NButton
size="small"
:disabled="disabled || saving || (policy.actionExceptions?.length ?? 0) >= 30"
@click="addException"
>添加例外</NButton
>
</template>
</WorkspaceSectionHeading>
<div v-for="(item, index) in policy.actionExceptions" :key="index" class="quality-exception-row">
<NFormItem label="主体引用"
><NInput
v-model:value="item.ownerRef"
:aria-label="`例外 ${index + 1} 主体引用`"
placeholder="填写镜头中的主体引用"
:disabled="disabled || saving"
/></NFormItem>
<NFormItem label="动作资源"
><NSelect
v-model:value="item.resource"
:aria-label="`例外 ${index + 1} 动作资源`"
:options="actionResourceOptions"
:disabled="disabled || saving"
/></NFormItem>
<NFormItem label="确认依据"
><NInput
v-model:value="item.reason"
:aria-label="`例外 ${index + 1} 确认依据`"
:disabled="disabled || saving"
/></NFormItem>
<!-- 以下是与输入框底部对齐的图标移除操作,保留明确的可访问名称 -->
<NButton
class="icon-button quality-exception-remove"
:aria-label="`移除例外 ${index + 1}`"
title="移除例外"
<div class="quality-policy-field">
<p id="quality-custom-rules-help" class="text-xs leading-6 text-muted">补充这个故事允许的特殊情况或需要遵守的要求,每行一条,最多 30 条。</p>
<NInput
v-model:value="rulesText"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
:input-props="{ id: 'quality-custom-rules', 'aria-describedby': 'quality-custom-rules-help' }"
placeholder="例如:跳跃可以夸张,但落地后必须恢复正常姿势。"
:disabled="disabled || saving"
@click="removeException(index)"
><Trash2 :size="16" aria-hidden="true"
/></NButton>
/>
</div>
</section>
</NFormItem>
<!-- 以下是已有例外的只读核对模块,首次拆解没有例外时完全隐藏 -->
<QualityPolicyExceptions :exceptions="policy.actionExceptions ?? []" />
<p v-if="issue" role="status" class="text-xs leading-6 text-danger">{{ issue }}</p>
</template>
<p v-if="notice" role="status" class="text-xs leading-6 text-muted">{{ notice }}</p>
@@ -242,19 +256,10 @@ defineExpose({ save, canSave })
gap: 24px;
padding-top: 20px;
}
.quality-exception-row {
.quality-policy-field {
display: grid;
grid-template-columns: minmax(120px, 1fr) minmax(100px, 0.7fr) minmax(160px, 1.5fr) auto;
align-items: end;
gap: 16px;
}
.quality-exception-remove {
justify-self: end;
}
@media (max-width: 640px) {
.quality-exception-row {
grid-template-columns: minmax(0, 1fr);
gap: 12px;
}
width: 100%;
min-width: 0;
gap: 8px;
}
</style>
+2 -2
View File
@@ -306,7 +306,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
>
<div class="production-tools-intro workspace-panel">
<div>
<p class="eyebrow">PRODUCTION</p>
<p class="eyebrow">镜头制作</p>
<h2 class="text-lg font-semibold">镜头生产</h2>
<p class="mt-2 text-sm text-muted">
从可生成的提示词和首帧,到异步视频任务与最终成片。
@@ -416,7 +416,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
><component :is="stage.icon" :size="17"
/></span>
<div>
<p class="eyebrow">STEP {{ stage.code }}</p>
<p class="eyebrow">步骤 {{ stage.code }}</p>
<h3 class="mt-2 text-sm font-semibold">
{{ stage.title }}
</h3>
@@ -79,8 +79,7 @@ const confirmationDescription = computed(
>依次补齐形态提示词、参考图、首帧质量校验与修复、视频提示词,再提交视频任务。视觉风格、身份母版、导演设计和即时状态仍需提前准备。</ContextNotice
>
<p class="mt-3 text-xs leading-6 text-muted">
范围固定为全项目并跳过已有有效结果。默认开启测试安全模式:允许 LLM、Vision、主体图、少量首帧和 Video
Prompt,但会在视频生成前正常停止,不向视频 Provider 提交任务。
处理整个项目,并保留已有可用结果。试运行可以整理文字、检查图片、生成主体图片和少量首帧,并准备视频描述;会在真正生成视频前停止。试运行中的文字和图片处理仍可能产生费用。
</p>
<!-- 以下是生产范围配置模块,修改任一参数后须重新预检。 -->
<div class="surface-inset mt-4 p-4">
@@ -67,7 +67,7 @@ onScopeDispose(() => controller?.abort())
<NSpin :show="loading">
<div class="flex flex-wrap items-center justify-between gap-3">
<p class="text-xs text-muted">
按 Beat 和 Shot 顺序拼接当前有效主视频。V1 只输出无声视频,不包含对白、配乐、字幕和转场。
按剧情段落和镜头顺序拼接当前选用的视频。目前只生成无声视频,不包含对白、配乐、字幕和转场。
</p>
<NButton size="small" :disabled="loading" @click="refresh">刷新就绪状态</NButton>
</div>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
@@ -150,7 +151,7 @@ async function loadPreview() {
</ContextNotice>
<div class="mt-5 flex flex-wrap items-center gap-3">
<NButton :loading="previewPending" @click="loadPreview">预览实际生成输入</NButton>
<span class="text-xs text-muted">只读取参考图规划与最终 Prompt,不调用图片模型。</span>
<span class="text-xs text-muted">只读取参考图规划与最终画面描述,不调用图片模型。</span>
</div>
<FeedbackMessage v-if="previewError" :message="previewError" />
<div v-if="preview" class="panel mt-3 p-4 text-xs leading-6">
@@ -192,7 +193,7 @@ async function loadPreview() {
:key="`${issue.code}:${issue.subjectRef ?? index}`"
class="mt-3 bg-muted/10 p-3"
>
<p class="font-medium">{{ issue.message }}</p>
<p class="font-medium">{{ userFacingText(issue.message) }}</p>
<p v-if="issue.subjectRef" class="mt-1 text-muted">主体:{{ issue.subjectRef }}</p>
<p class="mt-1 text-muted">涉及字段:{{ issue.fieldPaths.join('、') }}</p>
<p class="mt-1">建议:{{ issue.suggestion }}</p>
@@ -206,7 +207,7 @@ async function loadPreview() {
</li>
</ul>
<NCollapse class="mt-3" :default-expanded-names="['prompt']">
<NCollapseItem name="prompt" title="最终 Provider Prompt">
<NCollapseItem name="prompt" title="本次实际使用的画面描述">
<p class="mt-3 whitespace-pre-wrap">{{ preview.providerPrompt }}</p>
</NCollapseItem>
<NCollapseItem
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
@@ -210,11 +211,11 @@ const records = computed(() =>
: '未取得完整视觉结论'
}}
</p>
<p v-if="record.error" class="text-danger">{{ record.error }}</p>
<p v-if="record.error" class="text-danger">{{ userFacingText(record.error) }}</p>
<template v-if="record.validation">
<p>{{ record.validation.summary }}</p>
<p v-for="(issue, index) in record.validation.issues" :key="index" class="text-danger">
{{ issue.description }}
{{ userFacingText(issue.description) }}
</p>
</template>
<!-- 以下是原始校验结果的 Naive 折叠模块 -->
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
@@ -62,7 +63,7 @@ async function inspect() {
<FeedbackMessage v-if="error" :message="error" />
<template v-if="providers">
<p v-if="!providers.some(item => item.active)" class="mt-2 text-danger">
没有匹配的启用图片模型,请检查后端配置。
没有可用的图片模型,请先到项目配置中选择模型。
</p>
<p v-for="item in providers" :key="item.provider" class="mt-2">
{{ item.provider }} · {{ item.active ? '当前启用' : '已注册' }} ·
@@ -77,9 +78,9 @@ async function inspect() {
</template>
<ContextNotice v-if="capability" :type="capability.valid ? 'info' : 'error'" :show-icon="false" class="mt-3">{{
capability.valid
? capability.message ||
`当前镜头共有 ${capability.referenceCount} 张业务参考图,后端已判定本次规划符合 ${capability.provider} 能力。`
: capability.message || '当前镜头不满足模型能力限制。'
? userFacingText(capability.message) ||
`当前镜头有 ${capability.referenceCount} 张参考图,本次选择符合 ${capability.provider} 的使用要求。`
: userFacingText(capability.message) || '当前镜头不满足模型能力限制。'
}}</ContextNotice>
<p v-if="capability?.valid && capability.plannedReferenceCount !== undefined" class="mt-2 text-muted">
本次计划输入 {{ capability.plannedReferenceCount }} 张 · 转为文字约束
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { NButton } from 'naive-ui'
@@ -61,7 +62,7 @@ function exportReceipt() {
<ul v-if="receipt.result.failures.length" class="mt-3 space-y-2 text-xs text-danger">
<li v-for="failure in receipt.result.failures" :key="failure.shotId">
<code>{{ failure.shotId }}</code
>:{{ failure.error }}
>:{{ userFacingText(failure.error) }}
</li>
</ul>
</section>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import { computed, onScopeDispose, ref, watch } from 'vue'
@@ -72,7 +73,7 @@ async function inspect() {
{{ result.providerInputKeyframe.source === 'provider_variant' ? '模型专用变体' : '业务主首帧' }}
</p>
<p v-if="result.providerInputKeyframe.variantReason">
变体原因:{{ result.providerInputKeyframe.variantReason }}
变体原因:{{ userFacingText(result.providerInputKeyframe.variantReason) }}
</p>
<ul class="space-y-2">
<li v-for="reference in result.references" :key="`${reference.subjectId}:${reference.subjectFormId}`">
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { videoOperationAllowed } from '../video-permissions'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
@@ -265,7 +266,7 @@ const optionsExpanded = ref<string[]>(['options'])
type="warning"
:show-icon="false"
>
{{ videoQuery.error.value || videoQuery.data.value?.staleReason }}
{{ userFacingText(videoQuery.error.value || videoQuery.data.value?.staleReason) }}
</ContextNotice>
<AppForm
ref="formRef"
@@ -322,7 +323,7 @@ const optionsExpanded = ref<string[]>(['options'])
本次仅创建一个修复视频,不自动等待或复检。完成后请打开新候选的质量检查;修复约束沿用上次失败校验,不使用额外参数。
</p>
<ContextNotice v-if="!repairAvailable" type="warning" :show-icon="false" class="mt-3"
>当前候选不允许执行所选质量操作,请查看后端原因或刷新权限。</ContextNotice
>当前候选暂时不能执行这项检查,请查看原因或刷新任务状态。</ContextNotice
>
<NCollapse
v-if="!videoRepair"
@@ -399,7 +400,7 @@ const optionsExpanded = ref<string[]>(['options'])
个视频生成任务,可能产生费用;生成完成不会切换主视频,需再次付费复检通过后才会晋升。</template
>
<template v-else-if="target?.kind === 'video'"
>本次提交一次视频校验请求,后端可能调用多个视觉模型并产生费用。</template
>本次会检查视频画面,可能使用多个识图模型并产生费用。</template
>
<template v-else-if="valid"
>本次最多调用 {{ maxImages }} 次生图、{{ maxValidations }} 次视觉校验,均可能产生费用。</template
@@ -437,7 +438,7 @@ const optionsExpanded = ref<string[]>(['options'])
><NCollapseItem name="saved" :title="`本会话最近校验 · ${saved.passed ? '通过' : '未通过'}`"
><p>{{ saved.summary }}</p>
<p v-for="(issue, index) in saved.issues" :key="index" class="mt-2 text-danger">
{{ issue.description }}
{{ userFacingText(issue.description) }}
</p>
<p class="mt-3 text-xs text-muted">此为历史抽样结论,不保证当前上游素材仍然一致。</p></NCollapseItem
></NCollapse
@@ -1,4 +1,6 @@
<script setup lang="ts">
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { computed } from 'vue'
@@ -105,10 +107,10 @@ function exportResult() {
</p>
</template>
<template v-else>
<p class="mt-3 text-sm">{{ receipt.result.summary || '后端未提供摘要。' }}</p>
<p class="mt-3 text-sm">{{ receipt.result.summary || '本次检查没有提供结果摘要。' }}</p>
<p v-if="receipt.kind === 'video'" class="mt-2 text-xs text-muted">
{{
receipt.promoted ? '修复候选已通过,后端已将其设为主视频。' : '本次校验未晋升主视频。'
receipt.promoted ? '修复后的视频已通过检查,并设为主视频。' : '本次检查没有更换主视频。'
}}仅为抽样帧视觉结果,不含音频、口型或完整运动检测。
</p>
<p v-else class="mt-2 text-xs text-muted">只校验,不重生成或切换主首帧。</p>
@@ -120,7 +122,7 @@ function exportResult() {
:show-icon="false"
class="mt-3"
>
{{ issue.frameLabel ? `${issue.frameLabel} · ` : '' }}{{ issue.description }}
{{ issue.frameLabel ? `${issue.frameLabel} · ` : '' }}{{ userFacingText(issue.description) }}
</ContextNotice>
<NCollapse class="mt-4" :default-expanded-names="['details']">
<NCollapseItem name="details" title="主体检查与执行详情">
@@ -143,7 +145,7 @@ function exportResult() {
>{{
check.result.applicable === false ? '不适用' : check.result.passed ? '通过' : '未通过'
}}
· {{ check.result.summary }}</template
· {{ userFacingText(check.result.summary) }}</template
><template v-else>未执行</template>
</div>
<div
@@ -162,7 +164,7 @@ function exportResult() {
<p v-for="issue in subject.issues" :key="issue">{{ issue }}</p>
</div>
</template>
<pre class="quality-json">{{ JSON.stringify(receipt.result, null, 2) }}</pre>
<RawDataDetails :value="receipt.result" />
</NCollapseItem>
</NCollapse>
</section>
@@ -870,7 +870,7 @@ defineExpose({ inspectSpecs, inspecting })
videoStale
? '使用当前视频提示词、主首帧和主体参考图启动严格质量流水线;最多自动修复 2 次,通过后才接替当前过期主视频。'
: currentVideo
? '新增一个严格质量候选;后端会自动校验并最多修复 2 次,通过后才替换主视频。'
? '新增一个视频候选,自动检查并最多修复 2 次;通过检查后才替换主视频。'
: '启动严格视频质量流水线;任务在后台生成、校验并有限修复,通过后才晋升主视频。'
"
primary
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { computed } from 'vue'
@@ -145,7 +146,7 @@ function rollbackLabel(target: VideoQualityRollbackTarget) {
:key="index"
:class="issue.severity === 'error' ? 'text-danger' : 'text-muted'"
>
{{ issue.frameLabel ? `${issue.frameLabel} · ` : '' }}{{ issue.description }}
{{ issue.frameLabel ? `${issue.frameLabel} · ` : '' }}{{ userFacingText(issue.description) }}
</li>
</ul>
</article>
@@ -1,3 +1,4 @@
import { userFacingText } from '../../lib/user-facing-text'
import { issueLabel } from './model'
import type { ProductionIssue } from './types'
@@ -36,7 +37,7 @@ export function productionMessage(message: string): string {
.replace(/服务器内部错误[::]?\s*/g, '')
.replace(/\s*[::]?\s*\bc[a-z0-9]{20,}\b/g, '')
.trim()
return /[\u4e00-\u9fff]/.test(translated) ? translated : '暂时无法读取生成信息,请稍后重新获取。'
return userFacingText(translated, '暂时无法读取生成信息,请稍后重新获取。')
}
/**
@@ -266,7 +266,7 @@ export function useAdvancedProduction() {
}
throw cause
}
if (!started.executionId) throw new Error('后端未返回 Production executionId,请勿重复提交。')
if (!started.executionId) throw new Error('未取得制作任务编号,请先刷新状态,避免重复提交。')
await execution.track(started.executionId, projectId)
})
if (!disposed && id.value === projectId) {
+3 -3
View File
@@ -217,7 +217,7 @@ export function useQuality(
if (video.motionPlanStale || video.qualityTerminalStatus === 'stale_motion_plan')
clearVideoQualification(projectId, target.shotId, target.assetId)
if (!videoOperationAllowed(video, action === 'repair' ? 'repair' : 'validate'))
throw new Error(video.staleReason || '后端当前不允许此候选执行所选质量操作,请刷新权限。')
throw new Error(video.staleReason || '当前候选暂时不能执行这项检查,请刷新状态后再试。')
if (action === 'repair') {
if (videos.some(item => ['pending', 'queued', 'running'].includes(item.status)))
throw new Error('此镜头仍有活动视频任务,请结束后再修复。')
@@ -257,7 +257,7 @@ export function useQuality(
!Array.isArray(result.sampleFrames) ||
typeof result.isPrimary !== 'boolean'
)
throw new Error('视频校验结果与目标不匹配或不完整,请核对后端记录。')
throw new Error('视频检查结果不完整或与所选视频不一致,请刷新检查记录。')
receiptTarget.videoValidation = result
receipt = {
kind: 'video',
@@ -309,7 +309,7 @@ export function useQuality(
result.keyframeId !== target.assetId ||
!result.validationTaskId
)
throw new Error('首帧校验结果不完整或与目标不匹配,请核对后端记录。')
throw new Error('首帧检查结果不完整或与所选图片不一致,请刷新检查记录。')
receipt = { kind: 'keyframe', result }
}
}
@@ -15,18 +15,14 @@ import { errorMessage } from '../../lib/http'
import { projectsApi } from '../projects/api'
import { projectAssetsApi } from './api'
import type { GlobalProjectAsset, ProjectAssetProject } from './types'
import { assetCategoryLabel as categoryLabel, assetCategoryOptions } from './categories'
import AssetCategorySelect from './components/AssetCategorySelect.vue'
/** 后端当前允许的图片格式与大小。 */
const ACCEPTED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
const MAX_FILE_SIZE = 20 * 1024 * 1024
const categoryPattern = /^[a-z0-9_-]+$/
const categoryLabels: Record<string, string> = {
overall: '综合',
character: '人物',
scene: '场景',
prop: '道具',
reference: '参考素材'
}
/** 全局接口一次返回全部图片及所属剧本,避免按项目产生 N 次请求。 */
const query = useQuery(ref('all-project-assets'), (_, signal) => projectAssetsApi.listAll(signal))
@@ -59,11 +55,8 @@ const uploadProjectOptions = computed(() =>
.toSorted((a, b) => projectName(a).localeCompare(projectName(b), 'zh-CN'))
.map(project => ({ label: projectName(project), value: project.id }))
)
const categoryOptions = computed(() =>
[...new Set(assets.value.map(asset => asset.category))]
.toSorted()
.map(value => ({ label: categoryLabel(value), value }))
)
/** 筛选只展示已有分类,显示中文且仍提交原始分类值。 */
const categoryOptions = computed(() => assetCategoryOptions(assets.value.map(asset => asset.category), false))
const filteredAssets = computed(() => {
const keyword = search.value.trim().toLowerCase()
return assets.value.filter(asset => {
@@ -80,7 +73,7 @@ const formRules = {
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
category: fieldRule(
value => typeof value === 'string' && categoryPattern.test(value.trim()),
'分类只能包含小写字母、数字、下划线和连字符'
'请选择分类;自定义分类请使用小写字母、数字、下划线或短横线。'
)
}
@@ -88,9 +81,7 @@ function projectName(project: Pick<ProjectAssetProject, 'title' | 'topic'>) {
return project.title?.trim() || project.topic
}
function categoryLabel(value: string) {
return categoryLabels[value] ?? value
}
function formatBytes(value: number) {
if (value < 1024) return `${value} B`
@@ -329,20 +320,20 @@ async function removeAsset() {
:busy="busy"
>
<FeedbackMessage v-if="actionError" :message="actionError" />
<AppForm :model="uploadForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="uploadAsset">
<AppForm id="library-upload-form" :model="uploadForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="uploadAsset">
<p class="mb-4 text-sm">{{ selectedFile?.name }} · {{ formatBytes(selectedFile?.size ?? 0) }}</p>
<NFormItem path="projectId" label="所属剧本">
<NSelect v-model:value="uploadForm.projectId" filterable :options="uploadProjectOptions" />
</NFormItem>
<NFormItem path="name" label="素材名称"><NInput v-model:value="uploadForm.name" /></NFormItem>
<NFormItem path="category" label="分类标识">
<NInput v-model:value="uploadForm.category" placeholder="例如 character、scene、prop" />
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="uploadForm.category" :categories="assets.map(asset => asset.category)" :disabled="busy" />
</NFormItem>
<div class="mt-4 flex justify-end gap-3">
<NButton :disabled="busy" @click="uploadOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" :loading="busy">确认上传</NButton>
</div>
</AppForm>
<template #footer>
<NButton :disabled="busy" @click="uploadOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="library-upload-form" :loading="busy">确认上传</NButton>
</template>
</AppDialog>
<AppDialog
@@ -353,7 +344,7 @@ async function removeAsset() {
wide
>
<FeedbackMessage v-if="actionError" :message="actionError" />
<AppForm :model="editForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="updateAsset">
<AppForm id="library-edit-form" :model="editForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="updateAsset">
<div v-if="selectedAsset" class="asset-management-layout">
<AssetImage
:src="selectedAsset.publicUrl"
@@ -366,15 +357,15 @@ async function removeAsset() {
<NFormItem label="所属剧本">
<NInput :value="projectName(selectedAsset.project)" disabled />
</NFormItem>
<NFormItem path="name" label="素材名称"><NInput v-model:value="editForm.name" /></NFormItem>
<NFormItem path="category" label="分类标识">
<NInput v-model:value="editForm.category" />
<NFormItem path="name" label="素材名称" :label-props="{ for: 'library-asset-name' }"><NInput v-model:value="editForm.name" :input-props="{ id: 'library-asset-name' }" /></NFormItem>
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="editForm.category" :categories="assets.map(asset => asset.category)" :disabled="busy" />
</NFormItem>
<dl class="asset-detail-grid">
<dt>原始文件名</dt>
<dd>{{ metadataOriginalName(selectedAsset.metadata) }}</dd>
<dt>文件类型</dt>
<dd>{{ selectedAsset.mimeType }} · {{ selectedAsset.extension.toUpperCase() }}</dd>
<dd>{{ selectedAsset.extension.toUpperCase() }} 图片</dd>
<dt>文件大小</dt>
<dd>{{ formatBytes(selectedAsset.size) }}</dd>
<dt>创建时间</dt>
@@ -384,6 +375,8 @@ async function removeAsset() {
</dl>
</div>
</div>
</AppForm>
<template #footer>
<div class="asset-management-footer">
<NPopconfirm
:positive-button-props="{ disabled: busy }"
@@ -396,14 +389,14 @@ async function removeAsset() {
<template #icon><Trash2 :size="14" /></template>删除素材
</NButton>
</template>
删除后物理文件也会移除;正在被视觉风格引用的素材会由后端阻止删除。
删除后图片文件也会移除。正在用于视觉风格的素材需要先取消引用,才能删除。
</NPopconfirm>
<div class="flex gap-3">
<div class="ml-auto flex gap-2">
<NButton :disabled="busy" @click="editOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" :loading="busy">保存修改</NButton>
<NButton type="primary" attr-type="submit" form="library-edit-form" :loading="busy">保存修改</NButton>
</div>
</div>
</AppForm>
</template>
</AppDialog>
</WorkspacePage>
</template>
@@ -465,7 +458,7 @@ async function removeAsset() {
--asset-detail-image-max-height: min(56dvh, 560px);
display: block;
width: fit-content;
max-width: 100%;
max-width: min(40vw, 400px);
height: auto;
min-height: 0;
aspect-ratio: auto;
@@ -506,7 +499,7 @@ async function removeAsset() {
@apply min-w-0 break-all text-ink;
}
.asset-management-footer {
@apply flex items-center justify-between gap-3 mt-5 pt-4;
@apply flex w-full flex-wrap items-center justify-between gap-3;
}
@container asset-library (max-width: 840px) {
.asset-library-filters {
@@ -530,4 +523,9 @@ async function removeAsset() {
@apply justify-self-start;
}
}
/* 弹窗通过 Teleport 展示,使用视口适配,不依赖页面容器查询。 */
@media (max-width: 640px) {
.asset-management-layout { grid-template-columns: minmax(0, 1fr); }
.asset-management-preview { --asset-detail-image-max-height: min(36dvh, 320px); max-width: 100%; justify-self: center; }
}
</style>
@@ -15,18 +15,14 @@ import { runOperation } from '../workflows/operations'
import { useProjectMutationGuard } from '../workflows/useProjectMutationGuard'
import { projectAssetsApi } from './api'
import type { ProjectAsset } from './types'
import { assetCategoryLabel as categoryLabel, assetCategoryOptions } from './categories'
import AssetCategorySelect from './components/AssetCategorySelect.vue'
/** 后端第一阶段只支持这三种图片格式,单文件最多 20MB。 */
const ACCEPTED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
const MAX_FILE_SIZE = 20 * 1024 * 1024
const categoryPattern = /^[a-z0-9_-]+$/
const categoryLabels: Record<string, string> = {
overall: '综合',
character: '人物',
scene: '场景',
prop: '道具',
reference: '参考素材'
}
const { projectId, blocked } = useProjectMutationGuard()
const query = useQuery(projectId, async (id, signal) => {
@@ -47,10 +43,8 @@ const fileError = ref('')
const uploadForm = reactive({ name: '', category: 'reference' })
const editForm = reactive({ name: '', category: '' })
const categoryOptions = computed(() => {
const values = new Set([...Object.keys(categoryLabels), ...assets.value.map(asset => asset.category)])
return [...values].toSorted().map(value => ({ label: categoryLabel(value), value }))
})
/** 项目筛选复用中文分类映射,兼容已有自定义分类。 */
const categoryOptions = computed(() => assetCategoryOptions(assets.value.map(asset => asset.category)))
const filteredAssets = computed(() => {
const keyword = search.value.trim().toLowerCase()
return assets.value.filter(asset => {
@@ -65,13 +59,11 @@ const formRules = {
name: fieldRule(value => typeof value === 'string' && !!value.trim(), '请输入素材名称'),
category: fieldRule(
value => typeof value === 'string' && categoryPattern.test(value.trim()),
'分类只能包含小写字母、数字、下划线和连字符'
'请选择分类;自定义分类请使用小写字母、数字、下划线或短横线。'
)
}
function categoryLabel(value: string) {
return categoryLabels[value] ?? value
}
function metadataOriginalName(value: unknown) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return ''
@@ -126,7 +118,7 @@ async function uploadAsset() {
name: uploadForm.name.trim(),
category: uploadForm.category.trim()
})
if (!asset || asset.projectId !== id) throw new Error('后端未返回当前项目的素材记录,请刷新核对。')
if (!asset || asset.projectId !== id) throw new Error('未取得当前剧本的素材记录,请刷新后核对。')
})
if (!ok || projectId.value !== id) return
uploadOpen.value = false
@@ -151,7 +143,7 @@ async function updateAsset() {
category: editForm.category.trim()
})
if (!result || result.id !== asset.id || result.projectId !== id)
throw new Error('后端未确认素材更新,请刷新核对。')
throw new Error('素材更新结果尚未确认,请刷新后核对。')
})
if (!ok || projectId.value !== id) return
editOpen.value = false
@@ -165,7 +157,7 @@ async function removeAsset(asset: ProjectAsset) {
const ok = await runOperation(id, '删除项目素材', async () => {
const result = await projectAssetsApi.remove(id, asset.id)
if (!result || result.id !== asset.id || result.projectId !== id)
throw new Error('后端未确认素材删除,请刷新核对。')
throw new Error('素材删除结果尚未确认,请刷新后核对。')
})
if (ok && projectId.value === id) await query.refresh()
}
@@ -251,7 +243,7 @@ async function removeAsset(asset: ProjectAsset) {
<template #icon><Trash2 :size="14" /></template>删除
</NButton>
</template>
删除后物理文件也会移除;正在被视觉风格引用的素材会由后端阻止删除。
删除后图片文件也会移除。正在用于视觉风格的素材需要先取消引用,才能删除。
</NPopconfirm>
</div>
</div>
@@ -270,20 +262,20 @@ async function removeAsset(asset: ProjectAsset) {
<AppDialog
v-model:open="uploadOpen"
title="上传项目素材"
description="确认名称和分类后上传。分类会用于资产筛选,并进入后端存储路径。"
description="填写名称并选择分类,方便之后查找和使用这张图片。"
:busy="blocked"
>
<AppForm :model="uploadForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="uploadAsset">
<AppForm id="project-upload-form" :model="uploadForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="uploadAsset">
<p class="mb-4 text-sm">{{ selectedFile?.name }} · {{ formatBytes(selectedFile?.size ?? 0) }}</p>
<NFormItem path="name" label="素材名称"><NInput v-model:value="uploadForm.name" /></NFormItem>
<NFormItem path="category" label="分类标识">
<NInput v-model:value="uploadForm.category" placeholder="例如 character、scene、prop" />
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="uploadForm.category" :categories="assets.map(asset => asset.category)" :disabled="blocked" />
</NFormItem>
<div class="mt-4 flex justify-end gap-3">
<NButton :disabled="blocked" @click="uploadOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" :loading="blocked">确认上传</NButton>
</div>
</AppForm>
<template #footer>
<NButton :disabled="blocked" @click="uploadOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="project-upload-form" :loading="blocked">确认上传</NButton>
</template>
</AppDialog>
<AppDialog
@@ -292,14 +284,14 @@ async function removeAsset(asset: ProjectAsset) {
description="只修改名称和分类,不会替换图片文件或修改已保存的引用地址。"
:busy="blocked"
>
<AppForm :model="editForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="updateAsset">
<AppForm id="project-edit-form" :model="editForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="updateAsset">
<NFormItem path="name" label="素材名称"><NInput v-model:value="editForm.name" /></NFormItem>
<NFormItem path="category" label="分类标识"><NInput v-model:value="editForm.category" /></NFormItem>
<div class="mt-4 flex justify-end gap-3">
<NButton :disabled="blocked" @click="editOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" :loading="blocked">保存修改</NButton>
</div>
<NFormItem path="category" label="素材分类"><AssetCategorySelect v-model:value="editForm.category" :categories="assets.map(asset => asset.category)" :disabled="blocked" /></NFormItem>
</AppForm>
<template #footer>
<NButton :disabled="blocked" @click="editOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="project-edit-form" :loading="blocked">保存修改</NButton>
</template>
</AppDialog>
</WorkspacePage>
</template>
+23
View File
@@ -0,0 +1,23 @@
/** 素材分类的展示名称;取值仍使用现有接口约定,不改写已保存分类。 */
const labels: Record<string, string> = {
overall: '综合', character: '人物', scene: '场景', prop: '道具', reference: '参考素材',
'visual-style': '视觉风格', subjects: '主体图片', keyframes: '首帧图片', videos: '视频素材'
}
/**
* 将系统分类转换为中文,用户自定义名称保持原样。
* @param value 原始分类
* @returns 分类展示名称
*/
export function assetCategoryLabel(value: string): string { return labels[value] ?? value }
/**
* 为上传、编辑及筛选复用中文分类选项,原始值不受影响。
* @param values 当前素材已有的分类
* @param defaults 是否包含常用分类
* @returns 按原始值去重的分类选项
*/
export function assetCategoryOptions(values: string[], defaults = true) {
return [...new Set([...(defaults ? Object.keys(labels) : []), ...values])]
.toSorted().map(value => ({ label: assetCategoryLabel(value), value }))
}
@@ -0,0 +1,22 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NSelect } from 'naive-ui'
import { assetCategoryOptions } from '../categories'
/** 素材分类使用中文选择,仍保留已有分类和自定义分类能力。 */
const props = withDefaults(defineProps<{
/** 已有素材的分类,避免编辑时丢失自定义值。 */
categories?: string[]
/** 提交时禁止修改。 */
disabled?: boolean
}>(), { categories: () => [] })
/** 表单和请求始终保存原始分类值。 */
const value = defineModel<string>('value', { default: '' })
/** 常用分类及已有自定义分类共用同一份中文选项。 */
const options = computed(() => assetCategoryOptions([...props.categories, ...(value.value ? [value.value] : [])]))
</script>
<template>
<!-- 以下是中文分类选择模块,自定义取值仍由表单按接口要求校验 -->
<NSelect :value="value" :options="options" :disabled="disabled" filterable tag placeholder="选择分类,或输入自定义分类" aria-label="素材分类" @update:value="value = String($event ?? '')" />
</template>
+2 -2
View File
@@ -6,7 +6,7 @@ import { useRoute, useRouter } from 'vue-router'
import { NScrollbar, NButton, NPageHeader, NSpin, NEllipsis } from 'naive-ui'
import { EmptyState, WorkspaceRefreshButton } from '../../components/ui'
import { projectContextKey, useProjectData } from './context'
import { getOperation } from '../workflows/operations'
import { getOperation, operationErrorText } from '../workflows/operations'
import { projectAccessKey, projectSectionFromPath, type ProjectAccess } from './access'
import { useProjectStageAccess } from './useProjectStageAccess'
import { useWorkflowExecution } from '../workflows/execution'
@@ -116,7 +116,7 @@ type OperationGuide = {
}
/** 仅为明确缺失的前置条件提供恢复入口,不把同页生成失败变成无效跳转。 */
const operationGuide = computed<OperationGuide | null>(() => {
const error = operation.value.error?.trim()
const error = operationErrorText(operation.value).trim()
if (!error) return null
const normalized = error.toLowerCase()
if (normalized.includes('primary keyframe') || error.includes('主首帧'))
+1 -1
View File
@@ -202,7 +202,7 @@ function clearFilters() {
><div>
{{
query.error.value
? '等待连接后端'
? '正在尝试连接服务'
: projects.length
? '没有匹配的剧本'
: '还没有剧本,点击右上角新建'
@@ -46,7 +46,7 @@ async function remove() {
state.error = ''
try {
const result = await projectsApi.delete(id)
if (!result.deleted || result.id !== id) throw new Error('后端未确认项目删除结果。')
if (!result.deleted || result.id !== id) throw new Error('项目删除结果尚未确认,请刷新后核对。')
emit('deleted', id)
open.value = false
} catch (cause) {
@@ -64,8 +64,7 @@ async function remove() {
<!-- 删除范围与后台任务状态属于同组,保持 8px 间距 -->
<div class="space-y-2">
<ContextNotice type="error" :show-icon="false">
会永久删除剧本、主体、身份、形态、分镜、首帧、视频、工作流记录,以及本地 Storage
中属于该项目的图片、视频和上传素材。
会永久删除这个项目的剧本、人物、场景、道具、形态、分镜、首帧、视频和制作记录,以及上传或生成的素材文件。
</ContextNotice>
<ContextNotice v-if="readinessPending" type="info" :show-icon="false"
>正在检查项目后台任务…</ContextNotice
@@ -0,0 +1,93 @@
import { policyIssue } from './quality-policy'
import type { ProjectQualityPolicy } from './types'
/** 同一页面中主动保存规则后,也撤销无法持久化的临时确认。 */
const invalidations = new Map<string, number>()
/**
* 只比较质量规则的规范化内容,不把模型参数或对象属性顺序作为变更。
* @param policy 后端读取或用户编辑的完整规则
* @returns 可精确比较的内容签名,不是后端授权令牌
*/
export function qualityPolicySignature(policy: ProjectQualityPolicy): string {
if (!policy || !Array.isArray(policy.customRules) ||
(policy.actionExceptions !== undefined && !Array.isArray(policy.actionExceptions)))
throw new Error('质量规则响应不完整,请重新读取。')
const issue = policyIssue(policy)
if (issue) throw new Error(issue)
return JSON.stringify({
version: policy.version,
physicsMode: policy.physicsMode,
allowExaggeratedMotion: policy.allowExaggeratedMotion,
allowNonPhysicalActions: policy.allowNonPhysicalActions,
allowSupernaturalAbilities: policy.allowSupernaturalAbilities,
customRules: policy.customRules.map(rule => rule.trim()),
actionExceptions: (policy.actionExceptions ?? []).map(item => ({
code: item.code,
ownerRef: item.ownerRef.trim(),
resource: item.resource,
reason: item.reason.trim()
}))
})
}
/**
* 隔离项目及本地确认格式版本。
* @param projectId 当前项目
* @returns 本地 UX 记忆键
*/
function confirmationKey(projectId: string): string {
return `short-drama:breakdown-quality-confirmation:v1:${projectId}`
}
/**
* 读取当前浏览器明确确认过的规则,不将默认值当作确认。
* @param projectId 当前项目
* @returns 已确认内容或空值,损坏与不可用存储均不视为确认
*/
export function readQualityPolicyConfirmation(projectId: string): string | null {
try {
const raw = localStorage.getItem(confirmationKey(projectId))
if (!raw) return null
const parsed: unknown = JSON.parse(raw)
if (!parsed || typeof parsed !== 'object' || !('signature' in parsed) ||
!('formatVersion' in parsed) || parsed.formatVersion !== 1 ||
typeof parsed.signature !== 'string') return null
return parsed.signature
} catch {
return null
}
}
/**
* 仅在用户明确确认后记住当前浏览器的规则内容,不能代替后端门禁。
* @param projectId 当前项目
* @param signature 已核对的规则内容
* @returns 是否成功持久化,失败时调用方只保留本次会话确认
*/
export function rememberQualityPolicyConfirmation(projectId: string, signature: string): boolean {
try {
localStorage.setItem(confirmationKey(projectId), JSON.stringify({ formatVersion: 1, signature }))
return true
} catch {
return false
}
}
/**
* 规则有实质变化时撤销本地确认,无变化保存不调用此方法。
* @param projectId 规则所属项目
*/
export function invalidateQualityPolicyConfirmation(projectId: string) {
invalidations.set(projectId, qualityPolicyConfirmationEpoch(projectId) + 1)
try { localStorage.removeItem(confirmationKey(projectId)) } catch { /* 存储受限时仍撤销页面内确认。 */ }
}
/**
* 当前页面内的确认失效代次,用于存储受限的降级场景。
* @param projectId 当前项目
* @returns 规则失效代次
*/
export function qualityPolicyConfirmationEpoch(projectId: string): number {
return invalidations.get(projectId) ?? 0
}
+11 -2
View File
@@ -1,3 +1,4 @@
import { userFacingText } from '../../lib/user-facing-text'
import { computed, type Ref } from 'vue'
import type { ProjectAccess, ProjectSection } from './access'
import type { ProjectStageReadiness } from './types'
@@ -6,11 +7,17 @@ function accessState(ready: boolean | undefined, reason: string | null | undefin
return { enabled: Boolean(ready), reason: reason || fallback }
}
/** 将服务端统一 readiness 转为侧栏、URL 门禁和下一步引导,前端不复制制作规则。 */
/**
* 使用真实准备情况控制侧栏与页面入口,仅转换原因文案。
* @param projectId 当前项目编号
* @param readiness 当前项目各步骤的准备情况
* @returns 各步骤入口、原因与下一步引导
*/
export function useProjectStageAccess(projectId: Ref<string>, readiness: Ref<ProjectStageReadiness | null>) {
/** 当前步骤能否进入及对应中文说明,不改变原始准备状态。 */
const sections = computed<Record<ProjectSection, ProjectAccess['sections'][ProjectSection]>>(() => {
const state = readiness.value
return {
const result: Record<ProjectSection, ProjectAccess['sections'][ProjectSection]> = {
'create-drama': { enabled: true, reason: '' },
breakdown: {
...accessState(state?.script.ready, state?.script.reason, '请先完成剧本创作'),
@@ -71,6 +78,8 @@ export function useProjectStageAccess(projectId: Ref<string>, readiness: Ref<Pro
: '前往剧本拆解'
}
}
for (const section of Object.values(result)) section.reason = userFacingText(section.reason)
return result
})
const scriptReady = computed(() => readiness.value?.script.ready === true)
return { projectId, scriptReady, sections }
+6 -5
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../lib/user-facing-text'
import { isOperationRunning } from '../workflows/operations'
import ContextNotice from '../../components/ui/ContextNotice.vue'
@@ -231,8 +232,8 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
本集有 {{ currentEpisodeDurationIssues.length }} 条分镜时长建议(不阻断生成)
</div>
<div v-for="(issue, index) in currentEpisodeDurationIssues" :key="index" class="mt-1 text-sm">
Beat {{ issue.beatNo }}<span v-if="issue.shotNo"> · Shot {{ issue.shotNo }}</span
>:{{ issue.message }}
剧情段落 {{ issue.beatNo }}<span v-if="issue.shotNo"> · 镜头 {{ issue.shotNo }}</span
>:{{ userFacingText(issue.message) }}
</div>
</ContextNotice>
<span v-if="durationAuditError" class="text-xs text-muted">{{ durationAuditError }}</span>
@@ -267,10 +268,10 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
>
<span v-else>自动规划时长</span>
<span v-if="currentDurationBudget.plannedSeconds !== null"
>Beat {{ currentDurationBudget.plannedSeconds }} 秒</span
>剧情段落 {{ currentDurationBudget.plannedSeconds }} 秒</span
>
<span v-if="currentDurationBudget.shotCount > 0 && currentDurationBudget.shotSeconds !== null"
>Shot {{ currentDurationBudget.shotSeconds }} 秒</span
>镜头 {{ currentDurationBudget.shotSeconds }} 秒</span
>
<span
v-if="durationStatusLabel"
@@ -474,7 +475,7 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
</div>
<p class="mt-4 text-[11px] leading-6 text-muted">
修改或覆盖前面的设计后,已有状态和视频提示词不会自动更新;请按顺序重新生成后续内容。自动修复次数仅用于
VisualState。
画面即时状态。
</p>
<section>
<h3 class="text-sm font-semibold">视频提示词批量操作</h3>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { NScrollbar, NButton, NTable } from 'naive-ui'
@@ -32,7 +33,7 @@ function exportReceipt() {
</ContextNotice>
<template v-if="receipt.kind === 'shots'">
<p class="my-4 text-xs text-muted">
第 {{ receipt.result.episodeNo }} 集 · {{ receipt.result.storyboardShotSummary.beatCount }} 个 Beat ·
第 {{ receipt.result.episodeNo }} 集 · {{ receipt.result.storyboardShotSummary.beatCount }} 个剧情段落 ·
{{ receipt.result.storyboardShotSummary.shotCount }} 个镜头 ·
{{ receipt.result.storyboardShotSummary.totalDurationSeconds }} 秒 · 形态绑定覆盖率
{{ Math.round(receipt.result.storyboardShotSummary.bindingCoverage * 100) }}%
@@ -47,7 +48,7 @@ function exportReceipt() {
</ContextNotice>
<ul v-else class="mt-3 space-y-2 text-xs text-danger">
<li v-for="(issue, index) in receipt.result.storyboardShotValidation.issues" :key="index">
Beat {{ issue.beatNo ?? '—' }} / Shot {{ issue.shotNo ?? '—' }}:{{ issue.message }}
剧情段落 {{ issue.beatNo ?? '—' }} / 镜头 {{ issue.shotNo ?? '—' }}:{{ userFacingText(issue.message) }}
</li>
</ul>
</template>
@@ -81,8 +82,8 @@ function exportReceipt() {
<td class="min-w-48 whitespace-pre-wrap text-xs">
<p>{{ item.error || '—' }}</p>
<p v-for="(issue, index) in item.remainingIssues" :key="index" class="mt-2 text-danger">
Beat {{ issue.beatNo ?? '—' }} / Shot {{ issue.shotNo ?? '—' }}
{{ issue.subjectRef }}:{{ issue.message }}
剧情段落 {{ issue.beatNo ?? '—' }} / 镜头 {{ issue.shotNo ?? '—' }}
{{ issue.subjectRef }}:{{ userFacingText(issue.message) }}
</p>
</td>
</tr>
@@ -98,11 +99,11 @@ function exportReceipt() {
<ul class="mt-3 space-y-2 text-xs text-danger">
<li v-for="item in receipt.result.failures" :key="item.shotId">
<code>{{ item.shotId }}</code
>:{{ item.error }}
>:{{ userFacingText(item.error) }}
</li>
</ul>
<p class="mt-3 text-xs text-muted">
当前批量接口不返回成功镜头的 Prompt 正文;选择镜头后点击“读取/生成提示词”,已有内容会直接复用。
批量处理完成后,可选择镜头查看完整画面描述;已有描述会直接使用,无需重新生成。
</p>
</template>
<p class="mt-4 text-[11px] text-muted">回执仅保留在当前浏览器会话中。数据库结果是覆盖率和镜头详情的依据。</p>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import { computed } from 'vue'
import { NButton, NCheckbox, NInput, NInputNumber, NSelect, NTag } from 'naive-ui'
import { AppDialog, AssetImage } from '../../../components/ui'
@@ -301,7 +302,7 @@ function updateRefs(index: number, value: string) {
<section v-if="preview" class="motion-revision-feedback" aria-label="免费预检查结果">
<h3>预检查结果</h3>
<p>{{ preview.valid ? '结构检查通过,仍须视觉校验;尚不可激活。' : '结构检查未通过,请修改草稿。' }}</p>
<p v-for="(message, index) in previewMessages" :key="index">{{ message }}</p>
<p v-for="(message, index) in previewMessages" :key="index">{{ userFacingText(message) }}</p>
</section>
<!-- 以下是收费视觉校验与激活模块,费用说明和操作成组排列 -->
<section class="workspace-panel motion-revision-section" aria-label="动作起点视觉校验">
@@ -331,7 +332,7 @@ function updateRefs(index: number, value: string) {
<p v-if="state.execution.query.error.value" class="text-danger">
{{ state.execution.query.error.value }}
</p>
<p v-if="record?.error" class="text-danger">{{ record.error }}</p>
<p v-if="record?.error" class="text-danger">{{ userFacingText(record.error) }}</p>
<p v-if="record?.result?.summary">{{ record.result.summary }}</p>
<p v-for="(issue, index) in taskIssues" :key="index">{{ issue }}</p>
<NTag v-if="invalidated && record" type="warning" :bordered="false"
@@ -1,7 +1,9 @@
<script setup lang="ts">
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import { NScrollbar, NButton, NCheckbox } from 'naive-ui'
import { NButton, NCheckbox } from 'naive-ui'
import { computed, onScopeDispose, ref, watch } from 'vue'
import { Download, ExternalLink } from '@lucide/vue'
import IssueHint from '../../../components/ui/IssueHint.vue'
@@ -13,7 +15,7 @@ import type { ShotGenerationSpec } from '../generation-spec.types'
import { useQuery } from '../../../composables/useQuery'
import { errorMessage } from '../../../lib/http'
import { downloadText } from '../../../lib/format'
import { getOperation, runOperation } from '../../workflows/operations'
import { getOperation, operationErrorText, runOperation } from '../../workflows/operations'
import ConfirmAction from '../../workflows/ConfirmAction.vue'
/** 镜头级只读资源与显式 Prompt 生成;查询与耗费模型的操作分开。 */
@@ -75,12 +77,12 @@ async function load(kind: 'references' | 'spec') {
if (kind === 'references') {
const result = await storyboardApi.references(shotId, controller.signal)
if (version !== revision) return
if (result.shotId !== shotId) throw new Error('参考图返回的 Shot ID 不匹配。')
if (result.shotId !== shotId) throw new Error('参考图结果与当前镜头不一致,请重新读取。')
references.value = result
} else {
const result = await storyboardApi.generationSpec(shotId, controller.signal)
if (version !== revision) return
if (result.shotId !== shotId) throw new Error('生成规格返回的 Shot ID 不匹配。')
if (result.shotId !== shotId) throw new Error('生成方案与当前镜头不一致,请重新读取。')
spec.value = result
}
} catch (error) {
@@ -108,7 +110,7 @@ async function generatePrompt() {
if (!ok) {
// 单镜头错误由 runOperation 记录到项目操作状态;这里只处理可恢复的首帧前置问题。
const operation = getOperation(projectId)
if (!/primary keyframe|主首帧/i.test(operation.error)) return
if (!/primary keyframe|主首帧/i.test(operationErrorText(operation))) return
operation.recovery = {
target: 'keyframe',
shotId,
@@ -173,7 +175,7 @@ function exportResult(kind: 'spec' | 'prompt') {
</div>
<ul v-if="references.missing.length" class="alert mt-3 space-y-2 text-xs">
<li v-for="item in references.missing" :key="item.subjectId">
{{ item.subjectName }}({{ item.subjectRef }}):{{ item.reason }}
{{ item.subjectName }}({{ item.subjectRef }}):{{ userFacingText(item.reason) }}
</li>
</ul>
<p v-if="!references.references.length && !references.missing.length" class="mt-3 text-xs text-muted">
@@ -187,15 +189,15 @@ function exportResult(kind: 'spec' | 'prompt') {
<section>
<!-- 以下是统一的生成规格模块标题与读取操作模块 -->
<WorkspaceSectionHeading
title="镜头生成规格"
description="后端合并主体稳定身份、具体形态、摄影设计与即时状态,编译为 GenerationSpec,不调用模型。需要本镜头已有 Direction 和 VisualState。"
title="镜头生成方案"
description="汇总角色特征、形态、镜头设计和画面状态,整理成生成方案。请先补齐本镜头的设计和画面状态;这一步不生成图片或视频。"
>
<template #actions>
<NButton
:disabled="locked || busy.spec || !shot.direction || !shot.visualState"
:loading="busy.spec"
@click="load('spec')"
>{{ busy.spec ? '编译中…' : '读取生成规格' }}</NButton
>{{ busy.spec ? '整理中…' : '整理生成方案' }}</NButton
>
</template>
</WorkspaceSectionHeading>
@@ -204,18 +206,16 @@ function exportResult(kind: 'spec' | 'prompt') {
><div class="mt-4 flex items-center justify-between">
<span class="text-xs text-muted"
>{{ spec.subjects.length }} 个主体 · {{ spec.durationSeconds }} 秒</span
><NButton @click="exportResult('spec')" text size="small"><Download :size="13" />导出规格</NButton>
><NButton @click="exportResult('spec')" text size="small"><Download :size="13" />导出方案</NButton>
</div>
<NScrollbar class="code-scroll mt-3" x-scrollable>
<pre class="storyboard-json">{{ JSON.stringify(spec, null, 2) }}</pre>
</NScrollbar>
<RawDataDetails :value="spec" title="完整生成方案(高级)" />
</template>
</section>
<section>
<!-- 以下是统一的视频提示词模块标题与说明模块 -->
<WorkspaceSectionHeading
title="视频提示词"
description="已有提示词可直接复用,没有则依据 GenerationSpec 与参考图调用模型生成。此处只处理 Prompt;首帧和实际视频任务请到“镜头生产”。"
description="已有的视频描述可以直接使用;缺少时会根据镜头生成方案和参考图调用模型整理。生成图片和视频请前往“镜头生产”。"
/>
<div class="mt-4 flex flex-wrap items-center gap-4">
<ConfirmAction
@@ -244,7 +244,7 @@ function exportResult(kind: 'spec' | 'prompt') {
</div>
<p class="whitespace-pre-wrap text-sm leading-7">{{ prompt.videoPrompt }}</p>
<template v-if="prompt.negativePrompt"
><h4 class="mb-2 mt-5 text-xs font-medium text-muted">Negative prompt(负向提示词)</h4>
><h4 class="mb-2 mt-5 text-xs font-medium text-muted">避免出现的内容</h4>
<p class="whitespace-pre-wrap text-sm leading-6">{{ prompt.negativePrompt }}</p></template
>
</div>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { computed, ref } from 'vue'
@@ -41,7 +42,7 @@ const result = computed(() => query.data.value)
<template v-if="result">
<ContextNotice :type="result.valid ? 'success' : 'warning'" :show-icon="false">
{{ result.valid ? '未发现主体引用遗漏' : `发现 ${result.issueCount} 项引用遗漏` }} ·
{{ result.episodeCount }} 集 / {{ result.beatCount }} 个 Beat / {{ result.shotCount }} 镜
{{ result.episodeCount }} 集 / {{ result.beatCount }} 个剧情段落 / {{ result.shotCount }} 镜
</ContextNotice>
<p class="mt-2 text-muted">
检查主体 {{ result.subjectSummary.total }} · 人物 {{ result.subjectSummary.character }} / 场景
@@ -54,7 +55,7 @@ const result = computed(() => query.data.value)
>
<div class="flex flex-wrap items-center justify-between gap-3">
<strong
>第 {{ issue.episodeNo }} 集 · Beat {{ issue.beatNo
>第 {{ issue.episodeNo }} 集 · 剧情段落 {{ issue.beatNo
}}{{ issue.shotNo !== null ? ` · 镜头 ${issue.shotNo}` : '' }} · {{ issue.subjectName }}
{{ issue.subjectRef }}</strong
>
@@ -62,7 +63,7 @@ const result = computed(() => query.data.value)
issue.shotNo === null ? '查看所在剧集' : '定位镜头'
}}</NButton>
</div>
<p>{{ issue.message }}</p>
<p>{{ userFacingText(issue.message) }}</p>
<p class="text-muted">
原文匹配:{{ issue.matchedTerm }} ·
{{
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../lib/user-facing-text'
import { isOperationRunning } from '../workflows/operations'
import ContextNotice from '../../components/ui/ContextNotice.vue'
@@ -464,7 +465,7 @@ function runNextAction() {
<h3 class="text-sm font-semibold">角色选角</h3>
<p class="mt-2 text-xs leading-6 text-muted">
只处理
Character。每张候选都根据当前身份描述独立生成,不复用旧母版;确认选择后才会设为角色母版并锁定身份。
人物角色。每张候选都根据当前身份描述独立生成,不复用旧母版;确认选择后才会设为角色母版并锁定身份。
</p>
</div>
</div>
@@ -539,7 +540,7 @@ function runNextAction() {
!casting.total
"
acknowledgement
description="只生成 Character Identity 文本,不生成图片。已锁定角色始终跳过;覆盖文本不会自动更新已有候选图。"
description="只整理人物的角色特征,不生成图片。已锁定角色始终跳过;覆盖文本不会自动更新已有候选图。"
@confirm="generateProject(true)"
/>
<ConfirmAction
@@ -553,7 +554,7 @@ function runNextAction() {
!casting.missingAnchor
"
acknowledgement
description="最多按本批上限为缺少 Anchor 的 Character 调用 图片模型,各自独立生成一张停用的 primary 候选,不复用旧身份母版。已有候选、已有母版或已完成选角的角色不会重复处理。"
description="按本批上限,为缺少标准参考图的人物角色各生成一张新候选图,可能产生费用。已有候选、标准参考图或已选定外观的角色会跳过;生成后仍需手动选择和确认。"
@confirm="generateCastingCandidates"
/>
</div>
@@ -617,8 +618,7 @@ function runNextAction() {
><NCollapseItem name="details"
><template #header>高级:全部主体身份文本</template>
<p class="mt-3 text-xs leading-6 text-muted">
同时处理 Character、Scene 和
Prop;角色选角建议优先使用上方专用入口。已锁定身份始终跳过。
同时处理人物、场景和道具;角色选角建议优先使用上方专用入口。已锁定身份始终跳过。
</p>
<NSelect
v-model:value="identityBatchModule"
@@ -688,7 +688,7 @@ function runNextAction() {
</ContextNotice>
<ul class="mt-3 space-y-2 text-xs text-danger">
<li v-for="failure in session.receipt.result.failures" :key="failure.subjectId">
{{ failure.subjectRef }} · {{ failure.subjectId }}:{{ failure.error }}
{{ failure.subjectRef }} · {{ failure.subjectId }}:{{ userFacingText(failure.error) }}
</li>
</ul>
<p class="mt-3 text-[11px] text-muted">
@@ -706,7 +706,7 @@ function runNextAction() {
v-if="catalog.error.value || styleQuery.error.value || castingQuery.error.value"
><ContextNotice role="alert" type="error" :show-icon="false"
>{{ catalog.error.value || styleQuery.error.value || castingQuery.error.value }}
当前相关操作已暂停,请刷新核对后端。
当前操作已暂停,请刷新任务状态后核对。
<NButton
v-if="catalog.error.value"
text
@@ -938,7 +938,7 @@ function runNextAction() {
>
</div>
<p v-if="!subject.forms.length" class="text-xs text-muted">
此角色尚无正式形态,但可以先完成 Identity 与选角。
这个角色还没有正式形态,可以先完善角色特征并选择外观。
</p>
<RouterLink
v-if="subjectImagesAccess.enabled"
@@ -88,7 +88,7 @@ const formModel = computed(() => ({ prompt: prompt.value }))
:label-props="{ for: 'casting-candidate-prompt' }"
>
<NInput
placeholder="建议留空,使用后端编译的稳定身份和选角约束;未明确人物背景时默认中国人物"
placeholder="建议留空,自动使用已保存的角色特征;未明确人物背景时默认中国人物"
:input-props="{ id: 'casting-candidate-prompt' }"
class="min-h-24"
v-model:value="prompt"
@@ -97,7 +97,7 @@ const formModel = computed(() => ({ prompt: prompt.value }))
></NInput>
</NFormItem>
<p v-if="prompt.trim()" class="text-xs text-danger">
自定义文本会替换后端完整提示词,请自行包含人物身份、基础服装和中性参考图要求。
填写自定义描述后,会替换自动整理的描述;请写清角色特征、基础服装和参考图要求。
</p>
<GenerationModelControls
type="image"
@@ -1,4 +1,5 @@
<script setup lang="ts">
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
@@ -208,8 +209,7 @@ const rules = {
@submit="submit"
>
<ContextNotice type="info" :show-icon="false" class="text-xs">
调用 图片模型,每次新增一张图片,可能产生费用。第一张成功的 primary 图自动成为母版;已有母版时,新
primary 图仅作为停用候选保留。
调用 图片模型,每次新增一张图片,可能产生费用。第一张成功的主视图会成为标准参考图;已经有标准参考图时,新主视图只作为候选保留。
</ContextNotice>
<!-- 以下是多视角与已有身份图选择模块,单一选项不显示选择器 -->
<NFormItem
@@ -221,7 +221,7 @@ const rules = {
><NSelect
id="identity-view"
v-model:value="viewType"
:options="allowedViews.map(([value, label]) => ({ label: label + '(' + value + ')', value }))"
:options="allowedViews.map(([value, label]) => ({ label, value }))"
class="select-control"
></NSelect
></NFormItem>
@@ -235,7 +235,7 @@ const rules = {
<template #label>
<FieldLabel
label="身份锚定来源"
description="只能选择此主体已完成的图片。后端需取得图片服务可访问的远程地址;本地预览可见不保证远程地址仍有效。"
description="只能选择这个主体已生成完成的图片。图片链接需要仍可访问,预览能显示不代表链接一直有效。"
/>
</template>
<NSelect
@@ -243,7 +243,7 @@ const rules = {
v-model:value="referenceImageId"
:options="[
{
label: String(anchor ? '自动引用当前身份母版' : '自动选择(由后端解析参考图)'),
label: String(anchor ? '自动引用当前身份母版' : '自动选择合适的参考图'),
value: ''
},
...references.map(image => ({
@@ -260,7 +260,7 @@ const rules = {
label="覆盖本次完整提示词(可选)"
:label-props="{ for: 'identity-image-prompt' }"
><NInput
placeholder="建议留空,使用后端编译的身份约束和视角要求"
placeholder="建议留空,自动使用已保存的角色特征和视角要求"
:input-props="{ id: 'identity-image-prompt' }"
class="min-h-24"
v-model:value="prompt"
@@ -269,7 +269,7 @@ const rules = {
></NInput>
</NFormItem>
<p v-if="prompt.trim()" class="text-xs text-danger">
自定义文本会替换后端编译的完整提示词,请自行包含身份约束和视角要求。
填写自定义描述后,会替换自动整理的完整描述;请写清角色特征和视角要求。
</p>
<GenerationModelControls
type="image"
@@ -297,17 +297,7 @@ const rules = {
<div v-if="preview" class="text-xs space-y-3">
<p>实际供应方:{{ preview.provider }} · 模型:{{ preview.model }}</p>
<p class="whitespace-pre-wrap">最终提示词:{{ preview.providerPrompt }}</p>
<pre class="whitespace-pre-wrap break-all">{{
JSON.stringify(
{
referenceImages: preview.referenceImages,
referencePlan: preview.referencePlan,
generationConfig: preview.generationConfig
},
null,
2
)
}}</pre>
<RawDataDetails :value="{ referenceImages: preview.referenceImages, referencePlan: preview.referencePlan, generationConfig: preview.generationConfig }" title="参考图与生成设置(高级)" />
</div>
<NCheckbox
id="identity-image-cost"
@@ -89,7 +89,7 @@ function submit() {
<ContextNotice type="warning" :show-icon="false"
>最多生成
{{ maxRepairAttempts + 1 }}
张候选,并逐张调用视觉校验;道具还可能调用结构编译模型,均可能产生费用。只有真实通过后,后端才会切换母版并锁定身份。</ContextNotice
张候选,并逐张调用视觉校验;道具还可能调用结构编译模型,均可能产生费用。只有通过检查后,才会更换标准参考图并锁定角色特征。</ContextNotice
>
<GenerationModelControls
type="image"
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../lib/user-facing-text'
import { isOperationRunning } from '../workflows/operations'
import ContextNotice from '../../components/ui/ContextNotice.vue'
@@ -102,7 +103,7 @@ const impactOptions = computed(() => {
if (sourceShot.value && !items.some(item => item.shotId === sourceShot.value?.shotId)) items.push(sourceShot.value)
return items.map(item => ({
value: item.shotId,
label: `第 ${item.episodeNo} 集 · BEAT ${item.beatNo} / 镜头 ${item.shotNo}${item.inconsistent ? ' · 状态待核对' : item.primaryKeyframeStale ? ' · 首帧过期' : ' · 当前镜头'}`
label: `第 ${item.episodeNo} 集 · 剧情段落 ${item.beatNo} / 镜头 ${item.shotNo}${item.inconsistent ? ' · 状态待核对' : item.primaryKeyframeStale ? ' · 首帧过期' : ' · 当前镜头'}`
}))
})
const toolsOpen = ref(false)
@@ -432,7 +433,7 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
<ul class="mt-3 space-y-2 text-xs text-danger">
<li v-for="failure in session.receipt.result.failures" :key="failure.subjectFormId">
<code>{{ failure.subjectFormId }}</code
>:{{ failure.error }}
>:{{ userFacingText(failure.error) }}
</li>
</ul>
<p class="mt-3 text-[11px] text-muted">
@@ -476,7 +477,7 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
class="flex flex-wrap items-center gap-x-4 gap-y-2"
>
<span class="font-medium"
>第 {{ shot.episodeNo }} 集 · BEAT {{ shot.beatNo }} / 镜头 {{ shot.shotNo }}</span
>第 {{ shot.episodeNo }} 集 · 剧情段落 {{ shot.beatNo }} / 镜头 {{ shot.shotNo }}</span
>
<NTag size="small" :bordered="false" type="warning">{{
shot.inconsistent ? '状态待核对' : '首帧过期'
@@ -775,7 +776,7 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
:show-icon="false"
class="mt-3 text-xs leading-6"
>
第 {{ sourceShot.episodeNo }} 集 · BEAT {{ sourceShot.beatNo }} / 镜头
第 {{ sourceShot.episodeNo }} 集 · 剧情段落 {{ sourceShot.beatNo }} / 镜头
{{ sourceShot.shotNo }} 的待处理首帧关联此素材。
{{
sourceShot.inconsistent
@@ -787,7 +788,7 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
>
</ContextNotice>
<p v-if="form.images[0]?.status === 'failed'" class="mt-2 line-clamp-2 text-xs text-danger">
{{ form.images[0].error }}
{{ userFacingText(form.images[0].error) }}
</p>
<div class="mt-4 flex flex-wrap items-center justify-between gap-2">
<NButton @click="openGallery(form)" text size="small">查看图片与记录</NButton>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import AppForm from '../../../components/ui/AppForm.vue'
@@ -83,7 +84,7 @@ const rules = { concurrency: integerRule('提示词并发') }
<ul class="mt-3 space-y-2 text-xs text-danger">
<li v-for="failure in receipt.result.failures" :key="failure.subjectFormId">
<code>{{ failure.subjectFormId }}</code
>:{{ failure.error }}
>:{{ userFacingText(failure.error) }}
</li>
</ul>
</section>
@@ -19,7 +19,7 @@ function generate() {
if (!props.disabled && props.form) emit('generate', props.form.id, hasPrompt.value)
}
/** 导出数据库已保存的提示词,不把原始外观伪装成最终 Prompt。 */
/** 导出数据库已保存的提示词,不把原始外观伪装成最终画面描述。 */
function exportPrompt() {
if (props.form?.generationPrompt) downloadText(`form-${props.form.id}-prompt.txt`, props.form.generationPrompt)
}
@@ -33,7 +33,7 @@ function exportPrompt() {
>
<ContextNotice type="info" :show-icon="false" class="mt-5 text-xs">
结合形态描述与项目视觉风格生成并保存
generationPrompt。只调用文本模型,不生成图片;覆盖不会修改已有图片的实际提示词或主图。
画面描述。这里只整理文字,不生成图片;重新整理不会修改已有图片或主图。
</ContextNotice>
<section class="dialog-section mt-5">
<h3 class="text-sm font-medium">原始外观素材</h3>
@@ -44,7 +44,7 @@ function exportPrompt() {
<section class="dialog-section mt-4">
<h3 class="text-sm font-medium">正式生图提示词</h3>
<p class="mt-3 whitespace-pre-wrap break-words text-sm leading-6">
{{ form?.generationPrompt || '尚未生成。可先在这里生成检查,也可由生图接口自动补齐。' }}
{{ form?.generationPrompt || '尚未生成。可先在这里生成检查,也可在生成图片时自动补齐。' }}
</p>
</section>
<div class="mt-5 flex flex-wrap items-center gap-3">
@@ -128,14 +128,14 @@ const rules = {}
@submit="submit"
>
<ContextNotice type="info" :show-icon="false" class="text-xs"
>使用后端配置的图片模型,可能产生费用。每次新增一张图片,不删除历史结果。</ContextNotice
>使用当前配置的图片模型生成一张新图,可能产生费用。已有图片会保留。</ContextNotice
>
<p class="text-xs leading-6 text-muted">
基础形态默认复用已确认并锁定的身份母版,无需重复生成。此处会调用图片模型新增独立候选,用于不同形态或需要调整外观的情况;是否替换主图由下方选项决定。
</p>
<div class="flex flex-wrap items-center gap-3">
<NButton :loading="previewPending" :disabled="!form" @click="loadPreview">预览实际生成输入</NButton>
<span class="text-xs text-muted">只读取后端编译结果,不调用图片模型。</span>
<span class="text-xs text-muted">只查看本次生成图片会用到的参考图和描述,不生成图片。</span>
</div>
<ContextNotice v-if="previewError" type="error" :show-icon="false">{{ previewError }}</ContextNotice>
<div v-if="preview" class="dialog-result-card text-xs leading-6">
@@ -150,7 +150,7 @@ const rules = {}
</ul>
<p v-else class="mt-3 text-muted">本次没有图片参考。</p>
<NCollapse class="mt-3" :default-expanded-names="['prompt']">
<NCollapseItem name="prompt" title="最终 Provider Prompt">
<NCollapseItem name="prompt" title="本次实际使用的画面描述">
<p class="mt-3 whitespace-pre-wrap">{{ preview.providerPrompt }}</p>
</NCollapseItem>
<NCollapseItem name="config" title="生成配置">
@@ -166,7 +166,7 @@ const rules = {}
label="自定义提示词(可选,仅用于本次)"
:label-props="{ for: 'image-prompt' }"
><NInput
placeholder="留空使用正式 generationPrompt;缺失时后端先自动生成正式提示词"
placeholder="可留空使用已保存的画面描述;尚未准备时会先自动补齐。"
:input-props="{ id: 'image-prompt' }"
class="min-h-28"
v-model:value="prompt"
@@ -198,7 +198,7 @@ const rules = {}
@update:options="generationOptions = $event"
/>
<p v-if="!form?.generationPrompt" class="text-xs leading-6 text-muted">
未填写自定义提示词时,后端先调用文本模型补齐正式提示词,再生图;可能产生两类模型费用。原始外观素材不会直接作为最终生图提示词。
未填写自定义描述时,会先整理画面描述,再生成图片;这两个步骤都可能产生费用。角色的原始外观说明会先整理后使用。
</p>
<NCheckbox v-model:checked="setPrimary" class="flex gap-2 text-sm">生成成功后设为此形态主参考图</NCheckbox>
<p v-if="setPrimary && form && primaryImage(form.images)" class="text-xs text-muted">
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { NScrollbar, NButton, NTag } from 'naive-ui'
@@ -79,7 +80,7 @@ async function choosePrimary() {
!result.isPrimary ||
result.status !== 'completed'
)
throw new Error('接口未确认主图切换,请先刷新核对后端状态。')
throw new Error('主图切换结果尚未确认,请先刷新图片列表后核对。')
})
emit('changed')
await query.refresh()
@@ -108,7 +109,7 @@ async function choosePrimary() {
:key="selected.id"
:src="selected.status === 'completed' ? selected.imageUrl : null"
:alt="`${form?.subject.name} · ${form?.name}`"
:empty-text="selected.status === 'failed' ? '本次生成失败' : '等待后端生成结果'"
:empty-text="selected.status === 'failed' ? '本次生成失败' : '等待图片生成结果'"
class="asset-image-preview"
object-fit="contain"
preview
@@ -176,7 +177,7 @@ async function choosePrimary() {
type="error"
:show-icon="false"
class="mt-3 whitespace-pre-wrap"
>{{ selected.error }}</ContextNotice
>{{ userFacingText(selected.error) }}</ContextNotice
>
<div class="mt-4 flex flex-wrap items-center gap-3">
<NButton v-if="!selected.isPrimary" :disabled="!canSetPrimary" @click="confirming = true">
@@ -196,7 +197,7 @@ async function choosePrimary() {
><NButton @click="confirming = false" text size="small">取消</NButton>
</div></ContextNotice
>
<p class="mt-3 break-all font-mono text-[10px] text-muted">Image ID · {{ selected.id }}</p>
<p class="mt-3 break-all font-mono text-[10px] text-muted">图片编号 · {{ selected.id }}</p>
<p v-if="form && currentIdentityAnchorId(form)" class="mt-2 break-all text-[11px] text-muted">
当前已锁定身份母版 ID:{{ currentIdentityAnchorId(form) }}
</p>
@@ -1,8 +1,7 @@
<script setup lang="ts">
import AppForm from '../../../components/ui/AppForm.vue'
import { NFormItem } from 'naive-ui'
import { stringArrayJsonRule } from '../../../lib/form-rules'
import { NButton, NCheckbox, NInput, NTag } from 'naive-ui'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NInput, NTag } from 'naive-ui'
import { computed, reactive, ref, watch } from 'vue'
import type { SaveVisualStyleInput, VisualStyle } from '../types'
@@ -21,24 +20,33 @@ const form = reactive({
characterPrompt: '',
scenePrompt: '',
propPrompt: '',
constraints: '[]',
constraints: '',
isLocked: false
})
/** 上次成功读取的表单快照,用于识别未保存修改。 */
const baseline = ref('')
/** 已保存的要求原样保留,避免未编辑时拆开原有段落或丢失旧格式。 */
const savedConstraints = ref<unknown>([])
/** 与原始要求对应的文本,用于识别用户是否主动修改。 */
let savedConstraintsText = ''
/** 非文字列表的旧格式只读保留,不能用空白编辑器覆盖。 */
const legacyConstraints = ref(false)
/** 草稿变更时禁止 AI 覆盖现有输入。 */
const dirty = computed(() => JSON.stringify(form) !== baseline.value)
watch(
() => props.visualStyle,
value => {
if (baseline.value && dirty.value) return
savedConstraints.value = JSON.parse(JSON.stringify(value?.hardConstraints ?? []))
legacyConstraints.value = !Array.isArray(savedConstraints.value) || !savedConstraints.value.every(item => typeof item === 'string')
savedConstraintsText = legacyConstraints.value ? '' : (savedConstraints.value as string[]).join('\n')
Object.assign(form, {
name: value?.name ?? '默认视觉风格',
prompt: value?.prompt ?? '',
characterPrompt: value?.characterPrompt ?? '',
scenePrompt: value?.scenePrompt ?? '',
propPrompt: value?.propPrompt ?? '',
constraints: JSON.stringify(value?.hardConstraints ?? [], null, 2),
constraints: savedConstraintsText,
isLocked: value?.isLocked ?? false
})
baseline.value = JSON.stringify(form)
@@ -47,7 +55,7 @@ watch(
)
watch(dirty, value => emit('dirty', value), { immediate: true })
/** 显式校验 JSON 后保存结构化约束;不对错误结构做静默转换。 */
/** 每行一条的画面要求仍保存为原有文字列表,未编辑和旧格式内容原样保留。 */
function save() {
if (props.disabled) return
emit('save', {
@@ -56,15 +64,16 @@ function save() {
characterPrompt: form.characterPrompt,
scenePrompt: form.scenePrompt,
propPrompt: form.propPrompt,
hardConstraints: JSON.parse(form.constraints) as string[],
hardConstraints: legacyConstraints.value || form.constraints === savedConstraintsText
? savedConstraints.value
: form.constraints.split('\n').map(item => item.trim()).filter(Boolean),
isLocked: form.isLocked
})
}
const rules = { constraints: stringArrayJsonRule }
</script>
<template>
<AppForm :model="form" :rules="rules" :disabled="disabled" class="panel workspace-panel" @submit="save">
<AppForm :model="form" :disabled="disabled" class="panel workspace-panel" @submit="save">
<fieldset :disabled="disabled" class="space-y-5">
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="font-medium">风格说明</h3>
@@ -86,7 +95,7 @@ const rules = { constraints: stringArrayJsonRule }
</NFormItem>
<!-- 以下是始终展开的分类风格模块,人物、场景、道具各占一行 -->
<section class="style-category-section" aria-labelledby="style-category-heading">
<h3 id="style-category-heading" class="font-medium mb-5">分类风格与硬约束</h3>
<h3 id="style-category-heading" class="font-medium mb-5">分类风格与画面要求</h3>
<div class="style-category-fields grid grid-cols-1 gap-5">
<NFormItem path="characterPrompt" label="人物风格与选角背景"
><NInput
@@ -123,19 +132,23 @@ const rules = { constraints: stringArrayJsonRule }
<NFormItem
class="mt-4 block"
path="constraints"
label="硬约束 · JSON 字符串数组"
label="必须遵守的画面要求"
:label-props="{ for: 'style-constraints' }"
><NInput
:disabled="disabled"
:disabled="disabled || legacyConstraints"
spellcheck="false"
:input-props="{ id: 'style-constraints' }"
class="min-h-24 font-mono text-xs"
class="min-h-24"
placeholder="每行一条,例如:只使用古代服装"
v-model:value="form.constraints"
type="textarea"
:autosize="{ minRows: 3, maxRows: 12 }"
></NInput>
</NFormItem>
</section>
<!-- 以下是要求填写说明;旧格式只读核对,不在普通编辑时丢失内容 -->
<p class="text-xs leading-6 text-muted">每行填写一条画面要求,留空表示没有补充要求。</p>
<NCollapse v-if="legacyConstraints"><NCollapseItem name="legacy-rules" title="查看已有要求(高级)"><p class="text-xs leading-6 text-muted">已有要求使用旧格式,保存风格时会原样保留。</p><pre class="whitespace-pre-wrap break-words text-xs">{{ JSON.stringify(savedConstraints, null, 2) }}</pre></NCollapseItem></NCollapse>
<NCheckbox
:disabled="disabled"
id="style-lock"
+1 -1
View File
@@ -24,7 +24,7 @@ const history = computed(() => workflowCheckpoints(props.checkpoints, props.work
<h3 class="mb-1 flex items-center gap-2 text-sm font-semibold"><Clock3 :size="15" />执行记录</h3>
<NButton class="history-close" text size="small" @click="emit('close')">关闭</NButton>
</div>
<p class="mb-6 text-xs leading-5 text-muted">最近 18 个 checkpoint · 自动刷新</p>
<p class="mb-6 text-xs leading-5 text-muted">最近 18 条保存记录 · 自动更新</p>
<NButton v-if="projectId" text size="small" class="mb-4" @click="diagnosticsOpen = true"
>查看完整运行诊断</NButton
>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../lib/user-facing-text'
import ContextNotice from '../../components/ui/ContextNotice.vue'
import { computed, ref, watch } from 'vue'
@@ -6,7 +7,7 @@ import { NButton, NCollapse, NCollapseItem, NInput, NSelect, NTab, NTabs } from
import { Download, Search } from '@lucide/vue'
import { AppDialog, EmptyState } from '../../components/ui'
import { usePolling } from '../../composables/usePolling'
import { downloadText, formatDate, nodeLabel } from '../../lib/format'
import { downloadText, formatDate, nodeLabel, workflowLabel } from '../../lib/format'
import { loadWorkflowDiagnostics } from './diagnostics'
import type { Checkpoint } from './types'
@@ -21,8 +22,8 @@ const workflow = ref('all')
const search = ref('')
const checkpointMap = computed(() => new Map(props.checkpoints.map(item => [item.checkpointId, item])))
const options = computed(() => [
{ label: '全部工作流', value: 'all' },
...[...new Set(props.checkpoints.map(item => item.workflowName))].map(value => ({ label: value, value }))
{ label: '全部制作任务', value: 'all' },
...[...new Set(props.checkpoints.map(item => item.workflowName))].map(value => ({ label: workflowLabel(value), value }))
])
const groups = computed(() =>
(query.data.value?.groups ?? [])
@@ -67,12 +68,12 @@ function exportReport() {
<template>
<AppDialog
v-model:open="open"
title="工作流运行诊断"
description="展示全项目已保存的 checkpoint 指标与完整时间线,不启动或恢复任务。"
title="制作任务记录"
description="查看这个项目的任务记录、耗时和处理顺序,不会启动或恢复任务。"
wide
>
<ContextNotice type="info" :show-icon="false" class="mt-4 text-xs"
>后端指标按保存记录累计;耗时之和不等于实际墙钟耗时,“completed”也不代表图片或视频成功。生产任务状态请以资产页面为准。</ContextNotice
>这里统计的是已保存的处理记录,累计耗时可能与实际等待时间不同。步骤结束也不代表图片或视频已生成,请以素材页的实际结果为准。</ContextNotice
>
<ContextNotice v-if="query.error.value" role="alert" type="error" :show-icon="false" class="mt-3"
>{{ query.error.value }},当前保留上次数据。</ContextNotice
@@ -105,11 +106,11 @@ function exportReport() {
<NInput
v-model:value="search"
clearable
placeholder="搜索节点或 checkpoint"
placeholder="搜索制作步骤或保存记录"
:input-props="{ 'aria-label': '搜索运行记录' }"
><template #prefix><Search :size="14" /></template
></NInput>
<NSelect v-model:value="workflow" :options="options" aria-label="筛选工作流" />
<NSelect v-model:value="workflow" :options="options" aria-label="筛选制作任务" />
<span class="text-xs text-muted">{{ nodes.length }} 条记录</span>
</div>
<NTabs v-model:value="tab" type="line" class="mt-3"
@@ -126,7 +127,7 @@ function exportReport() {
>
</div>
<p class="mt-2 text-xs text-muted">
{{ checkpointMap.get(node.checkpointId)?.workflowName || '未标注工作流' }} · {{ node.phase }} ·
{{ workflowLabel(checkpointMap.get(node.checkpointId)?.workflowName) }} · {{ userFacingText(node.phase, '其他阶段') }} ·
{{ node.durationText }} · {{ formatDate(node.createdAt) }}
</p>
<p class="mt-2 break-all font-mono text-[11px] text-muted">{{ node.checkpointId }}</p>
@@ -137,13 +138,13 @@ function exportReport() {
v-for="group in groups"
:key="group.phase"
:name="group.phase"
:title="`${group.phase} · ${group.nodes.length} 条`"
:title="`${userFacingText(group.phase, '其他阶段')} · ${group.nodes.length} 条`"
>
<div class="diagnostics-records">
<article v-for="node in group.nodes" :key="node.checkpointId" class="surface-inset p-4">
<p class="text-sm">{{ nodeLabel(node.nodeName) }} · {{ node.durationText }}</p>
<p class="mt-2 text-xs text-muted">
{{ checkpointMap.get(node.checkpointId)?.workflowName || '未标注工作流' }} ·
{{ workflowLabel(checkpointMap.get(node.checkpointId)?.workflowName) }} ·
{{ recordLabel(node.checkpointId) }}
</p>
<p class="mt-2 break-all font-mono text-[11px] text-muted">{{ node.checkpointId }}</p>
@@ -154,7 +155,7 @@ function exportReport() {
<EmptyState
v-if="!query.loading.value && !nodes.length"
title="暂无匹配的运行记录"
description="可清空筛选后重试;尚未保存 checkpoint 的任务不会出现在时间线中。"
description="可清空筛选后重试;尚未保存进度的任务不会出现在时间线中。"
/>
</AppDialog>
</template>
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { userFacingText } from '../../lib/user-facing-text'
import ContextNotice from '../../components/ui/ContextNotice.vue'
import { computed } from 'vue'
@@ -323,7 +324,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
>目标 {{ keyframeCounts.targetCount }} · 通过 {{ keyframeCounts.passed }} · 修复未通过
{{ keyframeCounts.repairFailed }} · 调用失败 {{ keyframeCounts.failed }}</template
>
<template v-else>后端首帧质量统计不完整,请查看任务详情并刷新核对。</template>
<template v-else>首帧检查结果尚不完整,请刷新任务详情后核对。</template>
</p>
<p v-else-if="!videoQuality && !scriptCreation && !breakdownTask" class="mt-2 text-xs">
共 {{ result.total ?? execution.total }} · 生成 {{ result.generated ?? execution.current }} · 跳过
@@ -336,7 +337,7 @@ function isInputMode(value: unknown, inputMode: string): boolean {
:show-icon="false"
class="mt-3"
>
<p>{{ execution.error || '制作任务执行失败。' }}</p>
<p>{{ userFacingText(execution.error) || '制作任务执行失败。' }}</p>
<p class="mt-2 text-xs">
{{
scriptCreation
+9 -4
View File
@@ -1,3 +1,4 @@
import { userFacingText } from '../../lib/user-facing-text'
import { computed, onScopeDispose, reactive, ref, watch, type Ref } from 'vue'
import { usePolling } from '../../composables/usePolling'
import { workflowExecutionApi } from './execution-api'
@@ -38,9 +39,13 @@ export function hasActiveWorkflowExecution(projectId: string) {
return Object.values(executionActivity).some(record => record.projectId === projectId && record.active)
}
/** 任务阶段短标签;未知后端阶段保留原值,避免静默隐藏新能力。 */
/**
* 已知任务阶段使用中文名称,未知阶段显示待确认,不猜测任务结果。
* @param stage 当前任务阶段
* @returns 普通用户可读的阶段名称
*/
export function executionStageLabel(stage: string | null) {
if (!stage) return '等待后端开始'
if (!stage) return '等待任务开始'
const labels: Record<string, string> = {
createProject: '初始化项目',
generateCharacter: '生成角色设定',
@@ -95,7 +100,7 @@ export function executionStageLabel(stage: string | null) {
stale_motion_plan: '动作版本过期,质量流程已停止',
failed: '执行失败'
}
return labels[stage] ?? stage
return labels[stage] ?? userFacingText(stage, '状态待确认')
}
/** 有总量时按真实计数展示进度;未知总量保持不确定进度。 */
@@ -277,7 +282,7 @@ export function useWorkflowExecution(
* @returns 保存句柄与可用观察器刷新完成
*/
async function track(id: string, targetProjectId = projectId.value) {
if (typeof id !== 'string' || !id.trim()) throw new Error('后端未返回有效任务编号,请刷新状态,勿重复提交。')
if (typeof id !== 'string' || !id.trim()) throw new Error('未取得有效任务编号,请先刷新状态,避免重复提交。')
if (!targetProjectId) return
observedActive.add(id)
if (typeof localStorage !== 'undefined') localStorage.setItem(storageKey(targetProjectId, workflowName), id)
+16 -2
View File
@@ -10,6 +10,8 @@ export interface Operation {
label: string
/** 请求失败原因。 */
error: string
/** 原始错误只供恢复流程判断,不直接展示给用户。 */
cause?: unknown
/** 已确认的操作结果提示。 */
notice: string
/** 结果的实际语义;未指定时由工作区使用默认反馈。 */
@@ -56,6 +58,7 @@ export function getOperation(projectId: string): Operation {
},
label: '',
error: '',
cause: null,
notice: '',
noticeType: null,
recovery: null
@@ -63,6 +66,16 @@ export function getOperation(projectId: string): Operation {
return operations[projectId]
}
/**
* 业务恢复使用原始错误,避免中文展示转换改变缺少首帧等恢复条件。
* @param operation 当前项目操作状态
* @returns 与当前展示错误匹配的原始说明,或手动设置的错误
*/
export function operationErrorText(operation: Operation): string {
return operation.cause instanceof Error && errorMessage(operation.cause) === operation.error
? operation.cause.message : operation.error
}
/**
* 只让当前操作对应的按钮加载,项目内其它按钮继续使用禁用状态。
* @param operation 当前项目操作状态
@@ -108,14 +121,15 @@ export async function runOperation<T>(
) {
const operation = getOperation(projectId)
if (operation.pending) return false
Object.assign(operation, { pending: true, label, error: '', notice: '', noticeType: null, recovery: null })
Object.assign(operation, { pending: true, label, error: '', cause: null, notice: '', noticeType: null, recovery: null })
try {
const result = await action()
const notice = typeof feedback === 'function' ? feedback(result) : feedback
operation.noticeType = notice?.type ?? null
operation.notice = notice?.content ?? '请求已返回,正在重新读取后端状态;最终结果以下方记录为准。'
operation.notice = notice?.content ?? '操作已返回,正在更新任务状态;请以最新结果为准。'
return true
} catch (error) {
operation.cause = error
operation.error = errorMessage(error)
return false
} finally {
+1 -1
View File
@@ -1,4 +1,4 @@
/** 只允许 HTTP(S) 与后端 /storage 路径;生产环境绝对 API 地址使用其源站。 */
/** 只允许 HTTP(S) 与后端 /storage 路径;生产环境绝对 服务地址使用其源站。 */
export function mediaAssetUrl(value: string): string | null {
const raw = value.trim()
try {
+2 -2
View File
@@ -38,7 +38,7 @@ export function sizeRules(values: () => { width: unknown; height: unknown }) {
export const imageUrlRule = fieldRule(
value => typeof value === 'string' && !!referenceImageUrl(value),
'请填写有效的 HTTP(S) 或 /storage/ 图片地址',
'请填写可访问的图片链接或已上传图片的地址',
true
)
@@ -49,4 +49,4 @@ export const stringArrayJsonRule = fieldRule(value => {
} catch {
return false
}
}, '请输入 JSON 字符串数组,例如 ["真人写实", "禁止二次元"]')
}, '请按示例填写文字列表,例如 ["真人写实", "禁止二次元"]')
+22 -2
View File
@@ -1,4 +1,5 @@
import type { ProjectStatus } from '../features/projects/types'
import { userFacingText } from './user-facing-text'
/** 原始项目状态的中文名称。 */
export const statusLabels: Record<ProjectStatus, string> = {
@@ -24,7 +25,11 @@ export function formatDate(value?: string): string {
}).format(date)
}
/** 节点中文名称;未知新节点仍显示原名,方便后端扩展。 */
/**
* 展示制作步骤的中文名称,未知步骤不直接显示内部标识。
* @param name 原始步骤标识
* @returns 页面可读的制作步骤名称
*/
export function nodeLabel(name?: string): string {
const labels: Record<string, string> = {
createProject: '创建项目',
@@ -58,7 +63,22 @@ export function nodeLabel(name?: string): string {
partial_failed: '部分抽取失败',
finalize: '结果入库'
}
return name ? (labels[name] ?? name) : '状态记录'
return name ? (labels[name] ?? userFacingText(name, '其他制作步骤')) : '状态记录'
}
/**
* 制作任务名称用于筛选与历史记录,不改变接口中的流程标识。
* @param name 原始流程标识
* @returns 中文流程名称
*/
export function workflowLabel(name?: string): string {
const labels: Record<string, string> = {
'create-drama': '剧本创作', breakdown: '剧本拆解', 'visual-style': '视觉风格',
'subject-identity': '主体身份', 'subject-images': '形态图片', storyboard: '分镜设计', production: '镜头制作',
'storyboard-direction': '镜头设计', 'storyboard-visual-state': '画面状态', 'video-prompt': '视频描述',
'keyframe-generation': '首帧生成', 'keyframe-quality': '首帧检查', 'video-quality': '视频检查'
}
return name ? labels[name] ?? userFacingText(name, '其他制作任务') : '未标注制作任务'
}
/** 下载纯文本或 JSON,不将模型内容作为 HTML 渲染。 */
+13 -8
View File
@@ -1,3 +1,5 @@
import { businessErrorMessages, userFacingText } from './user-facing-text'
/** HTTP 错误携带状态码与后端细节,供页面区别空数据、校验错误与网络故障。 */
export class ApiError extends Error {
constructor(
@@ -57,7 +59,7 @@ export async function request<T>(path: string, options: RequestOptions = {}): Pr
try {
data = text ? JSON.parse(text) : undefined
} catch {
throw new ApiError('接口未返回 JSON,请检查 API 地址与代理配置。', response.status)
throw new ApiError('服务暂时无法返回有效结果,请稍后重试。', response.status)
}
if (!response.ok) {
const message =
@@ -75,7 +77,7 @@ export async function request<T>(path: string, options: RequestOptions = {}): Pr
if (options.signal?.aborted) throw error
if (controller.signal.aborted)
throw new ApiError('请求等待超时。后台任务可能仍在运行,请先刷新状态,不要重复提交。', 0)
throw new ApiError('无法连接后端。请检查服务与代理;已提交的任务可能仍在运行。', 0)
throw new ApiError('暂时无法连接服务,请检查网络后重试;已提交的任务可能仍在运行。', 0)
} finally {
clearTimeout(timer)
options.signal?.removeEventListener('abort', abort)
@@ -92,11 +94,14 @@ export async function optionalResource<T>(promise: Promise<T>): Promise<T | null
}
}
/** 页面统一显示可操作的错误信息。 */
/**
* 页面统一显示业务原因,原始错误与详情仍保留供程序判断和导出。
* @param error 原始请求或操作错误
* @returns 普通用户可理解的原因和处理建议
*/
export function errorMessage(error: unknown): string {
if (error instanceof ApiError && error.details) {
const details = typeof error.details === 'string' ? error.details : JSON.stringify(error.details)
return `${error.message} ${details}`
}
return error instanceof Error ? error.message : '操作失败,请刷新后重试。'
const fallback = '操作失败,请刷新后重试。'
if (error instanceof ApiError)
return [...new Set([userFacingText(error.message, fallback), ...businessErrorMessages(error.details)].filter(Boolean))].join(';') || fallback
return error instanceof Error ? userFacingText(error.message, fallback) || fallback : fallback
}
+66
View File
@@ -0,0 +1,66 @@
/** 系统说明中允许统一翻译的术语;不处理剧本、提示词正文、文件名或请求字段。 */
const terms: [RegExp, string][] = [
[/由项目 Creative Profile Canvas 决定;单次图片或视频生成不可覆盖。/g, '使用项目配置中的画面比例,单次生成时不能单独更改。'],
[/业务层必须显式选择,不能依赖 Provider 默认值。/g, '请明确选择是否开启。'],
[/业务默认关闭/g, '默认关闭'], [/业务参考图/g, '参考图'],
[/Creative Profile Canvas/gi, '项目画幅设置'],
[/Prompt\s*扩写模式/gi, '画面描述补充方式'], [/Prompt\s*扩写/gi, '自动补充画面描述'],
[/Storyboard Shot/gi, '分镜镜头'], [/Primary Keyframe/gi, '首帧'],
[/\bBreakdown\b/gi, '剧本拆解'], [/\bKeyframe\b/gi, '首帧'],
[/Creative Profile/gi, '项目生成配置'], [/Visual Style/gi, '视觉风格'],
[/GenerationSpec/gi, '镜头生成方案'], [/generationPrompt/gi, '正式生图提示词'],
[/VisualState/gi, '画面即时状态'], [/\bSubjectRefs?\b/gi, '主体引用'],
[/\bSubjectForms?\b/gi, '主体形态'], [/Identity Anchor/gi, '身份母版'],
[/Motion Plan/gi, '动作设计'], [/Video Prompt/gi, '视频提示词'],
[/Negative\s*prompt/gi, '避免出现的内容'], [/Episode Shots?/gi, '单集镜头'],
[/checkpoints?/gi, '保存记录'], [/Storyboard/gi, '分镜'],
[/\bDirection\b/gi, '镜头设计'], [/\bVisual Form\b/gi, '视觉形态'],
[/\bForm\b/g, '形态'], [/\bBeat\b/gi, '剧情段落'], [/\bShot\b/gi, '镜头'],
[/\bProvider\b/gi, '模型服务'], [/\bPrompt\b/gi, '提示词'],
[/\bThinking\b/gi, '深度思考'], [/\bLLM\b/g, '文字生成模型'], [/\bVision\b/g, '画面检查'], [/\bJSON\b/gi, '数据格式'],
[/\bexecutionId\b/g, '任务编号'], [/\bID\b/g, '编号'], [/\bAPI\b/g, '服务'],
[/\bbackend\b|后端/gi, '系统'], [/\bfrontend\b|前端/gi, '页面'],
[/\bcompleted\b/g, '已完成'], [/下游资产/g, '后续制作成果'],
[/后台状态/g, '任务状态'], [/入库/g, '保存'], [/指纹/g, '内容版本'],
[/^auto$/i, '自动'], [/^direct$/i, '直接增强'], [/^agent$/i, '智能补充']
]
/**
* 将系统生成的状态、错误与字段说明转为普通用户可读的中文,原始响应不受影响。
* @param value 系统说明,不能传入用户创作正文或模型品牌名称
* @param fallback 缺少可读信息时使用的中文说明
* @returns 页面可展示的说明
*/
export function userFacingText(value: string | null | undefined, fallback = '暂无可读说明,请查看相关状态。'): string {
let text = value?.trim() ?? ''
if (!text) return ''
if (/fetch failed|failed to fetch|network error|ECONNREFUSED|ETIMEDOUT/i.test(text))
return '暂时无法连接服务,请检查网络后重试;已提交的任务可能仍在运行。'
if (/PrismaClient|TypeError:|ReferenceError:|SyntaxError:|\bat \S+ \([^)]*:\d+:\d+\)|SELECT\s+.+\s+FROM/i.test(text)) return fallback
for (const [pattern, label] of terms) text = text.replace(pattern, label)
return /[\u4e00-\u9fff]/.test(text) ? text : fallback
}
/**
* 只提取错误中的业务说明,不把调试对象、堆栈或内部字段整体展示给用户。
* @param details 接口保留的原始错误详情
* @returns 去重后的可读业务原因
*/
export function businessErrorMessages(details: unknown): string[] {
/** 按有限层级遍历,忽略调试信息与原始请求数据。 */
function collect(value: unknown, depth: number): string[] {
if (depth > 4) return []
if (typeof value === 'string') {
const text = userFacingText(value, '')
return text ? [text] : []
}
if (Array.isArray(value)) return value.slice(0, 8).flatMap(item => collect(item, depth + 1))
if (!value || typeof value !== 'object') return []
const record = value as Record<string, unknown>
const result = ['message', 'reason', 'issues', 'errors', 'formErrors'].flatMap(key => collect(record[key], depth + 1))
if (record.fieldErrors && typeof record.fieldErrors === 'object')
result.push(...Object.values(record.fieldErrors).flatMap(item => collect(item, depth + 1)))
return result
}
return [...new Set(collect(details, 0))].slice(0, 6)
}
+20 -2
View File
@@ -7,6 +7,7 @@ import StyleEditor from '@/features/visual-style/components/StyleEditor.vue'
import SubjectList from '@/features/breakdown/components/SubjectList.vue'
import { selectMenu } from '@/testing/naive'
import type { SubjectCandidate } from '@/features/breakdown/types'
import { styleFixture } from '@/features/visual-style/testing/fixtures'
let wrapper: VueWrapper | undefined
afterEach(() => {
@@ -51,7 +52,7 @@ describe('精简入口保留功能', () => {
it('风格分类始终显示,保存保留人工补充与硬约束', async () => {
wrapper = mount(StyleEditor, { props: { visualStyle: null, disabled: false } })
expect(wrapper.find('#style-constraints').exists()).toBe(true)
await wrapper.get('#style-constraints').setValue('["保留硬约束"]')
await wrapper.get('#style-constraints').setValue('保持真人写实\n不使用现代服装')
const fields = wrapper.findAllComponents(NInput)
fields.find(item => item.props('placeholder')?.includes('人物质感'))!.vm.$emit('update:value', '人物风格')
await flushPromises()
@@ -60,10 +61,27 @@ describe('精简入口保留功能', () => {
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(wrapper.emitted('save')).toMatchObject([
[{ characterPrompt: '人物风格', hardConstraints: ['保留硬约束'] }]
[{ characterPrompt: '人物风格', hardConstraints: ['保持真人写实', '不使用现代服装'] }]
])
})
it('未编辑要求时完整保留原有多行条目,不按换行拆开已保存内容', async () => {
const requirements = ['只使用古代服装\n保留角色配饰', '保持人物外观一致']
wrapper = mount(StyleEditor, { props: { visualStyle: styleFixture({ hardConstraints: requirements }), disabled: false } })
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ hardConstraints: requirements })
})
it('旧格式要求只读核对,保存其他设置不会用空白要求覆盖旧内容', async () => {
const legacy = { legacyRules: ['完整保留旧要求'] }
wrapper = mount(StyleEditor, { props: { visualStyle: styleFixture({ hardConstraints: legacy }), disabled: false } })
expect(wrapper.get('#style-constraints').attributes('disabled')).toBeDefined()
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ hardConstraints: legacy })
})
it('主体长文收起仅影响显示,完整内容与图片入口不丢失', async () => {
const description = '主体完整经历。'.repeat(30)
wrapper = mount(SubjectList, {
+5 -9
View File
@@ -129,21 +129,17 @@ describe('统一的 Naive UI 表单校验', () => {
expect(wrapper.emitted('generate')).toBeUndefined()
})
it('分类风格始终显示,非法 JSON 拦截保存,修正后保留草稿正常提交', async () => {
it('画面要求按行填写,保存时保持原有文字列表格式', async () => {
wrapper = mount(StyleEditor, { attachTo: document.body, props: { visualStyle: null, disabled: false } })
await flushPromises()
expect(wrapper.find('button[aria-expanded]').exists()).toBe(false)
expect(wrapper.get('.style-category-section h3').text()).toBe('分类风格与硬约束')
expect(wrapper.get('.style-category-section h3').text()).toBe('分类风格与画面要求')
expect(wrapper.findAll('.style-category-fields .n-form-item')).toHaveLength(3)
await input('#style-name', '手工风格')
await input('#style-constraints', '{"invalid":true}')
await input('#style-constraints', '真人写实\n\n 只用古代服装 ')
await submit()
expect(wrapper.emitted('save')).toBeUndefined()
expect(feedback()).toContain('请输入 JSON 字符串数组')
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ name: '手工风格', hardConstraints: ['真人写实', '只用古代服装'] })
expect(wrapper.get('#style-constraints').isVisible()).toBe(true)
await input('#style-constraints', '["真人写实"]')
await submit()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ name: '手工风格', hardConstraints: ['真人写实'] })
})
it('登记参考图拦截非法地址和小数排序,允许有效存储地址与负整数排序', async () => {
@@ -159,7 +155,7 @@ describe('统一的 Naive UI 表单校验', () => {
await input('[aria-label="风格图片地址"]', 'javascript:alert(1)')
await input('[aria-label="风格图片排序"]', '1.5')
await submit()
expect(feedback()).toContain('请填写有效的 HTTP(S) 或 /storage/ 图片地址')
expect(feedback()).toContain('请填写可访问的图片链接或已上传图片的地址')
expect(feedback()).toContain('排序须为整数')
expect(wrapper.emitted('add')).toBeUndefined()
await input('[aria-label="风格图片地址"]', '/storage/style.png')
+98 -1
View File
@@ -14,9 +14,106 @@ import { effectScope } from 'vue'
import { useWorkflowExecution } from '@/features/workflows/execution'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import { breakdownApi } from '@/features/breakdown/api'
import { candidateCheckpoint, candidateReview, candidateState } from '../../fixtures/breakdown-candidate'
import { candidateCheckpoint, candidateReview, candidateState, resourceConflictState } from '../../fixtures/breakdown-candidate'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import { getOperation } from '@/features/workflows/operations'
let wrapper: VueWrapper | undefined
it('首次点击生成先读取并确认质量规则,不直接打开模型启动确认', async () => {
const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({
projectId: 'breakdown-scroll-test',
policy: { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
})
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
})
const start = vi.spyOn(breakdownApi, 'run')
mountPage()
await wrapper!.get('[data-workspace-tools]').trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '预览分组')!.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
expect(readPolicy).toHaveBeenCalledTimes(1)
expect(drawerPanel().text()).toContain('拆解前确认质量规则')
expect(document.querySelector('.app-dialog')).toBeNull()
expect(start).not.toHaveBeenCalled()
})
it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({
projectId: 'breakdown-scroll-test',
policy: { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
})
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
})
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const start = vi.spyOn(breakdownApi, 'run')
mountPage()
await wrapper!.get('[data-workspace-tools]').trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '预览分组')!.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '取消')!.trigger('click')
expect(drawerPanel().text()).toContain('第 1–1 集')
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
expect(drawerPanel().findAll('button').some(button => button.text() === '添加例外')).toBe(false)
await drawerPanel().findAll('[role="checkbox"]').find(box => box.text().includes('我已核对'))!.trigger('click')
await drawerPanel().findAll('button').find(button => button.text() === '确认规则并继续')!.trigger('click')
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('可能产生模型费用')
expect(save).not.toHaveBeenCalled()
expect(start).not.toHaveBeenCalled()
await new DOMWrapper(document.querySelector('.app-dialog')!).findAll('button').find(button => button.text() === '取消')!.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
expect(drawerPanel().text()).not.toContain('拆解前确认质量规则')
expect(document.querySelector('.app-dialog')?.textContent).toContain('可能产生模型费用')
expect(start).not.toHaveBeenCalled()
})
it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定关闭且保存后仍需审核', async () => {
let policy: ProjectQualityPolicy = { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'breakdown-scroll-test', policy }))
let finish!: () => void
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => {
await new Promise<void>(resolve => { finish = resolve })
policy = input
return { projectId: id, policy: input }
})
vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(candidateReview({
projectId: 'breakdown-scroll-test', actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1]
}))
mountPage([candidateCheckpoint(resourceConflictState({ projectId: 'breakdown-scroll-test' }))])
await flushPromises()
await wrapper!.get('.breakdown-desktop-issues').trigger('click')
await flushPromises()
const drawer = new DOMWrapper(document.querySelector('.breakdown-issues-drawer')!)
const panel = () => drawer.get('[aria-label="动作例外修订"]')
expect(panel().text()).toContain('左手握住铜铃')
await panel().findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await panel().get('textarea').setValue('剧本中的明确允许设定')
await panel().findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await flushPromises()
expect(drawer.findAll('button').find(button => button.text() === '关闭')!.attributes('disabled')).toBeDefined()
expect(save).toHaveBeenCalledOnce()
finish()
await flushPromises()
expect(drawer.text()).toContain('动作质量阻断')
expect(panel().text()).toContain('已有例外')
expect(drawer.findAll('button').find(button => button.text() === '关闭')!.attributes('disabled')).toBeUndefined()
Object.assign(getOperation('breakdown-scroll-test'), { error: '', notice: '', label: '' })
})
/** 跨组件后台任务观察器,验证结束时释放。 */
let taskScope: ReturnType<typeof effectScope> | undefined
afterEach(() => {
@@ -0,0 +1,158 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { actionExceptionTargets } from '@/features/breakdown/action-exceptions'
import ActionExceptionRepair from '@/features/breakdown/components/ActionExceptionRepair.vue'
import { breakdownQuality, selectBreakdownSource } from '@/features/breakdown/quality'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import { candidateCheckpoint, candidateReview, resourceConflictState } from '../../fixtures/breakdown-candidate'
import { getOperation } from '@/features/workflows/operations'
/**
* 同阶段同一角色左手执行两个互斥动作,坐标与后端审核一致。
* @returns 独立的真实契约形状的候选与审核
*/
function conflict() {
const state = resourceConflictState()
const shot = state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[0]!
const review = candidateReview({ actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1] })
const quality = breakdownQuality(selectBreakdownSource([candidateCheckpoint(state)]), review)
return { state, quality, shot }
}
/** 已有例外与独立全局规则,写入时必须全部保留。 */
const policy: ProjectQualityPolicy = {
version: 1, physicsMode: 'stylized', allowExaggeratedMotion: true, allowNonPhysicalActions: false,
allowSupernaturalAbilities: false, customRules: ['跳跃后正常落地'],
actionExceptions: [{ code: 'action_resource_conflict', ownerRef: '@CH0099', resource: 'right_hand', reason: '旧例外依据' }]
}
/** 当前真实修订面板实例。 */
let wrapper: VueWrapper<InstanceType<typeof ActionExceptionRepair>> | undefined
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
vi.restoreAllMocks()
localStorage.clear()
Object.assign(getOperation('candidate-project'), { pending: false, error: '', label: '', notice: '' })
})
describe('从实际问题建立动作例外', () => {
it('只从当前审核的互斥动作证据带入角色、部位与动作,不从文字猜测', () => {
const { state, quality, shot } = conflict()
expect(actionExceptionTargets(state, quality)).toMatchObject([{
episodeNo: 1, beatNo: 1, shotNo: 1, phaseNo: 1, ownerRef: '@CH0001', ownerName: '人物', resource: 'left_hand',
actions: ['左手握住铜铃', '左手向村民挥动']
}])
shot.durationPlanning!.phases[0]!.resourceOccupancy = []
expect(actionExceptionTargets(state, quality)).toEqual([])
})
it('不同阶段、可共享证据、未知角色或动作及历史审核都不能生成例外目标', () => {
const { state, quality, shot } = conflict()
const phase = shot.durationPlanning!.phases[0]!
phase.resourceOccupancy![1]!.ownerRef = '@CH9999'
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.resourceOccupancy![1]!.ownerRef = '@CH0001'
phase.actionIds = ['hold']
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.actionIds = ['hold', 'wave']
phase.resourceOccupancy!.forEach(item => { item.shareable = true; item.usage = 'hold' })
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.resourceOccupancy!.forEach(item => { item.shareable = false })
expect(actionExceptionTargets(state, { ...quality, source: 'history' })).toEqual([])
const resource = phase.resourceOccupancy!.pop()!
shot.durationPlanning!.phases.push({ ...phase, resourceOccupancy: [resource] })
expect(actionExceptionTargets(state, quality)).toEqual([])
})
it('用户仅填写原因,保存前重读并合并已有例外,不改全局规则或自动放行质量', async () => {
const { state, quality } = conflict()
const latest = { ...policy, customRules: ['其他入口刚保存的新规则'] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValueOnce({ projectId: 'candidate-project', policy }).mockResolvedValue({ projectId: 'candidate-project', policy: latest })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => ({ projectId: id, policy: input }))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises()
expect(wrapper.text()).toContain('左手握住铜铃')
expect(wrapper.text()).toContain('左手向村民挥动')
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
expect(wrapper.find('input').exists()).toBe(false)
expect(wrapper.find('textarea').element.value).toBe('')
expect(wrapper.text()).not.toContain('请填写允许原因')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
expect(wrapper.text()).toContain('请填写允许原因')
expect(save).not.toHaveBeenCalled()
await wrapper.get('textarea').setValue('剧本明确允许左手同时挥动持物')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledExactlyOnceWith('candidate-project', { ...latest, actionExceptions: [
policy.actionExceptions![0],
{ code: 'action_resource_conflict', ownerRef: '@CH0001', resource: 'left_hand', reason: '剧本明确允许左手同时挥动持物' }
] })
expect(wrapper.emitted('refresh')).toHaveLength(1)
expect(quality.actionStatus).toBe('blocked')
expect(wrapper.find('textarea').exists()).toBe(false)
})
it('保存前出现活动任务或切换检查点时,不提交旧问题的例外', async () => {
const { state, quality } = conflict()
let finish!: (value: { projectId: string; policy: ProjectQualityPolicy }) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await wrapper.get('textarea').setValue('允许原因')
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper.setProps({ disabled: true })
finish({ projectId: 'candidate-project', policy })
await flushPromises()
expect(save).not.toHaveBeenCalled()
expect(wrapper.find('textarea').element.value).toBe('允许原因')
await wrapper.setProps({ checkpointId: 'new-checkpoint' })
expect(wrapper.find('textarea').exists()).toBe(false)
expect(wrapper.emitted('refresh')).toBeUndefined()
})
it('已有同一角色部位的例外不重复添加,其他例外保持可见', async () => {
const { state, quality } = conflict()
const existing = { ...policy, actionExceptions: [...policy.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0001', resource: 'left_hand' as const, reason: '已确认的同类例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy: existing })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises()
expect(wrapper.text()).toContain('已有动作例外 · 2 项')
expect(wrapper.findAll('button').find(button => button.text() === '已有例外')!.attributes('disabled')).toBeDefined()
expect(wrapper.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
it('保存失败保留原因供修正,不增加本地例外或宣称已通过', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy })
vi.spyOn(projectsApi, 'saveQualityPolicy').mockRejectedValue(new Error('后端拒绝修改'))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await wrapper.get('textarea').setValue('仍需保存的依据')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await flushPromises()
expect(wrapper.get('textarea').element.value).toBe('仍需保存的依据')
expect(wrapper.text()).toContain('系统拒绝修改')
expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.emitted('refresh')).toBeUndefined()
expect(wrapper.emitted('busy')?.map(event => event[0])).toEqual([true, false])
})
it('读取失败或项目不符时不使用默认规则、不开放添加', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'other', policy })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
await flushPromises()
expect(wrapper.text()).toContain('规则所属项目不一致')
expect(wrapper.findAll('button').find(button => button.text() === '添加例外')!.attributes('disabled')).toBeDefined()
expect(wrapper.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,261 @@
import { effectScope, ref, type EffectScope } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '@/features/projects/types'
import { policyDraft } from '@/features/projects/quality-policy'
import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy'
import {
invalidateQualityPolicyConfirmation, qualityPolicySignature,
readQualityPolicyConfirmation, rememberQualityPolicyConfirmation
} from '@/features/projects/quality-policy-confirmation'
/**
* 使用真实接口形状的独立规则,不连接服务或调用模型。
* @returns 独立项目规则回执
*/
function receipt(): ProjectQualityPolicyResult {
return { projectId: 'policy-project', policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false,
allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} }
}
/** 每个测试释放组合函数观察器。 */
let scope: EffectScope | undefined
/**
* 创建可切换项目、预览和活动锁的测试观察器。
* @returns 流程及其响应式输入
*/
function setup() {
const id = ref('policy-project')
const input = ref('preview-1')
const allowed = ref(true)
scope = effectScope()
const flow = scope.run(() => useBreakdownStartPolicy(id, input, allowed))!
return { id, input, allowed, flow }
}
afterEach(() => {
scope?.stop()
vi.unstubAllGlobals()
localStorage.clear()
vi.restoreAllMocks()
})
describe('拆解质量规则内容与当前浏览器确认', () => {
it('忽略属性顺序、首尾空格和空例外表示,但识别许可、规则和例外的实际变化', () => {
const base = receipt().policy
expect(qualityPolicySignature({ ...base, actionExceptions: [] })).toBe(qualityPolicySignature(base))
const reversed = Object.fromEntries(Object.entries({ ...base, customRules: ['规则'] }).toReversed()) as unknown as ProjectQualityPolicy
expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(qualityPolicySignature(reversed))
for (const changed of [
{ ...base, physicsMode: 'fantasy' as const },
{ ...base, allowExaggeratedMotion: true },
{ ...base, allowNonPhysicalActions: true },
{ ...base, allowSupernaturalAbilities: true },
{ ...base, customRules: ['新规则'] },
{ ...base, actionExceptions: [{ code: 'action_resource_conflict' as const, ownerRef: '@CH1', resource: 'left_hand' as const, reason: '剧本许可' }] }
]) expect(qualityPolicySignature(changed)).not.toBe(qualityPolicySignature(base))
expect(() => qualityPolicySignature({ ...base, customRules: null } as unknown as ProjectQualityPolicy)).toThrow('质量规则响应不完整')
})
it('确认按项目隔离,损坏存储或存储权限失败不会被当作已确认', () => {
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
rememberQualityPolicyConfirmation('policy-project', 'signature')
expect(readQualityPolicyConfirmation('other')).toBeNull()
localStorage.setItem('short-drama:breakdown-quality-confirmation:v1:policy-project', '{')
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => { throw new Error('storage blocked') } })
expect(rememberQualityPolicyConfirmation('policy-project', 'new')).toBe(false)
})
})
describe('拆解前规则确认流程', () => {
it('首次读取失败不展示默认规则,重试后才能进入确认', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockRejectedValueOnce(new Error('读取不可用')).mockResolvedValue(receipt())
const { flow } = setup()
await flow.prepare()
expect(flow.policy.value).toBeNull()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.error.value).toBe('读取不可用')
expect(flow.consumePermit()).toBe(false)
await flow.prepare()
expect(read).toHaveBeenCalledTimes(2)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.error.value).toBe('')
})
it('首次读取真实规则,取消不记录确认,也不允许绕过确认直接启动', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
expect(read).not.toHaveBeenCalled()
await flow.prepare()
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
flow.cancel()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
expect(save).not.toHaveBeenCalled()
})
it('明确确认未改规则不重复保存,刷新会话后直接进入普通启动确认', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(receipt().policy)).toBe(true)
expect(flow.startOpen.value).toBe(true)
expect(save).not.toHaveBeenCalled()
expect(flow.consumePermit()).toBe(false)
flow.cancel()
scope!.stop()
const next = setup().flow
await next.prepare()
expect(next.reviewOpen.value).toBe(false)
expect(next.startOpen.value).toBe(true)
expect(await next.verifyStart()).toBe(true)
expect(next.consumePermit()).toBe(true)
expect(next.consumePermit()).toBe(false)
})
it('编辑的完整草稿先保存并重读,保存后的内容才记作已确认', async () => {
const saved = receipt()
const draft = { ...saved.policy, allowExaggeratedMotion: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => {
saved.policy = policyDraft(policy)
return { projectId: id, policy: policyDraft(policy) }
})
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(draft)).toBe(true)
expect(save).toHaveBeenCalledWith('policy-project', draft)
expect(read).toHaveBeenCalledTimes(3)
expect(readQualityPolicyConfirmation('policy-project')).toBe(qualityPolicySignature(draft))
})
it('规则在其他位置更新后重新确认,不覆盖服务端较新规则', async () => {
let saved = receipt()
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
await flow.prepare()
saved = { ...saved, policy: { ...saved.policy, allowNonPhysicalActions: true } }
expect(await flow.confirmRules(receipt().policy)).toBe(false)
expect(flow.policy.value?.policy.allowNonPhysicalActions).toBe(true)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(save).not.toHaveBeenCalled()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
})
it('真实保存期间锁定取消,保存后的只读回查可取消,迟到回查不记录确认', async () => {
const initial = receipt()
const draft = { ...initial.policy, allowNonPhysicalActions: true }
let finishSave!: (value: ProjectQualityPolicyResult) => void
let finishRead!: (value: ProjectQualityPolicyResult) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(() => new Promise(resolve => { finishSave = resolve }))
const { flow } = setup()
await flow.prepare()
const pending = flow.confirmRules(draft)
await Promise.resolve()
await Promise.resolve()
expect(save).toHaveBeenCalledOnce()
expect(flow.saving.value).toBe(true)
flow.cancel()
expect(flow.reviewOpen.value).toBe(true)
read.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve }))
finishSave({ ...initial, policy: draft })
await Promise.resolve()
await Promise.resolve()
expect(flow.saving.value).toBe(false)
expect(flow.reading.value).toBe(true)
flow.cancel()
finishRead({ ...initial, policy: draft })
expect(await pending).toBe(false)
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).toBeNull()
})
it('最终启动确认期间规则变化,返回规则界面并撤销启动许可', async () => {
const saved = receipt()
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
rememberQualityPolicyConfirmation(saved.projectId, qualityPolicySignature(saved.policy))
const { flow } = setup()
await flow.prepare()
saved.policy.customRules = ['新规则']
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it.each(['读取失败', '项目不符', '保存失败', '回执不符', '保存后变化'])('安全拦截%s,不记住确认', async kind => {
const initial = receipt()
const changed = { ...initial.policy, allowNonPhysicalActions: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockResolvedValue({ ...initial, policy: changed })
const { flow } = setup()
await flow.prepare()
if (kind === '读取失败') read.mockRejectedValueOnce(new Error('读取失败'))
if (kind === '项目不符') read.mockResolvedValueOnce({ ...initial, projectId: 'other' })
if (kind === '保存失败') save.mockRejectedValueOnce(new Error('保存失败'))
if (kind === '回执不符') save.mockResolvedValueOnce(initial)
expect(await flow.confirmRules(changed)).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).toBeNull()
})
it.each(['cancel', 'project', 'scope', 'locked'])('重复点击只读一次,%s 后丢弃迟到读取', async cause => {
let finish!: (value: ProjectQualityPolicyResult) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(() => new Promise(resolve => { finish = resolve }))
const { flow, id, input, allowed } = setup()
const pending = flow.prepare()
await flow.prepare()
expect(read).toHaveBeenCalledTimes(1)
if (cause === 'cancel') flow.cancel()
if (cause === 'project') id.value = 'other'
if (cause === 'scope') input.value = 'preview-2'
if (cause === 'locked') allowed.value = false
finish(receipt())
await pending
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it('最终重读失败不能启动,取消后迟到成功也不能启动', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
rememberQualityPolicyConfirmation('policy-project', qualityPolicySignature(receipt().policy))
const { flow } = setup()
await flow.prepare()
read.mockRejectedValueOnce(new Error('重读失败'))
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
let finish!: (value: ProjectQualityPolicyResult) => void
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
const pending = flow.verifyStart()
flow.cancel()
finish(receipt())
expect(await pending).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it('存储受限时仅在本次会话跳过确认,实际规则保存会撤销临时确认', async () => {
vi.stubGlobal('localStorage', { getItem: () => null, removeItem: () => {}, setItem: () => { throw new Error('blocked') } })
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(receipt().policy)).toBe(true)
flow.cancel()
await flow.prepare()
expect(flow.startOpen.value).toBe(true)
invalidateQualityPolicyConfirmation('policy-project')
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
})
})
@@ -31,7 +31,7 @@ describe('生成模型参数字段', () => {
expect(select.props('clearable')).toBe(false)
expect(select.props('options')).toEqual([
{ label: '目录支持尺寸', value: '2048*2048' },
{ label: 'auto', value: 'auto' },
{ label: '自动', value: 'auto' },
{ label: '2K', value: '2K' }
])
expect(wrapper.findComponent(NInputNumber).exists()).toBe(false)
+1 -1
View File
@@ -602,7 +602,7 @@ describe('视频修复候选与复检晋升', () => {
expect(data.fetcher.mock.calls.some(([, options]) => options?.method === 'PUT')).toBe(false)
wrapper!.unmount()
wrapper = mount(QualityResult, { props: { receipt } })
expect(wrapper.text()).toContain('后端已将其设为主视频')
expect(wrapper.text()).toContain('修复后的视频已通过检查,并设为主视频')
})
it('视频修复面板明确一次一任务及复检后替换,不展示生图次数', async () => {
+18 -4
View File
@@ -1,8 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
import { NTooltip } from 'naive-ui'
import { NSelect, NTooltip } from 'naive-ui'
import AssetLibraryPage from '@/features/project-assets/AssetLibraryPage.vue'
import AssetCategorySelect from '@/features/project-assets/components/AssetCategorySelect.vue'
let wrapper: VueWrapper | undefined
afterEach(() => {
@@ -52,8 +53,9 @@ describe('全局资产库', () => {
createdAt: '',
updatedAt: ''
}))
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
const url = String(input)
if (init?.method === 'PUT') return new Response(JSON.stringify({ data: { ...assets[0], ...JSON.parse(String(init.body)) } }))
return new Response(JSON.stringify({ data: url.endsWith('/projects') ? projects : assets }))
})
vi.stubGlobal('fetch', fetcher)
@@ -93,10 +95,22 @@ describe('全局资产库', () => {
await flushPromises()
const dialog = document.querySelector('[role="dialog"][aria-label="素材详情与管理"]')!
expect(dialog).not.toBeNull()
expect([...dialog.querySelectorAll('.n-card__footer button')].map(button => button.textContent?.trim())).toEqual(['删除素材', '取消', '保存修改'])
expect(dialog.querySelector('.asset-management-layout button[type="submit"]')).toBeNull()
expect(dialog.textContent).toContain('rain-street-original.png')
expect(dialog.textContent).toContain('image/png')
expect(dialog.textContent).toContain('PNG 图片')
expect(dialog.textContent).toContain('4.0 KB')
expect(router.currentRoute.value.path).toBe('/assets')
expect(wrapper.getComponent(AssetCategorySelect).getComponent(NSelect).props('options')).toContainEqual({ label: '视觉风格', value: 'visual-style' })
await new DOMWrapper(dialog).get('#library-asset-name').setValue('雨夜街道新版')
wrapper.getComponent(AssetCategorySelect).vm.$emit('update:value', 'visual-style')
await flushPromises()
const save = [...dialog.querySelectorAll<HTMLButtonElement>('.n-card__footer button')].find(button => button.textContent?.trim() === '保存修改')!
save.click()
await flushPromises()
const update = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(update[0]).toBe('/api/projects/project-one/assets/asset-scene')
expect(JSON.parse(String(update[1]?.body))).toEqual({ name: '雨夜街道新版', category: 'visual-style' })
await wrapper.get('input[aria-label="搜索资产图片"]').setValue('天降甘霖')
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
+49 -53
View File
@@ -4,6 +4,7 @@ import { policyDraft, policyIssue } from '@/features/projects/quality-policy'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import QualityPolicySettings from '@/features/generation-config/components/QualityPolicySettings.vue'
import { qualityPolicySignature, readQualityPolicyConfirmation, rememberQualityPolicyConfirmation } from '@/features/projects/quality-policy-confirmation'
/** 保留已有精确例外的服务端完整策略。 */
const saved: ProjectQualityPolicy = {
@@ -23,66 +24,61 @@ afterEach(() => {
settings?.unmount()
settings = undefined
vi.unstubAllGlobals()
vi.restoreAllMocks()
localStorage.clear()
})
describe('项目质量策略', () => {
it('进入和新增例外不立即报错,保存时拦截缺失字段,修正后才写入', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data: {
projectId: 'p',
policy:
init?.method === 'PUT'
? JSON.parse(String(init.body))
: { ...saved, actionExceptions: [] }
}
})
)
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false } })
it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => {
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(wrapper.findAll('button').some(button => button.text() === '添加例外')).toBe(false)
expect(wrapper.find('[aria-label="例外 1 主体引用"]').exists()).toBe(false)
expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(saved.actionExceptions)
})
it('启动入口复用真实回执,不重复读取,无变化保存保留确认,修改后撤销确认', async () => {
let currentPolicy = policyDraft(saved)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'p', policy: policyDraft(currentPolicy) }))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => { currentPolicy = policyDraft(policy); return { projectId: id, policy: policyDraft(policy) } })
const signature = qualityPolicySignature(saved)
rememberQualityPolicyConfirmation('p', signature)
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(read).not.toHaveBeenCalled()
expect(wrapper.vm.validatedDraft()).toEqual(saved)
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBe(signature)
await wrapper.get('#quality-custom-rules').setValue('新规则')
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBeNull()
})
it('保存基础规则时合并后来新增的例外,不覆盖隐藏的服务端最新例外', async () => {
const latest = { ...saved, actionExceptions: [...saved.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0002', resource: 'right_hand' as const, reason: '另一处刚添加的例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'p', policy: latest })
const write = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => ({ projectId: id, policy: policyDraft(policy) }))
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(wrapper.find('.text-danger').exists()).toBe(false)
await wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
expect(wrapper.text()).not.toContain('精确例外需填写')
expect(wrapper.vm.canSave).toBe(true)
await wrapper.vm.save()
expect(wrapper.text()).toContain('精确例外需填写')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(0)
await wrapper.get('[aria-label="例外 1 主体引用"] input').setValue('@CH0001')
expect(wrapper.text()).not.toContain('精确例外需填写')
await wrapper.vm.save()
expect(wrapper.text()).toContain('精确例外需填写')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(0)
await wrapper.get('[aria-label="例外 1 确认依据"] input').setValue('剧本明确的动作许可')
await wrapper.get('#quality-custom-rules').setValue('新的整体规则')
await wrapper.vm.save()
expect(write).toHaveBeenCalledExactlyOnceWith('p', { ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions })
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(latest.actionExceptions)
expect(wrapper.text()).toContain('已有动作例外 · 2 项')
})
it('基础规则已被其他位置修改时拒绝覆盖,保留用户草稿', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'p', policy: { ...saved, physicsMode: 'fantasy' } })
const write = vi.spyOn(projectsApi, 'saveQualityPolicy')
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
const writes = fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')
expect(writes).toHaveLength(1)
expect(JSON.parse(String(writes[0]?.[1]?.body))).toEqual({
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: ['规则'],
actionExceptions: [
{
code: 'action_resource_conflict',
ownerRef: '@CH0001',
resource: 'left_hand',
reason: '剧本明确的动作许可'
}
]
})
expect(wrapper.text()).toContain('质量策略已保存')
await wrapper.get('#quality-custom-rules').setValue('不能丢失的用户草稿')
await wrapper.vm.save()
expect(write).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('质量规则已在其他位置更新')
expect(wrapper.vm.validatedDraft()?.customRules).toEqual(['不能丢失的用户草稿'])
})
it('草稿编辑不污染已保存策略,完整保留精确例外', () => {
const draft = policyDraft(saved)
@@ -448,7 +448,7 @@ describe('过期首帧到具体素材定位', () => {
it('警告列出具体集数与镜头,可定位关联素材或打开对应生产镜头', async () => {
const { router, fetcher } = await gallery()
const warning = wrapper!.get('[data-keyframe-impact]')
expect(warning.text()).toContain('第 2 集 · BEAT 2 / 镜头 1')
expect(warning.text()).toContain('第 2 集 · 剧情段落 2 / 镜头 1')
const shotLink = warning.get('a[data-impact-shot-link]')
const location = new URL(shotLink.attributes('href')!, 'http://localhost')
expect(location.pathname).toBe('/projects/capability-test/production')
+2 -2
View File
@@ -75,9 +75,9 @@ describe('WorkflowExecution 前端契约', () => {
expect(wrapper.text()).toContain('更新时间')
wrapper.unmount()
})
it('保留未知阶段并限制真实进度范围', () => {
it('未知阶段以待确认展示且不影响真实进度范围', () => {
expect(executionStageLabel('repairing')).toBe('自动修复')
expect(executionStageLabel('new_backend_stage')).toBe('new_backend_stage')
expect(executionStageLabel('new_backend_stage')).toBe('状态待确认')
expect(executionPercentage(1, 2)).toBe(50)
expect(executionPercentage(4, 2)).toBe(100)
expect(executionPercentage(1, 0)).toBe(0)
+18 -12
View File
@@ -37,6 +37,7 @@ import { identityFixture, identityImageFixture } from '@/features/subject-identi
import { getIdentitySession } from '@/features/subject-identity/model'
import { drawerPanel, expandSections, selectControl } from '@/testing/naive'
import ProductionPage from '@/features/production/ProductionPage.vue'
import RawDataDetails from '@/components/ui/RawDataDetails.vue'
import { getProductionSession } from '@/features/production/model'
/**
@@ -353,7 +354,7 @@ describe('内容级滚动下的生产反馈', () => {
expect(wrapper.find('.workspace-tools-drawer').exists()).toBe(false)
const alert = wrapper.get('.workspace-split [role="alert"]')
expect(alert.element.closest('.workspace-tools-drawer')).toBeNull()
expect(alert.text()).toContain('无法连接后端')
expect(alert.text()).toContain('暂时无法连接服务')
})
it('回执返回时自动展开总览,部分失败诊断不会留在折叠区内', async () => {
@@ -827,7 +828,7 @@ describe('视觉风格与主体身份工作区', () => {
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写有效的')
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写可访问的图片链接')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('/storage/style.png')
button('添加参考图').click()
@@ -894,7 +895,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(button('确认AI 重新生成风格').disabled).toBe(true)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('视觉风格首次查询为空时可人工保存,JSON 校验和锁定字段准确传递', async () => {
it('视觉风格首次查询为空时可人工保存,画面要求与锁定字段准确传递', async () => {
let style: ReturnType<typeof styleFixture> | null = null
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'PUT') style = styleFixture(JSON.parse(init.body as string))
@@ -906,12 +907,7 @@ describe('视觉风格与主体身份工作区', () => {
await expandSections()
expect(wrapper!.text()).toContain('默认采用中国人物选角基线')
expect(wrapper!.text()).toContain('人物风格与选角背景')
await wrapper!.get('#style-constraints').setValue('{"不应静默丢弃":true}')
button('保存视觉风格').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('JSON 字符串数组')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
await wrapper!.get('#style-constraints').setValue('["真人写实"]')
await wrapper!.get('#style-constraints').setValue('真人写实')
await wrapper!.get('#style-lock').trigger('click')
await wrapper!.get('#style-name').setValue('雨夜风格')
button('保存视觉风格').click()
@@ -1347,7 +1343,7 @@ describe('视觉风格与主体身份工作区', () => {
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
expect(getOperation(fixture.id).error).toContain('无法连接后端')
expect(getOperation(fixture.id).error).toContain('暂时无法连接服务')
provided.data.value!.project = { ...fixture, status: 'generating' }
await flushPromises()
expect(new DOMWrapper(document.body).get('#identity-description').attributes('disabled')).toBeDefined()
@@ -1669,8 +1665,10 @@ describe('工作台页面交互', () => {
expect(wrapper.text()).toContain('图片不可用')
expect(wrapper.find('.reference-card a').exists()).toBe(false)
expect(wrapper.find('.reference-card img').exists()).toBe(false)
button('读取生成规格').click()
button('整理生成方案').click()
await flushPromises()
expect(wrapper.find('pre').exists()).toBe(false)
await wrapper.getComponent(RawDataDetails).get('.n-collapse-item__header-main').trigger('click')
expect(wrapper.get('pre').text()).toContain('form-db')
expect(wrapper.get('pre').text()).toContain('地面积水')
expect(fetcher.mock.calls[2]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/generation-spec')
@@ -1971,7 +1969,7 @@ describe('工作台页面交互', () => {
)
await flushPromises()
expect(wrapper.text()).not.toContain('旧镜头人物')
expect(button('读取生成规格').disabled).toBe(true)
expect(button('整理生成方案').disabled).toBe(true)
})
it('提示词必须确认才 POST,使用正式 Shot ID,返回内容以纯文本显示', async () => {
@@ -2083,6 +2081,9 @@ describe('工作台页面交互', () => {
return new Response(
'{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}'
)
if (String(url).includes('quality-policy')) return new Response(JSON.stringify({ data: { projectId: 'page-test-project', policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} } }))
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
stubFetch(fetcher)
@@ -2101,6 +2102,11 @@ describe('工作台页面交互', () => {
await flushPromises()
button('生成拆解候选').click()
await flushPromises()
const acknowledgement = Array.from(document.querySelectorAll<HTMLElement>('[role="checkbox"]')).find(input => input.textContent?.includes('我已核对'))!
acknowledgement.click()
await flushPromises()
button('确认规则并继续').click()
await flushPromises()
button('确认生成拆解候选').click()
await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST')
+22
View File
@@ -35,6 +35,28 @@ export function candidateState(overrides: Partial<BreakdownState> = {}): Breakdo
}
}
/**
* 创建有明确同阶段左手占用冲突的候选,供问题入口与例外保存的集成验收复用。
* @param overrides 当前项目与生命周期差异
* @returns 带完整角色和动作证据的独立候选
*/
export function resourceConflictState(overrides: Partial<BreakdownState> = {}): BreakdownState {
const state = candidateState(overrides)
const shot = state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[0]!
shot.requiredActions = [
{ id: 'hold', description: '左手握住铜铃', kind: 'action', mustPerformInShot: true },
{ id: 'wave', description: '左手向村民挥动', kind: 'action', mustPerformInShot: true }
]
shot.durationPlanning!.phases = [{
action: '握铃时挥手', actionIds: ['hold', 'wave'], estimatedSeconds: 4,
resourceOccupancy: [
{ ownerRef: '@CH0001', resource: 'left_hand', actionId: 'hold', usage: 'hold', shareable: false },
{ ownerRef: '@CH0001', resource: 'left_hand', actionId: 'wave', usage: 'move', shareable: false }
]
}]
return state
}
/**
* 构造稳定的当前候选检查点。
* @param state 当前候选状态
+1 -1
View File
@@ -169,7 +169,7 @@ describe('后端 API 契约', () => {
.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }))
)
await expect(request('/projects')).rejects.toMatchObject({ status: 400, details: ['缺少形态'] })
await expect(request('/projects')).rejects.toThrow('接口未返回 JSON')
await expect(request('/projects')).rejects.toThrow('服务暂时无法返回有效结果')
})
it('预览模块使用逗号参数,三种恢复不误发到 start', async () => {
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { ApiError, errorMessage } from '@/lib/http'
import { getOperation, operationErrorText, runOperation } from '@/features/workflows/operations'
describe('面向普通用户的系统提示', () => {
it('错误展示使用中文说明,不把技术字段和调试对象直接输出给用户', () => {
const details = { issues: [{ message: 'Shot 主体引用缺失:@CH0001' }], debug: { executionId: 'internal-id', sql: 'SELECT secret' } }
const error = new ApiError('后端 Storyboard 校验失败', 400, details)
const text = errorMessage(error)
expect(text).toContain('分镜')
expect(text).toContain('主体引用缺失:@CH0001')
expect(text).not.toMatch(/后端|前端|Storyboard|\bShot\b|executionId|SELECT|"issues"/)
expect(error.details).toBe(details)
})
it('连接失败给出可操作说明,保留任务可能仍在执行的提醒', () => {
const text = errorMessage(new Error('无法连接后端。已提交的任务可能仍在运行。'))
expect(text).not.toContain('后端')
expect(text).toContain('已提交的任务可能仍在运行')
})
it('中文展示不改变恢复流程读取的原始错误,手动更新后的提示也不会沿用旧原因', async () => {
const original = new ApiError('Shot 缺少 Primary Keyframe', 400)
await runOperation('copy-recovery-test', '生成视频描述', async () => { throw original })
const operation = getOperation('copy-recovery-test')
expect(operation.error).toContain('首帧')
expect(operation.error).not.toContain('Primary Keyframe')
expect(operationErrorText(operation)).toBe('Shot 缺少 Primary Keyframe')
operation.error = '新的操作原因'
expect(operationErrorText(operation)).toBe('新的操作原因')
})
})