feat(short-drama-agent-front): 完善主体身份骨架屏与交互反馈

This commit is contained in:
GJ committed 2026-10-11 17:23:14 +08:00
1 parent 5fa1c251a9
commit dd0bd79a35
19 files changed
+1552 -419

No files matched your search

+2
View File
@@ -82,6 +82,8 @@ watch(() => props.src, reset)
@apply w-full h-full min-w-0 min-h-0;
}
.reveal-image > .n-image img {
/* 所有图片从顶部展示,裁切缩略图时优先保留人物头部。 */
object-position: center top;
opacity: 0;
transition: opacity 220ms cubic-bezier(0.25, 1, 0.5, 1);
}
@@ -36,17 +36,14 @@ const imageGenerationOptions = ref<GenerationOptions>({})
const projectAspectRatio = ref<CreativeProfileAspectRatio>('9:16')
const canSubmit = computed(() => !props.disabled && confirmed.value)
/** 预览仅对应当前镜头、模型和参数;请求过期后不得覆盖新配置。 */
const previewRequestKey = computed(() => JSON.stringify([
props.shotId,
imageProvider.value,
imageGenerationOptions.value
]))
const previewRequestKey = computed(() =>
JSON.stringify([props.shotId, imageProvider.value, imageGenerationOptions.value])
)
watch(previewRequestKey, () => {
preview.value = null
previewError.value = ''
})
/** 切换镜头或重新打开时清空费用确认;新图一律先作为候选。 */
async function reset() {
confirmed.value = false
@@ -164,7 +161,11 @@ async function loadPreview() {
</NTag>
</div>
<!-- 规格审计仅提示导演约束风险,不阻止首帧生成。 -->
<section v-if="preview.specConsistencySummary" class="mt-3 bg-muted/10 p-3" aria-label="生成规格一致性检查">
<section
v-if="preview.specConsistencySummary"
class="mt-3 bg-muted/10 p-3"
aria-label="生成规格一致性检查"
>
<div class="flex flex-wrap items-center gap-2">
<strong>生成规格检查</strong>
<NTag
+54 -8
View File
@@ -2,6 +2,7 @@
import { computed, h, inject, onScopeDispose, provide, ref, watch, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NScrollbar, NAlert, NButton, NPageHeader, NSpin, NEllipsis } from 'naive-ui'
import type { MessageReactive } from 'naive-ui'
import { EmptyState } from '../../components/ui'
import { projectContextKey, useProjectData } from './context'
import { getOperation } from '../workflows/operations'
@@ -17,6 +18,7 @@ import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
import CreateDramaSkeleton from '../create-drama/CreateDramaSkeleton.vue'
import BreakdownSkeleton from '../breakdown/BreakdownSkeleton.vue'
import VisualStyleSkeleton from '../visual-style/VisualStyleSkeleton.vue'
import SubjectIdentitySkeleton from '../subject-identity/SubjectIdentitySkeleton.vue'
/** 项目标题只保留名称;下游工作区在剧本完成前不挂载,直接链接也无法越过限制。 */
const route = useRoute()
@@ -147,18 +149,40 @@ const operationGuide = computed<OperationGuide | null>(() => {
return { title: '操作未完成', description: error }
})
/** 镜头工作区的操作结果只在用户发起操作后显示,不在进入页面时重放旧提示。 */
/** 操作结果只在当前项目收到新响应后通知,不在进入工作区时重放旧提示。 */
const actionMessage = useActionMessage()
/** 分镜和生产页保留必要进度,操作成功或失败改用临时消息。 */
const quietFeedback = computed(() => currentSection.value === 'production' || currentSection.value === 'storyboard')
/** 分镜、生产和主体身份的操作结果使用临时消息。 */
const quietFeedback = computed(() =>
['production', 'storyboard', 'subject-identity'].includes(currentSection.value ?? '')
)
/** 主体身份请求进度使用消息,其余工作区继续展示已有任务进度。 */
const inlinePendingFeedback = computed(() => operation.value.pending && currentSection.value !== 'subject-identity')
/** 当前身份请求的加载消息,完成或离开工作区后立即销毁。 */
let pendingMessage: MessageReactive | null = null
/** 请求开始即反馈,切换主体时保留请求目标名称,避免无反馈的禁用按钮。 */
watch(
() => [id.value, currentSection.value, operation.value.pending, operation.value.label] as const,
([, section, pending, label]) => {
pendingMessage?.destroy()
pendingMessage = null
if (section === 'subject-identity' && pending)
pendingMessage = actionMessage?.loading(`${label || '主体身份操作'},请稍候…`, { duration: 0 }) ?? null
}
)
/** 关闭页面时清理未完成请求的加载消息。 */
onScopeDispose(() => pendingMessage?.destroy())
/** 只通知仍在当前项目的真实新结果,不把任务提交当作素材生成完成。 */
watch(
() => [id.value, operation.value.error, operation.value.notice] as const,
([projectId, error, notice], [previousProject, previousError, previousNotice]) => {
if (!quietFeedback.value || projectId !== previousProject) return
if (projectId !== previousProject) return
if (error && error !== previousError) {
if (!quietFeedback.value) return
const guide = operationGuide.value
const content = productionMessage(error)
const content =
currentSection.value === 'subject-identity'
? `${operation.value.label || '主体身份操作'}失败:${productionMessage(error)}`
: productionMessage(error)
actionMessage?.error(
() =>
h('div', { class: 'flex max-w-[min(600px,calc(100vw-48px))] flex-wrap items-center gap-3' }, [
@@ -181,9 +205,24 @@ watch(
{ duration: 8000, closable: true }
)
} else if (notice && notice !== previousNotice) {
if (/生成|提交/.test(operation.value.label))
if (!quietFeedback.value) return
if (operation.value.noticeType)
actionMessage?.[operation.value.noticeType](notice, {
duration: operation.value.noticeType === 'warning' ? 8000 : 4000,
closable: true
})
else if (operation.value.label === 'AI 生成主体身份')
actionMessage?.success('身份文本已生成并保存。', { duration: 3000, closable: true })
else if (operation.value.label === '保存主体身份')
actionMessage?.success('主体身份已保存。', { duration: 3000, closable: true })
else if (/生成|提交/.test(operation.value.label))
actionMessage?.info('任务已提交,完成后会显示结果。', { duration: 4000 })
else actionMessage?.success('操作已完成。', { duration: 3000 })
// 身份页已消费的反馈立即清除,切换主体或其它工作区都不会遗留旧横幅。
if (currentSection.value === 'subject-identity') {
operation.value.notice = ''
operation.value.noticeType = null
}
}
},
{ flush: 'post' }
@@ -240,7 +279,12 @@ onScopeDispose(() => {
</NPageHeader>
</header>
<NScrollbar
v-if="context.error.value || operation.pending || (!quietFeedback && (operation.error || operation.notice))"
v-if="
context.error.value ||
inlinePendingFeedback ||
(!quietFeedback && operation.error) ||
(!quietFeedback && operation.notice)
"
class="project-notices"
content-class="project-notices-content"
>
@@ -250,7 +294,7 @@ onScopeDispose(() => {
>重试读取</NButton
></NAlert
>
<NAlert v-if="operation.pending" :show-icon="false" role="status"
<NAlert v-if="inlinePendingFeedback" :show-icon="false" role="status"
>{{ operation.label || '后台制作任务执行中' }}。可切换页面查看结果,请勿重复提交。</NAlert
>
<NAlert v-if="operationGuide && !quietFeedback" type="error" :show-icon="false" class="operation-guide">
@@ -311,6 +355,8 @@ onScopeDispose(() => {
<BreakdownSkeleton v-else-if="isProjectInitialLoading && currentSection === 'breakdown'" />
<!-- 以下是视觉风格项目首次读取的骨架屏模块 -->
<VisualStyleSkeleton v-else-if="isProjectInitialLoading && currentSection === 'visual-style'" />
<!-- 以下是主体身份项目首次读取的骨架屏模块 -->
<SubjectIdentitySkeleton v-else-if="isProjectInitialLoading && currentSection === 'subject-identity'" />
<NSpin v-else-if="context.loading.value" class="workspace-loading" description="正在读取项目内容…" />
</div>
</section>
@@ -26,8 +26,11 @@ import ConfirmAction from '../workflows/ConfirmAction.vue'
import { castingStatusLabel, currentAnchor } from './model'
import { useSubjectIdentity } from './useSubjectIdentity'
import { useProjectContext } from '../projects/context'
import { useProjectStageAccess } from '../projects/useProjectStageAccess'
import StableAnchorQualityDialog from './components/StableAnchorQualityDialog.vue'
import IdentityEditor from './components/IdentityEditor.vue'
import SubjectIdentitySkeleton from './SubjectIdentitySkeleton.vue'
import IdentityDetailSkeleton from './components/IdentityDetailSkeleton.vue'
import IdentityGallery from './components/IdentityGallery.vue'
import IdentityImageDialog from './components/IdentityImageDialog.vue'
import CastingCandidateDialog from './components/CastingCandidateDialog.vue'
@@ -38,7 +41,6 @@ import type { IdentitySubject } from './types'
const route = useRoute()
const router = useRouter()
const projectContext = useProjectContext()
const stageComplete = computed(() => projectContext.stageReadiness.value?.identity.ready === true)
const {
projectId,
operation,
@@ -82,9 +84,31 @@ const {
confirmCasting,
validateImage,
generateStableAnchorQuality,
validationResult,
qualityResult
pendingImageOperation
} = useSubjectIdentity()
/** 所有形态图片入口复用侧栏和路由的服务端阶段准入规则。 */
const stageAccess = useProjectStageAccess(projectId, projectContext.stageReadiness)
/** 当前项目是否允许进入形态图片,以及尚未开放的具体原因。 */
const subjectImagesAccess = computed(() => stageAccess.sections.value['subject-images'])
/** 当前主体的生成进度或失败原因统一放在两栏上方,切换主体时跟随正式详情更新。 */
const generationFeedback = computed(() => {
if (!subject.value) return null
if (activeIdentityGeneration.value)
return {
type: 'info' as const,
message: `${subject.value.name} 的身份图片正在生成,刷新页面不会重复提交,请等待当前任务完成。`
}
if (latestIdentityFailure.value)
return {
type: 'error' as const,
message: `最近一次身份图片生成失败:${latestIdentityFailure.value.error || '未返回具体错误'}。可以调整模型参数后重新生成。`
}
return null
})
/** 首次读取目录才替换整页,刷新已有主体时保留选择与阅读位置。 */
const initialLoading = computed(() => catalog.loading.value && !catalog.data.value)
/** 切换主体时只替换尚未返回的详情,不遮挡已读取的主体目录。 */
const detailInitialLoading = computed(() => detail.loading.value && !detail.data.value)
const search = ref('')
const module = ref('all')
const identityBatchModule = ref<'all' | 'character' | 'scene' | 'prop'>('all')
@@ -219,7 +243,7 @@ const identityFlow = computed(() => {
const character = subject.value?.module === 'character'
return [
{ label: '身份文本', done: identityTextReady.value },
{ label: character ? '选角候选' : '身份参考图', done: candidateReady.value },
{ label: character ? '角色候选图' : '身份参考图', done: candidateReady.value },
{ label: '确认并锁定', done: identityReady.value }
]
})
@@ -227,6 +251,7 @@ const currentFlowIndex = computed(() => {
const index = identityFlow.value.findIndex(step => !step.done)
return index < 0 ? identityFlow.value.length : index
})
/** 按身份文本、角色候选图和母版确认状态说明下一步,明确 AI 生成的是文本还是图片。 */
const nextAction = computed<{ action: IdentityFlowAction; title: string; description: string; label: string }>(() => {
if (!hasStyle.value)
return {
@@ -246,16 +271,16 @@ const nextAction = computed<{ action: IdentityFlowAction; title: string; descrip
return {
action: 'identity',
title: '第 1 步:生成身份文本',
description: '生成稳定身份描述和核心提示词。',
label: '生成身份文本'
description: 'AI 填写下方身份描述和核心提示词,生成后会保存到项目。',
label: 'AI 生成主体身份'
}
if (!candidateReady.value)
return subject.value?.module === 'character'
? {
action: 'candidate',
title: '第 2 步:生成选角候选',
description: '生成候选后再确认正式演员。',
label: '生成选角候选'
title: '第 2 步:生成角色候选图',
description: 'AI 根据身份文本生成角色外观图片,选定一张作为角色母版,用于后续图片生成。',
label: 'AI 生成角色候选图'
}
: {
action: 'candidate',
@@ -280,7 +305,9 @@ const nextAction = computed<{ action: IdentityFlowAction; title: string; descrip
return {
action: 'forms',
title: '主体身份已完成',
description: '可以继续生成此主体的形态图片。',
description: subjectImagesAccess.value.enabled
? '可以继续生成此主体的形态图片。'
: `${subjectImagesAccess.value.reason},完成项目准备后可进入形态图片。`,
label: '查看形态图片'
}
})
@@ -290,10 +317,10 @@ function openProfileSettings() {
if (route.query.configure !== 'profile') void router.replace({ query: { ...route.query, configure: 'profile' } })
}
/** 根据当前主体的下一步引导执行操作,形态图片跳转仍遵守项目统一准入规则。 */
function runNextAction() {
if (nextAction.value.action === 'style') void router.push(`/projects/${projectId.value}/visual-style`)
else if (nextAction.value.action === 'profile') openProfileSettings()
else if (nextAction.value.action === 'identity') void generate()
else if (nextAction.value.action === 'candidate') {
if (subject.value?.module === 'character') castingOpen.value = true
else imageOpen.value = true
@@ -301,7 +328,7 @@ function runNextAction() {
document.querySelector('#identity-reference-gallery')?.scrollIntoView({ behavior: 'smooth', block: 'start' })
} else if (nextAction.value.action === 'lock') {
document.querySelector('#identity-lock')?.scrollIntoView({ behavior: 'smooth', block: 'center' })
} else if (nextAction.value.action === 'forms') {
} else if (nextAction.value.action === 'forms' && subjectImagesAccess.value.enabled) {
void router.push({
path: `/projects/${projectId.value}/subject-images`,
query: { subjectRef: subject.value?.ref }
@@ -311,9 +338,11 @@ function runNextAction() {
</script>
<template>
<WorkspacePage split compact mobile-scroll class="identity-workspace-page">
<!-- 以下是项目已读取但正式主体目录尚未返回时的完整骨架屏模块 -->
<SubjectIdentitySkeleton v-if="initialLoading" />
<WorkspacePage v-else split compact mobile-scroll class="identity-workspace-page">
<template #notice>
<NAlert v-if="stageComplete" type="success" :show-icon="false">
<NAlert v-if="subjectImagesAccess.enabled" type="success" :show-icon="false">
所有需要确认的角色身份已经准备好,可以继续制作主体形态图片。
<RouterLink :to="`/projects/${projectId}/subject-images`" class="text-button ml-2"
>继续形态图片 →</RouterLink
@@ -451,7 +480,7 @@ function runNextAction() {
@confirm="generateProject(true)"
/>
<ConfirmAction
label="生成选角候选"
label="AI 批量生成角色候选图"
:disabled="
castingBlocked ||
!hasStyle ||
@@ -612,6 +641,14 @@ function runNextAction() {
><NAlert role="alert" type="error" :show-icon="false"
>{{ catalog.error.value || styleQuery.error.value || castingQuery.error.value }}
当前相关操作已暂停,请刷新核对后端。
<NButton
v-if="catalog.error.value"
text
class="ml-3"
:loading="catalog.loading.value"
@click="catalog.refresh"
>重试读取目录</NButton
>
</NAlert></NScrollbar
>
<NAlert
@@ -625,209 +662,236 @@ function runNextAction() {
<NButton type="primary" @click="openProfileSettings">立即配置</NButton>
</div>
</NAlert>
<div v-if="subjects.length" class="identity-workspace">
<!-- 以下是主体目录 -->
<aside class="panel directory-panel identity-directory">
<div class="directory-heading">
<h3>
主体目录 <span>{{ filtered.length }} / {{ subjects.length }}</span>
</h3>
</div>
<div class="directory-filters">
<NInput
placeholder="搜索主体或引用"
aria-label="搜索主体身份"
:input-props="{ 'aria-label': '搜索主体身份' }"
v-model:value="search"
clearable
></NInput>
</div>
<NScrollbar
class="identity-subject-list panel-scroll directory-scroll"
content-class="directory-list-content identity-subject-list-content"
x-scrollable
>
<!-- 以下是主体选中项自动定位模块,不增加目录布局占位 -->
<div ref="subjectDirectoryRoot" class="identity-directory-items">
<DirectoryItem
v-for="item in filtered"
:key="item.id"
:aria-pressed="selectedId === item.id"
:active="selectedId === item.id"
@click="select(item.id)"
class="identity-subject-item"
>{{ item.name }}
<template #leading>
<IdentityThumbnail
:project-id="projectId"
:subject-id="item.id"
:name="item.name"
:module="item.module"
:identity-id="item.identity === null ? null : item.identity?.id"
:source="thumbnailSource(item)"
:refresh-key="thumbnailRefreshKey"
/>
</template>
<template #eyebrow>{{ item.ref }}</template>
<template #meta>
<span>{{ item.forms.length }} 个形态</span
><span v-if="castingBySubject.has(item.id)" class="directory-status">
{{ castingStatusLabel(castingBySubject.get(item.id)!.status) }}</span
>
</template></DirectoryItem
<div v-if="subjects.length" class="identity-workspace-region">
<!-- 以下是目录与详情上方的全栏生成提示模块,显示和隐藏时平滑收放高度 -->
<Transition name="identity-feedback" appear>
<div v-if="generationFeedback" class="identity-feedback-motion">
<div class="identity-feedback-body workspace-feedback">
<NAlert
:type="generationFeedback.type"
:show-icon="false"
class="identity-generation-feedback text-xs"
>{{ generationFeedback.message }}</NAlert
>
<p v-if="!filtered.length" class="py-6 text-xs text-muted">没有匹配主体,请调整筛选。</p>
</div>
</NScrollbar>
</aside>
<NScrollbar class="identity-detail panel-scroll min-w-0">
<NAlert v-if="pendingSelection" type="info" :show-icon="false" class="mb-4"
><p class="text-xs">当前主体有未保存修改,切换会丢弃草稿。</p>
<div class="mt-3 flex gap-3">
<NButton @click="discardAndSelect">放弃草稿并切换</NButton
><NButton @click="pendingSelection = ''" text size="small">继续编辑</NButton>
</div></NAlert
>
<section v-if="subject" class="panel workspace-panel">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="font-semibold">
{{ subject.name }} <code class="subject-ref ml-2">{{ subject.ref }}</code>
</h3>
</div>
<NButton :disabled="detail.loading.value" @click="detail.refresh" text size="small">
刷新身份
</NButton>
</div>
</Transition>
<div class="identity-workspace">
<!-- 以下是主体目录 -->
<aside class="panel directory-panel identity-directory">
<div class="directory-heading">
<h3>
主体目录 <span>{{ filtered.length }} / {{ subjects.length }}</span>
</h3>
</div>
<NAlert v-if="detail.error.value" role="alert" type="error" :show-icon="false" class="mt-4"
>{{ detail.error.value }} 查询失败时不允许生成或覆盖。
</NAlert>
<p v-if="!detail.data.value && detail.loading.value" class="py-8 text-sm text-muted" role="status">
正在读取主体身份…
</p>
<template v-if="detail.data.value">
<div class="identity-flow mt-4" aria-label="主体身份操作步骤">
<ol class="identity-flow-steps">
<li
v-for="(step, index) in identityFlow"
:key="step.label"
:class="{ done: step.done, current: index === currentFlowIndex }"
>
<span class="identity-flow-marker">
<Check v-if="step.done" :size="14" />
<Circle v-else :size="12" />
</span>
<span>{{ index + 1 }}. {{ step.label }}</span>
</li>
</ol>
<div class="identity-next-action">
<div>
<strong>{{ nextAction.title }}</strong>
<p>{{ nextAction.description }}</p>
</div>
<NButton
type="primary"
:disabled="
operation.pending ||
(nextAction.action === 'identity' && !canGenerateText) ||
(nextAction.action === 'candidate' &&
(subject.module === 'character'
? !canGenerateCandidate
: !canGenerateImage))
"
@click="runNextAction"
>{{ nextAction.label }}</NButton
>
</div>
<div class="directory-filters">
<NInput
placeholder="搜索主体或引用"
aria-label="搜索主体身份"
:input-props="{ 'aria-label': '搜索主体身份' }"
v-model:value="search"
clearable
></NInput>
</div>
<NScrollbar
class="identity-subject-list panel-scroll directory-scroll"
content-class="directory-list-content identity-subject-list-content"
x-scrollable
>
<!-- 以下是主体选中项自动定位模块,不增加目录布局占位 -->
<div ref="subjectDirectoryRoot" class="identity-directory-items">
<DirectoryItem
v-for="item in filtered"
:key="item.id"
:aria-pressed="selectedId === item.id"
:active="selectedId === item.id"
@click="select(item.id)"
class="identity-subject-item"
>{{ item.name }}
<template #leading>
<IdentityThumbnail
:project-id="projectId"
:subject-id="item.id"
:name="item.name"
:module="item.module"
:identity-id="item.identity === null ? null : item.identity?.id"
:source="thumbnailSource(item)"
:refresh-key="thumbnailRefreshKey"
/>
</template>
<template #eyebrow>{{ item.ref }}</template>
<template #meta>
<span>{{ item.forms.length }} 个形态</span
><span v-if="castingBySubject.has(item.id)" class="directory-status">
{{ castingStatusLabel(castingBySubject.get(item.id)!.status) }}</span
>
</template></DirectoryItem
>
<p v-if="!filtered.length" class="py-6 text-xs text-muted">没有匹配主体,请调整筛选。</p>
</div>
<p v-if="dirty" class="mt-3 text-xs text-muted">请先保存身份修改,再使用 AI 或生成图片。</p>
<IdentityEditor
:key="`${selectedId}:${editorRevision}`"
:identity="identity"
:module="subject.module"
:disabled="detailBlocked"
@save="save"
@dirty="dirty = $event"
/>
<div v-if="anchor" class="identity-anchor mt-5 flex items-center gap-4 pt-5">
<AssetImage
:src="anchor.imageUrl"
:alt="`${subject.name}当前身份母版`"
preview
class="h-20 w-20 shrink-0"
/>
</NScrollbar>
</aside>
<NScrollbar class="identity-detail panel-scroll min-w-0">
<NAlert v-if="pendingSelection" type="info" :show-icon="false" class="mb-4"
><p class="text-xs">当前主体有未保存修改,切换会丢弃草稿。</p>
<div class="mt-3 flex gap-3">
<NButton @click="discardAndSelect">放弃草稿并切换</NButton
><NButton @click="pendingSelection = ''" text size="small">继续编辑</NButton>
</div></NAlert
>
<section v-if="subject" class="panel workspace-panel">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<p class="text-sm font-medium">当前身份母版</p>
<p class="mt-2 text-xs text-muted">
{{
subject.module === 'character'
? identity?.isLocked
? '演员身份已确认并锁定,可用于形态图与镜头首帧。'
: '已有演员母版但 Identity 尚未锁定,镜头首帧仍会被阻塞。'
: subject.module === 'prop'
? '锁定后,后续道具形态图会继承当前母版。'
: '后续场景形态图会继承此图的空间结构。'
}}
</p>
<h3 class="font-semibold">
{{ subject.name }} <code class="subject-ref ml-2">{{ subject.ref }}</code>
</h3>
</div>
<NButton :disabled="detail.loading.value" @click="detail.refresh" text size="small">
刷新身份
</NButton>
</div>
<!-- 以下是场景与道具单主体母版质量生成模块 -->
<NButton
v-if="subject.module === 'scene' || subject.module === 'prop'"
class="mt-4"
:disabled="!canGenerateImage"
@click="qualityOpen = true"
>生成稳定母版并校验质量</NButton
>
<NAlert v-if="qualityResult" :type="qualityResult.passed ? 'success' : 'warning'" class="mt-3">
{{
qualityResult.passed
? '质量闭环通过,母版与锁定已确认'
: '质量闭环未通过,候选仍保留在图库'
}}
· 已修复 {{ qualityResult.repairAttempts }} 次
<p v-if="qualityResult.stopReason">停止原因:{{ qualityResult.stopReason }}</p>
<pre class="whitespace-pre-wrap break-all text-xs">{{
JSON.stringify(qualityResult.attempts, null, 2)
}}</pre>
<NAlert v-if="detail.error.value" role="alert" type="error" :show-icon="false" class="mt-4"
>{{ detail.error.value }} 查询失败时不允许生成或覆盖。
</NAlert>
<!-- 以下是已完成主体的候选生成与真实输入预览入口模块 -->
<NButton class="mt-4" :disabled="!canGenerateImage" @click="imageOpen = true">
{{ subject.module === 'character' ? '生成辅助参考图' : '生成母版候选' }}
</NButton>
<IdentityGallery
id="identity-reference-gallery"
:key="selectedId"
:images="images"
:subject-name="subject.name"
:module="subject.module"
:identity-locked="!!identity?.isLocked"
:disabled="detailBlocked || (subject.module === 'character' && !!castingQuery.error.value)"
:validation-result="validationResult"
@validate="validateImage"
@anchor="chooseAnchor"
/>
</template>
<div class="mt-5 pt-5">
<h4 class="text-xs font-medium">此主体的形态</h4>
<div class="mt-3 flex flex-wrap gap-2">
<NTag v-for="form in subject.forms" :key="form.id" size="small" :bordered="false"
>{{ form.name }}{{ form.isDefault ? ' · 默认' : '' }}</NTag
<!-- 以下是切换主体时的局部骨架模块,保留真实主体名称与目录 -->
<IdentityDetailSkeleton v-if="detailInitialLoading" class="mt-5" />
<template v-if="detail.data.value">
<div class="identity-flow" aria-label="主体身份操作步骤">
<ol class="identity-flow-steps">
<li
v-for="(step, index) in identityFlow"
:key="step.label"
:class="{ done: step.done, current: index === currentFlowIndex }"
>
<span class="identity-flow-marker">
<Check v-if="step.done" :size="14" />
<Circle v-else :size="12" />
</span>
<span>{{ index + 1 }}. {{ step.label }}</span>
</li>
</ol>
<div class="identity-next-action">
<div>
<strong>{{ nextAction.title }}</strong>
<p>{{ nextAction.description }}</p>
</div>
<NButton
v-if="
nextAction.action !== 'identity' &&
(nextAction.action !== 'forms' || subjectImagesAccess.enabled)
"
type="primary"
:disabled="
operation.pending ||
(nextAction.action === 'candidate' &&
(subject.module === 'character'
? !canGenerateCandidate
: !canGenerateImage))
"
@click="runNextAction"
>{{ nextAction.label }}</NButton
>
</div>
</div>
<p v-if="dirty" class="mt-3 text-xs text-muted">请先保存身份修改,再使用 AI 或生成图片。</p>
<IdentityEditor
:key="`${selectedId}:${editorRevision}`"
:identity="identity"
:module="subject.module"
:disabled="detailBlocked"
@save="save"
@dirty="dirty = $event"
>
<!-- 以下是唯一的单主体 AI 文本生成入口,覆盖已有文本时沿用确认弹窗 -->
<template #generate>
<ConfirmAction
v-if="identity?.description?.trim() || identity?.generationPrompt?.trim()"
label="AI 生成主体身份"
description="AI 将重新生成当前主体的身份描述和核心提示词,并覆盖已保存的文本;已有图片不会自动更新。"
:disabled="!canGenerateText"
primary
@confirm="generate"
/>
<NButton v-else type="primary" :disabled="!canGenerateText" @click="generate">
AI 生成主体身份
</NButton>
</template>
</IdentityEditor>
<div v-if="anchor" class="identity-anchor mt-5 flex items-center gap-4 pt-5">
<AssetImage
:src="anchor.imageUrl"
:alt="`${subject.name}当前身份母版`"
preview
class="h-20 w-20 shrink-0"
/>
<div>
<p class="text-sm font-medium">当前身份母版</p>
<p class="mt-2 text-xs text-muted">
{{
subject.module === 'character'
? identity?.isLocked
? '演员身份已确认并锁定,可用于形态图与镜头首帧。'
: '已有演员母版但 Identity 尚未锁定,镜头首帧仍会被阻塞。'
: subject.module === 'prop'
? '锁定后,后续道具形态图会继承当前母版。'
: '后续场景形态图会继承此图的空间结构。'
}}
</p>
</div>
</div>
<IdentityGallery
id="identity-reference-gallery"
:key="selectedId"
:images="images"
:subject-name="subject.name"
:module="subject.module"
:identity-locked="!!identity?.isLocked"
:disabled="
detailBlocked || (subject.module === 'character' && !!castingQuery.error.value)
"
:pending-operation="pendingImageOperation"
@validate="validateImage"
@anchor="chooseAnchor"
>
<!-- 以下是图库标题栏的生成入口模块,与身份保存操作分组 -->
<template #actions>
<NButton
v-if="subject.module === 'scene' || subject.module === 'prop'"
:disabled="!canGenerateImage"
@click="qualityOpen = true"
>生成稳定母版并校验质量</NButton
>
<NButton :disabled="!canGenerateImage" @click="imageOpen = true">
{{ subject.module === 'character' ? '生成辅助参考图' : '生成母版候选' }}
</NButton>
</template>
</IdentityGallery>
</template>
<!-- 以下是当前主体形态与可用跳转入口,各行沿用统一上下间距 -->
<div v-if="!detailInitialLoading" class="identity-subject-forms">
<h4 class="text-xs font-medium">此主体的形态</h4>
<div class="flex flex-wrap gap-2">
<NTag v-for="form in subject.forms" :key="form.id" size="small" :bordered="false"
>{{ form.name }}{{ form.isDefault ? ' · 默认' : '' }}</NTag
>
</div>
<p v-if="!subject.forms.length" class="text-xs text-muted">
此角色尚无正式形态,但可以先完成 Identity 与选角。
</p>
<RouterLink
v-if="subjectImagesAccess.enabled"
:to="{
path: `/projects/${projectId}/subject-images`,
query: { subjectRef: subject.ref }
}"
class="text-button justify-self-start"
>查看此主体形态图片 →</RouterLink
>
</div>
<p v-if="!subject.forms.length" class="mt-3 text-xs text-muted">
此角色尚无正式形态,但可以先完成 Identity 与选角。
</p>
<RouterLink
:to="{ path: `/projects/${projectId}/subject-images`, query: { subjectRef: subject.ref } }"
class="text-button mt-3"
>查看此主体形态图片 →</RouterLink
>
</div>
</section>
</NScrollbar>
</section>
</NScrollbar>
</div>
</div>
<p v-else-if="catalog.loading.value" class="py-8 text-sm text-muted" role="status">正在读取正式主体目录…</p>
<EmptyState
v-else-if="catalog.data.value"
title="还没有可展示的正式主体"
@@ -836,16 +900,6 @@ function runNextAction() {
>前往剧本拆解</RouterLink
></EmptyState
>
<NAlert v-if="activeIdentityGeneration" type="info" :show-icon="false" class="mb-4 text-xs">
{{ subject?.name }} 的身份图片正在生成({{
activeIdentityGeneration.provider || '图片模型'
}}),刷新页面不会重复提交,请等待当前任务完成。
</NAlert>
<NAlert v-else-if="latestIdentityFailure" type="error" :show-icon="false" class="mb-4 text-xs">
最近一次身份图片生成失败:{{
latestIdentityFailure.error || '未返回具体错误'
}}。可以调整模型参数后重新生成。
</NAlert>
<StableAnchorQualityDialog
v-if="
subject &&
@@ -927,8 +981,43 @@ function runNextAction() {
.identity-prerequisite {
@apply shrink-0 mx-0 mb-3;
}
/* 全栏提示与双栏工作区共用外层宽度,提示的间距随自身高度一起收放。 */
.identity-workspace-region {
@apply flex flex-col flex-1 min-h-0 overflow-hidden;
}
.identity-feedback-motion {
display: grid;
grid-template-rows: 1fr;
flex-shrink: 0;
}
.identity-feedback-body {
min-height: 0;
overflow: hidden;
}
.identity-generation-feedback {
margin-bottom: var(--app-content-gap);
}
/* 使用自然内容高度适配手机长文案,避免出现和消失时直接挤动目录与详情。 */
.identity-feedback-enter-active,
.identity-feedback-leave-active {
transition:
grid-template-rows 240ms cubic-bezier(0.25, 1, 0.5, 1),
opacity 180ms ease;
}
.identity-feedback-enter-from,
.identity-feedback-leave-to {
grid-template-rows: 0fr;
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.identity-feedback-enter-active,
.identity-feedback-leave-active {
transition: none;
}
}
.identity-flow {
@apply p-4 bg-(--app-subtle);
/* 步骤、下一步说明与上下方标题和字段共用面板边界,避免二次缩进。 */
@apply mt-5;
}
.identity-flow-steps {
@apply flex flex-wrap items-center gap-x-6 gap-y-2;
@@ -956,6 +1045,16 @@ function runNextAction() {
.identity-next-action p {
@apply mt-1 text-xs text-muted;
}
.identity-next-action > div {
@apply min-w-0;
}
.identity-next-action > .n-button {
@apply shrink-0;
}
/* 形态标题、标签和可用入口独立排列,避免内联链接的上边距失效。 */
.identity-subject-forms {
@apply mt-6 grid gap-4;
}
.toolbar-type-filter {
@apply w-[152px] min-w-0;
}
@@ -1052,6 +1151,11 @@ function runNextAction() {
}
@media (max-width: 760px) {
/* 主体详情自然撑高,提示与主体导航随正文滚走;顶部两行保留固定。 */
.identity-workspace-page .identity-workspace-region {
height: auto;
flex: none;
overflow: visible;
}
.identity-workspace-page .identity-workspace {
height: auto;
flex: none;
@@ -1067,6 +1171,9 @@ function runNextAction() {
.identity-next-action {
@apply items-start flex-col;
}
.identity-next-action > .n-button {
@apply w-full;
}
.identity-workspace {
@apply grid-cols-[minmax(0,_1fr)] grid-rows-[auto_minmax(0,_1fr)] gap-3;
}
@@ -0,0 +1,119 @@
<script setup lang="ts">
import { NScrollbar, NSkeleton } from 'naive-ui'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import IdentityDetailSkeleton from './components/IdentityDetailSkeleton.vue'
</script>
<template>
<!-- 以下是项目或正式主体目录首次读取的完整工作区骨架模块 -->
<WorkspacePage
split
compact
mobile-scroll
class="subject-identity-skeleton"
role="status"
aria-label="正在读取主体身份工作区"
aria-busy="true"
>
<template #header>
<div class="workspace-toolbar identity-skeleton-toolbar">
<NSkeleton :width="152" :height="34" />
<NSkeleton class="identity-skeleton-count" :width="100" :height="12" />
<NSkeleton class="identity-skeleton-tools" :width="120" :height="34" />
</div>
</template>
<div class="identity-skeleton-workspace">
<!-- 以下是主体目录、搜索与缩略图条目占位模块 -->
<aside class="panel directory-panel identity-skeleton-directory">
<div class="directory-heading"><NSkeleton :width="70" :height="14" /></div>
<div class="identity-skeleton-search"><NSkeleton :height="34" /></div>
<NScrollbar
x-scrollable
class="identity-skeleton-list panel-scroll"
content-class="identity-skeleton-list-content"
>
<div v-for="row in 6" :key="row" class="identity-skeleton-subject">
<NSkeleton :width="48" :height="64" />
<div class="identity-skeleton-subject-copy">
<NSkeleton :width="90" :height="14" />
<NSkeleton :width="60" :height="10" />
<NSkeleton :width="115" :height="10" />
</div>
</div>
</NScrollbar>
</aside>
<!-- 以下是与真实身份详情共用的步骤、文本与参考图库占位模块 -->
<NScrollbar class="identity-skeleton-detail panel-scroll">
<section class="panel workspace-panel"><IdentityDetailSkeleton heading /></section>
</NScrollbar>
</div>
</WorkspacePage>
</template>
<style>
@reference "../../styles/styles.css";
.identity-skeleton-workspace {
@apply grid grid-cols-[clamp(240px,_22%,_280px)_minmax(0,_1fr)] gap-3 flex-1 min-h-0 overflow-hidden;
}
.identity-skeleton-toolbar {
@apply flex-nowrap;
}
.identity-skeleton-tools {
@apply ml-auto shrink-0;
}
.identity-skeleton-directory,
.identity-skeleton-detail {
@apply min-w-0 min-h-0;
}
.identity-skeleton-search {
@apply p-3 shrink-0;
}
.identity-skeleton-list-content {
@apply flex flex-col gap-0.5 pb-2;
}
.identity-skeleton-subject {
@apply flex items-center gap-3 px-3.5 py-2.5 min-w-0;
}
.identity-skeleton-subject > .n-skeleton {
@apply shrink-0;
}
.identity-skeleton-subject-copy {
@apply flex flex-col gap-2 min-w-0;
}
.subject-identity-skeleton .n-skeleton {
--n-color-start: var(--app-border) !important;
--n-color-end: var(--app-field-hover) !important;
}
@media (max-width: 760px) {
.identity-skeleton-workspace {
@apply grid-cols-[minmax(0,_1fr)] grid-rows-[auto_auto] flex-none overflow-visible;
}
.identity-skeleton-count {
@apply hidden;
}
.identity-skeleton-tools {
width: 34px !important;
}
.identity-skeleton-list.panel-scroll,
.identity-skeleton-detail.panel-scroll,
.identity-skeleton-detail > .n-scrollbar-container {
height: auto;
max-height: none;
}
.identity-skeleton-detail.panel-scroll,
.identity-skeleton-detail > .n-scrollbar-container {
overflow: visible;
}
.identity-skeleton-list-content {
@apply flex-row w-max;
}
.identity-skeleton-subject {
@apply w-[230px] shrink-0;
}
}
@media (prefers-reduced-motion: reduce) {
.subject-identity-skeleton .n-skeleton {
animation: none;
}
}
</style>
@@ -60,7 +60,12 @@ const formModel = computed(() => ({ prompt: prompt.value }))
</script>
<template>
<AppDialog v-model:open="open" title="生成角色选角候选" :description="`${subjectName} · 候选不会自动成为身份母版`">
<!-- 以下是 AI 生成角色候选图模块,生成后仍需用户确认选角 -->
<AppDialog
v-model:open="open"
title="AI 生成角色候选图"
:description="`${subjectName} · 生成后需确认选角,才能设为角色母版`"
>
<AppForm
ref="formRef"
:model="formModel"
@@ -71,8 +76,8 @@ const formModel = computed(() => ({ prompt: prompt.value }))
@submit="submit"
>
<NAlert type="info" :show-icon="false" class="text-xs">
后端会依据角色 Identity、项目视觉风格和默认选角约束独立生成一张 primary
候选,不会复用当前身份母版。生成完成后仍需人工点击“确认选角”。
AI
会根据角色身份、项目视觉风格和选角要求生成一张新的候选图,不会复用当前身份母版。生成完成后,请在图库点击“确认选角并锁定”,将图片设为角色母版。
</NAlert>
<NFormItem
class="block"
@@ -117,7 +122,7 @@ const formModel = computed(() => ({ prompt: prompt.value }))
type="primary"
@click="formRef?.validate(submit)"
>
{{ disabled ? '生成中…' : '确认生成候选' }}
{{ disabled ? '生成中…' : 'AI 生成角色候选图' }}
</NButton>
</template>
</AppDialog>
@@ -0,0 +1,104 @@
<script setup lang="ts">
import { NSkeleton } from 'naive-ui'
/** 身份详情占位选项。 */
interface Props {
/** 是否显示未知主体的标题与刷新操作占位。 */
heading?: boolean
}
/** 完整工作区未知主体名称时显示标题占位,切换主体时保留真实名称。 */
withDefaults(defineProps<Props>(), { heading: false })
/** 占位高度对应身份描述与核心提示词的最低编辑高度。 */
const fieldHeights = [80, 96]
</script>
<template>
<!-- 以下是主体身份步骤、编辑器、参考图操作与形态入口占位模块 -->
<div class="identity-detail-skeleton" role="status" aria-label="正在读取主体身份内容" aria-busy="true">
<div v-if="heading" class="identity-skeleton-row identity-skeleton-heading">
<NSkeleton :width="120" :height="16" />
<NSkeleton :width="56" :height="12" />
</div>
<div class="identity-skeleton-steps">
<div v-for="step in 3" :key="step" class="identity-skeleton-row">
<NSkeleton circle :width="20" :height="20" />
<NSkeleton :width="88" :height="12" />
</div>
</div>
<div class="identity-skeleton-row identity-skeleton-next">
<div class="identity-skeleton-copy">
<NSkeleton :width="170" :height="14" />
<NSkeleton :width="'min(260px, 100%)'" :height="12" />
</div>
</div>
<div v-for="height in fieldHeights" :key="height" class="identity-skeleton-field">
<NSkeleton :width="70" :height="12" />
<NSkeleton :height="height" />
</div>
<div class="identity-skeleton-row">
<NSkeleton :width="16" :height="16" />
<NSkeleton :width="96" :height="12" />
</div>
<div class="identity-skeleton-row identity-skeleton-save">
<NSkeleton :width="96" :height="34" />
<NSkeleton :width="126" :height="34" />
</div>
<div class="identity-skeleton-row identity-skeleton-gallery-heading">
<NSkeleton :width="100" :height="14" />
<NSkeleton :width="126" :height="34" />
</div>
<NSkeleton :height="150" />
<div class="identity-skeleton-field">
<NSkeleton :width="85" :height="12" />
<div class="identity-skeleton-row">
<NSkeleton :width="70" :height="24" />
<NSkeleton :width="80" :height="24" />
</div>
</div>
</div>
</template>
<style scoped>
@reference "../../../styles/styles.css";
.identity-detail-skeleton {
@apply flex flex-col min-w-0 gap-5;
}
.identity-skeleton-row {
@apply flex min-w-0 items-center gap-3;
}
.identity-skeleton-row :deep(.n-skeleton) {
@apply shrink-0 max-w-full;
}
.identity-skeleton-heading,
.identity-skeleton-gallery-heading,
.identity-skeleton-next {
@apply justify-between flex-wrap;
}
.identity-skeleton-steps {
@apply flex flex-wrap gap-x-6 gap-y-2;
}
.identity-skeleton-copy,
.identity-skeleton-field {
@apply flex flex-col min-w-0 gap-3;
}
.identity-skeleton-save {
@apply flex-wrap;
}
.identity-detail-skeleton :deep(.n-skeleton) {
--n-color-start: var(--app-border) !important;
--n-color-end: var(--app-field-hover) !important;
}
@media (max-width: 760px) {
.identity-skeleton-next {
@apply items-start flex-col;
}
.identity-skeleton-save > :deep(.n-skeleton) {
width: 100% !important;
}
}
@media (prefers-reduced-motion: reduce) {
.identity-detail-skeleton :deep(.n-skeleton) {
animation: none;
}
}
</style>
@@ -7,10 +7,16 @@ import type { SaveIdentityInput, SubjectIdentity } from '../types'
/** 身份文本草稿不随轮询覆盖;父页面切换主体或保存成功后重建编辑器。 */
const props = defineProps<{ identity: SubjectIdentity | null; disabled: boolean; module: string }>()
/** 保存当前主体草稿,并同步尚未保存的修改状态。 */
const emit = defineEmits<{ save: [input: SaveIdentityInput]; dirty: [value: boolean] }>()
/** 身份描述、核心提示词和锁定状态共同组成编辑草稿。 */
const form = reactive({ description: '', generationPrompt: '', isLocked: false })
/** 上次成功读取的身份快照。 */
const baseline = ref('')
/** 人工输入变动时启用保存并暂停图片生成。 */
const dirty = computed(() => JSON.stringify(form) !== baseline.value)
/** 只有后端身份记录包含文本时才显示已保存,空记录和未创建身份都属于待填写。 */
const hasSavedText = computed(() => !!(props.identity?.description?.trim() || props.identity?.generationPrompt?.trim()))
watch(
() => props.identity,
value => {
@@ -33,7 +39,8 @@ function save() {
</script>
<template>
<AppForm :model="form" :disabled="disabled" class="mt-5" @submit="save">
<!-- 以下是身份文本、锁定与保存模块,图片生成入口归属下方图库 -->
<AppForm :model="form" :disabled="disabled" class="identity-editor mt-5" @submit="save">
<fieldset :disabled="disabled" class="space-y-4">
<NFormItem class="block" path="description" label="身份描述" :label-props="{ for: 'identity-description' }"
><NInput
@@ -68,13 +75,33 @@ function save() {
class="flex items-start gap-2 text-xs leading-6"
>{{ module === 'character' ? '锁定演员身份' : '锁定身份' }}</NCheckbox
>
<!-- 以下是表单底部的 AI 生成与人工保存模块,状态通过按钮表达 -->
<div class="page-form-actions">
<NButton :disabled="disabled || !dirty" type="primary" attr-type="submit">{{
dirty ? '保存主体身份' : '已保存'
<NButton :disabled="disabled || !dirty" attr-type="submit">{{
dirty || !hasSavedText ? '保存主体身份' : '已保存'
}}</NButton>
<span v-if="dirty" class="text-xs text-muted">有未保存修改</span>
<span v-else class="text-xs text-muted">当前内容已保存到项目</span>
<div v-if="$slots.generate" class="identity-generation-action"><slot name="generate" /></div>
</div>
</fieldset>
</AppForm>
</template>
<style>
@reference "../../../styles/styles.css";
/* 标签文字与主体标题及步骤内容共用左边界,取消表单默认的额外标签缩进。 */
.identity-editor .n-form-item-label {
padding-inline: 0;
}
.identity-generation-action {
@apply inline-flex items-center max-w-full;
}
@media (max-width: 760px) {
.identity-editor .page-form-actions > .n-button,
.identity-generation-action,
.identity-generation-action > .n-button,
.identity-generation-action > .confirm-action,
.identity-generation-action > .confirm-action > .n-button {
@apply w-full;
}
}
</style>
@@ -2,21 +2,25 @@
import ConfirmAction from '../../workflows/ConfirmAction.vue'
import { NScrollbar, NAlert, NButton, NTag } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { AssetImage, StatusBadge } from '../../../components/ui'
import { referenceImageUrl } from '../../../lib/assets'
import { AppDialog, AssetImage, StatusBadge } from '../../../components/ui'
import { formatDate } from '../../../lib/format'
import { canBeAnchor, currentAnchor, identityViewLabels } from '../model'
import type { IdentityImage, IdentityValidationResult } from '../types'
import type { IdentityImage, IdentityImageOperation } from '../types'
/** 身份图库区分权威母版、primary 候选和辅助视图,保留后端原始状态。 */
const props = defineProps<{
/** 指定图片本次校验回执。 */
validationResult?: IdentityValidationResult | null
/** 正式身份图片列表。 */
images: IdentityImage[]
/** 当前主体名称。 */
subjectName: string
/** 主体类型。 */
module: string
/** 身份是否已经锁定。 */
identityLocked: boolean
/** 当前项目或主体是否禁止写入。 */
disabled: boolean
/** 当前确认或校验请求的固定图片目标。 */
pendingOperation?: IdentityImageOperation | null
}>()
/** 用户确认的图片操作。 */
const emit = defineEmits<{ anchor: [imageId: string]; validate: [imageId: string] }>()
@@ -32,16 +36,23 @@ const selected = computed(
)
/** character 的当前界面状态与输入绑定。 */
const character = computed(() => props.module === 'character')
/** 仅为正在确认的图片显示加载状态。 */
const confirmLoading = computed(
() => props.pendingOperation?.imageId === selected.value?.id && props.pendingOperation?.kind === 'confirm'
)
/** 仅为正在校验的图片显示加载状态。 */
const validateLoading = computed(
() => props.pendingOperation?.imageId === selected.value?.id && props.pendingOperation?.kind === 'validate'
)
/** canSelect 的当前界面状态与输入绑定。 */
const canSelect = computed(
() =>
!props.disabled &&
!props.pendingOperation &&
!!selected.value &&
canBeAnchor(selected.value) &&
(!selected.value.isAnchor || (character.value && !props.identityLocked))
)
/** imageUrl 的当前界面状态与输入绑定。 */
const imageUrl = computed(() => referenceImageUrl(selected.value?.imageUrl ?? ''))
/** 监听界面目标变化并重置关联确认状态。 */
watch(
() => selected.value?.id,
@@ -59,10 +70,14 @@ function chooseAnchor() {
</script>
<template>
<section class="mt-5 pt-5" aria-label="身份参考图库">
<div class="flex items-center justify-between gap-3">
<h3 class="text-sm font-medium">身份参考图 · {{ images.length }}</h3>
<NTag size="small" :bordered="false">{{ anchor ? '已选母版' : '尚无母版' }}</NTag>
<section class="identity-gallery mt-5 pt-5" aria-label="身份参考图库">
<!-- 以下是图库标题、母版状态与图片生成操作模块 -->
<div class="identity-gallery-toolbar">
<div class="identity-gallery-title">
<h3 class="text-sm font-medium">身份参考图 · {{ images.length }}</h3>
<NTag size="small" :bordered="false">{{ anchor ? '已选母版' : '尚无母版' }}</NTag>
</div>
<div v-if="$slots.actions" class="identity-gallery-actions"><slot name="actions" /></div>
</div>
<template v-if="selected">
<AssetImage
@@ -112,7 +127,8 @@ function chooseAnchor() {
<span class="image-history-meta"><StatusBadge :status="image.status" /></span>
</NButton>
</NScrollbar>
<div class="mt-3 flex flex-wrap items-center justify-between gap-3">
<!-- 以下是当前图片的状态、尺寸与创建时间模块,模型信息不参与展示 -->
<div class="identity-image-meta">
<div class="flex flex-wrap items-center gap-2">
<StatusBadge :status="selected.status" /><NTag size="small" :bordered="false">{{
selected.isAnchor
@@ -121,68 +137,101 @@ function chooseAnchor() {
? '母版候选'
: identityViewLabels[selected.viewType]
}}</NTag
><span class="text-xs text-muted">{{ selected.width || '—' }} × {{ selected.height || '—' }}</span>
><span v-if="selected.width && selected.height" class="text-xs text-muted"
>{{ selected.width }} × {{ selected.height }}</span
>
</div>
<a
v-if="imageUrl && selected.status === 'completed'"
:href="imageUrl"
target="_blank"
rel="noopener noreferrer"
class="text-button"
>打开原图</a
<time :datetime="selected.createdAt" class="identity-image-created"
>创建于 {{ formatDate(selected.createdAt) }}</time
>
</div>
<NAlert v-if="selected.error" role="alert" type="error" :show-icon="false" class="mt-3">{{
selected.error
}}</NAlert>
<div class="mt-3 flex flex-wrap items-center gap-3">
<!-- 以下是当前图片的确认母版与质量校验模块,原图通过上方图片预览查看 -->
<div class="identity-image-actions" role="group" aria-label="当前身份图片操作">
<NButton
v-if="!selected.isAnchor || (character && !identityLocked)"
:disabled="!canSelect"
:loading="confirmLoading"
:aria-label="character ? '确认选角并锁定' : '设为身份母版'"
:aria-busy="confirmLoading"
type="primary"
@click="confirming = true"
>{{ character ? '确认选角并锁定' : '设为身份母版' }}</NButton
><span class="text-[11px] text-muted"
>{{ selected.provider }} · {{ selected.model }} · {{ formatDate(selected.createdAt) }}</span
>
<ConfirmAction
:key="selected.id"
label="校验此身份图片"
:description="`将校验图片 ${selected.id},会调用视觉模型并可能产生费用,不会切换母版。`"
:disabled="disabled || selected.status !== 'completed' || !selected.imageUrl"
:loading="validateLoading"
acknowledgement
@confirm="emit('validate', selected.id)"
/>
</div>
<!-- 以下是指定身份图片质量校验模块 -->
<ConfirmAction
:key="selected.id"
label="校验此身份图片"
:description="`将校验图片 ${selected.id},会调用视觉模型并可能产生费用,不会切换母版。`"
:disabled="disabled || selected.status !== 'completed' || !selected.imageUrl"
acknowledgement
@confirm="emit('validate', selected.id)"
/>
<NAlert
v-if="validationResult?.imageId === selected.id"
:type="validationResult.passed ? 'success' : 'warning'"
class="mt-3"
>
<p>{{ validationResult.passed ? '本次校验通过' : '本次校验未通过' }}:{{ validationResult.summary }}</p>
<p v-for="(issue, index) in validationResult.issues" :key="index">
{{ issue.severity }} · {{ issue.type }}:{{ issue.description }}
</p>
</NAlert>
<p v-if="selected.viewType !== 'primary'" class="mt-2 text-xs text-muted">
辅助视图不能直接设为母版;它会继承当前身份母版,不适合用来更换演员。
</p>
<NAlert v-if="confirming" type="info" :show-icon="false" class="mt-3"
><p class="text-xs">
{{
character
? '确认选择这张图片作为正式演员?后端会在同一事务中切换身份母版并锁定 Identity,完成后首帧才具备稳定人物身份。'
: '确认切换身份母版?旧 primary 母版将停用并保留。身份锁定后,后续场景/道具形态生图会引用新母版。此操作不调用模型。'
}}
</p>
<div class="mt-3 flex gap-3">
<!-- 以下是确认母版弹窗模块,操作确认不会被图库滚动位置遮住 -->
<AppDialog
v-model:open="confirming"
:title="character ? '确认选角并锁定' : '确认切换身份母版'"
:description="
character
? `确认将这张图片作为 ${subjectName} 的角色母版并锁定身份?后续图片生成会使用这张母版。`
: `确认切换 ${subjectName} 的身份母版?旧母版会保留在图库中,后续形态图片生成会使用新母版。`
"
>
<div class="dialog-footer mt-6">
<NButton @click="confirming = false">取消</NButton>
<NButton :disabled="!canSelect" @click="chooseAnchor" type="primary">{{
character ? '确认演员选择' : '确认切换身份母版'
}}</NButton
><NButton @click="confirming = false" text size="small">取消</NButton>
</div></NAlert
>
}}</NButton>
</div>
</AppDialog>
</template>
<p v-else class="py-8 text-sm text-muted">尚无身份参考图。先保存身份提示词,再生成第一张母版。</p>
</section>
</template>
<style>
@reference "../../../styles/styles.css";
/* 保存留在编辑器,图片入口随图库标题排列;换行后继续沿用同一左右边界。 */
.identity-gallery-toolbar {
@apply flex flex-wrap items-center justify-between gap-x-4 gap-y-3;
}
.identity-gallery-title,
.identity-gallery-actions {
@apply flex flex-wrap min-w-0 items-center gap-2;
}
/* 身份历史缩略图等宽等高,保留顶部裁切;上方大图继续完整预览。 */
.identity-gallery .image-history-item .asset-image {
height: auto;
aspect-ratio: 1;
}
/* 状态、时间与确认校验分别排列,信息栏与按钮之间保留统一间距。 */
.identity-image-meta {
@apply mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2;
}
.identity-image-created {
@apply text-[11px] text-muted whitespace-nowrap;
}
.identity-image-actions {
@apply mt-4 flex flex-wrap min-w-0 items-center gap-3;
}
@media (max-width: 760px) {
.identity-gallery-actions {
@apply w-full;
}
.identity-gallery-actions > .n-button {
@apply w-full;
}
/* 手机操作逐行铺满正文宽度,避免长按钮挤在一起或贴住下一行。 */
.identity-image-actions > .n-button,
.identity-image-actions > .confirm-action,
.identity-image-actions > .confirm-action > .n-button {
@apply w-full;
}
}
</style>
+12
View File
@@ -3,6 +3,18 @@ import type { SubjectImageStatus, SubjectFormAsset } from '../subject-images/typ
/** 只有 primary 视图可以选为身份母版,其余视图是辅助参考。 */
export type IdentityViewType = 'primary' | 'front' | 'three-quarter' | 'full-body'
/** 图片请求的固定目标,用于在切换主体或图片后正确显示按钮进度。 */
export interface IdentityImageOperation {
/** 请求所属项目。 */
projectId: string
/** 请求所属主体。 */
subjectId: string
/** 本次确认或校验的正式图片。 */
imageId: string
/** 当前正在执行的图片操作。 */
kind: 'confirm' | 'validate'
}
/** 身份参考图公开 DTO;查询与变更均返回明确的 isAnchor 标记。 */
export interface IdentityImage {
id: string
@@ -5,12 +5,13 @@ import { useProjectGenerationRevision } from '../generation-config/context'
import { generationConfigApi } from '../generation-config/api'
import { subjectImagesApi } from '../subject-images/api'
import { hasRunningImages } from '../subject-images/model'
import { runOperation } from '../workflows/operations'
import { runOperation, type OperationNotice } from '../workflows/operations'
import { useProjectMutationGuard } from '../workflows/useProjectMutationGuard'
import { useProjectContext } from '../projects/context'
import { subjectIdentityApi } from './api'
import { canBeAnchor, getIdentitySession, groupIdentitySubjects, mergeCastingSubjects } from './model'
import type {
IdentityImageOperation,
IdentityValidationResult,
StableAnchorQualityInput,
StableAnchorQualityResult,
@@ -185,6 +186,46 @@ export function useSubjectIdentity() {
const validationResult = computed(() => validationResults.value[selectedId.value] ?? null)
/** 当前主体的质量闭环回执。 */
const qualityResult = computed(() => qualityResults.value[selectedId.value] ?? null)
/** 固定图片请求目标,切换主体后不把旧请求的加载状态附在新图片上。 */
const pendingImageOperation = ref<IdentityImageOperation | null>(null)
/**
* 执行已确认的图片操作,并让加载状态持续到响应核对及刷新完成。
* @param kind 图片操作类型
* @param imageId 提交时固定的正式图片编号
* @param label 包含主体名称的操作提示
* @param action 提交请求并核验结果
* @param feedback 按实际结果显示的临时消息
* @returns 请求及结果核验是否成功
*/
async function runImageOperation<T>(
kind: IdentityImageOperation['kind'],
imageId: string,
label: string,
action: () => Promise<T>,
feedback: OperationNotice | ((result: T) => OperationNotice)
) {
if (operation.value.pending || !subject.value) return false
pendingImageOperation.value = { kind, imageId, subjectId: subject.value.id, projectId: projectId.value }
try {
return await runOperation(projectId.value, label, action, feedback)
} finally {
pendingImageOperation.value = null
}
}
/**
* 图片确认后刷新目录、选角与准入状态,仅更新仍在原主体的详情。
* @param project 请求提交时的项目编号
* @param subjectId 请求提交时的主体编号
*/
async function refreshImageConfirmation(project: string, subjectId: string) {
if (projectId.value !== project) return
await Promise.all([
catalog.refresh(),
castingQuery.refresh(),
projectContext.refreshStageReadiness(),
...(selectedId.value === subjectId ? [detail.refresh()] : [])
])
}
/**
* 校验当前主体的正式图片,费用确认由图库负责。
* @param imageId 指定正式身份图片 ID
@@ -193,13 +234,24 @@ export function useSubjectIdentity() {
const image = images.value.find(item => item.id === imageId)
if (detailBlocked.value || !subject.value || image?.status !== 'completed' || !image.imageUrl) return
const id = subject.value.id
const project = projectId.value
const name = subject.value.name
delete validationResults.value[id]
await runOperation(project, '校验身份参考图质量', async () => {
const result = await subjectIdentityApi.validateImage(id, imageId)
if (result.subjectId !== id || result.imageId !== imageId) throw new Error('身份校验回执与提交目标不匹配')
validationResults.value[id] = result
})
await runImageOperation(
'validate',
imageId,
`校验 ${name} 身份图片`,
async () => {
const result = await subjectIdentityApi.validateImage(id, imageId)
if (result.subjectId !== id || result.imageId !== imageId)
throw new Error('身份校验回执与提交目标不匹配')
validationResults.value[id] = result
return result
},
result => ({
type: result.passed ? 'success' : 'warning',
content: `${name} 的身份图片校验${result.passed ? '通过' : '未通过'}:${result.summary}`
})
)
}
/**
* 为场景或道具执行有限预算质量闭环,仅按真实回执确认锁定。
@@ -218,32 +270,42 @@ export function useSubjectIdentity() {
const id = subject.value.id
const identityId = identity.value.id
const project = projectId.value
const name = subject.value.name
delete qualityResults.value[id]
await runOperation(project, '生成稳定身份母版并校验质量', async () => {
const result = await subjectIdentityApi.generateStableAnchorQuality(id, input)
if (
result.passed &&
(!result.confirmed ||
result.confirmed.subjectId !== id ||
result.confirmed.identityId !== identityId ||
!result.confirmed.isLocked ||
!result.confirmed.anchor.isAnchor ||
result.confirmed.anchor.id !== result.imageId)
)
throw new Error('质量生成的母版与锁定回执未确认,请刷新核对')
qualityResults.value[id] = result
})
if (projectId.value === project) {
await Promise.all([
catalog.refresh(),
castingQuery.refresh(),
projectContext.refreshStageReadiness(),
...(selectedId.value === id ? [detail.refresh()] : [])
])
}
await runOperation(
project,
`生成 ${name} 稳定身份母版并校验质量`,
async () => {
const result = await subjectIdentityApi.generateStableAnchorQuality(id, input)
if (
result.passed &&
(!result.confirmed ||
result.confirmed.subjectId !== id ||
result.confirmed.identityId !== identityId ||
!result.confirmed.isLocked ||
!result.confirmed.anchor.isAnchor ||
result.confirmed.anchor.id !== result.imageId)
)
throw new Error('质量生成的母版与锁定回执未确认,请刷新核对')
qualityResults.value[id] = result
await refreshImageConfirmation(project, id)
return result
},
result => ({
type: result.passed ? 'success' : 'warning',
content: result.passed
? `${name} 的身份母版校验通过,已确认并锁定。`
: `${name} 的身份母版校验未通过,候选仍保留在图库。${result.stopReason || ''}`
})
)
}
/** 长请求跨主体切换后只更新原项目的操作回执,不用旧响应覆盖新主体。 */
/**
* 保存或生成身份后刷新项目准入状态,跨主体响应不覆盖新主体详情。
* @param label 操作反馈名称
* @param action 对指定主体执行的身份写入请求
* @returns 身份写入与当前项目状态刷新完成的异步结果
*/
async function writeIdentity(label: string, action: (id: string) => Promise<SubjectIdentity>) {
if (detailBlocked.value || !subject.value) return
const id = subject.value.id
@@ -258,7 +320,13 @@ export function useSubjectIdentity() {
dirty.value = false
}
})
if (ok) await Promise.all([detail.refresh(), castingQuery.refresh()])
if (ok && projectId.value === project) {
await Promise.all([
castingQuery.refresh(),
projectContext.refreshStageReadiness(),
...(selectedId.value === id ? [detail.refresh()] : [])
])
}
}
/** 人工保存可修改已锁定身份;锁定只阻止自动重生成。 */
@@ -363,7 +431,10 @@ export function useSubjectIdentity() {
await Promise.all([detail.refresh(), castingQuery.refresh()])
}
/** 生图不修改文字锁定;即使有自定义 Prompt,也需已有身份 Prompt 与项目风格。 */
/**
* 生图不修改文字锁定;即使有自定义提示词,也需已有身份提示词与项目风格。
* @param input 已确认的视图、模型与参考图片参数
*/
async function generateImage(input: GenerateIdentityImageInput) {
if (!canGenerateImage.value || !subject.value || !identity.value) return
if (
@@ -375,56 +446,86 @@ export function useSubjectIdentity() {
return
const id = subject.value.id
const identityId = identity.value.id
const ok = await runOperation(projectId.value, `提交 ${subject.value.name} 身份参考图生成`, async () => {
const image = await subjectIdentityApi.generateImage(id, input)
if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) {
throw new Error(image?.error || '身份参考图任务未成功创建,请刷新后重试。')
}
})
if (ok) {
await detail.refresh()
operation.value.notice = `${subject.value.name} 身份参考图已提交生成,可稍后刷新查看结果。`
}
const project = projectId.value
const name = subject.value.name
await runOperation(
project,
`提交 ${name} 身份参考图生成`,
async () => {
const image = await subjectIdentityApi.generateImage(id, input)
if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) {
throw new Error(image?.error || '身份参考图任务未成功创建,请刷新后重试。')
}
if (projectId.value === project && selectedId.value === id) await detail.refresh()
},
{ type: 'info', content: `${name} 的身份参考图已提交生成,完成后会显示结果。` }
)
}
/** 单角色候选图固定为独立 primary,不复用旧 Anchor,生成成功后仍需人工确认选角。 */
/**
* 单角色候选图固定独立生成,不复用旧母版,生成成功后仍需人工确认选角。
* @param input 已确认的候选图模型与生成参数
*/
async function generateCastingCandidate(input: GenerateCastingCandidateInput) {
if (!canGenerateCandidate.value || !subject.value || !identity.value) return
const id = subject.value.id
const identityId = identity.value.id
const ok = await runOperation(projectId.value, `提交 ${subject.value.name} 选角候选生成`, async () => {
const image = await subjectIdentityApi.generateCastingCandidate(id, input)
if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) {
throw new Error(image?.error || '选角候选任务未成功创建,请刷新后重试。')
}
})
if (ok) {
await Promise.all([detail.refresh(), castingQuery.refresh(), catalog.refresh()])
operation.value.notice = `${subject.value.name} 选角候选已提交生成,可稍后刷新查看结果。`
}
const project = projectId.value
const name = subject.value.name
await runOperation(
project,
`提交 ${name} 角色候选图生成`,
async () => {
const image = await subjectIdentityApi.generateCastingCandidate(id, input)
if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) {
throw new Error(image?.error || '选角候选任务未成功创建,请刷新后重试。')
}
if (projectId.value === project)
await Promise.all([
castingQuery.refresh(),
catalog.refresh(),
...(selectedId.value === id ? [detail.refresh()] : [])
])
},
{ type: 'info', content: `${name} 的角色候选图已提交生成,完成后会显示结果。` }
)
}
/** 候选切换母版只允许成功的 primary 图,不能将辅助视角直接升级为母版。 */
/**
* 候选切换母版只允许成功的 primary 图,不能将辅助视角直接升级为母版。
* @param imageId 要切换的正式身份图片编号
*/
async function setAnchor(imageId: string) {
const image = images.value.find(item => item.id === imageId)
if (detailBlocked.value || !subject.value || !image || !canBeAnchor(image) || image.isAnchor) return
const id = subject.value.id
const identityId = image.identityId
await runOperation(projectId.value, '切换主体身份母版', async () => {
const result = await subjectIdentityApi.setAnchor(id, imageId)
if (
!result ||
result.id !== imageId ||
result.identityId !== identityId ||
!result.isAnchor ||
!canBeAnchor(result)
)
throw new Error('身份母版切换结果未确认,请刷新后核对。')
})
await detail.refresh()
const project = projectId.value
const name = subject.value.name
await runImageOperation(
'confirm',
imageId,
`切换 ${name} 身份母版`,
async () => {
const result = await subjectIdentityApi.setAnchor(id, imageId)
if (
!result ||
result.id !== imageId ||
result.identityId !== identityId ||
!result.isAnchor ||
!canBeAnchor(result)
)
throw new Error('身份母版切换结果未确认,请刷新后核对。')
await refreshImageConfirmation(project, id)
},
{ type: 'success', content: `${name} 的身份母版已切换。` }
)
}
/** Scene / Prop 人工确认母版时原子完成 Anchor 切换与 Identity 锁定。 */
/**
* 场景或道具人工确认母版时原子完成母版切换与身份锁定。
* @param imageId 要确认的正式身份图片编号
*/
async function confirmStableAnchor(imageId: string) {
const image = images.value.find(item => item.id === imageId)
if (
@@ -437,24 +538,35 @@ export function useSubjectIdentity() {
return
const subjectId = subject.value.id
const identityId = identity.value.id
await runOperation(projectId.value, `确认 ${subject.value.name} 身份母版`, async () => {
const result = await subjectIdentityApi.confirmStableAnchor(subjectId, imageId)
if (
!result ||
result.identityId !== identityId ||
result.subjectId !== subjectId ||
!result.isLocked ||
result.anchor.id !== imageId ||
!result.anchor.isAnchor ||
result.anchor.identityId !== identityId ||
!canBeAnchor(result.anchor)
)
throw new Error('身份母版确认结果未保存,请刷新后核对。')
})
await Promise.all([detail.refresh(), catalog.refresh()])
const project = projectId.value
const name = subject.value.name
await runImageOperation(
'confirm',
imageId,
`确认 ${name} 身份母版`,
async () => {
const result = await subjectIdentityApi.confirmStableAnchor(subjectId, imageId)
if (
!result ||
result.identityId !== identityId ||
result.subjectId !== subjectId ||
!result.isLocked ||
result.anchor.id !== imageId ||
!result.anchor.isAnchor ||
result.anchor.identityId !== identityId ||
!canBeAnchor(result.anchor)
)
throw new Error('身份母版确认结果未保存,请刷新后核对。')
await refreshImageConfirmation(project, subjectId)
},
{ type: 'success', content: `${name} 的身份母版已确认并锁定。` }
)
}
/** Character 确认选角必须原子切换 Anchor 并锁定 Identity。 */
/**
* 角色确认选角必须原子切换身份母版并锁定身份。
* @param imageId 要确认的正式角色图片编号
*/
async function confirmCasting(imageId: string) {
const image = images.value.find(item => item.id === imageId)
if (
@@ -468,21 +580,29 @@ export function useSubjectIdentity() {
return
const subjectId = subject.value.id
const identityId = identity.value.id
await runOperation(projectId.value, `确认 ${subject.value.name} 角色选角`, async () => {
const result = await subjectIdentityApi.confirmCasting(subjectId, imageId)
if (
!result ||
result.identityId !== identityId ||
result.subjectId !== subjectId ||
!result.isLocked ||
result.anchor.id !== imageId ||
!result.anchor.isAnchor ||
result.anchor.identityId !== identityId ||
!canBeAnchor(result.anchor)
)
throw new Error('角色选角确认结果未保存,请刷新后核对。')
})
await Promise.all([detail.refresh(), castingQuery.refresh(), projectContext.refreshStageReadiness()])
const project = projectId.value
const name = subject.value.name
await runImageOperation(
'confirm',
imageId,
`确认 ${name} 角色选角`,
async () => {
const result = await subjectIdentityApi.confirmCasting(subjectId, imageId)
if (
!result ||
result.identityId !== identityId ||
result.subjectId !== subjectId ||
!result.isLocked ||
result.anchor.id !== imageId ||
!result.anchor.isAnchor ||
result.anchor.identityId !== identityId ||
!canBeAnchor(result.anchor)
)
throw new Error('角色选角确认结果未保存,请刷新后核对。')
await refreshImageConfirmation(project, subjectId)
},
{ type: 'success', content: `${name} 的角色选角已确认,身份已锁定。` }
)
}
return {
@@ -529,6 +649,7 @@ export function useSubjectIdentity() {
confirmStableAnchor,
confirmCasting,
validateImage,
pendingImageOperation,
generateStableAnchorQuality,
validationResult,
qualityResult
+25 -5
View File
@@ -5,14 +5,24 @@ import { AppDialog } from '../../components/ui'
/** 耗费模型额度或覆盖结果的动作必须经过明确确认。 */
const props = defineProps<{
/** 操作名称。 */
label: string
/** 确认前的操作说明。 */
description: string
/** 前置条件未满足时禁止操作。 */
disabled?: boolean
/** 当前操作请求是否仍在执行。 */
loading?: boolean
/** 是否需要确认后台任务停止。 */
acknowledgement?: boolean
/** 是否使用主要操作样式。 */
primary?: boolean
}>()
/** 用户明确确认操作后通知调用方。 */
const emit = defineEmits<{ confirm: [] }>()
/** 当前确认弹窗的可见状态。 */
const open = ref(false)
/** 用户是否确认任务与费用。 */
const acknowledged = ref(false)
/** 取消后重新打开,或确认目标改变,都必须重新确认任务与费用。 */
@@ -22,7 +32,7 @@ watch([open, () => props.label, () => props.description], () => {
/** 发出事件后关闭弹窗,操作状态由项目级锁负责。 */
function confirm() {
if (props.disabled || (props.acknowledgement && !acknowledged.value)) return
if (props.disabled || props.loading || (props.acknowledgement && !acknowledged.value)) return
emit('confirm')
open.value = false
acknowledged.value = false
@@ -34,9 +44,15 @@ function confirm() {
<!-- 稳定的根元素承接调用方间距;AppDialog 含多个根节点,不能替按钮接收 class。 -->
<AppDialog v-model:open="open" :title="label" :description="description">
<template #trigger
><NButton :type="primary ? 'primary' : 'default'" :disabled="disabled" @click="open = true">{{
label
}}</NButton></template
><NButton
:type="primary ? 'primary' : 'default'"
:disabled="disabled || loading"
:loading="loading"
:aria-label="label"
:aria-busy="!!loading"
@click="open = true"
>{{ label }}</NButton
></template
>
<NCheckbox
v-model:checked="acknowledged"
@@ -46,7 +62,11 @@ function confirm() {
>
<div class="dialog-footer mt-6">
<NButton @click="open = false">取消</NButton
><NButton :disabled="disabled || (acknowledgement && !acknowledged)" @click="confirm" type="primary">
><NButton
:disabled="disabled || loading || (acknowledgement && !acknowledged)"
@click="confirm"
type="primary"
>
确认{{ label }}</NButton
>
</div>
+35 -5
View File
@@ -4,13 +4,28 @@ import { hasActiveWorkflowExecution } from './execution'
/** 当前浏览器会话中的操作状态;切换路由不会丢失长请求。 */
export interface Operation {
/** 项目请求或后台任务是否仍在执行。 */
pending: boolean
/** 当前操作名称。 */
label: string
/** 请求失败原因。 */
error: string
/** 已确认的操作结果提示。 */
notice: string
/** 结果的实际语义;未指定时由工作区使用默认反馈。 */
noticeType: OperationNotice['type'] | null
/** 可执行的失败恢复入口。 */
recovery: OperationRecovery | null
}
/** 操作结果的临时消息,不将 HTTP 成功直接当作业务校验通过。 */
export interface OperationNotice {
/** 用户可理解的结果描述。 */
content: string
/** 成功、任务提交或业务校验未通过。 */
type: 'success' | 'info' | 'warning'
}
/** 失败后的可执行恢复位置;仅保留当前浏览器会话内的真实上下文。 */
export type OperationRecovery = {
target: 'keyframe'
@@ -42,19 +57,34 @@ export function getOperation(projectId: string): Operation {
label: '',
error: '',
notice: '',
noticeType: null,
recovery: null
}
return operations[projectId]
}
/** 只提交一次;断网不自动重试,后台是否已执行由刷新后的 checkpoint 确认。 */
export async function runOperation(projectId: string, label: string, action: () => Promise<unknown>) {
/**
* 只提交一次,并按真实业务回执生成反馈;断网不自动重试。
* @param projectId 当前项目编号
* @param label 操作名称
* @param action 提交请求并核对响应的操作
* @param feedback 固定反馈或从真实响应中取得的反馈
* @returns 请求及响应核对是否成功,不代表业务校验通过
*/
export async function runOperation<T>(
projectId: string,
label: string,
action: () => Promise<T>,
feedback?: OperationNotice | ((result: T) => OperationNotice)
) {
const operation = getOperation(projectId)
if (operation.pending) return false
Object.assign(operation, { pending: true, label, error: '', notice: '', recovery: null })
Object.assign(operation, { pending: true, label, error: '', notice: '', noticeType: null, recovery: null })
try {
await action()
operation.notice = '请求已返回,正在重新读取后端状态;最终结果以下方记录为准。'
const result = await action()
const notice = typeof feedback === 'function' ? feedback(result) : feedback
operation.noticeType = notice?.type ?? null
operation.notice = notice?.content ?? '请求已返回,正在重新读取后端状态;最终结果以下方记录为准。'
return true
} catch (error) {
operation.error = errorMessage(error)
+5
View File
@@ -419,6 +419,11 @@ body {
max-width: 100%;
min-width: 0;
}
/* 图片历史只负责左右滚动,上下滚轮继续滚动外层详情,避免停在缩略图时被拦截。 */
.image-history > .n-scrollbar-container {
overflow-y: hidden;
overscroll-behavior-y: auto;
}
.image-history-heading {
display: flex;
flex-wrap: wrap;
+66 -2
View File
@@ -106,7 +106,66 @@ async function openProject(initialPath: string) {
}
describe('剧本完成前的下游访问限制', () => {
it.each(['breakdown', 'visual-style'] as const)(
it('身份请求加载、成功和失败均使用临时消息,切换主体不遗留横幅', async () => {
vi.useFakeTimers()
const id = 'identity-message-test'
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project(id, 'completed'))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
const operation = getOperation(id)
Object.assign(operation, { pending: false, label: 'AI 生成主体身份', error: '', notice: '旧成功提示' })
const { router } = await openProject(`/projects/${id}/subject-identity`)
expect(wrapper!.text()).not.toContain('旧成功提示')
expect(document.querySelector('.n-message')).toBeNull()
Object.assign(operation, { pending: true, notice: '' })
await flushPromises()
expect(wrapper!.find('.project-notices').exists()).toBe(false)
expect(document.querySelector('.n-message--loading-type')!.textContent).toContain('AI 生成主体身份,请稍候')
await router.replace({ query: { subjectId: 'second-subject' } })
Object.assign(operation, {
pending: false,
notice: '请求已返回,正在重新读取后端状态;最终结果以下方记录为准。'
})
await flushPromises()
expect(document.querySelector('.n-message--success-type')!.textContent).toContain('身份文本已生成并保存')
expect(wrapper!.find('.project-notices').exists()).toBe(false)
expect(operation.notice).toBe('')
await vi.advanceTimersByTimeAsync(4000)
await flushPromises()
expect(document.querySelector('.n-message')).toBeNull()
await router.replace({ query: { subjectId: 'third-subject' } })
await flushPromises()
expect(document.querySelector('.n-message')).toBeNull()
expect(wrapper!.find('.project-notices').exists()).toBe(false)
operation.error = '模型不可用,请稍后重试'
await flushPromises()
expect(wrapper!.find('.operation-guide').exists()).toBe(false)
expect(document.querySelector('.n-message--error-type')!.textContent).toContain('模型不可用')
Object.assign(operation, { error: '', notice: '', pending: false })
})
it('图片校验未通过显示警告而非成功,关闭消息后不遗留校验结果块', async () => {
vi.useFakeTimers()
const id = 'identity-warning-test'
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project(id, 'completed'))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
await openProject(`/projects/${id}/subject-identity`)
const operation = getOperation(id)
Object.assign(operation, {
label: '校验林夏身份图片',
noticeType: 'warning',
notice: '林夏的身份图片校验未通过:面部模糊'
})
await flushPromises()
expect(document.querySelector('.n-message--warning-type')!.textContent).toContain('校验未通过:面部模糊')
expect(document.querySelector('.n-message--success-type')).toBeNull()
expect(wrapper!.find('.project-notices').exists()).toBe(false)
expect(operation).toMatchObject({ notice: '', noticeType: null })
await vi.advanceTimersByTimeAsync(9000)
await flushPromises()
expect(document.querySelector('.n-message')).toBeNull()
})
it.each(['breakdown', 'visual-style', 'subject-identity'] as const)(
'%s 首次读取显示骨架,刷新保留已有内容,切换项目完成后仍遵守访问限制',
async section => {
/** 延迟真实查询入口,覆盖初次读取、后台刷新和跨项目读取三个阶段。 */
@@ -118,7 +177,12 @@ describe('剧本完成前的下游访问限制', () => {
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, id === 'skeleton-first'))
const { router, mounted } = await openProject(`/projects/skeleton-first/${section}`)
const skeleton = section === 'breakdown' ? '.breakdown-skeleton' : '.visual-style-skeleton'
const skeleton =
section === 'subject-identity'
? '.subject-identity-skeleton'
: section === 'breakdown'
? '.breakdown-skeleton'
: '.visual-style-skeleton'
expect(wrapper!.get(skeleton).attributes('aria-busy')).toBe('true')
expect(wrapper!.find('.workspace-loading').exists()).toBe(false)
expect(wrapper!.get('.project-title').text()).toBe('')
@@ -0,0 +1,43 @@
import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import IdentityEditor from '@/features/subject-identity/components/IdentityEditor.vue'
import { identityFixture } from '@/features/subject-identity/testing/fixtures'
describe('主体身份保存状态', () => {
it.each([
{ name: '未创建身份', identity: null },
{ name: '空身份记录', identity: identityFixture({ description: null, generationPrompt: '' }) },
{ name: '仅空白字符', identity: identityFixture({ description: ' ', generationPrompt: '\n' }) }
])('$name 不显示已保存,输入后可保存,撤销输入后禁止空提交', async ({ identity }) => {
const wrapper = mount(IdentityEditor, { props: { identity, disabled: false, module: 'prop' } })
try {
const actions = wrapper.get('.page-form-actions')
expect(actions.text()).toBe('保存主体身份')
expect(actions.text()).not.toContain('已保存')
expect(actions.get('button').attributes('disabled')).toBeDefined()
await wrapper.get('#identity-description').setValue('竹编鱼篓,固定圆筒结构')
expect(actions.text()).toBe('保存主体身份')
expect(actions.get('button').attributes('disabled')).toBeUndefined()
await wrapper.get('#identity-description').setValue(identity?.description ?? '')
expect(actions.text()).toBe('保存主体身份')
expect(actions.text()).not.toContain('已保存')
} finally {
wrapper.unmount()
}
})
it('后端已有身份文本才显示已保存,修改后的草稿显示保存操作', async () => {
const wrapper = mount(IdentityEditor, {
props: { identity: identityFixture(), disabled: false, module: 'character' }
})
try {
expect(wrapper.get('.page-form-actions').text()).toBe('已保存')
expect(wrapper.get('.page-form-actions button').text()).toBe('已保存')
await wrapper.get('#identity-prompt').setValue('修改中的核心提示词')
expect(wrapper.get('.page-form-actions').text()).toBe('保存主体身份')
expect(wrapper.get('.page-form-actions button').text()).toBe('保存主体身份')
} finally {
wrapper.unmount()
}
})
})
@@ -1,8 +1,8 @@
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NImage, NScrollbar } from 'naive-ui'
import { AssetImage } from '@/components/ui'
import { NButton, NImage, NScrollbar } from 'naive-ui'
import { AppDialog, AssetImage } from '@/components/ui'
import IdentityImageDialog from '@/features/subject-identity/components/IdentityImageDialog.vue'
import IdentityGallery from '@/features/subject-identity/components/IdentityGallery.vue'
import CastingCandidateDialog from '@/features/subject-identity/components/CastingCandidateDialog.vue'
@@ -71,6 +71,8 @@ describe('身份图与母版契约', () => {
expect(images).toHaveLength(3)
expect(images.map(image => image.props('objectFit'))).toEqual(['contain', 'cover', 'cover'])
expect(images.map(image => image.props('previewDisabled'))).toEqual([false, true, true])
expect(wrapper.find('a[target="_blank"]').exists()).toBe(false)
expect(wrapper.text()).not.toContain('打开原图')
await wrapper.get('[aria-label="查看身份图片 front"] img').trigger('click')
await flushPromises()
expect(wrapper.get('[aria-label="查看身份图片 front"]').attributes('aria-pressed')).toBe('true')
@@ -86,19 +88,21 @@ describe('身份图与母版契约', () => {
expect(wrapper.emitted('anchor')).toBeUndefined()
})
it('身份图库使用精简资产,不展示已移除的提示词和启停状态', () => {
it('身份图库使用精简资产,不展示已移除的提示词、模型信息和启停状态', () => {
wrapper = mount(IdentityGallery, {
props: {
subjectName: '林夏',
module: 'character',
identityLocked: true,
disabled: false,
images: [identityImageFixture()]
images: [identityImageFixture({ provider: 'qwen-image', model: 'qwen-image-3.0-pro' })]
}
})
expect(wrapper.text()).toContain('当前身份母版')
expect(wrapper.text()).not.toContain('本次实际提示词')
expect(wrapper.text()).not.toContain('停用')
expect(wrapper.text()).not.toContain('qwen-image')
expect(wrapper.text()).toContain('创建于')
})
it('全部历史记录显示在预览下方,候选、辅助、失败和进行中图片均可切换查看', async () => {
@@ -200,9 +204,10 @@ describe('身份图与母版契约', () => {
})
button('确认选角并锁定').click()
await flushPromises()
expect(document.querySelector('[role="dialog"][aria-label="确认选角并锁定"]')).not.toBeNull()
expect(button('确认演员选择').disabled).toBe(false)
await wrapper.get('[aria-label="查看身份图片 candidate-b"]').trigger('click')
expect(wrapper.text()).not.toContain('确认选择这张图片作为正式演员')
expect(wrapper.findComponent(AppDialog).props('open')).toBe(false)
expect(wrapper.emitted('anchor')).toBeUndefined()
button('确认选角并锁定').click()
await flushPromises()
@@ -373,11 +378,42 @@ describe('身份图与母版契约', () => {
})
button('确认选角并锁定').click()
await flushPromises()
expect(document.body.textContent).toContain('同一事务中切换身份母版并锁定 Identity')
expect(document.body.textContent).toContain('作为 林夏 的角色母版并锁定身份')
button('确认演员选择').click()
expect(wrapper.emitted('anchor')).toEqual([['identity-image-1']])
})
it('图片操作加载只对应提交目标,不能重复确认,切换图片不会错误显示加载', async () => {
wrapper = mount(IdentityGallery, {
attachTo: document.body,
props: {
subjectName: '林夏',
module: 'character',
identityLocked: false,
disabled: false,
images: ['first', 'second'].map(id => identityImageFixture({ id, isAnchor: false }))
}
})
await wrapper.setProps({
pendingOperation: { projectId: 'project-1', subjectId: 'subject-1', imageId: 'first', kind: 'confirm' }
})
const confirm = wrapper.findAllComponents(NButton).find(item => item.text() === '确认选角并锁定')!
expect(confirm.props('loading')).toBe(true)
expect(button('确认选角并锁定').disabled).toBe(true)
button('确认选角并锁定').click()
expect(wrapper.emitted('anchor')).toBeUndefined()
await wrapper.get('[aria-label="查看身份图片 second"]').trigger('click')
expect(confirm.props('loading')).toBe(false)
await wrapper.setProps({
pendingOperation: { projectId: 'project-1', subjectId: 'subject-1', imageId: 'second', kind: 'validate' }
})
const validate = wrapper.findAllComponents(NButton).find(item => item.text() === '校验此身份图片')!
expect(validate.props('loading')).toBe(true)
expect(button('校验此身份图片').disabled).toBe(true)
await wrapper.setProps({ pendingOperation: null })
expect(validate.props('loading')).toBe(false)
})
it('选角候选发送当前图片 Provider 与动态参数,不携带旧宽高字段', async () => {
wrapper = mount(CastingCandidateDialog, {
attachTo: document.body,
@@ -422,7 +458,7 @@ describe('身份图与母版契约', () => {
expect(document.body.textContent).toContain('不会复用当前身份母版')
document.querySelector<HTMLInputElement>('#casting-candidate-cost')!.click()
await flushPromises()
button('确认生成候选').click()
button('AI 生成角色候选图').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([
[{ provider: 'qwen-image', generationOptions: { size: '1536*2688' } }]
@@ -1,6 +1,18 @@
import { describe, expect, it, vi } from 'vitest'
import { getOperation, runOperation } from '@/features/workflows/operations'
/**
* 根据真实校验值决定消息,不能只依据 Promise 成功。
* @param result 后端业务校验结果
* @returns 与通过状态相符的临时反馈
*/
function validationFeedback(result: { passed: boolean }) {
return {
type: result.passed ? ('success' as const) : ('warning' as const),
content: result.passed ? '身份图片校验通过' : '身份图片校验未通过'
}
}
describe('项目级长请求互斥', () => {
it('同一项目不同时执行两个 graph,错误不伪装成功', async () => {
let fail!: (reason: Error) => void
@@ -17,4 +29,36 @@ describe('项目级长请求互斥', () => {
expect(await first).toBe(false)
expect(getOperation('operation-test')).toMatchObject({ pending: false, error: '连接中断', notice: '' })
})
it('HTTP 成功但业务校验未通过时保留警告语义,再次通过时更新结果', async () => {
const projectId = 'operation-validation-test'
expect(await runOperation(projectId, '校验', async () => ({ passed: false }), validationFeedback)).toBe(true)
expect(getOperation(projectId)).toMatchObject({
noticeType: 'warning',
notice: '身份图片校验未通过',
pending: false
})
expect(await runOperation(projectId, '校验', async () => ({ passed: true }), validationFeedback)).toBe(true)
expect(getOperation(projectId)).toMatchObject({ noticeType: 'success', notice: '身份图片校验通过' })
expect(
await runOperation(
projectId,
'校验',
async () => {
throw new Error('服务不可用')
},
validationFeedback
)
).toBe(false)
expect(getOperation(projectId)).toMatchObject({ noticeType: null, notice: '', error: '服务不可用' })
})
it('异步任务提交只提示已提交,不提前提示生成完成', async () => {
const projectId = 'operation-submission-test'
await runOperation(projectId, '提交图片生成', async () => ({ status: 'pending' }), {
type: 'info',
content: '任务已提交生成'
})
expect(getOperation(projectId)).toMatchObject({ noticeType: 'info', notice: '任务已提交生成' })
})
})
+303 -5
View File
@@ -28,6 +28,9 @@ import { getImageSession } from '@/features/subject-images/model'
import VisualStylePage from '@/features/visual-style/VisualStylePage.vue'
import { visualStyleApi } from '@/features/visual-style/api'
import SubjectIdentityPage from '@/features/subject-identity/SubjectIdentityPage.vue'
import IdentityGallery from '@/features/subject-identity/components/IdentityGallery.vue'
import { subjectIdentityApi } from '@/features/subject-identity/api'
import { subjectImagesApi } from '@/features/subject-images/api'
import { styleFixture, styleImageFixture } from '@/features/visual-style/testing/fixtures'
import { identityFixture, identityImageFixture } from '@/features/subject-identity/testing/fixtures'
import { getIdentitySession } from '@/features/subject-identity/model'
@@ -213,7 +216,7 @@ afterEach(() => {
Object.assign(getStoryboardSession(fixture.id), { receipt: null, prompts: {}, regeneratedEpisodes: {} })
getImageSession(fixture.id).receipt = null
getImageSession(fixture.id).promptReceipt = null
Object.assign(getOperation(fixture.id), { pending: false, label: '', error: '', notice: '' })
Object.assign(getOperation(fixture.id), { pending: false, label: '', error: '', notice: '', noticeType: null })
})
describe('内容级滚动下的生产反馈', () => {
@@ -304,6 +307,217 @@ describe('内容级滚动下的生产反馈', () => {
})
describe('视觉风格与主体身份工作区', () => {
it('当前主体已确认但其它角色未完成时,隐藏形态入口;保存后按新阶段状态开放', async () => {
/** 当前主体已锁定,其它角色仍未确认,用真实项目准入规则约束页面入口。 */
const saved = identityFixture({ isLocked: true })
vi.spyOn(subjectIdentityApi, 'get').mockResolvedValue(saved)
vi.spyOn(subjectIdentityApi, 'save').mockImplementation(async (_id, input) => ({ ...saved, ...input }))
vi.spyOn(subjectIdentityApi, 'listImages').mockResolvedValue([identityImageFixture()])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [formFixture()] : styleFixture())
)
)
const provided = await mountAssets('identity')
provided.data.value!.stageReadiness.identity = { ready: false, reason: '还有角色身份需要确认' }
await flushPromises()
expect(wrapper!.get('.identity-next-action').text()).toContain('还有角色身份需要确认')
expect(wrapper!.get('.identity-next-action').find('button').exists()).toBe(false)
expect(wrapper!.get('.identity-subject-forms').text()).not.toContain('查看此主体形态图片')
expect(wrapper!.find('a[href*="/subject-images"]').exists()).toBe(false)
vi.mocked(provided.refreshStageReadiness).mockImplementation(async () => {
provided.data.value!.stageReadiness.identity = { ready: true, reason: null }
})
await wrapper!.get('#identity-description').setValue('保存后仍保留已确认母版')
button('保存主体身份').click()
await flushPromises()
expect(provided.refreshStageReadiness).toHaveBeenCalledOnce()
expect(button('查看形态图片').disabled).toBe(false)
expect(wrapper!.get('.identity-detail a[href*="/subject-images"]').attributes('href')).toContain(
'subjectRef=@CH0001'
)
})
it('生成进度与失败提示位于两栏上方,切换主体后不会保留其它主体的状态,完成后隐藏', async () => {
/** 两个主体分别处于生成中与失败状态,所有查询均使用隔离的测试响应。 */
const first = formFixture()
const second = { ...formFixture(), id: 'second-form', subjectId: 'second-subject', images: [] }
second.subject = { ...second.subject, id: second.subjectId, name: '第二个主体', ref: '@CH0002' }
vi.spyOn(subjectIdentityApi, 'get').mockImplementation(async id =>
identityFixture({ id: `identity-${id}`, subjectId: id })
)
vi.spyOn(subjectIdentityApi, 'listImages').mockImplementation(async id => [
identityImageFixture({
identityId: `identity-${id}`,
status: id === first.subjectId ? 'generating' : 'failed',
isAnchor: false,
imageUrl: null,
error: id === first.subjectId ? null : '模型暂时不可用'
})
])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [first, second] : styleFixture())
)
)
await mountAssets('identity')
const feedback = wrapper!.get('.identity-generation-feedback')
const workspace = wrapper!.get('.identity-workspace')
expect(feedback.element.closest('.identity-workspace-region')).toBe(
wrapper!.get('.identity-workspace-region').element
)
expect(feedback.element.closest('.identity-detail')).toBeNull()
expect(feedback.element.compareDocumentPosition(workspace.element) & 4).toBe(4)
expect(feedback.text()).toContain('林知夏 的身份图片正在生成')
await wrapper!
.findAll('.identity-subject-item')
.find(item => item.text().includes('第二个主体'))!
.trigger('click')
await flushPromises()
expect(wrapper!.get('.identity-generation-feedback').text()).toContain('模型暂时不可用')
expect(wrapper!.get('.identity-generation-feedback').text()).not.toContain('林知夏 的身份图片正在生成')
expect(wrapper!.findAll('.identity-generation-feedback')).toHaveLength(1)
vi.mocked(subjectIdentityApi.listImages).mockResolvedValue([
identityImageFixture({ identityId: `identity-${second.subjectId}`, status: 'completed' })
])
await wrapper!
.get('.identity-detail')
.findAll('button')
.find(item => item.text() === '刷新身份')!
.trigger('click')
await flushPromises()
expect(wrapper!.find('.identity-generation-feedback').exists()).toBe(false)
})
it('主体目录与详情分别显示骨架,查询失败结束占位并可重试恢复', async () => {
/** 分别阻塞目录与详情,避免将未完成查询误显示为空身份。 */
let rejectCatalog!: (error: Error) => void
let rejectDetail!: (error: Error) => void
vi.spyOn(subjectImagesApi, 'listForms')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectCatalog = reject
})
)
.mockResolvedValue([formFixture()])
vi.spyOn(subjectIdentityApi, 'get')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectDetail = reject
})
)
.mockResolvedValue(null)
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(styleFixture())))
await mountAssets('identity')
expect(wrapper!.get('.subject-identity-skeleton').attributes('aria-busy')).toBe('true')
expect(wrapper!.get('.subject-identity-skeleton').text()).toBe('')
expect(wrapper!.find('#identity-description').exists()).toBe(false)
expect(wrapper!.text()).not.toContain('尚无身份参考图')
rejectCatalog(new Error('主体目录读取失败'))
await flushPromises()
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.get('.workspace-feedback [role="alert"]').text()).toContain('主体目录读取失败')
button('重试读取目录').click()
await flushPromises()
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.findAll('.identity-subject-item')).toHaveLength(1)
expect(wrapper!.get('.identity-detail').text()).toContain('林知夏')
expect(wrapper!.get('.identity-detail-skeleton').attributes('aria-busy')).toBe('true')
rejectDetail(new Error('身份读取失败'))
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(wrapper!.get('.identity-detail [role="alert"]').text()).toContain('身份读取失败')
expect(wrapper!.find('#identity-description').exists()).toBe(false)
button('刷新身份').click()
await flushPromises()
expect(wrapper!.get<HTMLInputElement>('#identity-description').element.value).toBe('')
expect(wrapper!.text()).toContain('尚无身份参考图')
})
it('已有身份刷新保留草稿与图库,图片操作归属图库并遵守未保存限制', async () => {
/** 刷新返回前后均保持编辑器实例,防止骨架导致草稿丢失。 */
let finishRefresh!: (value: ReturnType<typeof identityFixture>) => void
vi.spyOn(subjectIdentityApi, 'get')
.mockResolvedValueOnce(identityFixture())
.mockImplementationOnce(
() =>
new Promise(resolve => {
finishRefresh = resolve
})
)
vi.spyOn(subjectIdentityApi, 'listImages').mockResolvedValue([identityImageFixture()])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [formFixture()] : styleFixture())
)
)
await mountAssets('identity')
const editor = wrapper!.get('#identity-description').element
const gallery = wrapper!.get('[aria-label="身份参考图库"]')
expect(gallery.get('.identity-gallery-actions').text()).toContain('生成辅助参考图')
expect(wrapper!.get('.page-form-actions').text()).not.toContain('生成辅助参考图')
expect(button('生成辅助参考图').disabled).toBe(false)
await wrapper!.get('#identity-description').setValue('保留人工身份草稿')
expect(button('生成辅助参考图').disabled).toBe(true)
button('刷新身份').click()
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(wrapper!.get('#identity-description').element).toBe(editor)
expect(gallery.find('img').exists()).toBe(true)
finishRefresh(identityFixture({ description: '服务器刷新结果' }))
await flushPromises()
expect(wrapper!.get<HTMLTextAreaElement>('#identity-description').element.value).toBe('保留人工身份草稿')
expect(button('生成辅助参考图').disabled).toBe(true)
})
it('风格首读显示骨架,失败后展示重试,恢复后分类与规则始终可见', async () => {
/** 延迟首次响应,确认骨架不会混入尚未创建或空参考图提示。 */
let rejectStyle!: (error: Error) => void
@@ -503,7 +717,9 @@ describe('视觉风格与主体身份工作区', () => {
const put = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(put[0]).toBe('/api/subjects/subject-db-1/identity')
expect(JSON.parse(put[1]!.body as string)).toMatchObject({ description: '人工稳定身份', isLocked: true })
expect(button('生成选角候选').disabled).toBe(false)
expect(wrapper!.get('.page-form-actions').text()).not.toContain('当前内容已保存到项目')
expect(wrapper!.get('.page-form-actions button[type="submit"]').text()).toBe('已保存')
expect(button('AI 生成角色候选图').disabled).toBe(false)
await new DOMWrapper(document.body).get('#identity-description').setValue('新的未保存草稿')
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
expect(document.body.textContent).toContain('切换会丢弃草稿')
@@ -515,6 +731,8 @@ describe('视觉风格与主体身份工作区', () => {
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
''
)
expect(wrapper!.get('.page-form-actions button[type="submit"]').text()).toBe('保存主体身份')
expect(wrapper!.get('.page-form-actions').text()).not.toContain('已保存')
})
it('链接添加拒绝危险 URL,只传已有地址及分类排序,成功后关闭并清空弹窗', async () => {
@@ -697,7 +915,34 @@ describe('视觉风格与主体身份工作区', () => {
expect(wrapper!.text()).toContain('2 个形态')
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/subjects/subject-db-1/identity'))).toBe(true)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/identity/images'))).toBe(false)
expect(button('生成身份文本').disabled).toBe(false)
expect(button('AI 生成主体身份').disabled).toBe(false)
})
it('AI 主体身份生成在表单底部保留唯一入口,覆盖已保存文本需要确认', async () => {
let identity = identityFixture()
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (String(url).endsWith('/identity/images')) return jsonResponse([])
if (init?.method === 'POST') identity = identityFixture({ description: 'AI 重新生成的身份描述' })
return jsonResponse(identity)
})
stubFetch(fetcher)
await mountAssets('identity')
const actions = wrapper!.get('.page-form-actions')
expect(actions.text()).toContain('AI 生成主体身份')
expect(actions.findAll('button').map(item => item.text())).toEqual(['已保存', 'AI 生成主体身份'])
expect(actions.text()).not.toContain('当前内容已保存到项目')
expect(wrapper!.findAll('button').filter(item => item.text() === 'AI 生成主体身份')).toHaveLength(1)
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
button('确认AI 生成主体身份').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/subjects/subject-db-1/identity/generate')
expect(JSON.parse(post[1]!.body as string)).toEqual({ force: true })
expect(wrapper!.get<HTMLTextAreaElement>('#identity-description').element.value).toBe('AI 重新生成的身份描述')
})
it('锁定阻止身份 AI 覆盖但不阻止人工编辑,并按步骤进入后续操作', async () => {
@@ -711,6 +956,7 @@ describe('视觉风格与主体身份工作区', () => {
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.text()).toContain('主体身份已完成')
expect(button('AI 生成主体身份').disabled).toBe(true)
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份草稿')
expect(button('保存主体身份').disabled).toBe(false)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
@@ -727,6 +973,7 @@ describe('视觉风格与主体身份工作区', () => {
)
await mountAssets('identity')
expect(button('设置视觉风格').disabled).toBe(false)
expect(button('AI 生成主体身份').disabled).toBe(true)
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份草稿')
expect(button('保存主体身份').disabled).toBe(false)
})
@@ -758,6 +1005,50 @@ describe('视觉风格与主体身份工作区', () => {
expect(drawerPanel().text()).toContain('文本模型超时')
})
it.each([true, false])(
'身份图片校验按真实 passed=%s 反馈,等待时显示目标按钮加载,结果不驻留页面',
async passed => {
/** 延迟校验回执以覆盖请求期间的真实按钮状态。 */
let finish!: (response: Response) => void
const response = new Promise<Response>(resolve => {
finish = resolve
})
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (init?.method === 'POST' && path.endsWith('/validate')) return response
if (path.endsWith('/identity/images')) return jsonResponse([identityImageFixture()])
return jsonResponse(identityFixture())
})
stubFetch(fetcher)
await mountAssets('identity')
const gallery = wrapper!.findComponent(IdentityGallery)
gallery.vm.$emit('validate', 'identity-image-1')
await flushPromises()
expect(gallery.props('pendingOperation')).toMatchObject({ imageId: 'identity-image-1', kind: 'validate' })
expect(button('校验此身份图片').disabled).toBe(true)
expect(getOperation(fixture.id).pending).toBe(true)
finish(
jsonResponse({
subjectId: 'subject-db-1',
imageId: 'identity-image-1',
passed,
summary: '本次视觉检查结果',
issues: []
})
)
await flushPromises()
expect(getOperation(fixture.id)).toMatchObject({
pending: false,
noticeType: passed ? 'success' : 'warning',
notice: `林知夏 的身份图片校验${passed ? '通过' : '未通过'}:本次视觉检查结果`
})
expect(gallery.props('pendingOperation')).toBeNull()
expect(wrapper!.text()).not.toContain('本次视觉检查结果')
}
)
it('身份候选母版切换需确认,只发送正确 Subject ID 的 anchor PUT', async () => {
let selected = false
const form = formFixture()
@@ -789,6 +1080,10 @@ describe('视觉风格与主体身份工作区', () => {
'/api/subjects/subject-db-1/identity/images/candidate/stable-anchor'
)
expect(wrapper!.text()).toContain('当前身份母版')
expect(getOperation(fixture.id)).toMatchObject({
noticeType: 'success',
notice: '林知夏 的身份母版已确认并锁定。'
})
const anchorImage = wrapper!
.findAllComponents(NImage)
.find(image => image.props('alt')?.endsWith('当前身份母版'))!
@@ -943,8 +1238,11 @@ describe('视觉风格与主体身份工作区', () => {
})
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(true)
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(
fetcher.mock.calls.find(([url]) => String(url).endsWith('/subject-db-1/identity'))?.[1]?.signal?.aborted
).toBe(true)
@@ -966,14 +1264,14 @@ describe('视觉风格与主体身份工作区', () => {
})
stubFetch(fetcher)
const provided = await mountAssets('identity')
button('生成身份文本').click()
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
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()
expect(button('生成身份文本').disabled).toBe(true)
expect(button('AI 生成主体身份').disabled).toBe(true)
})
})