feat(short-drama-agent-front): 完善镜头定位与项目配置

This commit is contained in:
GJ committed 2026-10-08 19:45:26 +08:00
1 parent 470b52e26d
commit 5b134207b8
66 files changed
+2042 -984

No files matched your search

+2
View File
@@ -8,3 +8,5 @@ coverage
.DS_Store
.worktree/
.worktrees/
.pnpm-store/
@@ -0,0 +1,53 @@
# 镜头定位与项目配置 Implementation Plan
> **For agentic workers:** 本次在当前 worktree 内逐项执行,保持用户已确认的范围。
**Goal:** 刷新后恢复镜头,清理独立刷新按钮,统一项目配置入口。
**Architecture:** 共享地址同步 composable 接入两个现有页面查询。ProjectLayout 打开 AppDialog 并复用 CreativeProfileSettings,配置修订通过项目注入上下文通知消费者。
**Tech Stack:** Vue 3、TypeScript、Vue Router、Naive UI、Tailwind。
## Global Constraints
- 全部新增/修改函数、类型、响应式声明和页面模块写中文注释。
- 页面和功能在本地 Chrome 的 localhost:4314 验证,不使用 Playwright。
- 用户未要求本次提交,不提交、不推送;不执行付费生成。
### Task 1: 地址保存镜头选择
Files: 新建 src/features/storyboard/useShotSelection.ts;修改 useStoryboard.ts、useProduction.ts、ProductionPage.vue;新增 tests/features/storyboard/shot-selection.test.ts。
- [x] 用真实 memory router 写恢复、选镜头保留其它参数、切集清旧镜头、外部导航测试;先运行确认缺失功能失败。
- [x] 导出 useShotSelection(currentEpisode: () => number),使用注入 route/router 与独立 ref;写入 router.replace({query: {...route.query, episodeNo: String(currentEpisode()), shotId}}),切集删除 shotId。
- [x] 两个 hook 复用选择;移除生产页重复 route 同步;无效明确 ID 不回退其它镜头。
- [x] 运行定向测试及 Chrome 刷新和地址导航验证。
### Task 2: 项目配置弹窗
Files: ProjectLayout.vue、CreativeProfileSettings.vue;新建 ProjectSettingsDialog.vue 与 context.ts(generation-config);调整现有配置消费者。
- [x] 标题栏增加“项目配置”;AppDialog 显示宽高比、图片配置、视频配置,图片与视频左右两列,小屏单列;操作按钮放 footer。
- [x] 保留模型 schema 与现有保存 payload;保存期间 busy 锁关闭;读取和保存捕获原项目及请求归属。
- [x] 注入项目配置 revision,保存后自增;单镜参数和已打开配置查询重新读取;配置错误恢复共用新入口。
- [x] Chrome 打开、滚动、保存相同配置并刷新核对,取消修改不写入。
### Task 3: 清理独立刷新图标
Files: 搜索全部 src 下 RefreshCw 的组件。
- [x] 移除只有图标的 NButton(图库同时移除包装 NPopover);保留有文字的刷新操作与错误重试。
- [x] 清理无用图标导入、按钮说明文字,保留仍被操作完成后调用的 refresh 函数。
- [x] 格式化修改文件,lint、类型检查、构建;Chrome 核对各页面,检视地址恢复和配置弹窗。
用户后续调整:项目配置弹窗改为图片、视频左右布局,操作按钮放在 footer;保存草稿原样保留实际项目参数。
验收记录:Chrome 在 localhost:4314 验证分镜与生产选择刷新恢复、配置左右布局、footer 按钮、标题下 description slot、2px 间距、有效参数启用保存和取消草稿隔离;其它页面独立刷新图标已删除。49 项定向检查通过,类型、lint 与构建通过;全量检查的既有失败已在交付前同步修正并全部通过。
现有守株待兔项目配置 size=1080*1920 已被当前后端目录拒绝,真实保存验证得到该错误;表单保留原值并先提示校验问题。未写入替代尺寸,也未执行付费模型调用。
用户最新要求:新增与本次调整的布局、间距和文字样式优先直接使用 Tailwind utility class,减少自定义 class。
## 本次交付检查
用户明确要求提交、合并 dev、检查无错误后推送。完整 pnpm check 已通过:44 个测试文件、349 项测试全部通过,lint、格式与类型检查通过;build 通过。同步了旧参数 schema、202 执行句柄、readiness 门禁和 Modal 测试契约,并排除其它 worktree 的重复测试。修复新建 footer 校验、图库配置修订更新、失效镜头正文提示及内嵌配置操作锁。Chrome 验证空白创建输入被拦截、失效镜头可从目录恢复,未执行付费模型调用。
@@ -0,0 +1,17 @@
# 镜头定位与项目配置设计
用户已确认:两个镜头页面通过地址的 episodeNo、shotId 恢复选择,保留其它参数;全站移除独立刷新图标;项目标题栏右侧打开图片、视频左右布局,操作按钮放 footer 的配置弹窗。
- 共用镜头选择 composable,选择镜头时写入正式 ID 与当前剧集;切集清除旧 ID;浏览器导航从地址同步。无 ID 首次显示首镜,错误 ID 不代选其它镜头。
- 配置使用现有 creative-profile GET/PUT 与 generation-models。宽高比在前,图片和视频区域左右两列,小屏回落单列,操作放 footer;使用 AppDialog 内滚动,保存期间禁止关闭,操作期间禁止保存。
- 保留带文字的刷新、重试与后台观察逻辑,移除全站仅有刷新图标的按钮及无用导入。
- 配置成功保存后通知当前项目消费者,重新读取默认参数;关闭未保存配置不影响实际生产。
- 开发在当前 worktree;后续按用户明确授权提交、合并 dev 并推送;localhost:4314 本地 Chrome 验证选择刷新、跨页、弹窗排版与保存。
用户后续调整:项目配置弹窗改为图片、视频左右布局,操作按钮放在 footer;保存草稿原样保留实际项目参数。
公共 AppDialog 新增 description slot:说明固定在 header 内标题下方,标题与说明间距 2px,正文滚动不带走说明。原 description 属性保留作为 slot 默认文本。按真实目录校验配置,旧尺寸不兼容时原样展示并提示重新选择,不自动写入替代尺寸。
用户最新要求:新增与本次调整的布局、间距和文字样式优先直接使用 Tailwind utility class,减少自定义 class。
字段说明收敛:使用公共 FieldLabel,在 label 后放问号图标;点击图标通过 NPopover 查看后端 schema 的完整说明。GenerationOptionFields 与 GenerationModelControls 共享此组件,项目配置、首帧质量、身份候选与形态图等弹窗同步生效。原字段下方说明不再占据版面,实时错误、校验问题、费用确认和实际数据保持直接可见。新组件全部使用 Tailwind utility class。
-1
View File
@@ -26,4 +26,3 @@
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+5 -1
View File
@@ -145,7 +145,11 @@ const menuOptions = computed<MenuOption[]>(() => {
disabled
? h(
'span',
{ class: 'admin-menu-label', title: sectionAccess?.reason || '请先完成前面的制作步骤', 'aria-disabled': 'true' },
{
class: 'admin-menu-label',
title: sectionAccess?.reason || '请先完成前面的制作步骤',
'aria-disabled': 'true'
},
label
)
: h(RouterLink, { to: target }, () =>
+54 -25
View File
@@ -2,14 +2,29 @@
import { NModal, NScrollbar } from 'naive-ui'
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
/** Naive UI 管理焦点锁定、Esc、遮罩与主题;长弹窗只滚动内部正文。 */
defineProps<{ title: string; description: string; busy?: boolean; wide?: boolean }>()
/** 公共弹窗的标题、说明、操作状态和宽度。 */
withDefaults(
defineProps<{
/** 弹窗标题,同时作为可访问名称。 */
title: string
/** 标题下的默认说明,可使用 description slot 覆盖。 */
description?: string
/** 提交期间锁定关闭操作。 */
busy?: boolean
/** 使用宽弹窗布局。 */
wide?: boolean
}>(),
{ description: '', busy: false, wide: false }
)
/** 弹窗显隐状态,关闭行为由 Naive 管理。 */
const open = defineModel<boolean>('open', { default: false })
/** 正文测量锚点,不包含固定 header 与 footer。 */
const bodyAnchor = ref<HTMLElement | null>(null)
/** 可用正文滚动高度。 */
const bodyHeight = ref(0)
let layoutObserver: ResizeObserver | undefined
/** 正文使用内容高度与剩余视口高度的较小值;为 NScrollbar 提供明确滚动高度。 */
/** 正文使用内容高度与剩余视口高度的较小值,扣除固定标题、说明与 footer。 */
function updateBodyHeight() {
const card = bodyAnchor.value?.closest('.app-dialog')
const scrollContent = bodyAnchor.value?.parentElement
@@ -20,27 +35,34 @@ function updateBodyHeight() {
const contentStyle = content ? getComputedStyle(content) : null
const available = Math.max(
0,
window.innerHeight - 32 - (header?.offsetHeight ?? 0) - (footer?.offsetHeight ?? 0)
- (contentStyle ? parseFloat(contentStyle.paddingTop) + parseFloat(contentStyle.paddingBottom) : 0)
- 2
window.innerHeight -
32 -
(header?.offsetHeight ?? 0) -
(footer?.offsetHeight ?? 0) -
(contentStyle ? parseFloat(contentStyle.paddingTop) + parseFloat(contentStyle.paddingBottom) : 0) -
2
)
bodyHeight.value = Math.min(scrollContent.scrollHeight, available)
}
watch(open, async shown => {
layoutObserver?.disconnect()
if (!shown) return
await nextTick()
updateBodyHeight()
const card = bodyAnchor.value?.closest('.app-dialog')
const scrollContent = bodyAnchor.value?.parentElement
if (!card || !scrollContent) return
layoutObserver = new ResizeObserver(updateBodyHeight)
const header = card.querySelector('.n-card-header')
const footer = card.querySelector('.n-card__footer')
if (header) layoutObserver.observe(header)
if (footer) layoutObserver.observe(footer)
layoutObserver.observe(scrollContent)
}, { flush: 'post' })
watch(
open,
async shown => {
layoutObserver?.disconnect()
if (!shown) return
await nextTick()
updateBodyHeight()
const card = bodyAnchor.value?.closest('.app-dialog')
const scrollContent = bodyAnchor.value?.parentElement
if (!card || !scrollContent) return
layoutObserver = new ResizeObserver(updateBodyHeight)
const header = card.querySelector('.n-card-header')
const footer = card.querySelector('.n-card__footer')
if (header) layoutObserver.observe(header)
if (footer) layoutObserver.observe(footer)
layoutObserver.observe(scrollContent)
},
{ flush: 'post', immediate: true }
)
onMounted(() => window.addEventListener('resize', updateBodyHeight))
onBeforeUnmount(() => {
layoutObserver?.disconnect()
@@ -53,7 +75,6 @@ onBeforeUnmount(() => {
<NModal
v-model:show="open"
preset="card"
:title="title"
:closable="!busy"
:mask-closable="!busy"
:close-on-esc="!busy"
@@ -62,9 +83,18 @@ onBeforeUnmount(() => {
role="dialog"
:aria-label="title"
>
<!-- 以下是固定标题与说明模块,说明位于标题下并可自定义 -->
<template #header>
<div class="min-w-0">
<div class="text-lg font-semibold">{{ title }}</div>
<div v-if="description || $slots.description" class="mt-[2px] text-sm leading-6 font-normal text-muted">
<slot name="description">{{ description }}</slot>
</div>
</div>
</template>
<!-- 以下是弹窗正文滚动模块 -->
<NScrollbar class="dialog-body-scroll" :style="{ height: bodyHeight + 'px' }">
<span ref="bodyAnchor" class="dialog-body-anchor" aria-hidden="true" />
<p v-if="description" class="text-sm leading-6 text-muted">{{ description }}</p>
<slot />
</NScrollbar>
<template v-if="$slots.footer" #footer>
@@ -86,9 +116,8 @@ onBeforeUnmount(() => {
}
.app-dialog .n-card-header {
@apply shrink-0;
@apply shrink-0 items-start;
}
/* 正文容器可收缩,滚动高度由内容与剩余视口共同确定。 */
.app-dialog .n-card-content {
@apply min-h-0 overflow-hidden;
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ref } from 'vue'
import { NPopover } from 'naive-ui'
import type { PopoverProps } from 'naive-ui'
import { CircleHelp } from '@lucide/vue'
/** 字段标签与按需打开的说明,适用于项目配置和各类生成表单。 */
withDefaults(
defineProps<{
/** 字段标签,保持实际文案与必填标记。 */
label: string
/** 原有字段说明,没有说明时不显示提示图标。 */
description?: string
/** 提示位置可按字段单独指定,默认居中显示在图标上方。 */
placement?: PopoverProps['placement']
}>(),
{ placement: 'top' }
)
/** 点击或键盘激活提示按钮时打开说明,点击外部后关闭。 */
const open = ref(false)
</script>
<template>
<!-- 以下是字段标签与说明提示模块 -->
<span class="inline-flex min-w-0 items-center gap-1.5">
<span>{{ 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-expanded="open"
@click.stop
>
<CircleHelp :size="14" aria-hidden="true" />
</button>
</template>
<div class="max-w-[min(360px,calc(100vw-48px))] whitespace-pre-wrap break-words text-xs leading-5">
{{ description }}
</div>
</NPopover>
</span>
</template>
-2
View File
@@ -62,5 +62,3 @@ const open = defineModel<boolean>('open', { default: false })
@apply grid-cols-[repeat(auto-fit,_minmax(min(100%,_230px),_1fr))];
}
</style>
+1
View File
@@ -1,4 +1,5 @@
/** 公共 UI 的统一导出入口。 */
export { default as FieldLabel } from './FieldLabel.vue'
export { default as AppDialog } from './AppDialog.vue'
export { default as EmptyState } from './EmptyState.vue'
export { default as StatusBadge } from './StatusBadge.vue'
-1
View File
@@ -78,4 +78,3 @@ export function usePolling<T>(
})
return { data, loading, error, updatedAt, refresh }
}
-1
View File
@@ -263,4 +263,3 @@ export function useTheme() {
})
return { preference, isDark, theme, overrides }
}
@@ -105,14 +105,15 @@ function exportScript() {
:loading="backgroundExecution.query.loading.value"
:error="backgroundExecution.query.error.value"
@refresh="backgroundExecution.query.refresh"
@dismiss="backgroundExecution.dismiss"
/>
@dismiss="backgroundExecution.dismiss" />
<div v-if="!complete" class="mt-5 flex flex-wrap items-center justify-between gap-4">
<p class="text-sm text-muted">
已写入 {{ episodes.length }}<span v-if="total"> / {{ total }}</span> 集<span v-if="!total">
· 等待计划集数</span
>。{{
project?.status === 'generating' ? '剧本仍在生成,请等待状态更新。' : '如中途停止,可从当前阶段继续。'
project?.status === 'generating'
? '剧本仍在生成,请等待状态更新。'
: '如中途停止,可从当前阶段继续。'
}}
</p>
<div class="flex flex-wrap gap-2">
@@ -10,43 +10,86 @@ import type {
GenerationModelItem,
GenerationOptions
} from '../types'
import { creativeProfileDraft, creativeProfileIssues } from '../profile-draft'
import { useProjectGenerationRevision } from '../context'
import GenerationOptionFields from './GenerationOptionFields.vue'
const props = defineProps<{ projectId: string }>()
const emit = defineEmits<{ saved: [profile: CreativeProfileInput] }>()
/** 项目配置表单参数。 */
const props = withDefaults(
defineProps<{
/** 当前项目 ID。 */
projectId: string
/** 弹窗由公共 footer 提供保存操作,隐藏表单自身操作区。 */
hideActions?: boolean
/** 有项目操作时禁止编辑和保存配置。 */
disabled?: boolean
}>(),
{ hideActions: false, disabled: false }
)
/** 保存后的实际配置与保存状态通知。 */
const emit = defineEmits<{ saved: [profile: CreativeProfileInput]; busy: [saving: boolean] }>()
/** 成功保存后通知当前项目生成表单更新默认值。 */
const revision = useProjectGenerationRevision()
/** 配置和模型目录读取状态。 */
const loading = ref(false)
/** 配置保存状态。 */
const saving = ref(false)
/** 读取或保存错误。 */
const error = ref('')
/** 真实保存结果提示。 */
const notice = ref('')
/** 后端支持的图片与视频模型目录。 */
const catalog = ref<GenerationModelCatalog | null>(null)
/** 当前项目的独立编辑草稿。 */
const profile = ref<CreativeProfileInput | null>(null)
/** 当前读取请求控制器。 */
let controller: AbortController | null = null
/** 组件销毁后忽略迟到保存响应,不更新新项目配置修订号。 */
let disposed = false
/** 项目画布支持的宽高比选项。 */
const aspectRatios = ['9:16', '16:9', '1:1', '4:3', '3:4'].map(value => ({ label: value, value }))
/** 当前可用的图片模型。 */
const enabledImages = computed(() => catalog.value?.images?.filter(item => item.enabled && item.model) ?? [])
/** 当前可用的视频模型。 */
const enabledVideos = computed(() => catalog.value?.videos?.filter(item => item.enabled && item.model) ?? [])
/** 当前图片模型的组合选项值。 */
const imageSelection = computed(() =>
profile.value ? selectionValue(profile.value.imageProvider, profile.value.imageModel) : null
)
/** 当前视频模型的组合选项值。 */
const videoSelection = computed(() =>
profile.value ? selectionValue(profile.value.videoProvider, profile.value.videoModel) : null
)
/** 图片模型对应的参数 schema。 */
const imageModel = computed(() =>
enabledImages.value.find(item =>
profile.value ? item.provider === profile.value.imageProvider && item.model === profile.value.imageModel : false
)
)
/** 视频模型对应的参数 schema。 */
const videoModel = computed(() =>
enabledVideos.value.find(item =>
profile.value ? item.provider === profile.value.videoProvider && item.model === profile.value.videoModel : false
)
)
/**
* 组合供应方与模型,避免同名模型混淆。
* @param provider 模型供应方
* @param model 模型名称
* @returns 下拉选项唯一值
*/
function selectionValue(provider: string, model: string) {
return `${provider}\u0000${model}`
}
/**
* 将实际模型目录转成下拉选项。
* @param items 当前媒介模型列表
* @returns 模型下拉选项
*/
function modelOptions(items: GenerationModelItem[]) {
return items.map(item => ({
label: `${item.providerLabel} · ${item.modelLabel}`,
@@ -54,6 +97,11 @@ function modelOptions(items: GenerationModelItem[]) {
}))
}
/**
* 依据目标模型 schema 创建合法初始参数。
* @param item 当前模型
* @returns 模型初始参数
*/
function defaultOptions(item: GenerationModelItem): GenerationOptions {
return Object.fromEntries(
item.generationOptions.flatMap(schema => {
@@ -75,22 +123,11 @@ function defaultOptions(item: GenerationModelItem): GenerationOptions {
)
}
/** 把历史 Profile 中已不属于当前模型 Schema 的参数收敛为当前模型默认值。 */
function normalizeSavedOptions(item: GenerationModelItem | undefined, saved: GenerationOptions): GenerationOptions {
if (!item) return { ...saved }
const defaults = defaultOptions(item)
const normalized = { ...saved }
for (const schema of item.generationOptions) {
const value = normalized[schema.key]
if (schema.type !== 'size' || typeof value !== 'string' || !schema.options?.length) continue
if (schema.options.some(option => option.value === value)) continue
const fallback = defaults[schema.key]
if (fallback !== undefined) normalized[schema.key] = fallback
else delete normalized[schema.key]
}
return normalized
}
/**
* 切换模型时清空上一模型参数。
* @param type 图片或视频媒介
* @param value 下拉选项唯一值
*/
function selectModel(type: 'image' | 'video', value: string) {
if (!profile.value) return
const items = type === 'image' ? enabledImages.value : enabledVideos.value
@@ -107,6 +144,11 @@ function selectModel(type: 'image' | 'video', value: string) {
}
}
/**
* 未配置项目使用后端可用默认模型初始化草稿。
* @param nextCatalog 当前模型目录
* @returns 初始项目配置,无完整模型时返回 null
*/
function createInitial(nextCatalog: GenerationModelCatalog): CreativeProfileInput | null {
const image =
nextCatalog.images.find(item => item.enabled && item.isDefault && item.model) ??
@@ -126,139 +168,153 @@ function createInitial(nextCatalog: GenerationModelCatalog): CreativeProfileInpu
}
}
/** 读取实际目录与项目配置,取消旧目标请求并忽略迟到响应。 */
async function load() {
controller?.abort()
controller = new AbortController()
const signal = controller.signal
const projectId = props.projectId
profile.value = null
catalog.value = null
loading.value = true
error.value = ''
notice.value = ''
try {
const [nextCatalog, saved] = await Promise.all([
generationConfigApi.catalog(controller.signal),
generationConfigApi.profile(props.projectId, controller.signal)
generationConfigApi.catalog(signal),
generationConfigApi.profile(projectId, signal)
])
if (signal.aborted || props.projectId !== projectId) return
if (saved && saved.projectId !== projectId) throw new Error('项目配置返回了不匹配的项目。')
catalog.value = nextCatalog
const savedImageModel = saved
? nextCatalog.images.find(
item => item.provider === saved.imageProvider && item.model === saved.imageModel
)
: undefined
const savedVideoModel = saved
? nextCatalog.videos.find(
item => item.provider === saved.videoProvider && item.model === saved.videoModel
)
: undefined
profile.value = saved
? {
aspectRatio: saved.aspectRatio,
imageProvider: saved.imageProvider,
imageModel: saved.imageModel,
imageOptions: normalizeSavedOptions(savedImageModel, saved.imageOptions),
videoProvider: saved.videoProvider,
videoModel: saved.videoModel,
videoOptions: normalizeSavedOptions(savedVideoModel, saved.videoOptions)
}
: createInitial(nextCatalog)
profile.value = saved ? creativeProfileDraft(saved) : createInitial(nextCatalog)
} catch (cause) {
if (!controller.signal.aborted) error.value = errorMessage(cause)
if (!signal.aborted && props.projectId === projectId) error.value = errorMessage(cause)
} finally {
if (!controller.signal.aborted) loading.value = false
if (!signal.aborted && props.projectId === projectId) loading.value = false
}
}
/** 保存独立配置快照,不因路由变化把结果写入其它项目。 */
async function save() {
if (!profile.value || saving.value) return
if (!canSave.value || !profile.value) return
const projectId = props.projectId
const input = creativeProfileDraft(profile.value)
saving.value = true
error.value = ''
notice.value = ''
try {
const saved = await generationConfigApi.saveProfile(props.projectId, profile.value)
profile.value = {
aspectRatio: saved.aspectRatio,
imageProvider: saved.imageProvider,
imageModel: saved.imageModel,
imageOptions: { ...saved.imageOptions },
videoProvider: saved.videoProvider,
videoModel: saved.videoModel,
videoOptions: { ...saved.videoOptions }
}
const saved = await generationConfigApi.saveProfile(projectId, input)
if (disposed || props.projectId !== projectId) return
if (saved.projectId !== projectId) throw new Error('保存结果与当前项目不匹配,请重新读取配置。')
profile.value = creativeProfileDraft(saved)
notice.value = '项目生成配置已保存,后续首帧和视频生成会继承此配置。'
revision.value++
emit('saved', profile.value)
} catch (cause) {
error.value = errorMessage(cause)
if (!disposed && props.projectId === projectId) error.value = errorMessage(cause)
} finally {
saving.value = false
}
}
/** 按后端实际 schema 展示不兼容参数,不静默替换用户已保存的值。 */
const validationIssues = computed(() =>
profile.value && catalog.value ? creativeProfileIssues(profile.value, catalog.value) : []
)
/** 有实际项目草稿、完整可用模型且无进行中的项目操作才允许保存。 */
const canSave = computed(
() =>
!props.disabled &&
!loading.value &&
!saving.value &&
!!profile.value &&
!!enabledImages.value.length &&
!!enabledVideos.value.length &&
!validationIssues.value.length
)
/** 向弹窗 footer 暴露同一个保存入口,避免复制表单与请求逻辑。 */
defineExpose({ save, canSave })
/** 保存状态同步给弹窗,保存完成前禁止关闭。 */
watch(saving, value => emit('busy', value), { flush: 'sync' })
/** 项目变化时重新读取配置。 */
watch(() => props.projectId, load, { immediate: true })
onScopeDispose(() => controller?.abort())
onScopeDispose(() => {
disposed = true
controller?.abort()
})
</script>
<template>
<!-- 以下是项目画布与图片、视频模型配置模块 -->
<section class="production-tool-section creative-profile-settings workspace-panel">
<h3 class="text-sm font-semibold">项目画布与生成模型</h3>
<h3 v-if="!hideActions" class="text-sm font-semibold">项目画布与生成模型</h3>
<NSpin :show="loading">
<NAlert v-if="error" type="error" :show-icon="false" class="mb-3">{{ error }}</NAlert>
<NAlert v-if="notice" type="success" :show-icon="false" class="mb-3">{{ notice }}</NAlert>
<NAlert
v-if="!loading && (!enabledImages.length || !enabledVideos.length)"
type="warning"
:show-icon="false"
>
当前没有可用的完整图片和视频模型,暂时无法保存项目生成配置。
</NAlert>
<div v-if="profile" class="creative-profile-grid">
<NFormItem label="作品宽高比">
<NAlert v-if="disabled" type="info" :show-icon="false" class="mb-3"
>项目正在执行制作任务,完成后可以修改配置。</NAlert
>
<NAlert v-if="error" type="error" :show-icon="false" class="mb-3">{{ error }}</NAlert>
<NAlert v-if="validationIssues.length" type="warning" :show-icon="false" class="mb-3">
<p v-for="issue in validationIssues" :key="issue">{{ issue }}</p>
</NAlert>
<NAlert v-if="notice" type="success" :show-icon="false" class="mb-3">{{ notice }}</NAlert>
<NAlert
v-if="!loading && (!enabledImages.length || !enabledVideos.length)"
type="warning"
:show-icon="false"
>
当前没有可用的完整图片和视频模型,暂时无法保存项目生成配置。
</NAlert>
<div v-if="profile" class="creative-profile-grid">
<NFormItem label="作品宽高比">
<NSelect
:value="profile.aspectRatio"
:options="aspectRatios"
:disabled="saving || disabled"
@update:value="profile.aspectRatio = $event as CreativeProfileAspectRatio"
/>
</NFormItem>
<div></div>
<!-- 以下是项目图片生成配置模块 -->
<section class="model-section min-w-0 pt-5">
<h3 class="mb-4 text-sm font-semibold">图片配置</h3>
<NFormItem label="图片模型">
<NSelect
:value="profile.aspectRatio"
:options="aspectRatios"
:disabled="saving"
@update:value="profile.aspectRatio = $event as CreativeProfileAspectRatio"
:value="imageSelection"
:options="modelOptions(enabledImages)"
:disabled="saving || disabled"
@update:value="selectModel('image', $event)"
/>
</NFormItem>
<div></div>
<section class="model-section">
<NFormItem label="图片模型">
<NSelect
:value="imageSelection"
:options="modelOptions(enabledImages)"
:disabled="saving"
@update:value="selectModel('image', $event)"
/>
</NFormItem>
<GenerationOptionFields
v-model="profile.imageOptions"
:schemas="imageModel?.generationOptions || []"
:disabled="saving"
<GenerationOptionFields
v-model="profile.imageOptions"
:schemas="imageModel?.generationOptions || []"
:disabled="saving || disabled"
/>
</section>
<!-- 以下是项目视频生成配置模块 -->
<section class="model-section min-w-0 pt-5">
<h3 class="mb-4 text-sm font-semibold">视频配置</h3>
<NFormItem label="视频模型">
<NSelect
:value="videoSelection"
:options="modelOptions(enabledVideos)"
:disabled="saving || disabled"
@update:value="selectModel('video', $event)"
/>
</section>
<section class="model-section">
<NFormItem label="视频模型">
<NSelect
:value="videoSelection"
:options="modelOptions(enabledVideos)"
:disabled="saving"
@update:value="selectModel('video', $event)"
/>
</NFormItem>
<GenerationOptionFields
v-model="profile.videoOptions"
:schemas="videoModel?.generationOptions || []"
:disabled="saving"
/>
</section>
</div>
<div class="page-form-actions creative-profile-actions">
<NButton
type="primary"
:loading="saving"
:disabled="loading || !profile || !enabledImages.length || !enabledVideos.length"
@click="save"
>保存项目生成配置</NButton
>
<span class="text-xs text-muted">切换模型时会按新模型重置生成参数。</span>
</div>
</NFormItem>
<GenerationOptionFields
v-model="profile.videoOptions"
:schemas="videoModel?.generationOptions || []"
:disabled="saving || disabled"
/>
</section>
</div>
<div v-if="!hideActions" class="page-form-actions creative-profile-actions">
<NButton type="primary" :loading="saving" :disabled="!canSave" @click="save">保存项目生成配置</NButton>
<span class="text-xs text-muted">切换模型时会按新模型重置生成参数。</span>
</div>
</NSpin>
</section>
</template>
@@ -268,9 +324,6 @@ onScopeDispose(() => controller?.abort())
.creative-profile-grid {
@apply grid grid-cols-[repeat(2,_minmax(0,_1fr))] items-start gap-x-5 gap-y-6;
}
.model-section {
@apply min-w-0;
}
.model-section > :deep(.n-form-item) {
@apply mb-6;
}
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NFormItem, NInputNumber, NSelect, NSwitch, NTag } from 'naive-ui'
import FieldLabel from '../../../components/ui/FieldLabel.vue'
import type { SelectOption } from 'naive-ui'
import type {
CreativeProfileAspectRatio,
@@ -9,6 +10,7 @@ import type {
GenerationOptions
} from '../types'
/** 本次生成模型与参数控件,字段说明在标签图标中按需查看。 */
const props = defineProps<{
type: 'image' | 'video'
catalog: GenerationModelCatalog
@@ -17,15 +19,19 @@ const props = defineProps<{
aspectRatio: CreativeProfileAspectRatio
disabled?: boolean
}>()
/** 模型与参数编辑通知。 */
const emit = defineEmits<{
'update:provider': [value: string]
'update:options': [value: GenerationOptions]
}>()
/** 当前已启用的媒介模型。 */
const models = computed(() =>
(props.type === 'image' ? props.catalog.images : props.catalog.videos).filter(item => item.enabled)
)
/** 本次选择的实际模型。 */
const model = computed(() => models.value.find(item => item.provider === props.provider) ?? models.value[0])
/** 可用模型的下拉选项。 */
const modelOptions = computed(() =>
models.value.map(item => ({
label: item.modelLabel ? `${item.providerLabel} · ${item.modelLabel}` : item.providerLabel,
@@ -88,7 +94,10 @@ function selectValue(key: string): string | number | null {
:key="item.key"
class="generation-model-field"
:label="item.label"
:show-feedback="false"
>
<!-- 以下是生成参数标签与说明提示模块 -->
<template #label><FieldLabel :label="item.label" :description="item.description" /></template>
<div class="generation-model-field-control">
<div v-if="item.type === 'boolean'" class="generation-model-toggle">
<NSwitch
@@ -120,14 +129,13 @@ function selectValue(key: string): string | number | null {
:disabled="disabled || item.userEditable === false"
@update:value="updateOption(item.key, $event)"
/>
<p v-if="item.description" class="generation-model-description">{{ item.description }}</p>
</div>
</NFormItem>
<NFormItem class="generation-model-field" label="画幅比例">
<NFormItem class="generation-model-field" label="画幅比例" :show-feedback="false">
<template #label><FieldLabel label="画幅比例" description="项目画幅 · 单次生成不可覆盖" /></template>
<div class="generation-model-static">
<NTag size="small">{{ aspectRatio }}</NTag>
<span class="generation-model-description">项目画幅 · 单次生成不可覆盖</span>
</div>
</NFormItem>
</template>
@@ -165,9 +173,6 @@ function selectValue(key: string): string | number | null {
.generation-model-static {
@apply flex min-h-[34px] min-w-0 items-center gap-2.5;
}
.generation-model-description {
@apply m-0 text-[11px] leading-5 text-muted;
}
@media (max-width: 760px) {
.generation-model-controls {
@apply grid-cols-[minmax(0,_1fr)] gap-y-4;
@@ -1,8 +1,18 @@
<script setup lang="ts">
import { NCheckbox, NFormItem, NInput, NInputNumber, NSelect } from 'naive-ui'
import FieldLabel from '../../../components/ui/FieldLabel.vue'
import type { GenerationOptionSchema, GenerationOptions } from '../types'
defineProps<{ schemas: GenerationOptionSchema[]; modelValue: GenerationOptions; disabled?: boolean }>()
/** 动态模型参数字段,实际说明由后端 schema 提供。 */
defineProps<{
/** 当前模型开放的参数列表。 */
schemas: GenerationOptionSchema[]
/** 本次实际参数值。 */
modelValue: GenerationOptions
/** 上游操作期间禁止编辑。 */
disabled?: boolean
}>()
/** 字段编辑后通知上游更新参数。 */
const emit = defineEmits<{ 'update:modelValue': [value: GenerationOptions] }>()
function update(model: GenerationOptions, key: string, value: string | number | boolean | null) {
@@ -70,9 +80,15 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
v-for="schema in schemas"
:key="schema.key"
:label="`${schema.label}${schema.required ? ' *' : ''}`"
:feedback="schema.description"
:show-feedback="!!schema.description"
:show-feedback="false"
>
<!-- 以下是参数标签与按需说明模块 -->
<template #label>
<FieldLabel
:label="`${schema.label}${schema.required ? ' *' : ''}`"
:description="schema.description"
/>
</template>
<NCheckbox
v-if="schema.type === 'boolean'"
:checked="modelValue[schema.key] === true"
@@ -131,11 +147,6 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
min-height: 34px;
align-items: center;
}
.generation-option-grid :deep(.n-form-item-feedback-wrapper:not(:empty)) {
min-height: 0;
padding: 8px 0 0;
line-height: 1.55;
}
@media (max-width: 760px) {
.generation-option-grid {
@apply grid-cols-[minmax(0,_1fr)];
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { ref } from 'vue'
import { NButton } from 'naive-ui'
import { AppDialog } from '../../../components/ui'
import type { CreativeProfileInput } from '../types'
import CreativeProfileSettings from './CreativeProfileSettings.vue'
/** 项目全局配置弹窗参数。 */
const props = defineProps<{
/** 当前正式项目 ID。 */
projectId: string
/** 项目操作期间只读查看,禁止保存模型配置。 */
disabled: boolean
}>()
/** 真实保存成功后通知项目布局更新就绪信息。 */
const emit = defineEmits<{ saved: [profile: CreativeProfileInput] }>()
/** 弹窗显隐状态。 */
const open = defineModel<boolean>('open', { default: false })
/** 保存进行中时禁止关闭弹窗,避免重复写入。 */
const saving = ref(false)
/** 配置表单实例,footer 调用表单自身的校验与保存入口。 */
const form = ref<InstanceType<typeof CreativeProfileSettings> | null>(null)
</script>
<template>
<!-- 以下是项目图片与视频全局配置弹窗模块 -->
<AppDialog v-model:open="open" title="项目全局配置" :busy="saving" wide>
<template #description>设置项目画布、图片和视频生成模型,后续生成默认使用这里保存的配置。</template>
<CreativeProfileSettings
v-if="open"
ref="form"
:key="props.projectId"
:project-id="props.projectId"
:disabled="props.disabled"
hide-actions
@busy="saving = $event"
@saved="emit('saved', $event)"
/>
<!-- 以下是固定底栏取消与保存配置模块 -->
<template #footer>
<NButton :disabled="saving" @click="open = false">取消</NButton>
<NButton type="primary" :loading="saving" :disabled="!form?.canSave" @click="form?.save()"
>保存配置</NButton
>
</template>
</AppDialog>
</template>
+12
View File
@@ -0,0 +1,12 @@
import { inject, ref, type InjectionKey, type Ref } from 'vue'
/** 项目内共享的配置修订号,成功保存后通知已挂载的生成表单重新读取。 */
export const projectGenerationRevisionKey: InjectionKey<Ref<number>> = Symbol('project-generation-revision')
/**
* 读取项目配置修订号,独立使用组件时保留本地修订状态。
* @returns 当前项目的响应式配置修订号
*/
export function useProjectGenerationRevision() {
return inject(projectGenerationRevisionKey, undefined) ?? ref(0)
}
@@ -0,0 +1,70 @@
import type { CreativeProfileInput, GenerationModelCatalog } from './types'
/**
* 创建独立编辑或提交快照,原样保留后端已保存的生成参数。
* @param profile 后端配置或当前编辑草稿
* @returns 与原对象隔离的项目配置快照
*/
export function creativeProfileDraft(profile: CreativeProfileInput): CreativeProfileInput {
return {
aspectRatio: profile.aspectRatio,
imageProvider: profile.imageProvider,
imageModel: profile.imageModel,
imageOptions: { ...profile.imageOptions },
videoProvider: profile.videoProvider,
videoModel: profile.videoModel,
videoOptions: { ...profile.videoOptions }
}
}
/**
* 按真实模型目录检查配置能否保存。
* @param profile 当前项目配置草稿
* @param catalog 后端实际模型目录
* @returns 可展示的参数问题列表
*/
export function creativeProfileIssues(profile: CreativeProfileInput, catalog: GenerationModelCatalog): string[] {
const issues: string[] = []
for (const media of ['image', 'video'] as const) {
const label = media === 'image' ? '图片配置' : '视频配置'
const models = media === 'image' ? catalog.images : catalog.videos
const model = models.find(
item =>
item.enabled && item.provider === profile[`${media}Provider`] && item.model === profile[`${media}Model`]
)
if (!model) {
issues.push(`${label}:已保存的模型当前不可用,请重新选择模型。`)
continue
}
const values = profile[`${media}Options`]
for (const schema of model.generationOptions) {
const value = values[schema.key]
const field = `${label} · ${schema.label}`
if (value === undefined || value === '') {
if (schema.required) issues.push(`${field}:请填写必填参数。`)
continue
}
const validType =
schema.type === 'boolean'
? typeof value === 'boolean'
: schema.type === 'integer'
? typeof value === 'number' && Number.isInteger(value)
: schema.type === 'number'
? typeof value === 'number' && Number.isFinite(value)
: typeof value === 'string'
if (!validType) {
issues.push(`${field}:参数格式不正确。`)
continue
}
if (schema.options?.length && !schema.options.some(option => option.value === value)) {
issues.push(`${field}:当前值 ${String(value)} 已不在模型支持范围内,请重新选择。`)
continue
}
if (typeof value === 'number' && !schema.specialValues?.some(option => option.value === value)) {
if (schema.min !== undefined && value < schema.min) issues.push(`${field}:不能小于 ${schema.min}。`)
if (schema.max !== undefined && value > schema.max) issues.push(`${field}:不能大于 ${schema.max}。`)
}
}
}
return issues
}
+16 -31
View File
@@ -6,7 +6,7 @@ import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import WorkspaceTools from '../../components/ui/WorkspaceTools.vue'
import { NScrollbar, NAlert, NButton, NCheckbox, NInputNumber, NProgress, NSelect } from 'naive-ui'
import { computed, inject, ref, watch } from 'vue'
import { ArrowLeft, CheckCircle2, CircleAlert, Film, Image, MessageSquareText, RefreshCw } from '@lucide/vue'
import { ArrowLeft, CheckCircle2, CircleAlert, Film, Image, MessageSquareText } from '@lucide/vue'
import { EmptyState, StatusBadge } from '../../components/ui'
import BeatShotDirectory from '../storyboard/components/BeatShotDirectory.vue'
import ConfirmAction from '../workflows/ConfirmAction.vue'
@@ -82,16 +82,6 @@ watch(
}
)
const route = inject(routeLocationKey, undefined)
/** 从素材页返回时恢复到指定剧集与正式镜头,不按重复的 Shot 编号定位。 */
watch(
() => [route?.query.episodeNo, route?.query.shotId],
() => {
const episode = Number(queryText(route?.query.episodeNo))
selectedEpisode.value = Number.isSafeInteger(episode) && episode > 0 ? episode : undefined
selectedShot.value = queryText(route?.query.shotId)
},
{ immediate: true }
)
const linkedShotMissing = computed(
() =>
queryText(route?.query.shotId) &&
@@ -249,13 +239,6 @@ watch(
if (receipt) toolsOpen.value = true
}
)
watch(
() => route?.query.configure,
value => {
if (value === 'profile') toolsOpen.value = true
},
{ immediate: true }
)
function profileSaved() {
operation.value.error = ''
@@ -309,15 +292,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
>
<div class="toolbar-actions">
<NButton :disabled="blocked || !episodeNo" @click="qualityOpen = true">首帧质量生成</NButton>
<NButton
:disabled="query.loading.value"
@click="query.refresh"
quaternary
class="icon-button"
aria-label="刷新就绪状态"
title="刷新就绪状态"
><RefreshCw :size="16" :class="{ 'animate-spin': query.loading.value }" />
</NButton>
<WorkspaceTools
v-model:open="toolsOpen"
title="项目生产总览与批量操作"
@@ -370,7 +345,11 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
</AppForm>
</section>
<div class="production-tool-stack workspace-section-stack">
<CreativeProfileSettings :project-id="id" @saved="profileSaved" />
<CreativeProfileSettings
:project-id="id"
:disabled="operation.pending"
@saved="profileSaved"
/>
<section class="production-tool-section workspace-panel">
<h3 class="text-sm font-semibold">处理范围与覆盖规则</h3>
<p class="mt-3 text-xs leading-6 text-muted">
@@ -743,7 +722,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
<span>过期首帧 {{ staleKeyframes }} · 过期视频 {{ staleVideos }} · 身份前置问题 {{ identityBlocked }}</span>
<NButton text size="small" @click="toolsOpen = true">查看处理方式</NButton>
</div>
<div v-if="shot" class="panel production-workspace workspace-surface">
<div v-if="shots.length" class="panel production-workspace workspace-surface">
<nav class="production-shot-list directory-panel" aria-label="本集生产镜头">
<div class="directory-heading">
<h3>
@@ -757,7 +736,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
>
<BeatShotDirectory
:shots="shots"
:active-id="shot.shotId"
:active-id="shot?.shotId || ''"
@select="selectedShot = $event"
item-class="production-shot-link"
>
@@ -805,7 +784,7 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
</NScrollbar>
</nav>
<article class="production-detail min-w-0">
<NScrollbar class="panel-scroll" content-class="p-5 lg:p-7">
<NScrollbar v-if="shot" class="panel-scroll" content-class="p-5 lg:p-7">
<header class="mb-5 pb-5">
<NAlert v-if="linkedShotMissing" type="warning" :show-icon="false" class="mb-4"
>链接中的镜头已不存在或不属于该剧集,请在左侧重新选择。</NAlert
@@ -870,6 +849,12 @@ const videoRules = { videoLimit: integerRule('本批镜头上限'), videoRepairA
@quality-started="trackKeyframeQuality"
/>
</NScrollbar>
<!-- 以下是无效镜头地址的定位反馈模块 -->
<EmptyState
v-if="!shot"
title="链接中的镜头已不存在或不属于本集"
description="请在左侧目录重新选择镜头。"
/>
</article>
</div>
<EmptyState
@@ -3,9 +3,13 @@ import AppForm from '../../../components/ui/AppForm.vue'
import { NAlert, NButton, NCheckbox, NCollapse, NCollapseItem, NTag } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { generationConfigApi } from '../../generation-config/api'
import type { CreativeProfileAspectRatio, GenerationModelCatalog, GenerationOptions } from '../../generation-config/types'
import type {
CreativeProfileAspectRatio,
GenerationModelCatalog,
GenerationOptions
} from '../../generation-config/types'
import GenerationModelControls from '../../generation-config/components/GenerationModelControls.vue'
import { AppDialog } from '../../../components/ui'
import { AppDialog, FieldLabel } from '../../../components/ui'
import { errorMessage } from '../../../lib/http'
import { productionApi } from '../api'
import type { GenerateKeyframeInput, KeyframeGenerationPreview } from '../types'
@@ -107,8 +111,12 @@ async function loadPreview() {
当前主首帧使用的主体参考资产已经变化。新图成功后应设为主首帧,旧图会继续保留为历史候选。
</NAlert>
<section v-if="generationCatalog" class="dialog-section mt-5" aria-label="本次首帧生成模型设置">
<p class="text-xs font-medium">本次生成设置</p>
<p class="mt-1 text-xs text-muted">仅覆盖当前镜头本次首帧生成,不修改项目默认图片模型。</p>
<p class="text-xs font-medium">
<FieldLabel
label="本次生成设置"
description="仅覆盖当前镜头本次首帧生成,不修改项目默认图片模型。"
/>
</p>
<GenerationModelControls
class="mt-4"
type="image"
@@ -175,8 +183,10 @@ async function loadPreview() {
</NCheckbox>
</AppForm>
<template #footer>
<NButton @click="open = false">取消</NButton>
<NButton :disabled="disabled || !confirmed" @click="formRef?.validate(submit)" type="primary">确认生成首帧</NButton>
<NButton @click="open = false">取消</NButton>
<NButton :disabled="disabled || !confirmed" @click="formRef?.validate(submit)" type="primary"
>确认生成首帧</NButton
>
</template>
</AppDialog>
</template>
@@ -1,7 +1,7 @@
<script setup lang="ts">
import ProviderInputInspector from './ProviderInputInspector.vue'
import { NAlert, NButton, NCollapse, NCollapseItem, NSelect, NTag } from 'naive-ui'
import { computed, onMounted, ref, watch } from 'vue'
import { computed, ref, watch } from 'vue'
import { ExternalLink, ImagePlus, RefreshCw } from '@lucide/vue'
import { AssetImage, StatusBadge } from '../../../components/ui'
import { usePolling } from '../../../composables/usePolling'
@@ -39,6 +39,7 @@ import { AppDialog } from '../../../components/ui'
import ModelCapabilities from './ModelCapabilities.vue'
import type { QualityTarget } from '../quality.types'
import { sessionKeyframePassed, sessionVideoValidation } from '../quality'
import { useProjectGenerationRevision } from '../../generation-config/context'
import { generationConfigApi } from '../../generation-config/api'
import type {
CreativeProfileAspectRatio,
@@ -156,25 +157,35 @@ const videoGenerationOptions = ref<GenerationOptions>({})
const videoInputModeOverride = ref<'auto' | 'first_frame' | 'omni_reference'>('auto')
const projectAspectRatio = ref<CreativeProfileAspectRatio>('9:16')
/** 单镜手动生成默认继承项目配置,用户修改只作用于本次请求。 */
onMounted(async () => {
try {
const [catalog, profile] = await Promise.all([
generationConfigApi.catalog(),
generationConfigApi.profile(props.projectId)
])
generationCatalog.value = catalog
projectAspectRatio.value = profile?.aspectRatio ?? '9:16'
videoProvider.value = profile?.videoProvider || catalog.defaults.videoProvider
const selected = catalog.videos.find(item => item.provider === videoProvider.value)
videoGenerationOptions.value = {
...selected?.defaults,
...profile?.videoOptions
/** 项目配置成功保存后同步当前单镜头默认参数。 */
const generationRevision = useProjectGenerationRevision()
/** 单镜手动生成默认继承项目配置,用户修改只作用于本次请求;取消旧项目响应。 */
watch(
[() => props.projectId, generationRevision],
async ([projectId], _previous, onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort())
generationCatalogError.value = ''
try {
const [catalog, profile] = await Promise.all([
generationConfigApi.catalog(controller.signal),
generationConfigApi.profile(projectId, controller.signal)
])
if (controller.signal.aborted) return
generationCatalog.value = catalog
projectAspectRatio.value = profile?.aspectRatio ?? '9:16'
videoProvider.value = profile?.videoProvider || catalog.defaults.videoProvider
const selected = catalog.videos.find(item => item.provider === videoProvider.value)
videoGenerationOptions.value = {
...selected?.defaults,
...profile?.videoOptions
}
} catch (cause) {
if (!controller.signal.aborted) generationCatalogError.value = errorMessage(cause)
}
} catch (cause) {
generationCatalogError.value = errorMessage(cause)
}
})
},
{ immediate: true }
)
/** 从实际候选打开质量面板,保留单镜头主操作。 */
function openQuality(kind: 'keyframe' | 'video', assetId: string) {
@@ -385,15 +396,6 @@ async function inspectSpecs() {
:items="[{ key: 'specs', label: '检查生成规格与模型限制', disabled: inspecting }]"
@select="inspectSpecs"
/>
<NButton
:disabled="query.loading.value"
@click="refreshAll"
quaternary
class="icon-button"
aria-label="刷新资产"
title="刷新资产"
><RefreshCw :size="16" :class="{ 'animate-spin': query.loading.value }" />
</NButton>
</div>
</div>
<NAlert v-if="query.error.value" role="alert" type="error" :show-icon="false" class="mt-4"
+9 -8
View File
@@ -1,3 +1,4 @@
import { useShotSelection } from '../storyboard/useShotSelection'
import type { KeyframeBatchResult } from './types'
import type { PromptBatchResult } from '../storyboard/types'
import { computed, ref, watch } from 'vue'
@@ -21,10 +22,8 @@ export function useProduction() {
const context = useProjectContext()
/** 当前工作区的响应式状态或派生业务条件。 */
const id = computed(() => context.project.value?.id ?? '')
/** 当前工作区的响应式状态或派生业务条件。 */
const selectedEpisode = ref<number>()
/** 当前工作区的响应式状态或派生业务条件。 */
const selectedShot = ref('')
/** 两个镜头工作区共用地址选择,刷新恢复同一正式镜头。 */
const { selectedEpisode, selectedShot } = useShotSelection(() => episodeNo.value)
/** 当前工作区的响应式状态或派生业务条件。 */
const concurrency = ref(2)
/** 当前工作区的响应式状态或派生业务条件。 */
@@ -68,7 +67,7 @@ export function useProduction() {
)
/** 当前工作区的响应式状态或派生业务条件。 */
const queryKey = computed(() => JSON.stringify([id.value, episodeNo.value, force.value]))
/** 生产页已有刷新按钮,就绪状态改为手动更新。 */
/** 就绪状态在进入、切集或自身操作完成后读取,不定时刷新。 */
const query = usePolling(
queryKey,
async (key, signal) => {
@@ -112,10 +111,12 @@ export function useProduction() {
const episodeSourceUnavailable = computed(
() => !!getStoryboardSession(id.value).invalidatedEpisodeSources[episodeNo.value]
)
/** 当前工作区的响应式状态或派生业务条件。 */
/** 当前剧集的正式镜头目录。 */
const shots = computed(() => mergeDesignedShots(query.data.value?.directions ?? null, null, source.value))
/** 当前工作区的响应式状态或派生业务条件。 */
const shot = computed(() => shots.value.find(item => item.shotId === selectedShot.value) ?? shots.value[0])
/** 明确指定的镜头不存在时不代选其它镜头;首次进入才选择第一镜。 */
const shot = computed(() =>
selectedShot.value ? shots.value.find(item => item.shotId === selectedShot.value) : shots.value[0]
)
/** 当前工作区的响应式状态或派生业务条件。 */
const promptItem = computed(() => query.data.value?.prompts.items.find(item => item.shotId === shot.value?.shotId))
/** 当前工作区的响应式状态或派生业务条件。 */
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { NAlert, NButton, NFormItem, NInput, NPopconfirm, NSelect, NTag, NTooltip } from 'naive-ui'
import { RefreshCw, Search, Trash2, Upload } from '@lucide/vue'
import { Search, Trash2, Upload } from '@lucide/vue'
import { AppDialog, AssetImage, EmptyState } from '../../components/ui'
import AppForm from '../../components/ui/AppForm.vue'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
@@ -111,11 +111,6 @@ function clearFilters() {
category.value = null
}
/** 同时刷新图片与上传所需的剧本选项。 */
async function refreshAll() {
await Promise.all([query.refresh(), projectsQuery.refresh()])
}
/** 先校验本地文件,再在当前页选择剧本并确认资料。 */
function selectFile(event: Event) {
const input = event.target as HTMLInputElement
@@ -237,16 +232,6 @@ async function removeAsset() {
>
<template #icon><Upload :size="16" /></template>上传图片
</NButton>
<NButton
quaternary
class="icon-button"
:loading="query.loading.value || projectsQuery.loading.value"
aria-label="刷新资产库"
title="刷新资产库"
@click="refreshAll"
>
<template #icon><RefreshCw :size="16" /></template>
</NButton>
</div>
</div>
</template>
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { NAlert, NButton, NFormItem, NInput, NPopconfirm, NSelect, NTag } from 'naive-ui'
import { Pencil, RefreshCw, Search, Trash2, Upload } from '@lucide/vue'
import { Pencil, Search, Trash2, Upload } from '@lucide/vue'
import { AppDialog, AssetImage, EmptyState } from '../../components/ui'
import AppForm from '../../components/ui/AppForm.vue'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
@@ -187,15 +187,6 @@ async function removeAsset(asset: ProjectAsset) {
<NButton type="primary" :disabled="disabled" @click="fileInput?.click()">
<template #icon><Upload :size="16" /></template>上传图片
</NButton>
<NButton
quaternary
class="icon-button"
aria-label="刷新资产库"
title="刷新资产库"
:loading="query.loading.value"
@click="query.refresh"
><template #icon><RefreshCw :size="16" /></template
></NButton>
</div>
</div>
</template>
+50 -8
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, inject, onScopeDispose, provide, watchEffect } from 'vue'
import { computed, 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 { EmptyState } from '../../components/ui'
@@ -9,6 +9,8 @@ import { projectAccessKey, projectSectionFromPath, type ProjectAccess } from './
import { useProjectStageAccess } from './useProjectStageAccess'
import { useWorkflowExecution } from '../workflows/execution'
import { clearEpisodeSourceInvalidations, invalidateEpisodeSource } from '../storyboard/model'
import ProjectSettingsDialog from '../generation-config/components/ProjectSettingsDialog.vue'
import { projectGenerationRevisionKey } from '../generation-config/context'
import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
/** 项目标题只保留名称;下游工作区在剧本完成前不挂载,直接链接也无法越过限制。 */
@@ -22,6 +24,32 @@ const isGallery = computed(() => {
})
const context = useProjectData(id)
provide(projectContextKey, context)
/** 项目全局配置保存后更新已挂载生成表单。 */
const generationRevision = ref(0)
provide(projectGenerationRevisionKey, generationRevision)
/** 项目标题栏共用配置弹窗开关。 */
const settingsOpen = ref(false)
/** 既有配置恢复链接打开同一个全局弹窗,不切换工作区。 */
watch(
() => route.query.configure,
value => {
if (value === 'profile') settingsOpen.value = true
},
{ immediate: true }
)
/** 关闭弹窗清除仅用于打开配置的参数,保留镜头与其它地址信息。 */
watch(settingsOpen, shown => {
if (!shown && route.query.configure === 'profile') {
const query = { ...route.query }
delete query.configure
void router.replace({ path: route.path, query, hash: route.hash })
}
})
/** 切项目时关闭旧配置,禁止把草稿带入其它项目。 */
watch(id, () => {
settingsOpen.value = false
generationRevision.value = 0
})
const operation = computed(() => getOperation(id.value))
const createDramaExecution = useWorkflowExecution(id, 'create-drama')
/** 项目内跨页面继续观察首帧后台任务,维持活动锁并在真实终态后释放。 */
@@ -128,13 +156,12 @@ function resolveOperationError() {
void router.push({ path: `/projects/${id.value}/production`, query })
} else if (target === 'style') void router.push(`/projects/${id.value}/visual-style`)
else if (target === 'identity') void router.push(`/projects/${id.value}/subject-identity`)
else if (target === 'profile') {
const onIdentityPage = route.path.replace(/\/+$/, '').endsWith('/subject-identity')
void router.push({
path: onIdentityPage ? route.path : `/projects/${id.value}/production`,
query: { ...route.query, configure: 'profile' }
})
}
else if (target === 'profile') settingsOpen.value = true
}
/** 配置真实保存后更新当前项目的就绪门禁并解除配置缺失提示。 */
function projectSettingsSaved() {
if (operationGuide.value?.target === 'profile') operation.value.error = ''
void context.refreshStageReadiness()
}
const access = inject(projectAccessKey, undefined)
let published: ProjectAccess | null = null
@@ -149,12 +176,18 @@ onScopeDispose(() => {
<template>
<section class="project-frame">
<header class="project-header">
<!-- 以下是项目标题与全局配置入口模块 -->
<NPageHeader @back="router.push('/projects')">
<template #title
><NEllipsis class="project-title" :tooltip="false">{{
context.project.value?.title || context.project.value?.topic || '读取项目'
}}</NEllipsis></template
>
<template #extra>
<NButton size="small" :disabled="!context.project.value" @click="settingsOpen = true"
>项目配置</NButton
>
</template>
</NPageHeader>
</header>
<NScrollbar
@@ -194,6 +227,15 @@ onScopeDispose(() => {
@refresh="createDramaExecution.query.refresh"
@dismiss="createDramaExecution.dismiss"
/>
<!-- 以下是当前项目图片与视频配置弹窗模块 -->
<ProjectSettingsDialog
:key="id"
v-if="context.project.value?.id === id"
v-model:open="settingsOpen"
:project-id="id"
:disabled="operation.pending"
@saved="projectSettingsSaved"
/>
<div class="project-view">
<RouterView v-if="context.project.value?.id === id && currentAccess?.enabled" :key="id" />
<EmptyState
+3 -11
View File
@@ -12,7 +12,7 @@ import {
type DataTableColumns,
type DataTableInst
} from 'naive-ui'
import { MoreHorizontal, Pencil, RefreshCw, Search, Trash2 } from '@lucide/vue'
import { MoreHorizontal, Pencil, Search, Trash2 } from '@lucide/vue'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import { useQuery } from '../../composables/useQuery'
import { StatusBadge } from '../../components/ui'
@@ -25,7 +25,7 @@ import DeleteProjectDialog from './components/DeleteProjectDialog.vue'
/** 项目表格使用固定表头与独立滚动;搜索筛选仍作用于真实接口数据。 */
const router = useRouter()
/** 列表已有刷新按钮,只在进入和手动刷新时读取;筛选在完整结果中进行。 */
/** 列表在进入或自身操作完成后读取;筛选在完整结果中进行。 */
const query = useQuery(ref('projects'), (_, signal) => projectsApi.list(signal))
const search = ref('')
const filter = ref('all')
@@ -150,7 +150,7 @@ function clearFilters() {
</div>
<CreateProjectDialog @created="openProject" />
</div>
<!-- 以下是状态筛选、搜索与刷新 -->
<!-- 以下是状态筛选与搜索模块 -->
<div class="project-index-toolbar">
<div class="project-status-filter-scroller">
<NRadioGroup
@@ -172,14 +172,6 @@ function clearFilters() {
:input-props="{ 'aria-label': '搜索项目' }"
><template #prefix><Search :size="15" /></template
></NInput>
<NButton
class="icon-button"
:loading="query.loading.value"
aria-label="刷新项目"
title="刷新项目"
@click="query.refresh"
><template #icon><RefreshCw :size="16" /></template
></NButton>
</div>
</div>
</div>
+12 -2
View File
@@ -1,7 +1,14 @@
import { request, optionalResource } from '../../lib/http'
import type { Checkpoint } from '../workflows/types'
import type { WorkflowExecutionStart } from '../workflows/execution.types'
import type { CreateProjectInput, DramaState, Project, ProjectDetail, ProjectStageReadiness, UpdateProjectInput } from './types'
import type {
CreateProjectInput,
DramaState,
Project,
ProjectDetail,
ProjectStageReadiness,
UpdateProjectInput
} from './types'
/** 项目与 Create Drama API;路径严格对应后端 dev。 */
export const projectsApi = {
@@ -11,7 +18,10 @@ export const projectsApi = {
stageReadiness: (id: string, signal?: AbortSignal) =>
request<ProjectStageReadiness>(`/projects/${encodeURIComponent(id)}/stage-readiness`, { signal }),
create: (input: CreateProjectInput) =>
request<{ projectId: string; status: string; executionId: string }>('/projects', { method: 'POST', body: input }),
request<{ projectId: string; status: string; executionId: string }>('/projects', {
method: 'POST',
body: input
}),
update: (id: string, input: UpdateProjectInput) =>
request<Project>(`/projects/${encodeURIComponent(id)}`, { method: 'PUT', body: input }),
deleteReadiness: (id: string, signal?: AbortSignal) =>
@@ -17,6 +17,8 @@ const open = ref(false)
const busy = ref(false)
/** 创建请求的错误提示。 */
const error = ref('')
/** 公共表单实例,底栏和回车提交共用同一字段校验。 */
const formRef = ref<InstanceType<typeof AppForm> | null>(null)
/** 与后端 POST /projects 入参一致的创建表单。 */
const form = reactive({ title: '', topic: '', style: '', episodeCount: 1 })
@@ -61,6 +63,7 @@ const rules = {
><NButton @click="open = true" type="primary"><Plus :size="16" />新建剧本</NButton></template
>
<AppForm
ref="formRef"
:model="form"
:rules="rules"
:disabled="busy"
@@ -116,11 +119,10 @@ const rules = {
建议先用 1 集验证生成效果。生成会实际调用后端模型,产生相应费用。
</p>
<NAlert v-if="error" role="alert" type="error" :show-icon="false" class=" ">{{ error }}</NAlert>
</AppForm>
<template #footer>
<NButton :disabled="busy" @click="open = false">取消</NButton>
<NButton :disabled="busy" type="primary" @click="submit">
<NButton :disabled="busy" type="primary" @click="formRef?.validate(submit)">
<LoaderCircle v-if="busy" :size="16" class="animate-spin" />
开始生成
<ArrowRight v-if="!busy" :size="16" />
@@ -53,18 +53,29 @@ async function remove() {
<template>
<AppDialog v-model:open="open" :title="`永久删除 · ${expected}`" description="删除后无法恢复。">
<NAlert type="error" :show-icon="false" class="mt-4">
会永久删除剧本、主体、身份、形态、分镜、首帧、视频、工作流记录,以及本地 Storage 中属于该项目的图片、视频和上传素材。
会永久删除剧本、主体、身份、形态、分镜、首帧、视频、工作流记录,以及本地 Storage
中属于该项目的图片、视频和上传素材。
</NAlert>
<NAlert v-if="readinessPending" type="info" :show-icon="false" class="mt-3">正在检查项目后台任务…</NAlert>
<NAlert v-else-if="readiness && !readiness.canDelete" type="warning" :show-icon="false" class="mt-3">
当前有 {{ readiness.totalActiveTasks }} 个后台任务正在执行,暂不能删除。请等待图片、首帧、视频或工作流任务结束后再试。
当前有
{{ readiness.totalActiveTasks }}
个后台任务正在执行,暂不能删除。请等待图片、首帧、视频或工作流任务结束后再试。
</NAlert>
<NAlert v-if="state.error" type="error" :show-icon="false" class="mt-3">{{ state.error }}</NAlert>
<p class="mt-5 text-xs">请输入 <strong>{{ expected }}</strong> 确认删除:</p>
<p class="mt-5 text-xs">
请输入 <strong>{{ expected }}</strong> 确认删除:
</p>
<NInput v-model:value="state.confirm" class="mt-2" placeholder="输入项目名称" />
<template #footer>
<NButton @click="open = false">取消</NButton>
<NButton type="error" :loading="state.pending" :disabled="!confirmed || readinessPending || !readiness?.canDelete" @click="remove">永久删除项目</NButton>
<NButton
type="error"
:loading="state.pending"
:disabled="!confirmed || readinessPending || !readiness?.canDelete"
@click="remove"
>永久删除项目</NButton
>
</template>
</AppDialog>
</template>
@@ -31,11 +31,23 @@ watch(
{ immediate: true }
)
async function save() {
if (!props.project || state.pending || !dirty.value || !form.title.trim() || !form.topic.trim() || !form.style.trim()) return
if (
!props.project ||
state.pending ||
!dirty.value ||
!form.title.trim() ||
!form.topic.trim() ||
!form.style.trim()
)
return
state.pending = true
state.error = ''
try {
await projectsApi.update(props.project.id, { title: form.title.trim(), topic: form.topic.trim(), style: form.style.trim() })
await projectsApi.update(props.project.id, {
title: form.title.trim(),
topic: form.topic.trim(),
style: form.style.trim()
})
emit('changed')
open.value = false
} catch (cause) {
@@ -46,16 +58,32 @@ async function save() {
}
</script>
<template>
<AppDialog v-model:open="open" :title="`编辑项目 · ${project?.title || project?.topic || ''}`" description="仅更新项目基础信息,不自动重生成剧本或 Production 资产。">
<AppDialog
v-model:open="open"
:title="`编辑项目 · ${project?.title || project?.topic || ''}`"
description="仅更新项目基础信息,不自动重生成剧本或 Production 资产。"
>
<NAlert v-if="state.error" type="error" :show-icon="false" class="mt-4">{{ state.error }}</NAlert>
<section class="dialog-form-stack">
<label class="block text-xs">项目名称<NInput v-model:value="form.title" class="mt-2" /></label>
<label class="block text-xs">故事主题<NInput v-model:value="form.topic" type="textarea" :autosize="{ minRows: 3, maxRows: 8 }" class="mt-2" /></label>
<label class="block text-xs"
>故事主题<NInput
v-model:value="form.topic"
type="textarea"
:autosize="{ minRows: 3, maxRows: 8 }"
class="mt-2"
/></label>
<label class="block text-xs">风格<NInput v-model:value="form.style" class="mt-2" /></label>
</section>
<template #footer>
<NButton @click="open = false">取消</NButton>
<NButton type="primary" :loading="state.pending" :disabled="!dirty || !form.title.trim() || !form.topic.trim() || !form.style.trim()" @click="save">保存项目</NButton>
<NButton
type="primary"
:loading="state.pending"
:disabled="!dirty || !form.title.trim() || !form.topic.trim() || !form.style.trim()"
@click="save"
>保存项目</NButton
>
</template>
</AppDialog>
</template>
+2 -1
View File
@@ -23,7 +23,8 @@ export function useProjectData(id: Ref<string>) {
const projectId = id.value
if (!projectId || !query.data.value) return
const nextReadiness = await projectsApi.stageReadiness(projectId)
if (id.value === projectId && query.data.value) query.data.value = { ...query.data.value, stageReadiness: nextReadiness }
if (id.value === projectId && query.data.value)
query.data.value = { ...query.data.value, stageReadiness: nextReadiness }
}
return { ...query, project, checkpoints, stageReadiness, refreshStageReadiness }
}
+20 -4
View File
@@ -35,8 +35,16 @@ export function useProjectStageAccess(projectId: Ref<string>, readiness: Ref<Pro
state?.visualStyle.reason ||
state?.identity.reason ||
'请先完成主体身份准备',
nextPath: state?.visualStyle.ready ? 'subject-identity' : state?.breakdown.ready ? 'visual-style' : 'breakdown',
nextLabel: state?.visualStyle.ready ? '前往主体身份' : state?.breakdown.ready ? '前往视觉风格' : '前往剧本拆解'
nextPath: state?.visualStyle.ready
? 'subject-identity'
: state?.breakdown.ready
? 'visual-style'
: 'breakdown',
nextLabel: state?.visualStyle.ready
? '前往主体身份'
: state?.breakdown.ready
? '前往视觉风格'
: '前往剧本拆解'
},
storyboard: {
enabled: Boolean(state?.breakdown.ready && state?.subjectAssets.ready),
@@ -51,8 +59,16 @@ export function useProjectStageAccess(projectId: Ref<string>, readiness: Ref<Pro
state?.subjectAssets.reason ||
state?.storyboard.reason ||
'请先完成镜头制作准备',
nextPath: state?.subjectAssets.ready ? 'storyboard' : state?.breakdown.ready ? 'subject-images' : 'breakdown',
nextLabel: state?.subjectAssets.ready ? '前往分镜设计' : state?.breakdown.ready ? '前往形态图片' : '前往剧本拆解'
nextPath: state?.subjectAssets.ready
? 'storyboard'
: state?.breakdown.ready
? 'subject-images'
: 'breakdown',
nextLabel: state?.subjectAssets.ready
? '前往分镜设计'
: state?.breakdown.ready
? '前往形态图片'
: '前往剧本拆解'
}
}
})
+10 -13
View File
@@ -7,7 +7,7 @@ import ActionMenu from '../../components/ui/ActionMenu.vue'
import WorkspaceTools from '../../components/ui/WorkspaceTools.vue'
import { NScrollbar, NAlert, NButton, NCheckbox, NInputNumber, NProgress, NSelect, NTab, NTabs } from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { ArrowLeft, RefreshCw } from '@lucide/vue'
import { ArrowLeft } from '@lucide/vue'
import { EmptyState } from '../../components/ui'
import { downloadText } from '../../lib/format'
import ConfirmAction from '../workflows/ConfirmAction.vue'
@@ -177,15 +177,6 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
</div>
<div class="toolbar-actions">
<div class="flex gap-3">
<NButton
:disabled="query.loading.value"
@click="query.refresh"
quaternary
class="icon-button"
aria-label="刷新分镜"
title="刷新分镜"
><RefreshCw :size="16" :class="{ 'animate-spin': query.loading.value }"
/></NButton>
<ActionMenu
label="分镜更多操作"
:items="[{ key: 'export', label: '导出本集', disabled: !shots.length }]"
@@ -441,7 +432,7 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
<div v-if="!data && query.loading.value" class="panel p-8 text-sm text-muted" role="status">
正在读取正式分镜数据……
</div>
<div v-else-if="shot" class="panel storyboard-workspace workspace-surface">
<div v-else-if="shots.length" class="panel storyboard-workspace workspace-surface">
<nav class="shot-list directory-panel" aria-label="本集镜头">
<div class="directory-heading">
<h3>
@@ -456,7 +447,7 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
>
<BeatShotDirectory
:shots="shots"
:active-id="shot.shotId"
:active-id="shot?.shotId || ''"
item-class="shot-link"
@select="selectedShot = $event"
>
@@ -468,7 +459,7 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
</NScrollbar>
</nav>
<article class="storyboard-detail min-w-0">
<NScrollbar class="panel-scroll" content-class="p-5 lg:p-7">
<NScrollbar v-if="shot" class="panel-scroll" content-class="p-5 lg:p-7">
<header class="mb-6">
<p class="eyebrow">
BEAT {{ shot.beatNo }} / SHOT {{ shot.shotNo }}
@@ -502,6 +493,12 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
</div>
</div>
</NScrollbar>
<!-- 以下是无效镜头地址的定位反馈模块 -->
<EmptyState
v-if="!shot"
title="链接中的镜头已不存在或不属于本集"
description="请在左侧目录重新选择镜头。"
/>
</article>
</div>
<EmptyState
@@ -0,0 +1,67 @@
import { computed, inject, ref, watch } from 'vue'
import { routeLocationKey, routerKey } from 'vue-router'
import type { LocationQueryRaw } from 'vue-router'
import { queryText } from '../production/asset-links'
/**
* 镜头选择与地址同步;初次读取及浏览器导航恢复正式 ID,切集清除上集镜头。
* @param currentEpisode 当前有效剧集,选择镜头时用于补全深链接
* @returns 可写的剧集和镜头选择状态
*/
export function useShotSelection(currentEpisode: () => number) {
/** 当前页面地址,非路由环境保留本地选择。 */
const route = inject(routeLocationKey, undefined)
/** 当前路由导航器,替换选择参数不产生逐镜头历史。 */
const router = inject(routerKey, undefined)
/** 当前选择的剧集,缺省时由页面决定首次有效剧集。 */
const episode = ref<number>()
/** 当前选择的正式镜头 ID。 */
const shotId = ref('')
/** 地址变化只读取选择,不触发反向写入或重置其它参数。 */
watch(
() => [route?.query.episodeNo, route?.query.shotId],
() => {
const number = Number(queryText(route?.query.episodeNo))
episode.value = Number.isSafeInteger(number) && number > 0 ? number : undefined
shotId.value = queryText(route?.query.shotId)
},
{ immediate: true, flush: 'sync' }
)
/**
* 仅替换当前页面的选择参数,保留来源动作、筛选参数与 hash。
* @param query 更新后的地址参数
*/
function replaceSelection(query: LocationQueryRaw) {
if (router && route) void router.replace({ path: route.path, query, hash: route.hash })
}
/** 切换剧集立即清除旧镜头,避免把上集 ID 带到下集。 */
const selectedEpisode = computed({
get: () => episode.value,
set: (number: number | undefined) => {
episode.value = number
shotId.value = ''
const query: LocationQueryRaw = { ...route?.query }
delete query.shotId
if (number && Number.isSafeInteger(number) && number > 0) query.episodeNo = String(number)
else delete query.episodeNo
replaceSelection(query)
}
})
/** 选择镜头同时写入有效剧集和正式 ID,刷新后按地址恢复。 */
const selectedShot = computed({
get: () => shotId.value,
set: (value: string) => {
shotId.value = value.trim()
const query: LocationQueryRaw = { ...route?.query }
const number = currentEpisode()
if (Number.isSafeInteger(number) && number > 0) query.episodeNo = String(number)
if (shotId.value) query.shotId = shotId.value
else delete query.shotId
replaceSelection(query)
}
})
return { selectedEpisode, selectedShot }
}
+8 -7
View File
@@ -1,3 +1,4 @@
import { useShotSelection } from './useShotSelection'
import { useWorkflowExecution } from '../workflows/execution'
import type { StoryboardBatchResult, PromptBatchResult, StoryboardShotRegenerationResult } from './types'
import { computed, ref, watch } from 'vue'
@@ -22,10 +23,8 @@ export function useStoryboard() {
const context = useProjectContext()
/** 当前工作区的响应式状态或派生业务条件。 */
const id = computed(() => context.project.value?.id ?? '')
/** 当前工作区的响应式状态或派生业务条件。 */
const selectedEpisode = ref<number>()
/** 当前工作区的响应式状态或派生业务条件。 */
const selectedShot = ref('')
/** 两个镜头工作区共用地址选择,刷新恢复同一正式镜头。 */
const { selectedEpisode, selectedShot } = useShotSelection(() => episodeNo.value)
/** 当前工作区的响应式状态或派生业务条件。 */
const concurrency = ref(2)
/** 当前工作区的响应式状态或派生业务条件。 */
@@ -88,12 +87,14 @@ export function useStoryboard() {
)
/** 重生成接口未返回新正文时,明确标记辅助剧情信息不可用。 */
const episodeSourceUnavailable = computed(() => !!session.value.invalidatedEpisodeSources[episodeNo.value])
/** 当前工作区的响应式状态或派生业务条件。 */
/** 当前剧集的正式镜头目录。 */
const shots = computed(() =>
mergeDesignedShots(data.value?.directions ?? null, data.value?.visualStates ?? null, source.value)
)
/** 当前工作区的响应式状态或派生业务条件。 */
const shot = computed(() => shots.value.find(item => item.shotId === selectedShot.value) ?? shots.value[0])
/** 明确指定的镜头不存在时不代选其它镜头;首次进入才选择第一镜。 */
const shot = computed(() =>
selectedShot.value ? shots.value.find(item => item.shotId === selectedShot.value) : shots.value[0]
)
/** 当前工作区的响应式状态或派生业务条件。 */
const prerequisites = computed(() => storyboardPrerequisites(context.checkpoints.value, episodeNo.value))
/** 当前工作区的响应式状态或派生业务条件。 */
@@ -18,7 +18,7 @@ import {
} from 'naive-ui'
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Check, Circle, RefreshCw, UserCheck } from '@lucide/vue'
import { Check, Circle, UserCheck } from '@lucide/vue'
import { AssetImage, DirectoryItem, EmptyState, StatusBadge } from '../../components/ui'
import { downloadText } from '../../lib/format'
import ConfirmAction from '../workflows/ConfirmAction.vue'
@@ -154,12 +154,6 @@ function exportReceipt() {
downloadText('subject-identities-receipt.json', JSON.stringify(session.value.receipt, null, 2), 'application/json')
}
/** 目录刷新同时读取正式形态和 Character Casting,避免无形态角色状态滞后。 */
function refreshDirectory() {
thumbnailRefreshKey.value++
void Promise.all([catalog.refresh(), castingQuery.refresh()])
}
/** Character 使用确认选角事务;Scene / Prop 保留普通母版切换。 */
async function submitIdentityImage(input: Parameters<typeof generateImage>[0]) {
await generateImage(input)
@@ -273,8 +267,8 @@ const nextAction = computed<{ action: IdentityFlowAction; title: string; descrip
}
})
/** 原配置恢复入口打开标题栏共用的全局配置弹窗。 */
function openProfileSettings() {
toolsOpen.value = true
if (route.query.configure !== 'profile') void router.replace({ query: { ...route.query, configure: 'profile' } })
}
@@ -301,14 +295,6 @@ async function profileSaved() {
operation.value.error = ''
await profileQuery.refresh()
}
watch(
() => route.query.configure,
value => {
if (value === 'profile') openProfileSettings()
},
{ immediate: true }
)
</script>
<template>
@@ -343,7 +329,11 @@ watch(
title="角色选角总览与批量操作"
:has-receipt="!!session.receipt"
>
<CreativeProfileSettings :project-id="projectId" @saved="profileSaved" />
<CreativeProfileSettings
:project-id="projectId"
:disabled="operation.pending"
@saved="profileSaved"
/>
<div class="identity-tools-intro flex flex-wrap items-end justify-between gap-4">
<div>
<h2 class="text-lg font-semibold">主体身份</h2>
@@ -633,16 +623,6 @@ watch(
<h3>
主体目录 <span>{{ filtered.length }} / {{ subjects.length }}</span>
</h3>
<NButton
:disabled="catalog.loading.value || castingQuery.loading.value"
@click="refreshDirectory"
quaternary
class="icon-button"
size="small"
aria-label="刷新主体目录"
title="刷新主体目录"
><template #icon><RefreshCw :size="14" /></template
></NButton>
</div>
<div class="directory-filters">
<NInput
@@ -4,11 +4,7 @@ import { computed, ref, watch } from 'vue'
import { AppDialog } from '../../../components/ui'
import AppForm from '../../../components/ui/AppForm.vue'
import GenerationModelControls from '../../generation-config/components/GenerationModelControls.vue'
import type {
CreativeProfile,
GenerationModelCatalog,
GenerationOptions
} from '../../generation-config/types'
import type { CreativeProfile, GenerationModelCatalog, GenerationOptions } from '../../generation-config/types'
import type { GenerateCastingCandidateInput } from '../types'
/** Character 选角候选表单固定使用 primary,每次独立生成且不会自动选择演员。 */
@@ -32,7 +28,8 @@ const valid = computed(() => Boolean(provider.value))
function reset() {
prompt.value = ''
provider.value = props.profile.imageProvider
const selected = props.catalog.images.find(item => item.provider === props.profile.imageProvider && item.enabled) ??
const selected =
props.catalog.images.find(item => item.provider === props.profile.imageProvider && item.enabled) ??
props.catalog.images.find(item => item.enabled)
provider.value = selected?.provider ?? ''
generationOptions.value = {
@@ -40,7 +37,10 @@ function reset() {
...(selected?.provider === props.profile.imageProvider ? props.profile.imageOptions : {})
}
const sizeSchema = selected?.generationOptions.find(item => item.key === 'size')
if (sizeSchema?.options?.length && !sizeSchema.options.some(option => option.value === generationOptions.value.size)) {
if (
sizeSchema?.options?.length &&
!sizeSchema.options.some(option => option.value === generationOptions.value.size)
) {
generationOptions.value.size = selected?.defaults.size ?? sizeSchema.options[0]?.value ?? ''
}
acknowledged.value = false
@@ -110,15 +110,15 @@ const formModel = computed(() => ({ prompt: prompt.value }))
</NCheckbox>
</AppForm>
<template #footer>
<NButton @click="open = false">取消</NButton>
<NButton
:disabled="disabled || !valid || !acknowledged"
:loading="disabled"
type="primary"
@click="formRef?.validate(submit)"
>
{{ disabled ? '生成中…' : '确认生成候选' }}
</NButton>
<NButton @click="open = false">取消</NButton>
<NButton
:disabled="disabled || !valid || !acknowledged"
:loading="disabled"
type="primary"
@click="formRef?.validate(submit)"
>
{{ disabled ? '生成中…' : '确认生成候选' }}
</NButton>
</template>
</AppDialog>
</template>
@@ -6,7 +6,7 @@ import { NFormItem } from 'naive-ui'
import { fieldRule } from '../../../lib/form-rules'
import { NAlert, NButton, NCheckbox, NInput, NSelect } from 'naive-ui'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { AppDialog } from '../../../components/ui'
import { AppDialog, FieldLabel } from '../../../components/ui'
import GenerationModelControls from '../../generation-config/components/GenerationModelControls.vue'
import type { CreativeProfile, GenerationModelCatalog, GenerationOptions } from '../../generation-config/types'
import { subjectIdentityApi } from '../api'
@@ -197,7 +197,14 @@ const rules = {
path="referenceImageId"
label="身份锚定来源"
:label-props="{ for: 'identity-reference' }"
><NSelect
>
<template #label>
<FieldLabel
label="身份锚定来源"
description="只能选择此主体已完成的图片。后端需取得图片服务可访问的远程地址;本地预览可见不保证远程地址仍有效。"
/>
</template>
<NSelect
id="identity-reference"
v-model:value="referenceImageId"
:options="[
@@ -213,9 +220,6 @@ const rules = {
class="select-control"
></NSelect
></NFormItem>
<p class="text-xs leading-6 text-muted">
只能选择此主体已完成的图片。后端需取得 Provider 可访问的远程地址;本地预览可见不保证远程地址仍有效。
</p>
<NFormItem
class="block"
path="prompt"
@@ -1,6 +1,7 @@
import { computed, ref, watch } from 'vue'
import { usePolling } from '../../composables/usePolling'
import { visualStyleApi } from '../visual-style'
import { useProjectGenerationRevision } from '../generation-config/context'
import { generationConfigApi } from '../generation-config/api'
import { subjectImagesApi } from '../subject-images/api'
import { hasRunningImages } from '../subject-images/model'
@@ -35,7 +36,7 @@ export function useSubjectIdentity() {
const concurrency = ref(3)
const candidateLimit = ref(3)
const force = ref(false)
/** 目录与身份已有刷新按钮,查询只在进入、切换和手动刷新时读取。 */
/** 主体与模型查询只在进入、切换和自身操作完成后读取。 */
const generationModelsQuery = usePolling(
projectId,
async (_id, signal) => generationConfigApi.catalog(signal),
@@ -67,9 +68,17 @@ export function useSubjectIdentity() {
},
false
)
/** 全局配置成功保存后重新读取主体生图的实际默认参数。 */
const generationRevision = useProjectGenerationRevision()
/** 配置查询按当前项目和修订号隔离。 */
const profileKey = computed(() => JSON.stringify([projectId.value, generationRevision.value]))
/** 主体身份使用保存后的正式项目配置。 */
const profileQuery = usePolling(
projectId,
async (id, signal) => ({ profile: await generationConfigApi.profile(id, signal) }),
profileKey,
async (key, signal) => {
const [id] = JSON.parse(key) as [string, number]
return { profile: await generationConfigApi.profile(id, signal) }
},
false
)
const castingQuery = usePolling(
@@ -6,30 +6,10 @@ import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import ActionMenu from '../../components/ui/ActionMenu.vue'
import DetailDisclosure from '../../components/ui/DetailDisclosure.vue'
import WorkspaceTools from '../../components/ui/WorkspaceTools.vue'
import {
NAlert,
NButton,
NCheckbox,
NInput,
NInputNumber,
NPopover,
NScrollbar,
NSelect,
NTag
} from 'naive-ui'
import { NAlert, NButton, NCheckbox, NInput, NInputNumber, NPopover, NScrollbar, NSelect, NTag } from 'naive-ui'
import { computed, onScopeDispose, ref, watch, type Directive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
Search,
RefreshCw,
Download,
ImagePlus,
ArrowLeft,
ArrowRight,
LayoutGrid,
Columns3,
Settings2
} from '@lucide/vue'
import { Search, Download, ImagePlus, ArrowLeft, ArrowRight, LayoutGrid, Columns3, Settings2 } from '@lucide/vue'
import { AssetImage, EmptyState, StatusBadge } from '../../components/ui'
import { downloadText } from '../../lib/format'
import ConfirmAction from '../workflows/ConfirmAction.vue'
@@ -377,60 +357,60 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
</p>
</div>
<p class="mt-2 text-[11px] leading-6 text-muted">
图库不自动刷新,可点击“刷新图库”读取最新记录。主图供分镜引用,候选图和历史失败记录均保留;过期主图不会自动删除或替换。
图库在进入和操作完成后读取最新记录。主图供分镜引用,候选图和历史失败记录均保留;过期主图不会自动删除或替换。
</p>
<section class="mt-4 pt-4">
<h3 class="text-sm font-semibold">项目批量生图</h3>
<AppForm :model="formModel" :rules="rules" :disabled="operation.pending" validate-on-change>
<div class="form-controls mt-4 flex flex-wrap gap-4">
<NFormItem
class="w-28"
path="concurrency"
label="批量并发"
:label-props="{ for: 'image-concurrency' }"
>
<NInputNumber
:disabled="operation.pending"
:input-props="{ id: 'image-concurrency' }"
:value="typeof concurrency === 'number' ? concurrency : null"
@update:value="concurrency = $event ?? 0"
:min="1"
:step="1"
></NInputNumber>
</NFormItem>
<NFormItem class="w-36" path="limit" label="本批上限(可选)"
><NInputNumber
:disabled="operation.pending"
:value="typeof limit === 'number' ? limit : null"
@update:value="limit = $event ?? ''"
:min="1"
:step="1"
placeholder="不限制"
:input-props="{ 'aria-label': '生图本批上限' }"
/></NFormItem>
<NCheckbox
v-model:checked="force"
<h3 class="text-sm font-semibold">项目批量生图</h3>
<AppForm :model="formModel" :rules="rules" :disabled="operation.pending" validate-on-change>
<div class="form-controls mt-4 flex flex-wrap gap-4">
<NFormItem
class="w-28"
path="concurrency"
label="批量并发"
:label-props="{ for: 'image-concurrency' }"
>
<NInputNumber
:disabled="operation.pending"
class="control-row-checkbox text-xs"
>已有主图也新增候选图
</NCheckbox>
<ConfirmAction
:label="force ? '为全项目新增候选图' : '补齐项目主参考图'"
:disabled="blocked || running || !batchValid || !forms.length"
acknowledgement
:description="
force
? '对项目全部形态调用图片模型新增一张图片。已有主图不会被替换,生成后可在图片记录中手动选择主图。'
: '对缺少主图或主图已过期的形态调用图片模型,仍有效的主图跳过。已有过期主图不会被自动替换,生成后请在图片记录中确认新主图。操作面向整个项目,不受列表筛选影响。'
"
@confirm="generateProject"
/>
</div>
</AppForm>
<p class="mt-3 text-xs leading-6 text-muted">
作用于整个项目,不受下方筛选影响。上限只限制本次真正生图数量,其余显示为“待后续处理”,不计入跳过。默认使用项目尺寸与正式提示词,不会启动视频生成。
</p>
</section>
:input-props="{ id: 'image-concurrency' }"
:value="typeof concurrency === 'number' ? concurrency : null"
@update:value="concurrency = $event ?? 0"
:min="1"
:step="1"
></NInputNumber>
</NFormItem>
<NFormItem class="w-36" path="limit" label="本批上限(可选)"
><NInputNumber
:disabled="operation.pending"
:value="typeof limit === 'number' ? limit : null"
@update:value="limit = $event ?? ''"
:min="1"
:step="1"
placeholder="不限制"
:input-props="{ 'aria-label': '生图本批上限' }"
/></NFormItem>
<NCheckbox
v-model:checked="force"
:disabled="operation.pending"
class="control-row-checkbox text-xs"
>已有主图也新增候选图
</NCheckbox>
<ConfirmAction
:label="force ? '为全项目新增候选图' : '补齐项目主参考图'"
:disabled="blocked || running || !batchValid || !forms.length"
acknowledgement
:description="
force
? '对项目全部形态调用图片模型新增一张图片。已有主图不会被替换,生成后可在图片记录中手动选择主图。'
: '对缺少主图或主图已过期的形态调用图片模型,仍有效的主图跳过。已有过期主图不会被自动替换,生成后请在图片记录中确认新主图。操作面向整个项目,不受列表筛选影响。'
"
@confirm="generateProject"
/>
</div>
</AppForm>
<p class="mt-3 text-xs leading-6 text-muted">
作用于整个项目,不受下方筛选影响。上限只限制本次真正生图数量,其余显示为“待后续处理”,不计入跳过。默认使用项目尺寸与正式提示词,不会启动视频生成。
</p>
</section>
</div>
<section v-if="session.receipt" class="panel workspace-panel" aria-label="生图批量回执">
<div class="flex items-center justify-between gap-3">
@@ -598,25 +578,7 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
</template>
瀑布流布局
</NPopover>
<NPopover trigger="hover" placement="top" :disabled="isMobile">
<template #trigger>
<NButton
class="icon-button gallery-action-button"
size="small"
:disabled="query.loading.value || impact.query.loading.value"
aria-label="刷新图库"
@click="refreshAssets"
>
<template #icon>
<RefreshCw
:size="16"
:class="{ 'animate-spin': query.loading.value }"
/>
</template>
</NButton>
</template>
刷新图库
</NPopover>
<NPopover trigger="hover" placement="top" :disabled="isMobile">
<template #trigger>
<NButton
@@ -808,11 +770,11 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
/>
<NButton :disabled="blocked || hasRunningImages(form.images)" @click="openGenerate(form)"
><ImagePlus :size="14" />
{{
form.images.some(image => image.status === 'completed' && image.imageUrl)
? '再生成一张'
: '生成图片'
}}</NButton
{{
form.images.some(image => image.status === 'completed' && image.imageUrl)
? '再生成一张'
: '生成图片'
}}</NButton
>
</div>
</div>
@@ -35,7 +35,8 @@ watch(
() => [open.value, props.form?.id],
() => {
prompt.value = ''
const selected = props.catalog.images.find(item => item.provider === props.profile.imageProvider && item.enabled) ??
const selected =
props.catalog.images.find(item => item.provider === props.profile.imageProvider && item.enabled) ??
props.catalog.images.find(item => item.enabled)
provider.value = selected?.provider ?? ''
generationOptions.value = {
@@ -43,7 +44,10 @@ watch(
...(selected?.provider === props.profile.imageProvider ? props.profile.imageOptions : {})
}
const sizeSchema = selected?.generationOptions.find(item => item.key === 'size')
if (sizeSchema?.options?.length && !sizeSchema.options.some(option => option.value === generationOptions.value.size)) {
if (
sizeSchema?.options?.length &&
!sizeSchema.options.some(option => option.value === generationOptions.value.size)
) {
generationOptions.value.size = selected?.defaults.size ?? sizeSchema.options[0]?.value ?? ''
}
acknowledged.value = false
@@ -189,14 +193,14 @@ const rules = {}
>
</AppForm>
<template #footer>
<NButton @click="open = false">取消</NButton
><NButton
:disabled="disabled || !form || !provider || !acknowledged"
type="primary"
@click="formRef?.validate(submit)"
>
确认生成图片
</NButton>
<NButton @click="open = false">取消</NButton
><NButton
:disabled="disabled || !form || !provider || !acknowledged"
type="primary"
@click="formRef?.validate(submit)"
>
确认生成图片
</NButton>
</template>
</AppDialog>
</template>
+19 -13
View File
@@ -4,6 +4,7 @@ import { ApiError } from '../../lib/http'
import { useProjectContext } from '../projects/context'
import { getOperation, runOperation } from '../workflows/operations'
import { workflowCheckpoints } from '../workflows/selectors'
import { useProjectGenerationRevision } from '../generation-config/context'
import { generationConfigApi } from '../generation-config/api'
import { subjectImagesApi } from './api'
import { getImageSession, hasRunningImages } from './model'
@@ -24,18 +25,26 @@ export function useSubjectImages() {
const promptConcurrency = ref(3)
const promptForce = ref(false)
const batchModule = ref<'all' | SubjectModule>('all')
const generationModelsQuery = usePolling(
id,
async (_id, signal) => generationConfigApi.catalog(signal),
false
)
const generationModelsQuery = usePolling(id, async (_id, signal) => generationConfigApi.catalog(signal), false)
/** 项目配置保存后重新读取实际默认参数,避免图库生图沿用旧模型。 */
const generationRevision = useProjectGenerationRevision()
/** 配置查询按项目和保存修订号隔离。 */
const profileKey = computed(() => JSON.stringify([id.value, generationRevision.value]))
/** 当前图库使用后端最新保存的项目配置。 */
const profileQuery = usePolling(
id,
async (projectId, signal) => ({ profile: await generationConfigApi.profile(projectId, signal) }),
profileKey,
async (key, signal) => {
const [projectId] = JSON.parse(key) as [string, number]
return { profile: await generationConfigApi.profile(projectId, signal) }
},
false
)
const queryRef = {} as { current?: ReturnType<typeof usePolling<Awaited<ReturnType<typeof subjectImagesApi.listForms>>>> }
const pollInterval = computed(() => queryDataHasRunningImages(queryRef.current?.data.value ?? null) ? 4000 : false)
const queryRef = {} as {
current?: ReturnType<typeof usePolling<Awaited<ReturnType<typeof subjectImagesApi.listForms>>>>
}
const pollInterval = computed(() =>
queryDataHasRunningImages(queryRef.current?.data.value ?? null) ? 4000 : false
)
const query = usePolling(
id,
async (projectId, signal) => {
@@ -53,10 +62,7 @@ export function useSubjectImages() {
return forms
} catch (error) {
if (error instanceof ApiError && error.status === 404)
throw new Error(
'暂时无法读取形态图片,请稍后重试。',
{ cause: error }
)
throw new Error('暂时无法读取形态图片,请稍后重试。', { cause: error })
throw error
}
},
+33 -39
View File
@@ -2,7 +2,7 @@
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import DetailDisclosure from '../../components/ui/DetailDisclosure.vue'
import { NAlert, NButton } from 'naive-ui'
import { LoaderCircle, LockKeyhole, LockKeyholeOpen, Palette, RefreshCw, TriangleAlert } from '@lucide/vue'
import { LoaderCircle, LockKeyhole, LockKeyholeOpen, Palette, TriangleAlert } from '@lucide/vue'
import { computed, ref } from 'vue'
import { useQuery } from '../../composables/useQuery'
import { runOperation } from '../workflows/operations'
@@ -32,7 +32,7 @@ const nextReady = computed(() => projectContext.stageReadiness.value?.visualStyl
/** 状态是只读说明,与操作按钮分组;读取失败不能被误报成尚未创建。 */
const statusInfo = computed(() => {
if (query.error.value) return { label: '读取失败', hint: '请刷新重试,现有内容不会被覆盖', icon: TriangleAlert }
if (query.error.value) return { label: '读取失败', hint: '请重试读取,现有内容不会被覆盖', icon: TriangleAlert }
if (!query.data.value) return { label: '正在读取', hint: '正在获取项目视觉风格', icon: LoaderCircle }
if (!style.value) return { label: '尚未创建', hint: '可使用 AI 生成,或在下方手动填写', icon: Palette }
return style.value.isLocked
@@ -126,52 +126,46 @@ function removeImage(image: VisualStyleImage) {
description="调用文本模型生成整体及分类风格。重新生成会覆盖已保存的文本与硬约束;旧身份、旧图片和已有提示词不会自动更新。"
@confirm="generate"
/>
<NButton
:loading="query.loading.value"
@click="query.refresh"
quaternary
class="icon-button"
aria-label="刷新风格"
title="刷新风格"
><template #icon><RefreshCw :size="16" /></template
></NButton>
</div>
</div>
</template>
<template #notice>
<NAlert v-if="nextReady" type="success" :show-icon="false">
视觉风格已准备好,可以继续确认人物、场景和道具的主体身份。
<RouterLink :to="`/projects/${projectId}/subject-identity`" class="text-button ml-2">继续主体身份 →</RouterLink>
<RouterLink :to="`/projects/${projectId}/subject-identity`" class="text-button ml-2"
>继续主体身份 →</RouterLink
>
</NAlert>
</template>
<div class="workspace-section-stack">
<NAlert v-if="query.error.value" role="alert" type="error" :show-icon="false"
>{{ query.error.value }} 当前内容读取失败,请刷新后重试;已有内容不会被覆盖。
</NAlert>
<p v-if="dirty" class="mb-4 text-xs text-muted">
有未保存修改,AI 重生成暂不可用。刷新不会覆盖编辑内容;离开页面不会自动保存。
</p>
<DetailDisclosure title="风格生成规则" >
AI
生成时,若项目和世界观没有明确其它人物背景,人物风格默认采用中国人物选角基线;人工填写的人物背景和角色事实优先。修改风格只影响之后的生成,旧资产不会自动更新。 </DetailDisclosure
><StyleEditor
v-if="query.data.value"
:key="editorRevision"
:visual-style="style"
:disabled="disabled"
@save="save"
@dirty="dirty = $event" />
<p v-else-if="query.loading.value" class="py-8 text-sm text-muted" role="status">正在读取视觉风格…</p>
<StyleImages
:key="imageRevision"
:project-id="projectId"
:images="style?.images ?? []"
:disabled="disabled || !style"
@add="addImage"
@toggle="toggleImage"
@remove="removeImage"
/>
<NAlert v-if="query.error.value" role="alert" type="error" :show-icon="false"
>{{ query.error.value }} 当前内容读取失败;已有内容不会被覆盖。
<NButton text class="ml-3" :loading="query.loading.value" @click="query.refresh">重试读取</NButton>
</NAlert>
<p v-if="dirty" class="mb-4 text-xs text-muted">
有未保存修改,AI 重生成暂不可用。刷新不会覆盖编辑内容;离开页面不会自动保存。
</p>
<DetailDisclosure title="风格生成规则">
AI
生成时,若项目和世界观没有明确其它人物背景,人物风格默认采用中国人物选角基线;人工填写的人物背景和角色事实优先。修改风格只影响之后的生成,旧资产不会自动更新。 </DetailDisclosure
><StyleEditor
v-if="query.data.value"
:key="editorRevision"
:visual-style="style"
:disabled="disabled"
@save="save"
@dirty="dirty = $event"
/>
<p v-else-if="query.loading.value" class="py-8 text-sm text-muted" role="status">正在读取视觉风格…</p>
<StyleImages
:key="imageRevision"
:project-id="projectId"
:images="style?.images ?? []"
:disabled="disabled || !style"
@add="addImage"
@toggle="toggleImage"
@remove="removeImage"
/>
</div>
</WorkspacePage>
</template>
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NAlert, NButton, NCollapse, NCollapseItem, NInput, NSelect, NTab, NTabs } from 'naive-ui'
import { Download, RefreshCw, Search } from '@lucide/vue'
import { Download, Search } from '@lucide/vue'
import { AppDialog, EmptyState } from '../../components/ui'
import { usePolling } from '../../composables/usePolling'
import { downloadText, formatDate, nodeLabel } from '../../lib/format'
@@ -96,13 +96,7 @@ function exportReport() {
<div class="flex items-center gap-2">
<NButton :disabled="!query.data.value" @click="exportReport"
><template #icon><Download :size="14" /></template>导出诊断</NButton
><NButton
class="icon-button"
:loading="query.loading.value"
aria-label="刷新运行诊断"
@click="query.refresh"
><template #icon><RefreshCw :size="16" /></template
></NButton>
>
</div>
</div>
<div class="diagnostics-filters mt-5">
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NAlert, NButton, NProgress, NTag } from 'naive-ui'
import { RefreshCw, X } from '@lucide/vue'
import { X } from '@lucide/vue'
import { formatDate } from '../../lib/format'
import { executionPercentage, executionStageLabel } from './execution'
import type { WorkflowExecution } from './execution.types'
@@ -88,14 +88,6 @@ function isInputMode(value: unknown, inputMode: string): boolean {
</div>
<div class="flex items-center gap-2">
<NButton
class="icon-button"
quaternary
:loading="loading"
aria-label="刷新制作任务状态"
title="刷新制作任务状态"
@click="emit('refresh')"
><RefreshCw :size="15" /></NButton
><NButton
v-if="finished || error"
class="icon-button"
quaternary
@@ -172,7 +164,8 @@ function isInputMode(value: unknown, inputMode: string): boolean {
</details>
</template>
<NAlert v-if="error" type="error" :show-icon="false" class="mt-3">
{{ error }}。任务可能仍在运行,请先点击刷新;不要直接重复提交。
{{ error }}。任务可能仍在运行,请先重新读取状态;不要直接重复提交。
<NButton text class="ml-3" :loading="loading" @click="emit('refresh')">重试读取</NButton>
</NAlert>
</section>
</template>
+4 -1
View File
@@ -3,7 +3,10 @@ import { NSelect } from 'naive-ui'
/** 工作区工具弹窗通过真实 Teleport 挂到 body,测试从外层读取,不禁用 Teleport 掩盖挂载问题。 */
export function drawerPanel() {
return new DOMWrapper(document.body).get<HTMLElement>('.workspace-tools-modal')
const body = document.querySelector<HTMLElement>('.workspace-tools-body')
const modal = body?.closest<HTMLElement>('.app-dialog')
if (!modal) throw new Error('工作区工具弹窗未打开')
return new DOMWrapper(modal)
}
/** 通过真实菜单触发器访问低频功能,不直接调用组件内部方法绕过可见性。 */
+16 -9
View File
@@ -169,7 +169,9 @@ describe('全站平面主题', () => {
expect(css).toMatch(/\.asset-impact-links\s*\{[^}]*width:\s*max-content;[^}]*white-space:\s*nowrap;/)
expect(css).toMatch(/\.gallery-sticky-controls > \.form-image-filter-region\s*\{[^}]*margin-block:\s*0;/)
// 间距归列表所有,吸顶时底部不留固定色带。
expect(css).toMatch(/\.gallery-workspace-page \.form-image-grid\s*\{[^}]*padding-top:\s*12px;/)
expect(css).toMatch(
/\.gallery-workspace-page \.form-image-grid\s*\{[^}]*padding-top:\s*var\(--app-content-gap\);/
)
const sticky = css.match(/\.gallery-workspace-page \.gallery-sticky-controls\s*\{([^}]*)\}/)?.[1]
expect(sticky).not.toMatch(/padding|border-bottom|::after/)
expect(css).toMatch(
@@ -177,7 +179,7 @@ describe('全站平面主题', () => {
)
expect(css).toMatch(/\.asset-impact-links-scroll\.n-scrollbar\s*\{[^}]*height:\s*auto;[^}]*max-width:\s*100%;/)
expect(readFileSync('src/features/subject-images/SubjectImagesPage.vue', 'utf8')).toMatch(
/<WorkspacePage\b[^>]*>\s*<template #default>/
/<WorkspacePage\b[^>]*>[\s\S]*?<template #default>/
)
})
@@ -205,10 +207,8 @@ describe('全站平面主题', () => {
const source = readFileSync('src/features/subject-images/SubjectImagesPage.vue', 'utf8')
expect(source).not.toContain('class="toolbar-summary"')
expect(source).toMatch(/<WorkspaceTools\s+triggerless/)
expect(source.match(/<NPopover trigger="hover" placement="top" :disabled="isMobile">/g)).toHaveLength(4)
expect(source).toMatch(/aria-label="网格布局"/)
expect(source).toMatch(/aria-label="瀑布流布局"/)
expect(source).toMatch(/aria-label="刷新图库"/)
expect(source).toMatch(/data-workspace-tools\s+aria-label="批量生图"/)
expect(source).not.toContain('title="网格布局"')
expect(source).not.toContain('title="瀑布流布局"')
@@ -239,7 +239,6 @@ describe('全站平面主题', () => {
expect(css).toMatch(
/\.gallery-layout-switch \.layout-option-button:not\(\.layout-option-active\),\s*\.gallery-layout-switch \.gallery-action-button\s*\{[^}]*background:\s*var\(--app-control-hover\);/
)
expect(source.match(/class="icon-button gallery-action-button"/g)).toHaveLength(2)
expect(css).toMatch(
/\.gallery-layout-switch\s*\{[^}]*display:\s*flex;[^}]*align-items:\s*center;[^}]*gap:\s*8px;/
)
@@ -262,15 +261,17 @@ describe('全站平面主题', () => {
for (const file of [
'src/App.vue',
'src/components/ui/ThemeToggle.vue',
'src/components/ui/WorkspaceTools.vue',
'src/features/projects/ProjectsPage.vue',
'src/features/subject-identity/SubjectIdentityPage.vue'
'src/features/subject-images/SubjectImagesPage.vue'
]) {
const source = readFileSync(file, 'utf8')
expect(source).toContain('icon-button')
expect(source).not.toMatch(/<NButton\b[^>]*\bcircle\b/)
}
expect(readFileSync('src/components/ui/DirectoryItem.vue', 'utf8')).not.toContain('icon-button')
expect(readFileSync('src/components/ui/WorkspaceTools.vue', 'utf8')).not.toContain('icon-button')
const projects = readFileSync('src/features/projects/ProjectsPage.vue', 'utf8')
expect(projects).not.toContain('aria-label="刷新项目"')
expect(projects).not.toMatch(/<NButton\b[^>]*\bcircle\b/)
})
it('风格参考图操作按钮与输入行对齐,缩略图在宽屏下保持紧凑', () => {
@@ -285,7 +286,13 @@ describe('全站平面主题', () => {
// happy-dom 不计算布局;此项保护 CSS 契约,不能替代浏览器视觉验收。
const css = readAllStyles()
expect(css).not.toMatch(/border-radius:\s*[1-9]/)
expect(css).not.toMatch(/border(?:-[\w]+)?:\s*1px (?:solid|dashed) var\(--(?:app-border|color-line)\)/)
// 主体身份的新流程用单条分隔线区分下一步操作,普通业务面板仍保持平面表面。
const separators = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)]
.filter(([, , declarations]) =>
/border(?:-[\w]+)?:\s*1px (?:solid|dashed) var\(--(?:app-border|color-line)\)/.test(declarations!)
)
.map(([, selector]) => selector!.trim())
expect(separators).toEqual(['.identity-next-action'])
expect(css).toMatch(/\.surface-inset\s*\{[^}]*background:\s*var\(--app-subtle\)/)
expect(css).toMatch(/\.record-list > article:nth-child\(even\)\s*\{\s*background:/)
expect(css).toMatch(/\.directory-group-heading\s*\{[^}]*background:\s*var\(--app-control\)/)
+53 -32
View File
@@ -1,7 +1,8 @@
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { defineComponent, h, reactive } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NFormItem, NInput } from 'naive-ui'
import { NFormItem, NInput, NSelect } from 'naive-ui'
import AppForm from '@/components/ui/AppForm.vue'
import CreateProjectDialog from '@/features/projects/components/CreateProjectDialog.vue'
import GenerateImageDialog from '@/features/subject-images/components/GenerateImageDialog.vue'
@@ -10,22 +11,8 @@ import StyleImages from '@/features/visual-style/components/StyleImages.vue'
import { formFixture } from '@/features/subject-images/testing/fixtures'
import { requiredTextRule } from '@/lib/form-rules'
const imageCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [{
type: 'image' as const, provider: 'qwen-image', providerLabel: 'Qwen', model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image', supported: true as const, enabled: true, isDefault: true, capabilities: {},
generationOptions: [{ key: 'size', label: '图片尺寸', type: 'size' as const, required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }] }],
defaults: { size: '2048*2048' }, projectConstraints: []
}],
videos: []
}
const creativeProfile = {
projectId: 'gallery-test', aspectRatio: '1:1' as const, imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro', imageOptions: { size: '2048*2048' },
videoProvider: 'seedance', videoModel: 'seedance', videoOptions: {}
}
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
@@ -34,6 +21,11 @@ afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
/**
* 查找真实弹窗的可见操作按钮。
* @param text 按钮完整文案
* @returns 实际按钮元素
*/
function button(text: string) {
const result = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
el => el.textContent?.trim() === text
@@ -41,15 +33,29 @@ function button(text: string) {
if (!result) throw new Error(`找不到按钮:${text}`)
return result
}
/**
* 更新真实表单字段并等待 Vue 绑定同步。
* @param selector 字段选择器
* @param value 本次输入值
* @returns 字段绑定同步完成
*/
async function input(selector: string, value: string) {
const el = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(selector)!
el.value = value
el.dispatchEvent(new Event('input', { bubbles: true }))
await flushPromises()
}
/**
* 汇总实际字段错误反馈。
* @returns 当前全部校验错误文案
*/
function feedback() {
return [...document.querySelectorAll('.n-form-item-feedback--error')].map(el => el.textContent).join(' ')
}
/**
* 提交实际表单以执行统一字段校验。
* @returns 表单校验与响应同步完成
*/
async function submit() {
document.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await flushPromises()
@@ -57,25 +63,30 @@ async function submit() {
describe('统一的 Naive UI 表单校验', () => {
it('新建剧本使用字段反馈拦截空白主题和小数集数,修正后只发送一次请求', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response('{"projectId":"created","status":"generating"}', { status: 202 }))
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
new Response('{"projectId":"created","executionId":"create-execution-1","status":"pending"}', {
status: 202
})
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(CreateProjectDialog, { attachTo: document.body })
button('新建剧本').click()
await flushPromises()
expect(document.querySelector('form')!.noValidate).toBe(true)
expect(document.querySelector('[required]')).toBeNull()
await input('#title', ' 雨夜来信标题 ')
await input('#topic', ' ')
const focus = vi.spyOn(HTMLTextAreaElement.prototype, 'focus')
await submit()
button('开始生成').click()
await flushPromises()
expect(feedback()).toContain('请填写故事主题')
// 无布局的 DOM 环境会被模态框焦点圈带回哨兵,检查实际聚焦目标。
expect(focus.mock.contexts).toContain(document.querySelector('#topic'))
expect(fetcher).not.toHaveBeenCalled()
await input('#topic', ' 雨夜来信 ')
await input('#episode-count', '1.5')
await submit()
button('开始生成').click()
await flushPromises()
expect(feedback()).toContain('计划集数须为正整数')
expect(fetcher).not.toHaveBeenCalled()
await input('#episode-count', '3')
@@ -84,24 +95,34 @@ describe('统一的 Naive UI 表单校验', () => {
button('开始生成').click()
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(1)
expect(wrapper.emitted('created')).toEqual([['created']])
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({
title: '雨夜来信标题',
topic: '雨夜来信',
style: '',
episodeCount: 3
})
expect(wrapper.emitted('created')).toEqual([['created', 'create-execution-1']])
})
it('图片宽高错误显示在两侧字段,补全后同时消失,切换目标清除校验状态', async () => {
it('图片尺寸采用目录必填枚举,切换目标清空提示词和费用确认', async () => {
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form: formFixture(), disabled: false, catalog: imageCatalog, profile: creativeProfile }
})
await flushPromises()
await input('#image-width', '1024')
expect(document.querySelectorAll('.n-form-item-feedback--error')).toHaveLength(2)
expect(feedback()).toContain('宽高须同时填写正整数')
await input('#image-height', '768')
expect(feedback()).toBe('')
await input('#image-height', '')
expect(feedback()).not.toBe('')
await wrapper.setProps({ form: formFixture('other') })
const size = wrapper.findAllComponents(NSelect).find(select => select.props('value') === '2048*2048')!
expect(size.props('clearable')).toBe(false)
expect(size.props('options')).toEqual([{ label: '1:1 · 2048×2048', value: '2048*2048' }])
expect(document.querySelector('#image-width')).toBeNull()
expect(document.querySelector('#image-height')).toBeNull()
await input('#image-prompt', '仅用于上一形态')
document.querySelector<HTMLElement>('#confirm-image-cost')!.click()
await flushPromises()
expect(button('确认生成图片').disabled).toBe(false)
await wrapper.setProps({ form: { ...formFixture(), id: 'other-form' } })
await flushPromises()
expect(document.querySelector<HTMLTextAreaElement>('#image-prompt')?.value).toBe('')
expect(button('确认生成图片').disabled).toBe(true)
expect(feedback()).toBe('')
expect(wrapper.emitted('generate')).toBeUndefined()
})
+64 -37
View File
@@ -1,8 +1,8 @@
import { h } from 'vue'
import { h, ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { NConfigProvider, NDrawer, NDrawerContent, NMenu, NModal, NPopover, NScrollbar, NTooltip } from 'naive-ui'
import { NConfigProvider, NMenu, NModal, NPopover, NScrollbar, NTooltip } from 'naive-ui'
import App from '@/App.vue'
import WorkspacePage from '@/components/ui/WorkspacePage.vue'
import AppDialog from '@/components/ui/AppDialog.vue'
@@ -115,6 +115,7 @@ describe('管理后台组件边界', () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/assets', component: { render: () => h('p', '资产库') } },
{ path: '/projects', component: { render: () => h('p', '项目列表') } },
{
path: '/projects/:projectId/:workspace',
@@ -156,9 +157,9 @@ describe('管理后台组件边界', () => {
expect(document.documentElement.dataset.theme).toBe(expectedTheme)
expect(wrapper.getComponent(NConfigProvider).props('theme')?.name ?? 'light').toBe(expectedTheme)
}
expect(wrapper.find('.admin-topbar [aria-label="后端连接"]').exists()).toBe(false)
expect(wrapper.find('.admin-nav-scroll [aria-label="后端连接"]').exists()).toBe(false)
expect(wrapper.get('.admin-sider-footer [aria-label="后端连接"]').text()).toBe('后端连接')
expect(wrapper.find('.admin-topbar [aria-label="连接设置"]').exists()).toBe(false)
expect(wrapper.find('.admin-nav-scroll [aria-label="连接设置"]').exists()).toBe(false)
expect(wrapper.get('.admin-sider-footer [aria-label="连接设置"]').text()).toBe('连接设置')
expect(wrapper.getComponent(NMenu).props()).toMatchObject({
collapsed: false,
collapsedWidth: 64,
@@ -205,11 +206,11 @@ describe('管理后台组件边界', () => {
'分镜设计',
'镜头生产'
])
const settings = wrapper.get('.admin-sider-footer [aria-label="后端连接"]')
expect(settings.text()).toBe('后端连接')
const settings = wrapper.get('.admin-sider-footer [aria-label="连接设置"]')
expect(settings.text()).toBe('连接设置')
await settings.trigger('click')
await flushPromises()
expect(document.querySelector('[role="dialog"][aria-label="后端连接"]')).not.toBeNull()
expect(document.querySelector('[role="dialog"][aria-label="连接设置"]')).not.toBeNull()
expect(wrapper.findAll('.admin-nav-scroll .n-menu .n-menu-item')).toHaveLength(9)
})
@@ -227,8 +228,8 @@ describe('管理后台组件边界', () => {
expect(css).toMatch(/@media \(max-width: 800px\)[\s\S]*?\.admin-brand\s*\{[^}]*height:\s*48px/)
expect(css).toContain('@media (max-width: 800px)')
expect(css).toMatch(/\.admin-sider\s*\{[^}]*transition:\s*width\s+0\.32s/)
expect(css).toMatch(/\.workspace-tools-body\s*\{[^}]*padding:\s*16px/)
expect(css).toMatch(/\.workspace-tools-drawer \.n-drawer-header[\s\S]*?padding:\s*16px/)
expect(css).toMatch(/\.workspace-tools-body\s*\{[^}]*padding-inline:\s*0;[^}]*padding-bottom:\s*20px/)
expect(css).toMatch(/\.app-dialog\s*\{[^}]*max-width:\s*calc\(100vw\s*-\s*32px\)/)
expect(css).toMatch(
/@media \(max-width: 800px\)[\s\S]*?\.admin-sider\s*\{[^}]*position:\s*fixed;[^}]*inset:\s*0;[^}]*width:\s*100%\s*!important;[^}]*transform:\s*translateX\(0\)/
)
@@ -271,6 +272,7 @@ describe('管理后台组件边界', () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/assets', component: { render: () => h('p', '资产库') } },
{ path: '/projects', component: { render: () => h('p', '项目列表') } },
{
path: '/projects/:projectId/:workspace',
@@ -300,8 +302,8 @@ describe('管理后台组件边界', () => {
const collapsedBrand = wrapper.get('.admin-brand')
expect(collapsedBrand.classes()).toContain('is-collapsed')
expect(collapsedBrand.text()).toContain('短剧工作台')
const collapsedSettings = wrapper.get('.admin-sider-footer [aria-label="后端连接"]')
expect(collapsedSettings.text()).toBe('后端连接')
const collapsedSettings = wrapper.get('.admin-sider-footer [aria-label="连接设置"]')
expect(collapsedSettings.text()).toBe('连接设置')
expect(collapsedSettings.classes()).toContain('is-collapsed')
expect(wrapper.get('.admin-topbar [aria-label="打开主菜单"] svg').classes()).toContain('lucide-panel-left-open')
await wrapper.get('.admin-topbar [aria-label="打开主菜单"]').trigger('click')
@@ -320,8 +322,8 @@ describe('管理后台组件边界', () => {
const expandedBrand = wrapper.get('.admin-brand')
expect(expandedBrand.classes()).not.toContain('is-collapsed')
expect(expandedBrand.text()).toContain('短剧工作台')
const expandedSettings = wrapper.get('.admin-sider-footer [aria-label="后端连接"]')
expect(expandedSettings.text()).toBe('后端连接')
const expandedSettings = wrapper.get('.admin-sider-footer [aria-label="连接设置"]')
expect(expandedSettings.text()).toBe('连接设置')
expect(expandedSettings.classes()).not.toContain('is-collapsed')
expect(wrapper.get('.mobile-sider-close').attributes('aria-label')).toBe('关闭主菜单')
await wrapper.get('.mobile-sider-close').trigger('click')
@@ -330,7 +332,7 @@ describe('管理后台组件边界', () => {
expect(wrapper.get('.admin-sider').attributes('style')).toContain('width: 100%')
expect(wrapper.get('.admin-sider').attributes('aria-hidden')).toBe('true')
expect(wrapper.get('.admin-brand').text()).toContain('短剧工作台')
expect(wrapper.get('.admin-sider-footer [aria-label="后端连接"]').text()).toBe('后端连接')
expect(wrapper.get('.admin-sider-footer [aria-label="连接设置"]').text()).toBe('连接设置')
})
it('长弹窗使用内部滚动,提交期间禁止遮罩和 Esc 关闭', async () => {
@@ -348,12 +350,24 @@ describe('管理后台组件边界', () => {
expect(document.querySelector('.dialog-body-scroll .n-scrollbar-container')).not.toBeNull()
})
it('抽屉挂载 body 覆盖完整视口,开关保留列表与配置草稿', async () => {
it('操作弹窗挂载 body 并限制视口尺寸,开关保留列表与配置草稿', async () => {
/** 配置由工作区拥有,弹窗开关不会清空用户填写的数据。 */
const draft = ref('')
wrapper = mount(WorkspacePage, {
attachTo: document.body,
props: { split: true, compact: true },
slots: {
header: () => h(WorkspaceTools, { title: '测试操作' }, () => h('input', { 'aria-label': '配置草稿' })),
header: () =>
h(WorkspaceTools, { title: '测试操作' }, () =>
h('input', {
'aria-label': '配置草稿',
value: draft.value,
/** 输入后的草稿保存在工作区,关闭弹窗后仍可恢复。 */
onInput: (event: Event) => {
draft.value = (event.target as HTMLInputElement).value
}
})
),
default: '<article class="test-list">主体列表</article>'
}
})
@@ -362,39 +376,42 @@ describe('管理后台组件边界', () => {
expect(wrapper.get('.workspace-heading').find('[data-workspace-tools]').exists()).toBe(true)
await wrapper.get('[data-workspace-tools]').trigger('click')
await flushPromises()
expect(wrapper.getComponent(NDrawer).props()).toMatchObject({
to: 'body',
expect(wrapper.getComponent(AppDialog).props('wide')).toBe(true)
expect(wrapper.getComponent(NModal).props()).toMatchObject({
preset: 'card',
blockScroll: true,
placement: 'right',
width: 'min(960px, 100%)',
trapFocus: true,
maskClosable: true,
closeOnEsc: true
})
expect(wrapper.getComponent(NDrawerContent).props('nativeScrollbar')).toBe(false)
expect(wrapper.find('.workspace-tools-drawer').exists()).toBe(false)
const container = drawerPanel().element.closest('.n-drawer-container')!
expect(wrapper.find('.app-dialog').exists()).toBe(false)
const container = drawerPanel().element.closest('.n-modal-container')!
expect(container.parentElement).toBe(document.body)
expect(container.closest('main, .admin-content, .workspace-page')).toBeNull()
expect(container.querySelector('.n-drawer-mask')).not.toBeNull()
expect(drawerPanel().find('.n-scrollbar-container').exists()).toBe(true)
expect(container.querySelector('.n-modal-mask')).not.toBeNull()
expect(drawerPanel().find('.dialog-body-scroll .n-scrollbar-container').exists()).toBe(true)
await drawerPanel().get('input[aria-label="配置草稿"]').setValue('保留配置')
await drawerPanel().get('[aria-label="关闭操作面板"]').trigger('click')
await drawerPanel().get('.n-card-header__close').trigger('click')
await flushPromises()
expect(wrapper.getComponent(NDrawer).props('show')).toBe(false)
expect(wrapper.getComponent(NModal).props('show')).toBe(false)
expect(wrapper.get('.test-list').element).toBe(list)
await wrapper.get('[data-workspace-tools]').trigger('click')
await flushPromises()
expect(drawerPanel().get<HTMLInputElement>('input[aria-label="配置草稿"]').element.value).toBe('保留配置')
container.querySelector<HTMLElement>('.n-drawer-mask')!.click()
const reopenedContainer = drawerPanel().element.closest('.n-modal-container')!
// Naive 的 clickoutside 由完整按下/抬起事件触发,单独 click 不代表遮罩交互。
const mask = reopenedContainer.querySelector<HTMLElement>('.n-modal-mask')!
mask.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))
mask.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }))
await flushPromises()
expect(wrapper.getComponent(NDrawer).props('show')).toBe(false)
expect(wrapper.getComponent(NModal).props('show')).toBe(false)
expect(wrapper.get('.test-list').element).toBe(list)
wrapper.unmount()
wrapper = undefined
expect(document.querySelector('.n-drawer-container')).toBeNull()
expect(document.querySelector('.n-modal-container')).toBeNull()
})
it('完成项目解锁全部左侧链接,标题不再显示状态标签和刷新按钮', async () => {
it('服务端制作阶段就绪后解锁全部左侧链接,标题只保留项目配置入口', async () => {
const detail = vi.spyOn(projectsApi, 'detail').mockResolvedValue({
id: 'navigation-test',
title: '导航测试项目',
@@ -408,6 +425,15 @@ describe('管理后台组件边界', () => {
world: null
})
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.spyOn(projectsApi, 'stageReadiness').mockResolvedValue({
projectId: 'navigation-test',
script: { ready: true, reason: null },
breakdown: { ready: true, reason: null },
visualStyle: { ready: true, reason: null },
identity: { ready: true, reason: null },
subjectAssets: { ready: true, reason: null },
storyboard: { ready: true, reason: null }
})
const paths = [
'create-drama',
'breakdown',
@@ -420,6 +446,8 @@ describe('管理后台组件边界', () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/assets', component: { render: () => h('p', '资产库') } },
{ path: '/projects', component: { render: () => h('p', '项目列表') } },
{
path: '/projects/:projectId',
component: ProjectLayout,
@@ -442,11 +470,12 @@ describe('管理后台组件边界', () => {
expect(wrapper.get('.project-view .workspace-page').text()).toBe(path)
}
expect(detail).toHaveBeenCalledOnce()
expect(wrapper.find('.project-header .n-button').exists()).toBe(false)
expect(wrapper.get('.project-header .n-button').text()).toBe('项目配置')
expect(wrapper.find('.project-header [aria-label="刷新项目"]').exists()).toBe(false)
expect(wrapper.find('.project-header .n-tag').exists()).toBe(false)
})
it('确认按钮有稳定根元素承接调用方间距,生产按钮显式保留上下留白', () => {
it('确认按钮有稳定根元素承接调用方间距,生产卡片用网格间距排列操作', () => {
wrapper = mount(ConfirmAction, {
props: { label: '测试操作', description: '仅展示,不提交请求' },
attrs: { class: 'mt-4' }
@@ -455,8 +484,6 @@ describe('管理后台组件边界', () => {
expect(wrapper.classes()).toContain('confirm-action')
expect(wrapper.classes()).toContain('mt-4')
expect(wrapper.get('button').text()).toBe('测试操作')
expect(readAllStyles()).toMatch(
/\.production-pipeline-card > \.confirm-action\s*\{[^}]*margin-block:\s*16px 4px/
)
expect(readAllStyles()).toMatch(/\.production-pipeline-card\s*\{[^}]*display:\s*grid;[^}]*gap:\s*16px;/)
})
})
-1
View File
@@ -84,4 +84,3 @@ describe('异步轮询生命周期', () => {
scope.stop()
})
})
-1
View File
@@ -190,4 +190,3 @@ describe('微信风格明暗主题', () => {
expect(document.documentElement.dataset.theme).toBe('dark')
})
})
@@ -414,7 +414,7 @@ describe('拆解页内容滚动', () => {
await flushPromises()
expect(drawerPanel().element.closest('.workspace-split')).toBeNull()
await drawerPanel().get('#group-size').setValue('2')
await drawerPanel().get('[aria-label="关闭操作面板"]').trigger('click')
await drawerPanel().get('.n-card-header__close').trigger('click')
provided.data.value!.checkpoints = [checkpoint()]
await flushPromises()
expect(wrapper!.get('.breakdown-results-scroll .n-scrollbar-container').element).toBe(results)
@@ -4,6 +4,11 @@ import { describe, expect, it } from 'vitest'
import GenerationOptionFields from '../../../src/features/generation-config/components/GenerationOptionFields.vue'
import type { GenerationOptionSchema } from '../../../src/features/generation-config/types'
/**
* 挂载实际模型参数组件以核对下拉枚举与当前值。
* @param schemas 后端参数目录
* @returns 挂载后的组件
*/
function mountFields(schemas: GenerationOptionSchema[]) {
return mount(GenerationOptionFields, {
props: { schemas, modelValue: { size: '2K', durationSeconds: 4, seed: 1 } }
@@ -11,20 +16,24 @@ function mountFields(schemas: GenerationOptionSchema[]) {
}
describe('生成模型参数字段', () => {
it('图片尺寸使用下拉框并保留标准尺寸与当前值', () => {
it('图片尺寸只保留当前 Provider 枚举、默认值与当前值', () => {
const wrapper = mountFields([
{ key: 'size', label: '图片尺寸', type: 'size', required: true, providerDefault: 'auto' }
{
key: 'size',
label: '图片尺寸',
type: 'size',
required: true,
providerDefault: 'auto',
options: [{ label: '目录支持尺寸', value: '2048*2048' }]
}
])
const select = wrapper.getComponent(NSelect)
expect(select.props('clearable')).toBe(false)
expect(select.props('options')).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: '1K' }),
expect.objectContaining({ value: '1.5K' }),
expect.objectContaining({ value: '2K' }),
expect.objectContaining({ value: 'auto' })
])
)
expect(select.props('options')).toEqual([
{ label: '目录支持尺寸', value: '2048*2048' },
{ label: 'auto', value: 'auto' },
{ label: '2K', value: '2K' }
])
expect(wrapper.findComponent(NInputNumber).exists()).toBe(false)
})
@@ -0,0 +1,113 @@
import { describe, expect, it } from 'vitest'
import { creativeProfileDraft, creativeProfileIssues } from '../../../src/features/generation-config/profile-draft'
import type { CreativeProfileInput, GenerationModelCatalog } from '../../../src/features/generation-config/types'
/** 后端已保存的竖屏自定义尺寸,不限于目录的尺寸预设。 */
const saved: CreativeProfileInput = {
aspectRatio: '9:16',
imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro',
imageOptions: { size: '1080*1920', count: 1, promptExtend: false },
videoProvider: 'wan',
videoModel: 'wan3.0-video',
videoOptions: { aspectRatio: 'adaptive', resolution: '1080P', duration: 5, audio: false }
}
describe('项目配置编辑草稿', () => {
it('读取与保存草稿保留真实自定义尺寸和未显示的供应方参数', () => {
const draft = creativeProfileDraft(saved)
expect(draft.imageOptions).toEqual({ size: '1080*1920', count: 1, promptExtend: false })
expect(draft.videoOptions).toEqual({ aspectRatio: 'adaptive', resolution: '1080P', duration: 5, audio: false })
})
it('未保存的图片和视频参数修改不会污染实际已保存对象', () => {
const draft = creativeProfileDraft(saved)
draft.imageOptions.size = '2048*2048'
draft.videoOptions.duration = 10
expect(saved.imageOptions.size).toBe('1080*1920')
expect(saved.videoOptions.duration).toBe(5)
})
})
/** 模型目录枚举与数字限制以真实后端 schema 规则为准。 */
const catalog: GenerationModelCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'wan' },
images: [
{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
defaults: {},
projectConstraints: [],
generationOptions: [
{
key: 'size',
label: '图片尺寸',
type: 'size',
required: true,
options: [{ label: '竖屏', value: '1536*2688' }]
},
{ key: 'count', label: '数量', type: 'integer', required: true, min: 1, max: 1 }
]
}
],
videos: [
{
type: 'video',
provider: 'wan',
providerLabel: 'Wan',
model: 'wan3.0-video',
modelLabel: 'Wan',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
defaults: {},
projectConstraints: [],
generationOptions: [
{
key: 'duration',
label: '时长',
type: 'integer',
required: true,
min: 2,
max: 30,
specialValues: [{ label: '自动', value: -1 }]
},
{ key: 'audio', label: '音轨', type: 'boolean', required: true }
]
}
]
}
describe('项目配置保存前校验', () => {
it('保留但提示不再支持的历史尺寸,选择有效尺寸后可保存', () => {
const draft = creativeProfileDraft(saved)
expect(creativeProfileIssues(draft, catalog)).toHaveLength(1)
expect(draft.imageOptions.size).toBe('1080*1920')
draft.imageOptions.size = '1536*2688'
expect(creativeProfileIssues(draft, catalog)).toEqual([])
})
it('拒绝无效数值与缺失必填参数,允许后端支持的特殊时长', () => {
const draft = creativeProfileDraft(saved)
draft.imageOptions.size = '1536*2688'
draft.imageOptions.count = 2
delete draft.videoOptions.audio
draft.videoOptions.duration = -1
expect(creativeProfileIssues(draft, catalog)).toHaveLength(2)
draft.imageOptions.count = 1
draft.videoOptions.audio = false
expect(creativeProfileIssues(draft, catalog)).toEqual([])
})
it('模型更新后拒绝目录中已不存在的旧模型', () => {
const draft = creativeProfileDraft(saved)
draft.imageOptions.size = '1536*2688'
draft.imageModel = 'removed-image-model'
expect(creativeProfileIssues(draft, catalog)).toHaveLength(1)
})
})
+64 -8
View File
@@ -1,3 +1,4 @@
import { generationProfile } from '../../fixtures/generation'
import { defineComponent } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -22,6 +23,7 @@ afterEach(() => {
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
localStorage.clear()
for (const id of ['capability-test', 'new-project']) {
Object.assign(getOperation(id), { pending: false, error: '', notice: '', label: '' })
Object.assign(getProductionSession(id), { receipt: null, pipelineReceipt: null })
@@ -33,7 +35,12 @@ function stageFixture() {
return { total: 1, planned: 1, skipped: 0, upstreamResolvable: 0, manualBlocked: 0 }
}
/**
* 构造正式预检、202 任务句柄与后续数据库结果的模拟服务。
* @returns 测试上下文、响应数据和已提交请求
*/
function server() {
localStorage.clear()
const context = testProjectContext()
const form = formFixture('capability-test')
const readiness = {
@@ -75,6 +82,9 @@ function server() {
videoGenerationResult: { total: 1, created: 1, skipped: 0, inProgress: 0, blocked: 0, failed: 0 }
}
const plan = {
canStart: true,
canAutoRun: true,
providers: { image: 'qwen-image', video: 'seedance' },
projectId: 'capability-test',
completed: false,
stage: 'subject_images',
@@ -114,7 +124,26 @@ function server() {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
const path = String(url)
let data: unknown = context.project.value
if (path.endsWith('/checkpoints')) data = context.checkpoints.value
if (path.endsWith('/creative-profile')) data = generationProfile('capability-test')
else if (path.includes('/workflow-executions/'))
data = {
id: 'capability-execution-1',
projectId: 'capability-test',
workflowName: 'production',
status: 'completed',
stage: 'finalize',
current: 1,
total: 1,
currentResourceId: null,
metadata: null,
result: receipt,
error: null,
startedAt: '2026-10-08T00:00:00Z',
completedAt: '2026-10-08T00:00:01Z',
createdAt: '2026-10-08T00:00:00Z',
updatedAt: '2026-10-08T00:00:01Z'
}
else if (path.endsWith('/checkpoints')) data = context.checkpoints.value
else if (path.endsWith('/subject-forms')) data = [form]
else if (path.endsWith('/production/plan')) data = plan
else if (path.endsWith('/production/status')) data = status
@@ -134,7 +163,7 @@ function server() {
}
else if (init?.method === 'POST')
data = path.endsWith('/production/start')
? receipt
? { executionId: 'capability-execution-1', status: 'pending' }
: { total: 1, targetCount: 1, generated: 1, skipped: 0, blocked: 0, failed: 0, failures: [] }
return new Response(JSON.stringify({ data }))
})
@@ -154,6 +183,10 @@ function server() {
}
}
/**
* 挂载实际生产组合函数并等待只读绑定。
* @returns 测试数据和实际生产服务
*/
async function advanced() {
const data = server()
let service!: ReturnType<typeof useAdvancedProduction>
@@ -171,7 +204,7 @@ async function advanced() {
}
describe('高级串联生产的安全边界', () => {
it('挂载不查询或生成,通过预检仍需显式启动,再次预检后提交空参数', async () => {
it('挂载不查询或生成,通过预检仍需显式启动,再次预检后提交安全范围与项目模型参数', async () => {
const { service, fetcher, posts } = await advanced()
expect(fetcher).not.toHaveBeenCalled()
await service.start()
@@ -180,9 +213,19 @@ describe('高级串联生产的安全边界', () => {
expect(service.check.value?.issues).toEqual([])
expect(posts()).toHaveLength(0)
await service.start()
await flushPromises()
expect(posts()).toHaveLength(1)
expect(posts()[0]?.[0]).toBe('/api/projects/capability-test/production/start')
expect(JSON.parse(String(posts()[0]?.[1]?.body))).toEqual({})
expect(JSON.parse(String(posts()[0]?.[1]?.body))).toEqual({
stopAfter: 'videoPrompts',
stableIdentityAnchorLimit: 1,
subjectImageLimit: 1,
keyframeLimit: 1,
videoPromptLimit: 1,
imageProvider: 'qwen-image',
videoProvider: 'seedance',
imageGenerationOptions: { size: '2048*2048' }
})
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/production/plan'))).toHaveLength(2)
expect(service.session.value.pipelineReceipt?.errors).toEqual(['一个提示词未生成'])
expect(service.check.value).toBeNull()
@@ -248,7 +291,7 @@ describe('高级串联生产的安全边界', () => {
await flushPromises()
expect(service.check.value).toBeNull()
})
it('已提交的长请求只写回原项目的回执,不污染新项目', async () => {
it('迟到启动响应只保存原项目句柄,返回原项目后读取真实回执', async () => {
const { service, context, fetcher, receipt } = await advanced()
await service.preflight()
const original = fetcher.getMockImplementation()!
@@ -264,18 +307,31 @@ describe('高级串联生产的安全边界', () => {
await flushPromises()
context.data.value!.project.id = 'new-project'
await flushPromises()
finish(new Response(JSON.stringify({ data: receipt })))
finish(
new Response(JSON.stringify({ data: { executionId: 'capability-execution-1', status: 'pending' } }), {
status: 202
})
)
await pending
expect(service.session.value.pipelineReceipt).toBeNull()
expect(getProductionSession('capability-test').pipelineReceipt?.projectId).toBe('capability-test')
expect(getProductionSession('capability-test').pipelineReceipt).toBeNull()
expect(localStorage.getItem('short-drama:workflow-execution:capability-test:production')).toBe(
'capability-execution-1'
)
expect(localStorage.getItem('short-drama:workflow-execution:new-project:production')).toBeNull()
context.data.value!.project.id = 'capability-test'
await flushPromises()
expect(getProductionSession('capability-test').pipelineReceipt?.projectId).toBe(receipt.projectId)
})
it('回执项目不匹配时不发布成功回执', async () => {
const { service, receipt } = await advanced()
await service.preflight()
receipt.projectId = 'wrong'
await service.start()
await flushPromises()
expect(service.execution.query.data.value?.status).toBe('completed')
expect(service.execution.query.data.value?.result?.projectId).toBe('wrong')
expect(service.session.value.pipelineReceipt).toBeNull()
expect(getOperation('capability-test').error).toContain('回执项目不匹配')
})
it('界面区分流程返回与视频完成,显示部分错误,启动需要费用确认', async () => {
const { context, receipt, posts } = server()
+45 -15
View File
@@ -1,10 +1,16 @@
import { generationProfile, imageCatalog } from '../../fixtures/generation'
import { flushPromises, mount } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import QualityResult from '@/features/production/components/QualityResult.vue'
import { expandSections } from '@/testing/naive'
import ShotProductionAssets from '@/features/production/components/ShotProductionAssets.vue'
import { primaryKeyframe } from '@/features/production/model'
import { qualityKey, qualitySession, sessionKeyframePassed, sessionVideoValidation } from '@/features/production/quality'
import {
qualityKey,
qualitySession,
sessionKeyframePassed,
sessionVideoValidation
} from '@/features/production/quality'
import { keyframeFixture, videoFixture } from '@/features/production/testing/fixtures'
import { storyboardApi } from '@/features/storyboard/api'
import { hasRunningWorkflow } from '@/features/workflows/selectors'
@@ -64,7 +70,13 @@ describe('精简公开资产回归', () => {
async url =>
new Response(
JSON.stringify({
data: String(url).endsWith('/videos') ? [video] : []
data: String(url).endsWith('/generation-models')
? imageCatalog
: String(url).endsWith('/creative-profile')
? generationProfile(projectId)
: String(url).endsWith('/videos')
? [video]
: []
})
)
)
@@ -100,7 +112,13 @@ describe('精简公开资产回归', () => {
async url =>
new Response(
JSON.stringify({
data: String(url).endsWith('/keyframes') ? [variant] : []
data: String(url).endsWith('/generation-models')
? imageCatalog
: String(url).endsWith('/creative-profile')
? generationProfile('public-variant-contract')
: String(url).endsWith('/keyframes')
? [variant]
: []
})
)
)
@@ -110,7 +128,10 @@ describe('精简公开资产回归', () => {
})
try {
await flushPromises()
await wrapper.findAll('button').find(item => item.text().includes('管理候选'))!.trigger('click')
await wrapper
.findAll('button')
.find(item => item.text().includes('管理候选'))!
.trigger('click')
await flushPromises()
expect(document.body.textContent).toContain('模型输入变体')
expect(wrapper.findAll('button').some(button => button.text() === '设为主首帧')).toBe(false)
@@ -129,7 +150,13 @@ describe('精简公开资产回归', () => {
async url =>
new Response(
JSON.stringify({
data: String(url).endsWith('/keyframes') ? [primary, candidate] : []
data: String(url).endsWith('/generation-models')
? imageCatalog
: String(url).endsWith('/creative-profile')
? generationProfile(projectId)
: String(url).endsWith('/keyframes')
? [primary, candidate]
: []
})
)
)
@@ -144,12 +171,15 @@ describe('精简公开资产回归', () => {
expect(wrapper.find('.primary-keyframe-mark').attributes('aria-label')).toBe('当前主首帧')
expect(wrapper.findAll('button').some(item => item.text().includes('设为主首帧'))).toBe(false)
await wrapper.findAll('button').find(item => item.text().includes('管理候选'))!.trigger('click')
await wrapper
.findAll('button')
.find(item => item.text().includes('管理候选'))!
.trigger('click')
await flushPromises()
expect(document.body.textContent).toContain('首帧候选管理')
expect([...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))).toBe(
false
)
expect(
[...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))
).toBe(false)
const session = qualitySession(
qualityKey(projectId, { kind: 'keyframe', shotId: shot.shotId, assetId: candidate.id, title: '' })
@@ -172,16 +202,16 @@ describe('精简公开资产回归', () => {
}
await flushPromises()
expect(sessionKeyframePassed(projectId, shot.shotId, candidate.id)).toBe(false)
expect([...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))).toBe(
false
)
expect(
[...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))
).toBe(false)
session.receipt.result.passed = true
await flushPromises()
expect(sessionKeyframePassed(projectId, shot.shotId, candidate.id)).toBe(true)
expect([...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))).toBe(
true
)
expect(
[...document.querySelectorAll('button')].some(item => item.textContent?.includes('设为主首帧'))
).toBe(true)
} finally {
wrapper.unmount()
}
+105 -29
View File
@@ -1,25 +1,41 @@
import { h } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
import App from '@/App.vue'
import ProjectLayout from '@/features/projects/ProjectLayout.vue'
import { isProjectComplete } from '@/features/projects/access'
import { useProjectContext } from '@/features/projects/context'
import { projectsApi } from '@/features/projects/api'
import { getOperation } from '@/features/workflows/operations'
import type { ProjectDetail, ProjectStatus } from '@/features/projects/types'
import type { ProjectDetail, ProjectStageReadiness, ProjectStatus } from '@/features/projects/types'
import { readAllStyles } from '@/testing/styles'
const downstream = [
'breakdown',
'visual-style',
'subject-identity',
'subject-images',
'assets',
'storyboard',
'production'
]
const downstream = ['breakdown', 'visual-style', 'subject-identity', 'subject-images', 'storyboard', 'production']
/**
* 构造服务端完整阶段状态,允许测试单独模拟各步骤的就绪变化。
* @param id 项目编号
* @param ready 所有制作阶段是否就绪
* @returns 项目阶段响应
*/
function readiness(id: string, ready = true): ProjectStageReadiness {
/** 每个阶段独立创建,避免修改某一步时污染其它前置状态。 */
const stage = () => ({ ready, reason: ready ? null : '请先完成剧本创作' })
return {
projectId: id,
script: stage(),
breakdown: stage(),
visualStyle: stage(),
identity: stage(),
subjectAssets: stage(),
storyboard: stage()
}
}
beforeEach(() => {
vi.spyOn(projectsApi, 'stageReadiness').mockImplementation(async id => readiness(id))
})
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
@@ -30,7 +46,12 @@ afterEach(() => {
vi.restoreAllMocks()
})
/** 用已有剧集模拟中途生成的项目,完成与否必须取 status 而非数组长度。 */
/**
* 用已有剧集模拟中途生成的项目,完成与否必须取 status 而非数组长度。
* @param id 项目编号
* @param status 项目状态
* @returns 含部分剧集的项目详情
*/
function project(id: string, status: ProjectStatus): ProjectDetail {
return {
id,
@@ -46,12 +67,17 @@ function project(id: string, status: ProjectStatus): ProjectDetail {
}
}
/** 真实项目布局与侧栏,子工作区以挂载探针代替,防止测试发起实际生成请求。 */
/**
* 真实项目布局与侧栏,子工作区以挂载探针代替,防止测试发起实际生成请求。
* @param initialPath 首次访问的项目地址
* @returns 真实路由与工作区挂载记录
*/
async function openProject(initialPath: string) {
const mounted = vi.fn<(path: string) => void>()
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/assets', component: { render: () => h('div', '资产库') } },
{ path: '/projects', component: { render: () => h('div', '项目列表') } },
{
path: '/projects/:projectId',
@@ -61,7 +87,12 @@ async function openProject(initialPath: string) {
component: {
setup() {
mounted(path)
return () => h('div', { class: 'workspace-probe' }, path)
/** 测试探针只执行手动项目读取,不发起制作任务。 */
const context = useProjectContext()
return () => [
h('div', { class: 'workspace-probe' }, path),
h('button', { class: 'probe-refresh', onClick: context.refresh }, '手动刷新')
]
}
}
}))
@@ -75,7 +106,7 @@ async function openProject(initialPath: string) {
}
describe('剧本完成前的下游访问限制', () => {
it('进入图库暂停父级轮询,返回其他工作区恢复定时更新', async () => {
it('切换图库与其他工作区不自动重复读取项目状态', async () => {
vi.useFakeTimers()
const detail = vi.spyOn(projectsApi, 'detail').mockResolvedValue(project('manual-gallery', 'completed'))
const checkpoints = vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
@@ -88,13 +119,15 @@ describe('剧本完成前的下游访问限制', () => {
await router.push('/projects/manual-gallery/production')
await flushPromises()
await vi.advanceTimersByTimeAsync(6000)
expect(detail).toHaveBeenCalledTimes(2)
expect(checkpoints).toHaveBeenCalledTimes(2)
expect(detail).toHaveBeenCalledTimes(1)
expect(checkpoints).toHaveBeenCalledTimes(1)
expect(projectsApi.stageReadiness).toHaveBeenCalledTimes(1)
})
it('图库直接链接只读取一次项目,未完成时可手动刷新解锁', async () => {
vi.useFakeTimers()
let status: ProjectStatus = 'generating'
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, status === 'completed'))
const detail = vi.spyOn(projectsApi, 'detail').mockImplementation(async id => project(id, status))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
await openProject('/projects/manual-gate/subject-images')
@@ -112,6 +145,7 @@ describe('剧本完成前的下游访问限制', () => {
it.each(['draft', 'generating', 'need_review', 'failed'] as const)(
'%s 不解锁导航,也不挂载直接链接对应的工作区',
async status => {
vi.mocked(projectsApi.stageReadiness).mockResolvedValue(readiness('unfinished', false))
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project('unfinished', status))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
const { router, mounted } = await openProject('/projects/unfinished/production')
@@ -126,31 +160,41 @@ describe('剧本完成前的下游访问限制', () => {
expect(wrapper!.findAll('.n-menu [aria-disabled="true"]')).toHaveLength(6)
await wrapper!.get('.project-access-gate button').trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/projects/unfinished/breakdown')
expect(mounted).not.toHaveBeenCalled()
await wrapper!.get('.project-access-gate button').trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/projects/unfinished/create-drama')
expect(wrapper!.get('.workspace-probe').text()).toBe('create-drama')
expect(mounted).toHaveBeenCalledExactlyOnceWith('create-drama')
}
)
it('轮询完成状态自动解锁;重新变为待审核时撤下下游面板', async () => {
it('手动刷新就绪状态解锁;服务端撤销就绪后撤下下游面板', async () => {
vi.useFakeTimers()
let status: ProjectStatus = 'generating'
vi.spyOn(projectsApi, 'detail').mockImplementation(async id => project(id, status))
let ready = false
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project('manual-refresh', 'completed'))
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, ready))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
const { mounted } = await openProject('/projects/polling/production')
const { router, mounted } = await openProject('/projects/manual-refresh/subject-images')
expect(mounted).not.toHaveBeenCalled()
status = 'completed'
await vi.advanceTimersByTimeAsync(6000)
ready = true
await vi.advanceTimersByTimeAsync(30_000)
expect(mounted).not.toHaveBeenCalled()
const refresh = wrapper!.findAll('button').find(button => button.text() === '刷新项目状态')!
await refresh.trigger('click')
await flushPromises()
expect(wrapper!.get('.workspace-probe').text()).toBe('production')
expect(wrapper!.get('.workspace-probe').text()).toBe('subject-images')
expect(wrapper!.findAll('.n-menu a')).toHaveLength(9)
status = 'need_review'
await vi.advanceTimersByTimeAsync(6000)
await router.push('/projects/manual-refresh/production')
await flushPromises()
ready = false
await wrapper!.get('.probe-refresh').trigger('click')
await flushPromises()
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('请先完成剧本创作')
expect(wrapper!.findAll('.n-menu a')).toHaveLength(3)
expect(mounted).toHaveBeenCalledExactlyOnceWith('production')
expect(mounted.mock.calls.map(([path]) => path)).toEqual(['subject-images', 'production'])
})
it('切换项目与首次读取期间不能沿用上一个已完成项目的权限', async () => {
@@ -162,6 +206,7 @@ describe('剧本完成前的下游访问限制', () => {
id === 'first' ? project(id, 'completed') : pending
)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.mocked(projectsApi.stageReadiness).mockImplementation(async id => readiness(id, id === 'first'))
const { router, mounted } = await openProject('/projects/first/production')
expect(wrapper!.findAll('.n-menu a')).toHaveLength(9)
await router.push('/projects/second/production')
@@ -177,7 +222,7 @@ describe('剧本完成前的下游访问限制', () => {
expect(wrapper!.findAll('.n-menu a')).toHaveLength(2)
})
it('读取失败保持锁定;错误区重试成功后解锁,页头不恢复标签与刷新按钮', async () => {
it('读取失败保持锁定;重试成功后解锁,标题只保留项目配置入口', async () => {
const detail = vi
.spyOn(projectsApi, 'detail')
.mockRejectedValueOnce(new Error('项目读取失败'))
@@ -186,7 +231,8 @@ describe('剧本完成前的下游访问限制', () => {
const { mounted } = await openProject('/projects/retry/storyboard')
expect(mounted).not.toHaveBeenCalled()
expect(wrapper!.findAll('.n-menu a')).toHaveLength(3)
expect(wrapper!.find('.project-header .n-button').exists()).toBe(false)
expect(wrapper!.get('.project-header .n-button').text()).toBe('项目配置')
expect(wrapper!.get('.project-header button').attributes('disabled')).toBeDefined()
expect(wrapper!.find('.project-header .n-tag').exists()).toBe(false)
await wrapper!.get('.project-notices button').trigger('click')
await flushPromises()
@@ -194,6 +240,36 @@ describe('剧本完成前的下游访问限制', () => {
expect(mounted).toHaveBeenCalledExactlyOnceWith('storyboard')
})
it('剧本完成仍按服务端前置步骤逐步解锁,不能直接进入生产', async () => {
const state = readiness('staged', false)
state.script = { ready: true, reason: null }
state.breakdown.reason = '请先完成剧本拆解'
vi.mocked(projectsApi.stageReadiness).mockImplementation(async () => structuredClone(state))
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project('staged', 'completed'))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
const { router, mounted } = await openProject('/projects/staged/production')
expect(mounted).not.toHaveBeenCalled()
expect(wrapper!.get('.project-access-gate').text()).toContain('请先完成剧本拆解')
expect(wrapper!.find('.n-menu a[href="/projects/staged/breakdown"]').exists()).toBe(true)
expect(wrapper!.find('.n-menu a[href="/projects/staged/visual-style"]').exists()).toBe(false)
await wrapper!.get('.project-access-gate button').trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/projects/staged/breakdown')
state.breakdown = { ready: true, reason: null }
state.subjectAssets = { ready: true, reason: null }
state.storyboard = { ready: false, reason: '请先完成分镜设计' }
await wrapper!.get('.probe-refresh').trigger('click')
await flushPromises()
await router.push('/projects/staged/production')
await flushPromises()
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('请先完成分镜设计')
await wrapper!.get('.project-access-gate button').trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/projects/staged/storyboard')
expect(wrapper!.get('.workspace-probe').text()).toBe('storyboard')
})
it('不存在、未知状态或项目 ID 不匹配时默认锁定', () => {
expect(isProjectComplete(null, 'p')).toBe(false)
expect(isProjectComplete({ id: 'other', status: 'completed' }, 'p')).toBe(false)
@@ -0,0 +1,71 @@
import { createApp, effectScope, type EffectScope } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import { afterEach, describe, expect, it } from 'vitest'
import { useShotSelection } from '../../../src/features/storyboard/useShotSelection'
/** 测试作用域在每例结束后释放地址监听。 */
let scope: EffectScope | undefined
afterEach(() => scope?.stop())
/**
* 使用真实路由和注入环境创建镜头选择状态。
* @param url 初始页面地址
* @returns 地址同步状态与真实路由
*/
async function selection(url: string) {
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/projects/:projectId/:section', component: {} }]
})
await router.push(url)
const app = createApp({})
app.use(router)
scope = effectScope()
const state = app.runWithContext(() => scope!.run(() => useShotSelection(() => 2))!)
return { router, state }
}
/** 等待 replace 导航完成,不替换路由实现。 */
async function settled() {
await new Promise(resolve => setTimeout(resolve, 0))
}
describe('镜头地址选择', () => {
it('刷新后的分镜和生产地址恢复剧集与正式镜头', async () => {
for (const section of ['storyboard', 'production']) {
scope?.stop()
const { state } = await selection(`/projects/p1/${section}?episodeNo=2&shotId=shot-9`)
expect(state.selectedEpisode.value).toBe(2)
expect(state.selectedShot.value).toBe('shot-9')
}
})
it('选择镜头记录当前剧集并保留来源动作及其它参数', async () => {
const { router, state } = await selection('/projects/p1/production?action=keyframe&filter=ready')
state.selectedShot.value = 'shot-8'
await settled()
expect(router.currentRoute.value.query).toEqual({
action: 'keyframe',
filter: 'ready',
episodeNo: '2',
shotId: 'shot-8'
})
})
it('切换剧集清除上集镜头且保留其它参数', async () => {
const { router, state } = await selection('/projects/p1/storyboard?episodeNo=2&shotId=old-shot&filter=ready')
state.selectedEpisode.value = 3
await settled()
expect(router.currentRoute.value.query).toEqual({ episodeNo: '3', filter: 'ready' })
expect(state.selectedShot.value).toBe('')
})
it('浏览器导航同步目标,拒绝无效或多值剧集', async () => {
const { router, state } = await selection('/projects/p1/storyboard?episodeNo=2&shotId=shot-9')
await router.push('/projects/p1/storyboard?episodeNo=3&shotId=shot-11')
expect(state.selectedEpisode.value).toBe(3)
expect(state.selectedShot.value).toBe('shot-11')
await router.push('/projects/p1/storyboard?episodeNo=-1&shotId=missing')
expect(state.selectedEpisode.value).toBeUndefined()
expect(state.selectedShot.value).toBe('missing')
await router.push('/projects/p1/storyboard?episodeNo=2&episodeNo=3')
expect(state.selectedEpisode.value).toBeUndefined()
})
})
@@ -1,3 +1,4 @@
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'
@@ -43,40 +44,8 @@ function input(selector: string, value: string) {
item.dispatchEvent(new Event(item.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }))
}
const imageCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [{
type: 'image' as const,
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image',
supported: true as const,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [{
key: 'size',
label: '图片尺寸',
type: 'size' as const,
required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }]
}],
defaults: { size: '2048*2048' },
projectConstraints: []
}],
videos: []
}
const creativeProfile = {
projectId: 'project-1',
aspectRatio: '1:1' as const,
imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro',
imageOptions: { size: '2048*2048' },
videoProvider: 'seedance',
videoModel: 'seedance',
videoOptions: {}
}
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('project-1')
describe('身份图与母版契约', () => {
it('详情大图 contain 完整显示,历史仍为 cover,缩略图只切换记录', async () => {
@@ -185,7 +154,7 @@ describe('身份图与母版契约', () => {
.findAllComponents(AssetImage)
.find(item => item.classes().includes('asset-image-preview'))!
expect(preview.props('src')).toBe(image.status === 'completed' ? image.imageUrl : null)
expect(wrapper.text()).toContain(`Identity image ID · ${image.id}`)
expect(preview.props('alt')).toBe(`林夏 · ${image.viewType === 'primary' ? '身份母版' : '正面'}`)
}
await history.get('[aria-label="查看身份图片 failed"]').trigger('click')
expect(wrapper.get('.asset-image-preview').text()).toContain('本次生成失败')
@@ -288,13 +257,14 @@ describe('身份图与母版契约', () => {
expect(castingStatusLabel('candidate_pending')).toBe('等待确认演员')
})
it('辅助视角传递明确参考图、成对尺寸和本次 Prompt,不传形态生图字段', async () => {
it('辅助视角传递明确参考图、目录尺寸和本次 Prompt,不传旧宽高字段', async () => {
wrapper = mount(IdentityImageDialog, {
attachTo: document.body,
props: {
open: true,
subjectId: 's1',
subjectName: '林夏',
module: 'character',
images: [identityImageFixture()],
disabled: false,
catalog: imageCatalog,
@@ -304,13 +274,14 @@ describe('身份图与母版契约', () => {
await flushPromises()
input('#identity-view', 'three-quarter')
input('#identity-reference', 'identity-image-1')
input('#identity-width', '2048')
document.querySelector<HTMLInputElement>('#identity-image-cost')!.click()
await flushPromises()
expect(document.querySelector('#identity-width')).toBeNull()
expect(document.querySelector('#identity-height')).toBeNull()
expect(button('确认生成身份图').disabled).toBe(true)
input('#identity-height', '2048')
input('#identity-image-prompt', ' 自定义身份提示词 ')
await flushPromises()
document.querySelector<HTMLInputElement>('#identity-image-cost')!.click()
await flushPromises()
button('确认生成身份图').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([
@@ -318,8 +289,8 @@ describe('身份图与母版契约', () => {
{
viewType: 'three-quarter',
referenceImageId: 'identity-image-1',
width: 2048,
height: 2048,
provider: 'qwen-image',
generationOptions: { size: '2048*2048' },
prompt: '自定义身份提示词'
}
]
@@ -333,6 +304,7 @@ describe('身份图与母版契约', () => {
open: true,
subjectId: 's1',
subjectName: '林夏',
module: 'character',
images: [identityImageFixture()],
disabled: false,
catalog: imageCatalog,
@@ -416,20 +388,22 @@ describe('身份图与母版契约', () => {
disabled: false,
catalog: {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [],
defaults: { size: '1536*2688' },
projectConstraints: []
}],
images: [
{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [],
defaults: { size: '1536*2688' },
projectConstraints: []
}
],
videos: []
},
profile: {
@@ -450,9 +424,9 @@ describe('身份图与母版契约', () => {
await flushPromises()
button('确认生成候选').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([[
{ provider: 'qwen-image', generationOptions: { size: '1536*2688' } }
]])
expect(wrapper.emitted('generate')).toEqual([
[{ provider: 'qwen-image', generationOptions: { size: '1536*2688' } }]
])
})
it('角色选角接口区分批量身份、候选生图与确认事务', async () => {
@@ -9,10 +9,53 @@ import { referenceLocation, referenceTargets } from '@/features/production/asset
import StaleKeyframeNotice from '@/features/production/components/StaleKeyframeNotice.vue'
import SubjectImagesPage from '@/features/subject-images/SubjectImagesPage.vue'
import ProductionPage from '@/features/production/ProductionPage.vue'
import ImageGalleryDialog from '@/features/subject-images/components/ImageGalleryDialog.vue'
import type { CreativeProfile, GenerationModelCatalog } from '@/features/generation-config/types'
import { directionsResult, storyboardCheckpoint } from '@/features/storyboard/testing/fixtures'
import type { ProductionIssue } from '@/features/production/types'
import type { ShotReferences } from '@/features/storyboard/types'
/** 使用后端模型目录结构,避免空数组被误当成可用模型。 */
const imageCatalog: GenerationModelCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [
{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [
{
key: 'size',
label: '图片尺寸',
type: 'size',
required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }]
}
],
defaults: { size: '2048*2048' },
projectConstraints: []
}
],
videos: []
}
/** 模拟当前项目持久化的创作配置。 */
const creativeProfile: CreativeProfile = {
projectId: 'capability-test',
aspectRatio: '1:1',
imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro',
imageOptions: { size: '2048*2048' },
videoProvider: 'seedance',
videoModel: 'seedance',
videoOptions: {}
}
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
@@ -98,29 +141,40 @@ function fixture() {
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
const data = path.endsWith('/subject-forms')
? [first, second, other]
: path.includes('/keyframes/readiness')
? keyframes
: path.includes('/videos/readiness')
? videos
: path.endsWith('/references')
? references
: []
const data = path.endsWith('/generation-models')
? imageCatalog
: path.endsWith('/creative-profile')
? creativeProfile
: path.endsWith('/subject-forms')
? [first, second, other]
: path.includes('/keyframes/readiness')
? keyframes
: path.includes('/videos/readiness')
? videos
: path.endsWith('/references')
? references
: []
return new Response(JSON.stringify({ data }))
})
vi.stubGlobal('fetch', fetcher)
return { first, second, other, references, issues, keyframes, videos, fetcher }
}
/** 在真实内存路由中验证跨页 URL,不替换 RouterLink 行为。 */
async function gallery(query = '') {
/**
* 在真实内存路由中验证跨页 URL,并在首次请求前设置服务端状态。
* @param query 初始素材定位参数
* @param prepare 挂载前准备当前项目的接口响应
* @returns 当前接口数据与真实内存路由
*/
async function gallery(query = '', prepare?: (data: ReturnType<typeof fixture>) => void) {
const data = fixture()
prepare?.(data)
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/projects/:projectId/subject-images', component: SubjectImagesPage },
{ path: '/projects/:projectId/production', component: { template: '<div />' } }
{ path: '/projects/:projectId/production', component: { template: '<div />' } },
{ path: '/projects/:projectId/storyboard', component: { template: '<div />' } }
]
})
await router.push('/projects/capability-test/subject-images' + query)
@@ -132,14 +186,24 @@ async function gallery(query = '') {
return { ...data, router }
}
/**
* 模拟图片记录中的主图变更完成通知,验证父页重读图库及影响状态。
* @returns 全部资产查询完成
*/
async function assetsChanged() {
wrapper!.findComponent(ImageGalleryDialog).vm.$emit('changed')
await flushPromises()
}
describe('过期首帧到具体素材定位', () => {
it('没有图片的形态卡片标记为方形占位', async () => {
const { first } = await gallery()
first.images = []
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
const { first } = await gallery('', data => {
data.first.images = []
})
const card = wrapper!.findAll('.form-image-card').find(item => item.attributes('data-form-id') === first.id)!
expect(card.get('.asset-image').classes()).toContain('form-image-empty')
expect(card.get('.asset-image').classes()).not.toContain('form-image-has-source')
expect(card.get('.asset-image-empty').text()).toContain('尚未生成主参考图')
expect(card.find('img').exists()).toBe(false)
})
it('网格与瀑布流切换保留卡片、滚动容器和筛选,不发起额外请求', async () => {
@@ -159,7 +223,7 @@ describe('过期首帧到具体素材定位', () => {
.get('.gallery-layout-switch')
.findAll('button')
.map(button => button.attributes('aria-label'))
).toEqual(['网格布局', '瀑布流布局', '刷新图库', '批量生图'])
).toEqual(['网格布局', '瀑布流布局', '批量生图'])
await wrapper!.get('[aria-label="网格布局"]').trigger('click')
expect(wrapper!.find('.form-image-masonry').exists()).toBe(false)
expect(wrapper!.get('[aria-label="网格布局"]').attributes('aria-pressed')).toBe('true')
@@ -182,7 +246,7 @@ describe('过期首帧到具体素材定位', () => {
expect(fetcher).toHaveBeenCalledTimes(requestCount)
})
it('图库与关联检查不定时刷新,手动刷新仍能更新数据', async () => {
it('图库与关联检查不定时刷新,图片记录变更后更新数据', async () => {
vi.useFakeTimers()
const { fetcher } = await gallery('?sourceShotId=shot-target')
const count = fetcher.mock.calls.length
@@ -191,13 +255,12 @@ describe('过期首帧到具体素材定位', () => {
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(count)
expect(wrapper!.get('.form-image-grid').element).toBe(grid)
const refresh = wrapper!.get('[aria-label="刷新图库"]')
await refresh.trigger('click')
await flushPromises()
await assetsChanged()
expect(fetcher.mock.calls.length).toBeGreaterThan(count)
const refreshed = fetcher.mock.calls.length
await vi.advanceTimersByTimeAsync(30_000)
expect(fetcher).toHaveBeenCalledTimes(refreshed)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('切换镜头时筛选、关联说明和图片共用稳定纵向容器,长关联列表单独横向滚动', async () => {
@@ -224,8 +287,7 @@ describe('过期首帧到具体素材定位', () => {
})
: original(url, init)
)
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
await assetsChanged()
wrapper!
.findAllComponents(NSelect)
.find(item => item.attributes('aria-label') === '选择关联镜头')!
@@ -428,8 +490,7 @@ describe('过期首帧到具体素材定位', () => {
it('精简图库没有历史母版字段时,不误报形态过期或破坏定位', async () => {
const { first, router } = await gallery('?subjectFormId=form-other')
first.subject.identity = { id: 'identity-1', isLocked: true, anchorImageId: 'anchor-new' }
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
await assetsChanged()
expect(wrapper!.text()).not.toContain('形态主图需要更新')
expect(router.currentRoute.value.query.subjectFormId).toBe('form-other')
expect(wrapper!.findAll('button').some(item => item.text() === '重新生成过期形态')).toBe(false)
@@ -437,8 +498,7 @@ describe('过期首帧到具体素材定位', () => {
it('仅视频接口报告过期时也显示警告,并明确两种检查不一致', async () => {
const { keyframes } = await gallery('?sourceShotId=shot-target&subjectFormId=form-special')
keyframes.items[0]!.primaryKeyframeStale = false
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
await assetsChanged()
expect(wrapper!.get('[data-keyframe-impact]').text()).toContain('检查结果不一致')
expect(wrapper!.get('.form-image-card').text()).toContain('不要据此重复生图')
})
@@ -446,8 +506,7 @@ describe('过期首帧到具体素材定位', () => {
const { keyframes, videos } = await gallery('?sourceShotId=shot-target&subjectFormId=form-special')
keyframes.items[0]!.primaryKeyframeStale = false
videos.items[0]!.issues = []
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
await assetsChanged()
expect(wrapper!.find('[data-keyframe-impact]').exists()).toBe(false)
expect(wrapper!.text()).toContain('未被标记为过期')
})
@@ -466,8 +525,7 @@ describe('过期首帧到具体素材定位', () => {
? Promise.resolve(new Response('{}', { status: 500 }))
: original(url, init)
)
await wrapper!.get('[aria-label="刷新图库"]').trigger('click')
await flushPromises()
await assetsChanged()
expect(wrapper!.text()).toContain('暂时无法确认有无过期首帧')
expect(wrapper!.findAll('.form-image-card')).toHaveLength(3)
})
@@ -480,11 +538,15 @@ describe('过期首帧到具体素材定位', () => {
const path = String(url)
return new Response(
JSON.stringify({
data: path.includes('/storyboard-directions')
? data
: path.includes('/readiness') || path.endsWith('/videos/status')
? { total: 0, items: [] }
: []
data: path.endsWith('/generation-models')
? imageCatalog
: path.endsWith('/creative-profile')
? creativeProfile
: path.includes('/storyboard-directions')
? data
: path.includes('/readiness') || path.endsWith('/videos/status')
? { total: 0, items: [] }
: []
})
)
})
+27 -27
View File
@@ -1,3 +1,4 @@
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AssetImage } from '@/components/ui'
@@ -8,22 +9,8 @@ import { coverImage, hasRunningImages, primaryImage, validImageSize } from '@/fe
import { formFixture, imageFixture } from '@/features/subject-images/testing/fixtures'
import { expandSections } from '@/testing/naive'
const imageCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [{
type: 'image' as const, provider: 'qwen-image', providerLabel: 'Qwen', model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image', supported: true as const, enabled: true, isDefault: true, capabilities: {},
generationOptions: [{ key: 'size', label: '图片尺寸', type: 'size' as const, required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }] }],
defaults: { size: '2048*2048' }, projectConstraints: []
}],
videos: []
}
const creativeProfile = {
projectId: 'gallery-test', aspectRatio: '1:1' as const, imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro', imageOptions: { size: '2048*2048' },
videoProvider: 'seedance', videoModel: 'seedance', videoOptions: {}
}
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
let wrapper: VueWrapper | undefined
/** Naive 将弹窗挂载到 body,需要从实际弹窗找到按钮。 */
function button(label: string): HTMLButtonElement {
@@ -81,7 +68,10 @@ describe('形态图片选择与操作', () => {
it.each(['character', 'scene', 'prop'])('按后端最新 %s 模块展示母版继承范围', async module => {
const form = formFixture()
form.subject.module = module
wrapper = mount(GenerateImageDialog, { attachTo: document.body, props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile } })
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile }
})
await flushPromises()
expect(document.body.textContent).toContain('母版')
expect(document.body.textContent).not.toContain('道具形态生图暂不自动引用')
@@ -149,7 +139,7 @@ describe('形态图片选择与操作', () => {
expect(validImageSize(width, height)).toBe(false)
})
it('生图确认发送正式形态 ID,不覆盖后端模型,默认不替换已有主图', async () => {
it('生图确认发送正式形态 ID 和项目模型参数,默认不替换已有主图', async () => {
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form: formFixture(), disabled: false, catalog: imageCatalog, profile: creativeProfile }
@@ -160,29 +150,39 @@ describe('形态图片选择与操作', () => {
await flushPromises()
button('确认生成图片').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([['form-db-1', { setPrimary: false }]])
expect(wrapper.emitted('generate')).toEqual([
['form-db-1', { setPrimary: false, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
])
})
it('新形态默认设主图,填写一侧尺寸时不能提交,切换形态清空自定义提示词', async () => {
it('新形态默认设主图并继承目录尺寸,切换形态清空提示词和费用确认', async () => {
const form = formFixture()
form.images = []
wrapper = mount(GenerateImageDialog, { attachTo: document.body, props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile } })
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile }
})
await flushPromises()
const width = document.querySelector<HTMLInputElement>('#image-width')!
width.value = '2048'
width.dispatchEvent(new Event('input', { bubbles: true }))
const prompt = document.querySelector<HTMLTextAreaElement>('#image-prompt')!
prompt.value = '上一形态自定义提示词'
prompt.dispatchEvent(new Event('input', { bubbles: true }))
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
expect(button('确认生成图片').disabled).toBe(true)
expect(button('确认生成图片').disabled).toBe(false)
expect(wrapper.emitted('generate')).toBeUndefined()
await wrapper.setProps({ form: { ...form, id: 'form-db-2' } })
await flushPromises()
expect(width.value).toBe('')
expect(prompt.value).toBe('')
expect(document.querySelector('#image-width')).toBeNull()
expect(document.querySelector('#image-height')).toBeNull()
expect(document.querySelector('#confirm-image-cost')!.getAttribute('aria-checked')).toBe('false')
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
button('确认生成图片').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([['form-db-2', { setPrimary: true }]])
expect(wrapper.emitted('generate')).toEqual([
['form-db-2', { setPrimary: true, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
])
})
it('图库不自动生图,主图切换经确认后 PUT,失败图片不能设主图', async () => {
+15 -20
View File
@@ -1,3 +1,4 @@
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { defineComponent } from 'vue'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -10,22 +11,8 @@ import { useSubjectImages } from '@/features/subject-images/useSubjectImages'
import FormPromptDialog from '@/features/subject-images/components/FormPromptDialog.vue'
import GenerateImageDialog from '@/features/subject-images/components/GenerateImageDialog.vue'
const imageCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [{
type: 'image' as const, provider: 'qwen-image', providerLabel: 'Qwen', model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image', supported: true as const, enabled: true, isDefault: true, capabilities: {},
generationOptions: [{ key: 'size', label: '图片尺寸', type: 'size' as const, required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }] }],
defaults: { size: '2048*2048' }, projectConstraints: []
}],
videos: []
}
const creativeProfile = {
projectId: 'gallery-test', aspectRatio: '1:1' as const, imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro', imageOptions: { size: '2048*2048' },
videoProvider: 'seedance', videoModel: 'seedance', videoOptions: {}
}
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
let wrapper: VueWrapper | undefined
const projectId = 'capability-test'
/** 从实际挂载的确认弹窗查找操作按钮。 */
@@ -115,7 +102,7 @@ describe('形态正式提示词与批量配置', () => {
new Response(JSON.stringify({ data: { id: 'form-db-1', subjectId: 'subject-db-1', generationPrompt: '' } }))
)
await service.generatePrompt('form-db-1', false)
expect(getOperation(projectId).error).toContain('未确认正式提示词已保存')
expect(getOperation(projectId).error).toContain('提示词保存结果未确认')
})
it('批量提示词保留部分失败回执,不覆盖图片回执且不传图片上限', async () => {
const { service, posts } = await setup()
@@ -178,7 +165,10 @@ describe('形态正式提示词与批量配置', () => {
})
it('正式提示词确认必须勾选,未确认不发送事件', async () => {
const form = formFixture()
wrapper = mount(FormPromptDialog, { attachTo: document.body, props: { open: true, disabled: false, form, catalog: imageCatalog, profile: creativeProfile } })
wrapper = mount(FormPromptDialog, {
attachTo: document.body,
props: { open: true, disabled: false, form, catalog: imageCatalog, profile: creativeProfile }
})
await flushPromises()
find('生成正式提示词').click()
await flushPromises()
@@ -194,7 +184,10 @@ describe('形态正式提示词与批量配置', () => {
const form = formFixture()
form.appearancePrompt = null
form.generationPrompt = null
wrapper = mount(GenerateImageDialog, { attachTo: document.body, props: { open: true, disabled: false, form, catalog: imageCatalog, profile: creativeProfile } })
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, disabled: false, form, catalog: imageCatalog, profile: creativeProfile }
})
await flushPromises()
document.querySelector<HTMLElement>('#confirm-image-cost')!.click()
await flushPromises()
@@ -204,6 +197,8 @@ describe('形态正式提示词与批量配置', () => {
expect(submit.disabled).toBe(false)
submit.click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([['form-db-1', { setPrimary: false }]])
expect(wrapper.emitted('generate')).toEqual([
['form-db-1', { setPrimary: false, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
])
})
})
+213 -135
View File
@@ -1,8 +1,9 @@
import { generationProfile, imageCatalog } from '../../fixtures/generation'
import { computed, ref } from 'vue'
import { NImage, NRadioGroup, NScrollbar } from 'naive-ui'
import { createMemoryHistory, createRouter } from 'vue-router'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
import CreateProjectDialog from '@/features/projects/components/CreateProjectDialog.vue'
import BreakdownPage from '@/features/breakdown/BreakdownPage.vue'
import CreateDramaPage from '@/features/create-drama/CreateDramaPage.vue'
@@ -15,7 +16,6 @@ import ShotTools from '@/features/storyboard/components/ShotTools.vue'
import {
designedShot,
directionsResult,
episodeShots,
storyboardCheckpoint,
visualStatesResult
} from '@/features/storyboard/testing/fixtures'
@@ -53,6 +53,58 @@ function jsonResponse(data: unknown) {
return new Response(JSON.stringify({ data }))
}
/**
* 为页面模拟请求补齐正式模型目录和配置,后台启动返回 202 句柄,结果只从任务 GET 读取;响应逐次复制避免消费同一正文。
* @param fetcher 业务 API 模拟请求
*/
function stubFetch(fetcher: Mock<typeof fetch>) {
const implementation = fetcher.getMockImplementation()!
const executions = new Map<string, object>()
let executionCount = 0
fetcher.mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
if (path.includes('/workflow-executions/')) return jsonResponse(executions.get(path.split('/').at(-1)!))
const response = await implementation(url, init)
const workflowName = path.endsWith('/storyboard-directions/generate')
? 'storyboard-direction'
: path.endsWith('/storyboard-visual-states/generate')
? 'storyboard-visual-state'
: path.endsWith('/storyboard-shots/regenerate')
? 'breakdown'
: ''
if (init?.method === 'POST' && workflowName && response.ok) {
const result = (await response.clone().json()).data
const executionId = `page-execution-${++executionCount}`
const body = JSON.parse(String(init.body))
executions.set(executionId, {
id: executionId,
projectId: fixture.id,
workflowName,
status: 'completed',
stage: 'finalize',
current: 1,
total: 1,
currentResourceId: null,
metadata:
workflowName === 'breakdown'
? { action: 'regenerate-storyboard-episode', episodeNo: body.episodeNo }
: null,
result,
error: null,
startedAt: '2026-10-08T00:00:00Z',
completedAt: '2026-10-08T00:00:01Z',
createdAt: '2026-10-08T00:00:00Z',
updatedAt: '2026-10-08T00:00:01Z'
})
return new Response(JSON.stringify({ data: { executionId, status: 'pending' } }), { status: 202 })
}
return response.clone()
})
vi.stubGlobal('fetch', fetcher)
}
/** 模拟 API 响应仅用于测试,不会打包进生产页面。 */
const fixture: ProjectDetail = {
id: 'page-test-project',
@@ -109,7 +161,9 @@ function button(label: string): HTMLButtonElement {
async function confirmGeneration(label: string) {
button(label).click()
await flushPromises()
const acknowledgement = document.querySelector<HTMLElement>('.app-dialog [role="checkbox"]')
const acknowledgement = button('确认' + label)
.closest('.app-dialog')!
.querySelector<HTMLElement>('[role="checkbox"]')
expect(button('确认' + label).disabled).toBe(true)
acknowledgement!.click()
await flushPromises()
@@ -153,6 +207,7 @@ afterEach(() => {
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
localStorage.clear()
Object.assign(getStoryboardSession(fixture.id), { receipt: null, prompts: {}, regeneratedEpisodes: {} })
getImageSession(fixture.id).receipt = null
getImageSession(fixture.id).promptReceipt = null
@@ -181,7 +236,7 @@ describe('内容级滚动下的生产反馈', () => {
})
return jsonResponse([])
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
@@ -207,7 +262,7 @@ describe('内容级滚动下的生产反馈', () => {
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('默认折叠总览时查询错误仍显示在内容区外层', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new Error('生产连接中断')))
stubFetch(vi.fn<typeof fetch>().mockRejectedValue(new Error('生产连接中断')))
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
@@ -221,7 +276,7 @@ describe('内容级滚动下的生产反馈', () => {
})
it('回执返回时自动展开总览,部分失败诊断不会留在折叠区内', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockRejectedValue(new Error('离线测试')))
stubFetch(vi.fn<typeof fetch>().mockRejectedValue(new Error('离线测试')))
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
@@ -255,17 +310,16 @@ describe('视觉风格与主体身份工作区', () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => jsonResponse(locked === null ? null : styleFixture({ isLocked: locked })))
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('style')
const status = wrapper!.get('.visual-style-status')
expect(status.attributes('role')).toBe('status')
expect(status.get('strong').text()).toBe(label)
expect(status.find('button').exists()).toBe(false)
expect(wrapper!.find('.visual-style-toolbar .n-tag').exists()).toBe(false)
expect(wrapper!.get('.visual-style-actions').findAll('button')).toHaveLength(2)
expect(wrapper!.get('.visual-style-actions').findAll('button')).toHaveLength(1)
expect(button(action).disabled).toBe(disabled)
expect(button(action).style.getPropertyValue('--n-height')).toBe('34px')
expect(button('刷新风格').style.getPropertyValue('--n-height')).toBe('34px')
expect(fetcher.mock.calls.every(([, options]) => !options?.method || options.method === 'GET')).toBe(true)
})
@@ -320,9 +374,9 @@ describe('视觉风格与主体身份工作区', () => {
})
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
await drawerPanel().get('[aria-label="关闭操作面板"]').trigger('click')
await drawerPanel().get('.n-card-header__close').trigger('click')
await flushPromises()
const items = wrapper!.findAll('.identity-subject-item')
expect(items).toHaveLength(3)
@@ -337,7 +391,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('从形态深链接进入后,手动切换主体不会被目录刷新切回', async () => {
it('从形态深链接进入后,手动选择其它主体保持当前选择', async () => {
const form = formFixture()
const second = {
...form,
@@ -346,8 +400,7 @@ describe('视觉风格与主体身份工作区', () => {
images: [],
subject: { ...form.subject, id: 'subject-2', name: '陆川', ref: '@CH0002' }
}
vi.stubGlobal(
'fetch',
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([form, second])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
@@ -360,8 +413,6 @@ describe('视觉风格与主体身份工作区', () => {
expect(sidebar.get('.identity-subject-list').findAll('.directory-item')).toHaveLength(2)
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
await flushPromises()
await wrapper!.get('[aria-label="刷新主体目录"]').trigger('click')
await flushPromises()
expect(wrapper!.findAll('.identity-subject-item')[1]!.attributes('aria-pressed')).toBe('true')
})
@@ -383,23 +434,27 @@ describe('视觉风格与主体身份工作区', () => {
if (init?.method === 'PUT') identity = { ...identity, ...JSON.parse(init.body as string) }
return jsonResponse(identity)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
await wrapper!.get('#identity-description').setValue('人工稳定身份')
await wrapper!.get('#identity-lock').trigger('click')
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份')
await new DOMWrapper(document.body).get('#identity-lock').trigger('click')
button('保存主体身份').click()
await flushPromises()
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)
await wrapper!.get('#identity-description').setValue('新的未保存草稿')
await new DOMWrapper(document.body).get('#identity-description').setValue('新的未保存草稿')
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
expect(wrapper!.text()).toContain('切换会丢弃草稿')
expect((wrapper!.get('#identity-description').element as HTMLTextAreaElement).value).toBe('新的未保存草稿')
expect(document.body.textContent).toContain('切换会丢弃草稿')
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
'新的未保存草稿'
)
button('放弃草稿并切换').click()
await flushPromises()
expect((wrapper!.get('#identity-description').element as HTMLTextAreaElement).value).toBe('')
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
''
)
})
it('风格图拒绝危险 URL,登记只传已有地址及分类排序', async () => {
@@ -407,7 +462,7 @@ describe('视觉风格与主体身份工作区', () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async (_url, init) => jsonResponse(init?.method === 'POST' ? image : styleFixture()))
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('style')
await wrapper!.get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('登记参考图').click()
@@ -431,7 +486,7 @@ describe('视觉风格与主体身份工作区', () => {
it('AI 确认取消后重新打开必须再次确认,不能复用上次勾选', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(styleFixture()))
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('style')
button('AI 重新生成风格').click()
await flushPromises()
@@ -451,7 +506,7 @@ describe('视觉风格与主体身份工作区', () => {
if (init?.method === 'PUT') style = styleFixture(JSON.parse(init.body as string))
return jsonResponse(style)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('style')
expect(wrapper!.text()).toContain('尚未创建')
await expandSections()
@@ -479,26 +534,19 @@ describe('视觉风格与主体身份工作区', () => {
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('刷新风格不覆盖未保存草稿,草稿存在时禁止 AI 重生成', async () => {
it('未保存风格草稿保持人工输入并禁止 AI 重生成', async () => {
let style = styleFixture()
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(style))
)
stubFetch(vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(style)))
await mountAssets('style')
await wrapper!.get('#style-prompt').setValue('人工草稿')
style = styleFixture({ prompt: '后台新内容' })
button('刷新风格').click()
await flushPromises()
expect((wrapper!.get('#style-prompt').element as HTMLTextAreaElement).value).toBe('人工草稿')
expect(button('AI 重新生成风格').disabled).toBe(true)
})
it('风格接口 404 显示错误而不是当作空风格,禁止写入', async () => {
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockResolvedValue(new Response('{"message":"路由不存在"}', { status: 404 }))
)
stubFetch(vi.fn<typeof fetch>().mockResolvedValue(new Response('{"message":"路由不存在"}', { status: 404 })))
await mountAssets('style')
expect(wrapper!.text()).toContain('路由不存在')
expect(button('AI 生成风格').disabled).toBe(true)
@@ -520,7 +568,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(String(url)).toContain('/visual-style')
return jsonResponse(styleFixture({ images: removed ? [] : [image] }))
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('style')
button('停用').click()
await flushPromises()
@@ -546,13 +594,13 @@ describe('视觉风格与主体身份工作区', () => {
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
return jsonResponse(null)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.findAll('.identity-subject-item')).toHaveLength(1)
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('生成身份文本').disabled).toBe(false)
})
it('锁定阻止身份 AI 覆盖但不阻止人工编辑,并按步骤进入后续操作', async () => {
@@ -563,16 +611,16 @@ describe('视觉风格与主体身份工作区', () => {
if (String(url).endsWith('/identity/images')) return jsonResponse([identityImageFixture()])
return jsonResponse(identityFixture({ isLocked: true }))
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.text()).toContain('主体身份已完成')
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)
})
it('无项目风格时禁止生成身份和图片,但仍可人工保存身份', async () => {
vi.stubGlobal(
'fetch',
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(null)
@@ -582,6 +630,7 @@ describe('视觉风格与主体身份工作区', () => {
)
await mountAssets('identity')
expect(button('设置视觉风格').disabled).toBe(false)
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份草稿')
expect(button('保存主体身份').disabled).toBe(false)
})
@@ -601,7 +650,7 @@ describe('视觉风格与主体身份工作区', () => {
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
return jsonResponse(null)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
await confirmGeneration('补齐全部主体身份文本')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
@@ -621,13 +670,18 @@ describe('视觉风格与主体身份工作区', () => {
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (init?.method === 'PUT') {
selected = true
return jsonResponse(identityImageFixture({ id: 'candidate' }))
return jsonResponse({
identityId: 'identity-db-1',
subjectId: 'subject-db-1',
isLocked: true,
anchor: identityImageFixture({ id: 'candidate', isAnchor: true })
})
}
if (String(url).endsWith('/identity/images'))
return jsonResponse([identityImageFixture({ id: 'candidate', isAnchor: selected })])
return jsonResponse(identityFixture())
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
button('设为身份母版').click()
await flushPromises()
@@ -635,7 +689,7 @@ describe('视觉风格与主体身份工作区', () => {
button('确认切换身份母版').click()
await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe(
'/api/subjects/subject-db-1/identity/images/candidate/anchor'
'/api/subjects/subject-db-1/identity/images/candidate/stable-anchor'
)
expect(wrapper!.text()).toContain('当前身份母版')
const anchorImage = wrapper!
@@ -686,7 +740,7 @@ describe('视觉风格与主体身份工作区', () => {
})
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
expect(drawerPanel().get('.identity-tools-intro').text()).toContain('为同一个人物、场景或道具固定稳定特征')
const cards = drawerPanel().get('[aria-label="角色选角进度"]').findAll('.casting-item')
@@ -702,7 +756,9 @@ describe('视觉风格与主体身份工作区', () => {
expect(cards[0]!.attributes('aria-pressed')).toBe('false')
expect(cards[1]!.attributes('aria-pressed')).toBe('true')
expect(cards[1]!.classes()).toContain('selected')
expect(wrapper!.get<HTMLTextAreaElement>('#identity-description').element.value).toBe('老周的稳定身份')
expect(new DOMWrapper(document.body).get<HTMLTextAreaElement>('#identity-description').element.value).toBe(
'老周的稳定身份'
)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/subjects/subject-db-2/identity'))).toBe(true)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
@@ -751,7 +807,7 @@ describe('视觉风格与主体身份工作区', () => {
}
return jsonResponse(identityFixture({ isLocked: locked }))
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.text()).toContain('等待确认演员')
button('确认选角并锁定').click()
@@ -788,7 +844,7 @@ describe('视觉风格与主体身份工作区', () => {
identityFixture({ id: 'identity-2', subjectId: 'subject-2', description: '陆川的稳定身份' })
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountAssets('identity')
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
await flushPromises()
@@ -797,7 +853,9 @@ describe('视觉风格与主体身份工作区', () => {
).toBe(true)
finish(jsonResponse(identityFixture()))
await flushPromises()
expect((wrapper!.get('#identity-description').element as HTMLTextAreaElement).value).toBe('陆川的稳定身份')
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
'陆川的稳定身份'
)
})
it('生成失败不自动重发,后端正在拆解时禁止身份写操作', async () => {
@@ -809,7 +867,7 @@ describe('视觉风格与主体身份工作区', () => {
if (String(url).endsWith('/identity')) return jsonResponse(null)
return jsonResponse(identityFixture())
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
const provided = await mountAssets('identity')
button('生成身份文本').click()
await flushPromises()
@@ -817,7 +875,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(getOperation(fixture.id).error).toContain('无法连接后端')
provided.data.value!.project = { ...fixture, status: 'generating' }
await flushPromises()
expect(button('保存主体身份').disabled).toBe(true)
expect(new DOMWrapper(document.body).get('#identity-description').attributes('disabled')).toBeDefined()
expect(button('生成身份文本').disabled).toBe(true)
})
})
@@ -832,7 +890,7 @@ describe('工作台页面交互', () => {
subject: { ...person.subject, id: 'scene-subject', ref: '@SC0001', name: '旧书店', module: 'scene' }
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse([person, scene]))
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
const filters = wrapper!.get('.form-image-filters')
expect(wrapper!.get('.form-image-toolbar').classes()).not.toContain('has-impact-picker')
@@ -879,18 +937,23 @@ describe('工作台页面交互', () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: [formFixture()] })))
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
expect(wrapper!.get('.form-image-card img').attributes('src')).toContain(
'/storage/subjects/project/form/image.png'
)
expect(wrapper!.text()).toContain('林知夏')
expect(wrapper!.text()).toContain('主参考图')
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method])).toEqual([
['/api/projects/page-test-project/subject-forms', 'GET'],
['/api/projects/page-test-project/keyframes/readiness?force=false', 'GET'],
['/api/projects/page-test-project/videos/readiness?force=false', 'GET']
])
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method])).toEqual(
expect.arrayContaining([
['/api/projects/page-test-project/subject-forms', 'GET'],
['/api/generation-models', 'GET'],
['/api/projects/page-test-project/creative-profile', 'GET'],
['/api/projects/page-test-project/keyframes/readiness?force=false', 'GET'],
['/api/projects/page-test-project/videos/readiness?force=false', 'GET']
])
)
expect(fetcher).toHaveBeenCalledTimes(5)
await wrapper!.get('[aria-label="搜索形态图片"]').setValue('不存在的形态')
expect(wrapper!.text()).toContain('没有匹配的形态')
button('清除筛选').click()
@@ -905,9 +968,9 @@ describe('工作台页面交互', () => {
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [form] : form.images)
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
await drawerPanel().get('[aria-label="关闭操作面板"]').trigger('click')
await drawerPanel().get('.n-card-header__close').trigger('click')
const card = wrapper!.get('.form-image-card')
expect(card.getComponent(NImage).props()).toMatchObject({ objectFit: 'contain', previewDisabled: false })
await card.get('img').trigger('click')
@@ -916,7 +979,7 @@ describe('工作台页面交互', () => {
'/storage/subjects/project/form/image.png'
)
expect(document.querySelector('.image-history')).toBeNull()
expect(fetcher).toHaveBeenCalledTimes(3)
expect(fetcher).toHaveBeenCalledTimes(5)
document.querySelector<HTMLElement>('.n-image-preview-overlay')!.click()
await flushPromises()
button('查看图片与记录').click()
@@ -930,25 +993,32 @@ describe('工作台页面交互', () => {
const form = formFixture()
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'POST') {
const candidate = imageFixture({ id: 'new-candidate', isPrimary: false, imageUrl: '/storage/new.png' })
const candidate = imageFixture({
id: 'new-candidate',
isPrimary: false,
status: 'pending',
imageUrl: null
})
form.images.unshift(candidate)
return new Response(JSON.stringify({ data: candidate }))
}
return new Response(JSON.stringify({ data: [form] }))
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
button('再生成一张').click()
await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
document
.querySelector('.app-dialog form')!
.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
button('确认生成图片').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/subject-forms/form-db-1/images')
expect(JSON.parse(post[1]!.body as string)).toEqual({ setPrimary: false })
expect(JSON.parse(post[1]!.body as string)).toEqual({
setPrimary: false,
provider: 'qwen-image',
generationOptions: { size: '2048*2048' }
})
expect(wrapper!.text()).toContain('2 条记录')
expect(wrapper!.get('.form-image-card img').attributes('src')).not.toContain('/storage/new.png')
expect(fetcher.mock.calls.some(([url]) => String(url).includes('production/start'))).toBe(false)
@@ -973,7 +1043,7 @@ describe('工作台页面交互', () => {
})
)
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
await wrapper!.get('[aria-label="搜索形态图片"]').setValue('@CH0001')
await confirmGeneration('补齐项目主参考图')
@@ -981,7 +1051,10 @@ describe('工作台页面交互', () => {
expect(drawerPanel().text()).toContain('服务暂不可用')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(JSON.parse(post[1]!.body as string)).toEqual({ concurrency: 2, force: false })
await drawerPanel().get('.n-collapse [role="checkbox"]').trigger('click')
await drawerPanel()
.findAll('[role="checkbox"]')
.find(item => item.text().includes('已有主图也新增候选图'))!
.trigger('click')
await confirmGeneration('为全项目新增候选图')
const lastPost = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST').at(-1)!
expect(JSON.parse(lastPost[1]!.body as string).force).toBe(true)
@@ -998,15 +1071,17 @@ describe('工作台页面交互', () => {
? new Response('{"message":"数据库异常"}', { status: 500 })
: new Response(JSON.stringify({ data: [form] }))
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountSubjectImages()
expect(button('再生成一张').disabled).toBe(true)
expect(wrapper!.text()).toContain('数据库中仍有排队或生成中的图片')
expect(wrapper!.text()).toContain('数据库中有形态图片正在后台生成')
fail = true
button('刷新图库').click()
button('查看图片与记录').click()
await flushPromises()
expect(wrapper!.text()).toContain('数据库异常')
expect(document.body.textContent).toContain('数据库异常')
expect(wrapper!.find('.form-image-card img').exists()).toBe(true)
await new DOMWrapper(button('刷新图片').closest('.app-dialog')!).get('.n-card-header__close').trigger('click')
await flushPromises()
expect(button('补齐项目主参考图').disabled).toBe(true)
})
it('分镜参考图使用 cover 和原生预览,查看图片不触发生成功能', async () => {
@@ -1030,9 +1105,8 @@ describe('工作台页面交互', () => {
missing: []
})
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
wrapper = mount(ShotTools, { attachTo: document.body, props: { projectId: fixture.id, shot, disabled: false } })
button('读取参考图').click()
await flushPromises()
expect(wrapper.getComponent(NImage).props()).toMatchObject({ objectFit: 'cover', previewDisabled: false })
const image = wrapper.get('.reference-card img')
@@ -1097,9 +1171,8 @@ describe('工作台页面交互', () => {
})
)
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
wrapper = mount(ShotTools, { attachTo: document.body, props: { projectId: fixture.id, shot, disabled: false } })
button('读取参考图').click()
await flushPromises()
expect(wrapper.text()).toContain('图片不可用')
expect(wrapper.find('.reference-card a').exists()).toBe(false)
@@ -1130,12 +1203,12 @@ describe('工作台页面交互', () => {
)
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
await confirmGeneration('补齐项目导演设计')
expect(button('补齐项目导演设计').disabled).toBe(true)
await drawerPanel().get('[aria-label="关闭操作面板"]').trigger('click')
await drawerPanel().get('.n-card-header__close').trigger('click')
await flushPromises()
expect(wrapper!.get('[data-workspace-tools]').attributes('aria-expanded')).toBe('false')
expect(getOperation(fixture.id).pending).toBe(true)
@@ -1149,6 +1222,12 @@ describe('工作台页面交互', () => {
)
)
await flushPromises()
expect(getStoryboardSession(fixture.id).receipt).toBeNull()
expect(localStorage.getItem('short-drama:workflow-execution:page-test-project:storyboard-direction')).toBe(
'page-execution-1'
)
await mountStoryboard()
await flushPromises()
expect(getStoryboardSession(fixture.id).receipt).toMatchObject({
kind: 'batch',
title: '项目导演设计'
@@ -1191,7 +1270,7 @@ describe('工作台页面交互', () => {
: visualStatesResult(fixture.id)
return new Response(JSON.stringify({ data: result }))
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
expect(wrapper!.text()).not.toContain('生成本集导演设计')
@@ -1211,16 +1290,12 @@ describe('工作台页面交互', () => {
expect(drawerPanel().text()).toContain('缺少主体状态')
})
it('重生成当前集镜头后刷新正式设计,并用接口回执替换过期 Breakdown 文本', async () => {
const regenerated = episodeShots()
regenerated.beatShots[0]!.shots[0]!.title = '重生成后的开场镜头'
regenerated.beatShots[0]!.shots[0]!.description = '新的镜头正文'
it('重生成当前集镜头后读取后台终态,并废弃过期 Breakdown 文本', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return jsonResponse({
projectId: fixture.id,
episodeNo: 1,
episodeShot: regenerated,
storyboardShotSummary: {
episodeCount: 1,
beatCount: 2,
@@ -1238,20 +1313,25 @@ describe('工作台页面交互', () => {
: visualStatesResult(fixture.id)
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await confirmGeneration('重生成第 1 集镜头')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/projects/page-test-project/storyboard-shots/regenerate')
expect(JSON.parse(post[1]!.body as string)).toEqual({ episodeNo: 1 })
expect(wrapper!.text()).toContain('重生成后的开场镜头')
expect(wrapper!.text()).toContain('新的镜头正文')
expect(wrapper!.text()).not.toContain('第1集镜头1')
expect(wrapper!.text()).not.toContain('门口收到一封信')
expect(getStoryboardSession(fixture.id).invalidatedEpisodeSources[1]).toBe(true)
expect(wrapper!.text()).toContain('新标题和剧情详情尚未提供')
expect(drawerPanel().text()).toContain('本集新镜头已保存')
expect(drawerPanel().text()).toContain('2 个镜头')
expect(fetcher.mock.calls.filter(([, init]) => !init?.method || init.method === 'GET')).toHaveLength(4)
expect(fetcher.mock.calls.filter(([, init]) => !init?.method || init.method === 'GET')).toHaveLength(8)
expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe(
true
)
})
it('批量 200 部分失败不显示全成功,默认补齐与显式覆盖参数独立', async () => {
it('后台终态部分失败不显示全成功,默认补齐与显式覆盖参数独立', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return new Response(
@@ -1286,7 +1366,7 @@ describe('工作台页面交互', () => {
})
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
await confirmGeneration('补齐项目导演设计')
@@ -1319,7 +1399,7 @@ describe('工作台页面交互', () => {
)
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
selectControl(wrapper!, 'aria-label', '选择分镜剧集').vm.$emit('update:value', 2)
@@ -1341,8 +1421,8 @@ describe('工作台页面交互', () => {
expect(fetcher.mock.calls).toHaveLength(4)
})
it('查询失败保留已读取镜头并禁用生成,刷新恢复后才允许操作', async () => {
let fail = false
it('首次分镜读取失败时禁用生成,重试恢复后才允许操作', async () => {
let fail = true
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (fail) return new Response('{"message":"数据库暂不可用"}', { status: 503 })
return new Response(
@@ -1353,19 +1433,16 @@ describe('工作台页面交互', () => {
})
)
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
fail = true
button('刷新分镜').click()
await flushPromises()
expect(wrapper!.text()).toContain('shot-db-1-1')
expect(wrapper!.text()).toContain('数据库暂不可用')
expect(button('补齐项目导演设计').disabled).toBe(true)
fail = false
button('重试查询').click()
await flushPromises()
expect(button('补齐项目导演设计').disabled).toBe(false)
expect(wrapper!.text()).toContain('shot-db-1-1')
})
it('镜头工具按需 GET,切换镜头会废弃旧参考图,未完成设计不能编译规格', async () => {
@@ -1376,13 +1453,12 @@ describe('工作台页面交互', () => {
finish = resolve
})
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
wrapper = mount(ShotTools, {
attachTo: document.body,
props: { projectId: fixture.id, shot: designedShot(), disabled: false }
})
expect(fetcher).not.toHaveBeenCalled()
button('读取参考图').click()
expect(fetcher).toHaveBeenCalledTimes(1)
await flushPromises()
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/references')
await wrapper.setProps({ shot: { ...designedShot('shot-db-1-2'), visualState: null } })
@@ -1398,40 +1474,41 @@ describe('工作台页面交互', () => {
})
it('提示词必须确认才 POST,使用正式 Shot ID,返回内容以纯文本显示', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
new Response(
JSON.stringify({
data: {
shotId: 'shot-db-1-1',
updatedAt: '2026-09-10T00:00:00Z',
videoPrompt: '<script>模型内容</script>',
negativePrompt: '模糊',
status: 'prompt_ready'
}
})
)
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) =>
init?.method !== 'POST'
? jsonResponse({ shotId: 'shot-db-1-1', references: [], missing: [] })
: new Response(
JSON.stringify({
data: {
shotId: 'shot-db-1-1',
updatedAt: '2026-09-10T00:00:00Z',
videoPrompt: '<script>模型内容</script>',
negativePrompt: '模糊',
status: 'prompt_ready'
}
})
)
)
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
wrapper = mount(ShotTools, {
attachTo: document.body,
props: { projectId: fixture.id, shot: designedShot(), disabled: false }
})
expect(fetcher).not.toHaveBeenCalled()
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
await confirmGeneration('读取/生成提示词')
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/video-prompt')
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ force: false })
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/storyboard-shots/shot-db-1-1/video-prompt')
expect(JSON.parse(post[1]!.body as string)).toEqual({ force: false })
expect(wrapper.text()).toContain('<script>模型内容</script>')
expect(wrapper.find('script').exists()).toBe(false)
})
it('提示词生成缺少主首帧时保存当前剧集和镜头作为恢复位置', async () => {
vi.stubGlobal(
'fetch',
stubFetch(
vi.fn<typeof fetch>().mockResolvedValue(
new Response(
JSON.stringify({
message:
'服务器内部错误 Shot 缺少可用于视频 0 秒起点校验的 Primary Keyframe: shot-db-1-1'
message: '服务器内部错误 Shot 缺少可用于视频 0 秒起点校验的 Primary Keyframe: shot-db-1-1'
}),
{ status: 500 }
)
@@ -1451,8 +1528,7 @@ describe('工作台页面交互', () => {
})
})
it('项目筛选无结果时可清除条件并返回真实列表', async () => {
vi.stubGlobal(
'fetch',
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: [fixture] })))
)
const router = createRouter({
@@ -1463,10 +1539,6 @@ describe('工作台页面交互', () => {
wrapper = mount(ProjectsPage, { attachTo: document.body, global: { plugins: [router] } })
await flushPromises()
expect(wrapper.getComponent(NRadioGroup).props('size')).toBe('medium')
const refresh = wrapper.get('[aria-label="刷新项目"]')
expect(refresh.classes()).toContain('icon-button')
expect(refresh.find('.n-button__icon svg').exists()).toBe(true)
expect(refresh.text()).toBe('')
expect(wrapper.text()).toContain('雨夜来信')
await wrapper.get('input[aria-label="搜索项目"]').setValue('不存在的关键词')
expect(wrapper.text()).toContain('没有匹配的剧本')
@@ -1478,11 +1550,16 @@ describe('工作台页面交互', () => {
it('新建弹窗提交真实参数并返回 202 的项目 ID', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValue(new Response('{"projectId":"created","status":"generating"}', { status: 202 }))
vi.stubGlobal('fetch', fetcher)
.mockResolvedValue(
new Response('{"projectId":"created","executionId":"create-1","status":"pending"}', { status: 202 })
)
stubFetch(fetcher)
wrapper = mount(CreateProjectDialog, { attachTo: document.body })
button('新建剧本').click()
await flushPromises()
const title = document.querySelector<HTMLInputElement>('#title')!
title.value = ' 雨夜来信标题 '
title.dispatchEvent(new Event('input', { bubbles: true }))
const topic = document.querySelector<HTMLTextAreaElement>('#topic')!
topic.value = ' 雨夜来信 '
topic.dispatchEvent(new Event('input', { bubbles: true }))
@@ -1491,8 +1568,9 @@ describe('工作台页面交互', () => {
count.dispatchEvent(new Event('input', { bubbles: true }))
document.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await flushPromises()
expect(wrapper.emitted('created')).toEqual([['created']])
expect(wrapper.emitted('created')).toEqual([['created', 'create-1']])
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({
title: '雨夜来信标题',
topic: '雨夜来信',
style: '',
episodeCount: 6
@@ -1507,7 +1585,7 @@ describe('工作台页面交互', () => {
)
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
vi.stubGlobal('fetch', fetcher)
stubFetch(fetcher)
const provided = context()
wrapper = mount(BreakdownPage, {
attachTo: document.body,
+49
View File
@@ -0,0 +1,49 @@
import type { CreativeProfile, GenerationModelCatalog } from '@/features/generation-config/types'
/** 模拟后端图片目录,只开放该模型支持的尺寸枚举。 */
export const imageCatalog: GenerationModelCatalog = {
defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' },
images: [
{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-image-3.0-pro',
modelLabel: 'Qwen Image',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [
{
key: 'size',
label: '图片尺寸',
type: 'size',
required: true,
options: [{ label: '1:1 · 2048×2048', value: '2048*2048' }]
}
],
defaults: { size: '2048*2048' },
projectConstraints: []
}
],
videos: []
}
/**
* 构造与目录一致的正式项目生成配置。
* @param projectId 当前正式项目 ID
* @returns 项目画布、模型和有限尺寸参数
*/
export function generationProfile(projectId: string): CreativeProfile {
return {
projectId,
aspectRatio: '1:1',
imageProvider: 'qwen-image',
imageModel: 'qwen-image-3.0-pro',
imageOptions: { size: '2048*2048' },
videoProvider: 'seedance',
videoModel: 'seedance',
videoOptions: {}
}
}
+65 -13
View File
@@ -1,4 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { effectScope, ref } from 'vue'
import { useWorkflowExecution } from '@/features/workflows/execution'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
import { ApiError, optionalResource, request } from '@/lib/http'
import { projectsApi } from '@/features/projects/api'
import { breakdownApi } from '@/features/breakdown/api'
@@ -184,21 +188,69 @@ describe('后端 API 契约', () => {
])
})
it('长工作流不使用普通查询的超时,不自动重试 POST', async () => {
it('拆解返回 202 观察句柄,后续轮询失败终态不会自动重发 POST', async () => {
vi.useFakeTimers()
let finish!: (value: Response) => void
const fetcher = vi.fn<(url: string, options: RequestInit) => Promise<Response>>().mockImplementation(
() =>
new Promise<Response>(resolve => {
finish = resolve
})
/** 真实执行查询字段,开始回执与失败终态分别由不同接口返回。 */
const record: WorkflowExecution = {
id: 'http-breakdown-execution',
projectId: 'http-breakdown-project',
workflowName: 'breakdown',
status: 'running',
stage: 'breakdown',
current: 0,
total: 1,
currentResourceId: null,
metadata: null,
result: null,
error: null,
startedAt: '2026-10-08T00:00:00Z',
completedAt: null,
createdAt: '2026-10-08T00:00:00Z',
updatedAt: '2026-10-08T00:00:00Z'
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data: init?.method === 'POST' ? { executionId: record.id, status: 'pending', total: 1 } : record
}),
{ status: init?.method === 'POST' ? 202 : 200 }
)
)
vi.stubGlobal('fetch', fetcher)
const running = breakdownApi.run('p', 'start', { groupSize: 3, modules: ['prop'] })
await vi.advanceTimersByTimeAsync(120_000)
expect(fetcher).toHaveBeenCalledTimes(1)
expect(fetcher.mock.calls[0]![1].signal?.aborted).toBe(false)
finish(new Response('{"data":{"workflowExecution":{"status":"failed"}}}'))
expect(await running).toMatchObject({ workflowExecution: { status: 'failed' } })
const started = await breakdownApi.run(record.projectId, 'start', { groupSize: 3, modules: ['prop'] })
expect(started).toEqual({ executionId: record.id, status: 'pending', total: 1 })
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/projects/http-breakdown-project/breakdown/start')
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ groupSize: 3, modules: ['prop'] })
const scope = effectScope()
const tracker = scope.run(() => useWorkflowExecution(ref(record.projectId), 'breakdown'))!
try {
await tracker.track(started.executionId)
await flushPromises()
expect(tracker.active.value).toBe(true)
expect(tracker.query.data.value?.status).toBe('running')
record.status = 'failed'
record.error = '后端抽取失败'
record.completedAt = '2026-10-08T00:01:00Z'
await vi.advanceTimersByTimeAsync(1_500)
await flushPromises()
expect(tracker.query.data.value).toMatchObject({ status: 'failed', error: '后端抽取失败' })
expect(tracker.active.value).toBe(false)
const completedCount = fetcher.mock.calls.length
await vi.advanceTimersByTimeAsync(120_000)
expect(fetcher).toHaveBeenCalledTimes(completedCount)
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
expect(
fetcher.mock.calls
.slice(1)
.every(
([url, init]) =>
url === '/api/workflow-executions/http-breakdown-execution' && init?.method === 'GET'
)
).toBe(true)
} finally {
tracker.dismiss()
scope.stop()
}
})
})
+7 -2
View File
@@ -1,10 +1,15 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vitest/config'
import { configDefaults, defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
/** 使用轻量 DOM 测试 API、异步状态和 Vue 页面行为。 */
export default defineConfig({
plugins: [vue()],
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
test: { environment: 'happy-dom', restoreMocks: true }
test: {
environment: 'happy-dom',
restoreMocks: true,
/** 只检查当前 checkout,避免收集其它隔离 worktree 中的重复测试。 */
exclude: [...configDefaults.exclude, '**/.worktrees/**', '**/.worktree/**']
}
})