fix(short-drama-agent-front): 修复拆解进度展示与问题交互

This commit is contained in:
GJ committed 2026-10-17 10:21:44 +08:00
1 parent 3414cc8232
commit db91a4b871
19 files changed
+870 -150

No files matched your search

+12
View File
@@ -1,5 +1,17 @@
# 接口数据同步说明
## 2026-10-17 拆解任务发现与过程展示
- 项目布局通过 `GET /projects/:projectId/workflow-executions/latest?workflowName=breakdown` 发现服务端最新拆解任务,并通过同项目 `workflow-executions/events` 订阅任务变化。后端发起的新任务不再依赖当前浏览器保存过启动回执;没有任务时明确返回 null。
- 拆解页页头、设置弹窗和活动锁共用实际任务记录。运行期间隐藏“查看诊断”和节拍/镜头诊断按钮,禁用恢复、候选提交与质量修订。结束后读取最新结果,按真实终态恢复入口;切换项目和迟到消息不覆盖当前项目,终态不会被旧 running 消息重新激活。
- 后端只读观察视图使用同次运行时间窗口内的阶段快照补充阶段和进度。`metadata.progressUnit` 明确区分抽取任务与分镜剧集;状态仍以持久化任务为准,不把抽取 3/3 当作整个拆解完成。新任务尚无快照时标注“上次结果”,未知总量保持未知。
- 任务执行结束但 `storyboardShotValidation.valid=false` 时显示校验未通过,保留候选提交限制。发现失败提供重读入口,页面不定时刷新全量项目或完整 Checkpoint;只观察任务状态,终态时刷新业务结果。
- 本地 Chrome 读取“掩耳盗铃”的真实任务与校验结果;在临时隔离页面验证后台启动事件到达后诊断消失、进度显示“分镜剧集 1/3”、恢复操作禁用,以及结束事件后恢复诊断。隔离页禁止写请求,验证后已删除并恢复真实项目页面;没有重新拆解或调用模型。
- 详细执行异常与分镜校验问题移到独立“拆解问题”弹窗,按剧集/节拍/镜头分组,保留后端原始描述并合并重复消息。设置页仅展示问题数量和查看入口,移除重复快照统计、进度及长错误清单;问题弹窗关闭后可定位分镜或返回设置,弹窗之间不叠加焦点陷阱。候选、修订与恢复说明同步精简。
- 问题定位、错误详情卡片及问题摘要统一使用 `--app-danger-soft` 柔和红色背景,移除定位区域的绿色轮廓线;深浅主题分别使用适配底色,内部按钮的键盘焦点提示保留。Chrome 已验证深浅主题的真实问题镜头定位,验证后恢复原跟随系统主题。
本轮验证:前端全量 58 个文件/435 项测试及构建通过,颜色变更另通过 43 项针对性回归;后端只读观察、阶段归属和状态转换 16 项专项测试、类型检查、本次文件格式及静态检查通过。后端全量检查在格式阶段报告 8 个既有文件问题,均不属于本次改动,未修改这些文件。
## 2026-10-17 候选拆解、质量规则与阶段续跑
依据同级后端 `dev@dc884f0f` 的正式路由、候选提交服务、质量策略 schema、人工修订服务与 Production Prepare 节点核对。本轮在前端项目根目录 `dev` 适配,保留工作区原有页面改动。
+3 -1
View File
@@ -21,6 +21,8 @@ withDefaults(
}
)
const open = defineModel<boolean>('open', { default: false })
/** 工具弹窗完全关闭后通知调用方,便于切换独立的问题弹窗。 */
const emit = defineEmits<{ closed: [] }>()
</script>
<template>
@@ -41,7 +43,7 @@ const open = defineModel<boolean>('open', { default: false })
<span class="workspace-tools-label">{{ pending ? pendingLabel || '任务执行中' : label }}</span
><span v-if="hasReceipt" class="workspace-tools-receipt text-xs text-muted"> · 有回执</span>
</NButton>
<AppDialog v-model:open="open" :title="title" description="" wide>
<AppDialog v-model:open="open" :title="title" description="" wide @closed="emit('closed')">
<div class="workspace-tools-body"><slot /></div>
</AppDialog>
</template>
+157 -96
View File
@@ -1,32 +1,31 @@
<script setup lang="ts">
import ContextNotice from '../../components/ui/ContextNotice.vue'
import AppForm from '../../components/ui/AppForm.vue'
import { NFormItem } from 'naive-ui'
import { integerRule, fieldRule } from '../../lib/form-rules'
import WorkspacePage from '../../components/ui/WorkspacePage.vue'
import WorkspaceExportButton from '../../components/ui/WorkspaceExportButton.vue'
import { NScrollbar, NButton, NCheckbox, NInputNumber, NProgress, NTab, NTable, NTabs } from 'naive-ui'
import { computed, h, onScopeDispose, ref, watch } from 'vue'
import { NScrollbar, NButton, NCheckbox, NInputNumber, NTab, NTable, NTabs } from 'naive-ui'
import { computed, h, nextTick, onScopeDispose, ref, watch } from 'vue'
import { useActionMessage } from '../../components/ui/useActionMessage'
import { Layers, LoaderCircle, Settings2 } from '@lucide/vue'
import { EmptyState, StatusBadge, WorkspaceTools } from '../../components/ui'
import { useProjectContext } from '../projects/context'
import { breakdownApi } from './api'
import type { BreakdownAction, BreakdownInput, BreakdownModule, BreakdownPreview } from './types'
import type { BreakdownAction, BreakdownInput, BreakdownModule, BreakdownPreview, ShotValidation } from './types'
import { breakdownSnapshot, recoveryOptions, workflowCheckpoints } from '../workflows/selectors'
import { getOperation, isOperationRunning, runOperation } from '../workflows/operations'
import ConfirmAction from '../workflows/ConfirmAction.vue'
import WorkflowExecutionPanel from '../workflows/WorkflowExecutionPanel.vue'
import { useWorkflowExecution } from '../workflows/execution'
import { executionStageLabel, useWorkflowExecution } from '../workflows/execution'
import SubjectList from './components/SubjectList.vue'
import StoryboardList from './components/StoryboardList.vue'
import StoryboardDiagnosis from './components/StoryboardDiagnosis.vue'
import BreakdownCandidatePanel from './components/BreakdownCandidatePanel.vue'
import StoryboardQualityRepair from './components/StoryboardQualityRepair.vue'
import BreakdownIssuesDialog from './components/BreakdownIssuesDialog.vue'
import type { DiagnosisLocation } from './diagnosis'
import { errorMessage } from '../../lib/http'
import { downloadText, nodeLabel } from '../../lib/format'
import { downloadText } from '../../lib/format'
/** 拆解工作区:先预览真实分组,再启动;恢复操作根据 checkpoint 分阶段展示。 */
const { project, checkpoints, refresh, refreshStageReadiness, stageReadiness, error } = useProjectContext()
@@ -38,6 +37,10 @@ const previewBusy = ref(false)
const candidateOnly = ref(true)
const tab = ref('character')
const toolsOpen = ref(false)
/** 错误详情使用独立弹窗,不在设置区展开长文本。 */
const issuesOpen = ref(false)
/** 从设置切换时等待关闭动画结束,避免两层弹窗同时显示。 */
const pendingIssues = ref(false)
const moduleOptions: { value: BreakdownModule; label: string; description: string }[] = [
{ value: 'character', label: '人物', description: '人物身份、外观与形态' },
{ value: 'scene', label: '场景', description: '故事空间与环境特征' },
@@ -87,6 +90,7 @@ const diagnosisPanel = ref<InstanceType<typeof StoryboardDiagnosis> | null>(null
* @param location 当前分镜坐标
*/
function openShotDiagnosis(location: DiagnosisLocation) {
if (breakdownBusy.value || backgroundExecution.discovering.value) return
diagnosisPanel.value?.open(location)
}
/**
@@ -98,7 +102,72 @@ function locateDiagnosisShot(location: DiagnosisLocation) {
}
const backgroundExecution = useWorkflowExecution(projectId, 'breakdown')
const recovery = computed(() => recoveryOptions(checkpoints.value))
const execution = computed(() => snapshot.value?.workflowExecution)
/** 运行状态优先采用持久化任务;历史快照只作没有任务记录时的兼容来源。 */
const execution = computed(() => {
const record = backgroundExecution.query.data.value
return record
? {
executionId: record.id,
status: record.status === 'pending' ? ('running' as const) : record.status,
errorMessage: record.error ?? undefined,
startedAt: record.startedAt ?? record.createdAt,
completedAt: record.completedAt ?? undefined
}
: snapshot.value?.workflowExecution
})
/** 拆解运行状态同时控制状态栏、诊断入口及所有恢复写操作。 */
const breakdownBusy = computed(
() =>
backgroundExecution.active.value ||
execution.value?.status === 'running' ||
(operation.value.pending &&
['正在拆解剧本', '正在重试失败抽取', '正在补齐镜头', '正在修复分镜绑定'].includes(operation.value.label))
)
/** 当前持久化任务对应的后端阶段标签。 */
const runningStage = computed(() => executionStageLabel(backgroundExecution.query.data.value?.stage ?? 'breakdown'))
/** 新任务尚未保存阶段快照时,已有内容只代表上一轮结果。 */
const previousSnapshot = computed(() => {
const startedAt = backgroundExecution.query.data.value?.startedAt
return (
breakdownBusy.value &&
!!startedAt &&
!!latestCheckpoint.value &&
Date.parse(latestCheckpoint.value.createdAt) < Date.parse(startedAt)
)
})
/** 当前保存结果中的具体问题,只显示后端明确返回的校验失败。 */
const storyboardIssues = computed(() => (validation.value?.valid === false ? validation.value.issues : []))
/** 打开独立问题弹窗,从设置进入时先释放原弹窗焦点。 */
function openIssues() {
if (toolsOpen.value) {
pendingIssues.value = true
toolsOpen.value = false
} else issuesOpen.value = true
}
/** 设置弹窗离场完成后打开问题详情。 */
function finishOpeningIssues() {
if (pendingIssues.value) {
pendingIssues.value = false
issuesOpen.value = true
}
}
/**
* 切换到分镜结果并定位后端返回的真实问题坐标。
* @param issue 问题所属剧集、节拍和镜头
* @returns 分镜切换和定位完成
*/
async function locateIssue(issue: ShotValidation['issues'][number]) {
tab.value = 'storyboard'
selectedEpisodeNo.value = issue.episodeNo
await nextTick()
if (issue.beatNo)
await storyboardList.value?.locate({
episodeNo: issue.episodeNo,
beatNo: issue.beatNo,
...(issue.shotNo ? { shotNo: issue.shotNo } : {})
})
}
const taskStopped = computed(() => execution.value?.status === 'failed' || execution.value?.status === 'completed')
/** 后台拆解结束后自动刷新项目、Checkpoint 与正式主体/分镜数据。 */
watch(
@@ -137,6 +206,7 @@ watch(
() => {
const executionError = execution.value?.errorMessage
const invalid = validation.value?.valid === false
if (breakdownBusy.value || backgroundExecution.discovering.value) return
if (!executionError && !invalid) return
actionMessage?.warning(
() =>
@@ -152,10 +222,10 @@ watch(
{
text: true,
onClick: () => {
toolsOpen.value = true
openIssues()
}
},
() => '查看详情与恢复操作'
() => '查看问题'
)
]),
{ duration: 6000, closable: true }
@@ -176,6 +246,8 @@ const canStart = computed(
configValid.value &&
!operation.value.pending &&
!backgroundExecution.active.value &&
!backgroundExecution.discovering.value &&
!backgroundExecution.discoveryError.value &&
!error.value &&
(!records.value.length || taskStopped.value)
)
@@ -230,6 +302,7 @@ async function loadPreview() {
*/
async function run(action: BreakdownAction) {
if (project.value?.status !== 'completed' || operation.value.pending || error.value) return
if (breakdownBusy.value || backgroundExecution.discovering.value || backgroundExecution.discoveryError.value) return
if (action === 'start' && !canStart.value) return
const labels: Record<BreakdownAction, string> = {
start: '正在拆解剧本',
@@ -279,23 +352,40 @@ const rules = {
<!-- 以下是拆解状态与设置 -->
<div class="workspace-toolbar">
<h2 class="font-semibold">剧本拆解</h2>
<div v-if="snapshot" class="toolbar-summary">
<div v-if="snapshot || execution || backgroundExecution.discovering.value" class="toolbar-summary">
<span v-if="previousSnapshot">上次结果</span>
<span v-if="summary"
>抽取 {{ summary.completed }} / {{ summary.total }} · 失败 {{ summary.failed }}</span
>
<span>主体 {{ subjects.length }} · 分镜剧集 {{ shots.length }} / {{ plans.length }}</span>
<StatusBadge
:status="execution?.status || 'unknown'"
:status="
breakdownBusy
? 'running'
: validation?.valid === false
? 'blocked'
: execution?.status || 'unknown'
"
:label="
execution?.status === 'completed'
? latestCheckpoint?.state.candidateOnly && !latestCheckpoint.state.storyboardPersisted
? '候选生成已完成'
: '工作流已完成'
: execution?.status === 'failed'
? '工作流失败'
: '执行状态待确认'
breakdownBusy
? '拆解进行中'
: backgroundExecution.discovering.value
? '正在读取任务状态'
: validation?.valid === false
? '分镜校验未通过'
: execution?.status === 'completed'
? latestCheckpoint?.state.candidateOnly &&
!latestCheckpoint.state.storyboardPersisted
? '候选生成已完成'
: '工作流已完成'
: execution?.status === 'failed'
? '工作流失败'
: '执行状态待确认'
"
/>
<span v-if="breakdownBusy" class="flex items-center gap-2" role="status"
><LoaderCircle :size="13" class="animate-spin" />最近阶段:{{ runningStage }}</span
>
</div>
<!-- 以下是轻量状态入口,详细问题与恢复操作统一放入弹窗;阶段切换使用侧栏 -->
<div v-if="project?.episodes.length" class="toolbar-actions">
@@ -303,7 +393,7 @@ const rules = {
v-if="execution?.errorMessage || validation?.valid === false"
text
type="error"
@click="toolsOpen = true"
@click="openIssues"
>查看拆解问题</NButton
>
@@ -313,15 +403,22 @@ const rules = {
v-model:open="toolsOpen"
title="拆解设置与恢复"
label="拆解设置与恢复"
@closed="finishOpeningIssues"
>
<section class="panel workspace-panel breakdown-settings-panel">
<p
v-if="backgroundExecution.discoveryError.value"
class="mb-4 text-xs leading-6 text-danger"
role="alert"
>
{{ backgroundExecution.discoveryError.value }}
<NButton text @click="backgroundExecution.discover">重新读取后台状态</NButton>
</p>
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 class="flex items-center gap-2 font-semibold"><Layers :size="17" />拆解设置</h2>
<p class="mt-2 text-xs leading-5 text-muted">
读取已保存的
{{ project.episodes.length }}
集剧本。每个分组分别抽取所选模块,再生成主体与分镜。
按所选模块拆解已保存的 {{ project.episodes.length }} 集剧本。
</p>
</div>
</div>
@@ -401,9 +498,6 @@ const rules = {
>
仅生成候选,确认后再提交正式结果
</NCheckbox>
<p class="text-xs leading-6 text-muted">
候选不会替换现有主体和分镜。重新拆解使用候选模式,完成后单独审核与提交。
</p>
</div>
<div v-if="preview" class="group-preview">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
@@ -439,8 +533,11 @@ const rules = {
<p v-if="project.status === 'generating'" class="mt-4 text-xs text-danger">
剧本仍在生成,暂不允许启动拆解,避免读取到不完整的剧集。
</p>
<p v-if="records.length && !taskStopped" class="mt-4 text-xs leading-5 text-muted">
当前任务还没有明确的完成或失败记录。为避免重复执行,已暂停重新拆解;如任务已中断,请先刷新状态,再选择对应恢复操作。
<p v-if="breakdownBusy" class="mt-4 text-xs leading-5 text-muted">
拆解进行中,结束后自动更新结果。
</p>
<p v-else-if="records.length && !taskStopped" class="mt-4 text-xs leading-5 text-muted">
任务状态尚未确认,请重新读取后台状态后再操作。
</p>
</section>
<BreakdownCandidatePanel
@@ -468,76 +565,23 @@ const rules = {
@refresh="backgroundExecution.query.refresh"
@dismiss="backgroundExecution.dismiss"
/>
<section v-if="snapshot">
<div class="mb-3 flex flex-wrap items-center justify-between gap-3">
<h2 class="text-sm font-medium">
最近可用拆解快照
<span class="ml-2 text-xs font-normal text-muted">{{
nodeLabel(records.at(-1)?.metadata?.nodeName)
}}</span>
</h2>
<StatusBadge
:status="execution?.status || 'unknown'"
:label="
execution?.status === 'completed'
? '工作流已完成'
: execution?.status === 'failed'
? '工作流失败'
: '阶段快照 · 执行状态待确认'
"
/>
</div>
<div v-if="summary" class="flex flex-wrap items-center gap-x-6 gap-y-2 text-xs text-muted">
<span
>抽取完成
<strong class="text-ink"
>{{ summary.completed }} / {{ summary.total }}</strong
></span
><span>失败 {{ summary.failed }}</span
><span>主体 {{ subjects.length }}</span
><span>分镜剧集 {{ shots.length }} / {{ plans.length }}</span>
</div>
<NProgress
v-if="summary?.total"
aria-label="已完成抽取任务"
type="line"
:show-indicator="false"
:height="4"
:percentage="
Math.min(100, Math.max(0, (summary.completed / Math.max(1, summary.total)) * 100))
"
class="mt-3"
></NProgress>
<ContextNotice
v-if="execution?.errorMessage"
role="alert"
type="error"
:show-icon="false"
class="mt-4"
>{{ execution.errorMessage }}</ContextNotice
<!-- 以下是简洁的问题摘要与恢复操作,详细错误只在独立弹窗展示 -->
<section v-if="snapshot" class="space-y-4">
<div
v-if="execution?.errorMessage || validation?.valid === false"
class="workspace-panel problem-surface flex flex-wrap items-center justify-between gap-3"
>
<ContextNotice
v-if="validation && !validation.valid"
type="error"
:show-icon="false"
class="mt-4"
><p class="font-medium">分镜校验未通过</p>
<ul class="mt-2 list-inside list-disc space-y-1">
<li v-for="(issue, index) in validation.issues" :key="index">
第 {{ issue.episodeNo }} 集<span v-if="issue.beatNo">
/ Beat {{ issue.beatNo }}</span
><span v-if="issue.shotNo"> / Shot {{ issue.shotNo }}</span
>:{{ issue.message }}
</li>
</ul></ContextNotice
>
<div v-if="showRecovery" class="recovery-strip mt-4">
<p class="text-sm">
{{ execution?.errorMessage ? '拆解执行异常' : '分镜校验未通过'
}}<span v-if="storyboardIssues.length" class="ml-2 text-xs text-muted"
>{{ storyboardIssues.length }} 项问题</span
>
</p>
<NButton text @click="openIssues">查看问题</NButton>
</div>
<div v-if="showRecovery" class="recovery-strip">
<div>
<p class="text-sm font-medium">从中断处继续</p>
<p class="mt-1 text-xs leading-5 text-muted">
抽取失败、镜头缺失、主体绑定异常分别处理。禁用表示近期 checkpoint
不具备所需数据。
</p>
</div>
<div class="flex flex-wrap gap-2">
<ConfirmAction
@@ -549,6 +593,8 @@ const rules = {
project?.status !== 'completed' ||
!recovery.retry ||
operation.pending ||
backgroundExecution.discovering.value ||
!!backgroundExecution.discoveryError.value ||
!!error
"
@confirm="run('retry')"
@@ -561,6 +607,8 @@ const rules = {
project?.status !== 'completed' ||
!recovery.shots ||
operation.pending ||
backgroundExecution.discovering.value ||
!!backgroundExecution.discoveryError.value ||
!!error
"
@confirm="run('resume-shots')"
@@ -573,6 +621,8 @@ const rules = {
project?.status !== 'completed' ||
!recovery.storyboard ||
operation.pending ||
backgroundExecution.discovering.value ||
!!backgroundExecution.discoveryError.value ||
!!error
"
@confirm="run('resume-storyboard')"
@@ -644,11 +694,13 @@ const rules = {
v-model:episode-no="selectedEpisodeNo"
:plans="plans"
:episodes="shots"
:diagnosis-disabled="breakdownBusy || backgroundExecution.discovering.value"
@diagnose="openShotDiagnosis"
>
<!-- 以下是跟随当前剧集的一行诊断摘要,诊断弹窗独立于列表滚动 -->
<template #diagnosis>
<StoryboardDiagnosis
v-if="!breakdownBusy && !backgroundExecution.discovering.value"
ref="diagnosisPanel"
:project-id="projectId"
:episode-no="currentEpisodeNo"
@@ -716,12 +768,21 @@ const rules = {
</section>
</template>
</WorkspacePage>
<!-- 以下是与拆解设置分离的问题详情弹窗 -->
<BreakdownIssuesDialog
v-model:open="issuesOpen"
:issues="storyboardIssues"
:workflow-error="execution?.errorMessage"
:locatable="!breakdownBusy && !!shots.length"
@locate="locateIssue"
@settings="toolsOpen = true"
/>
</template>
<style>
/* 本组件专属布局与 Naive 内部结构覆盖。 */
@reference "../../styles/styles.css";
/* 任务卡片取消二次内缩,与快照、校验详情及设置卡片边缘对齐。 */
/* 任务进度与设置面板共用水平边界,避免重复内缩。 */
.workspace-tools-body .breakdown-execution-panel {
padding: 0;
}
@@ -85,11 +85,7 @@ async function commit() {
>
</div>
<p class="text-xs leading-6 text-muted">
{{
committed
? '这份结果已写入正式主体、形态与分镜。'
: '候选生成不替换正式数据。确认后由后端核对剧本版本、审核结果和下游资产,再统一提交。已有身份、参考图或镜头生产资产时会拒绝替换。'
}}
{{ committed ? '这份结果已写入正式主体、形态与分镜。' : '候选不替换正式数据,校验通过后单独提交。' }}
</p>
<p v-if="!committed && issue" class="text-xs leading-6 text-muted" role="status">{{ issue }}</p>
<div class="flex flex-wrap items-center gap-3">
@@ -0,0 +1,116 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton } from 'naive-ui'
import { AppDialog } from '../../../components/ui'
import type { ShotValidation } from '../types'
/** 同一剧集、节拍和镜头的校验问题分组。 */
interface BreakdownIssueGroup {
/** 稳定的位置键。 */
key: string
/** 后端提供的原始位置。 */
location: ShotValidation['issues'][number]
/** 去重后的原始错误描述。 */
messages: string[]
}
/** 拆解问题单独展示,设置弹窗不承载长错误正文。 */
const props = defineProps<{
/** 后端分镜校验问题,保留原始描述和位置。 */
issues: ShotValidation['issues']
/** 工作流执行异常,空值表示没有执行异常。 */
workflowError?: string
/** 当前结果是否允许定位到分镜正文。 */
locatable: boolean
}>()
/** 独立问题弹窗显隐。 */
const open = defineModel<boolean>('open', { default: false })
/** 弹窗关闭后再定位正文或打开设置,避免叠加焦点陷阱。 */
const emit = defineEmits<{ locate: [issue: ShotValidation['issues'][number]]; settings: [] }>()
/** 相同镜头的问题合并为一组,重复消息不重复显示。 */
const groups = computed(() => {
const result = new Map<string, BreakdownIssueGroup>()
for (const issue of props.issues) {
const key = `${issue.episodeNo}:${issue.beatNo ?? ''}:${issue.shotNo ?? ''}`
const group = result.get(key) ?? { key, location: issue, messages: [] }
if (!group.messages.includes(issue.message)) group.messages.push(issue.message)
result.set(key, group)
}
return [...result.values()]
})
/** 当前去重后的问题总数,不把多个位置合为一个错误。 */
const count = computed(() => groups.value.reduce((total, group) => total + group.messages.length, 0))
/** 等待离场后执行的定位。 */
const pendingLocation = ref<ShotValidation['issues'][number] | null>(null)
/** 等待离场后打开设置。 */
const pendingSettings = ref(false)
/**
* 关闭问题弹窗后定位到对应剧集、节拍或镜头。
* @param issue 后端提供的问题位置
*/
function locate(issue: ShotValidation['issues'][number]) {
if (!props.locatable) return
pendingLocation.value = { ...issue }
open.value = false
}
/** 关闭当前弹窗后打开拆解设置,避免同时显示两个操作弹窗。 */
function settings() {
pendingSettings.value = true
open.value = false
}
/** 离场动画结束后再交接焦点。 */
function finish() {
if (pendingLocation.value) {
const issue = pendingLocation.value
pendingLocation.value = null
emit('locate', issue)
}
if (pendingSettings.value) {
pendingSettings.value = false
emit('settings')
}
}
</script>
<template>
<!-- 以下是独立的拆解执行错误与分镜校验问题模块 -->
<AppDialog v-model:open="open" title="拆解问题" wide @closed="finish">
<template #description
><span v-if="count">{{ count }} 项校验问题 · {{ groups.length }} 个位置</span
><span v-else>查看最近保存结果中的问题</span></template
>
<div class="space-y-4">
<section v-if="workflowError" class="workspace-panel problem-surface space-y-3" aria-label="执行异常">
<h3 class="text-sm font-medium">执行异常</h3>
<p class="whitespace-pre-wrap break-words text-sm leading-6">{{ workflowError }}</p>
</section>
<article
v-for="group in groups"
:key="group.key"
class="workspace-panel problem-surface breakdown-issue-group space-y-3"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-medium">
第 {{ group.location.episodeNo }} 集<span v-if="group.location.beatNo">
· 节拍 {{ group.location.beatNo }}</span
><span v-if="group.location.shotNo"> · 镜头 {{ group.location.shotNo }}</span>
</h3>
<NButton v-if="locatable" size="small" text @click="locate(group.location)">{{
group.location.beatNo ? '定位分镜' : '查看本集'
}}</NButton>
</div>
<p v-for="message in group.messages" :key="message" class="break-words text-sm leading-6">
{{ message }}
</p>
</article>
<p v-if="!groups.length && !workflowError" class="py-5 text-sm text-muted">
后端尚未返回具体问题,请刷新拆解结果后查看。
</p>
</div>
<template #footer
><NButton @click="settings">拆解设置</NButton
><NButton type="primary" @click="open = false">关闭</NButton></template
>
</AppDialog>
</template>
@@ -14,6 +14,8 @@ const props = defineProps<{
plans: EpisodePlan[]
/** 正式分集镜头。 */
episodes: EpisodeShots[]
/** 拆解期间隐藏节拍和镜头诊断入口。 */
diagnosisDisabled?: boolean
}>()
/** 分镜卡片只负责发出诊断定位,确认及模型任务交由页面处理。 */
const emit = defineEmits<{ diagnose: [scope: DiagnosisLocation] }>()
@@ -114,7 +116,7 @@ defineExpose({ locate })
<h3 class="text-sm font-semibold">{{ beat.title }}</h3>
<NTag size="small" :bordered="false">{{ purposeLabels[beat.purpose] || beat.purpose }}</NTag>
<NButton
v-if="plan"
v-if="plan && !diagnosisDisabled"
size="tiny"
text
class="diagnose-hover-action ml-auto"
@@ -145,7 +147,7 @@ defineExpose({ locate })
<div class="flex items-center justify-between gap-3">
<h4 class="text-sm font-medium">{{ shot.title }}</h4>
<NButton
v-if="plan"
v-if="plan && !diagnosisDisabled"
size="tiny"
text
class="diagnose-hover-action"
@@ -188,10 +190,10 @@ defineExpose({ locate })
<style>
/* 本组件专属布局与 Naive 内部结构覆盖。 */
@reference "../../../styles/styles.css";
/* 问题定位保留轮廓提示,便于关闭弹窗后识别目标。 */
.diagnosis-located {
outline: 1px solid var(--app-accent);
outline-offset: 3px;
/* 问题定位使用柔和红色底面,不改变行高和间距;内部控件保留键盘焦点。 */
.breakdown-storyboard .diagnosis-located {
background: var(--app-danger-soft);
outline: none;
}
.beat-section {
@apply mt-[25px] pt-[23px];
@@ -199,9 +199,7 @@ onScopeDispose(() => {
<h3 class="text-sm font-medium">分镜质量修订</h3>
<NButton :loading="loading" :disabled="disabled || loading" @click="load">读取修复清单</NButton>
</div>
<p class="text-xs leading-6 text-muted">
用于尚未入库的质量阻断镜头。读取不调用模型;人工修订保存为新快照,通过后再恢复拆解。
</p>
<p class="text-xs leading-6 text-muted">仅修订尚未入库的镜头,保存后再恢复拆解。</p>
<p v-if="error" role="alert" class="text-xs leading-6 text-danger">{{ error }}</p>
<p v-if="plan && !plan.repairPlan.length && !error" role="status" class="text-xs text-muted">
当前没有可人工修订的质量阻断镜头,不代表未诊断镜头已通过。
+1 -1
View File
@@ -72,7 +72,7 @@ for (const workflowName of [
useWorkflowExecution(id, workflowName)
}
/** 即使直接刷新到生产页,也按真实重生成任务恢复旧剧情快照的失效标记。 */
const breakdownExecution = useWorkflowExecution(id, 'breakdown')
const breakdownExecution = useWorkflowExecution(id, 'breakdown', { discover: true })
/** 只有后端确认有效的新分镜才废弃旧正文,不推测未完成或失败任务。 */
watchEffect(() => {
const record = breakdownExecution.query.data.value
@@ -19,7 +19,7 @@ const props = withDefaults(
loading: boolean
/** 状态读取错误。 */
error: string
/** 是否展示运行与完成说明,已有消息及详细快照的页面可关闭。 */
/** 是否展示运行、完成和错误详情;关闭后由调用方单独呈现问题。 */
showStatusHint?: boolean
}>(),
{ title: '制作任务', showStatusHint: true }
@@ -28,9 +28,35 @@ const props = withDefaults(
const emit = defineEmits<{ refresh: []; dismiss: [] }>()
const percentage = computed(() => executionPercentage(props.execution?.current ?? 0, props.execution?.total ?? 0))
const result = computed(() => props.execution?.result ?? {})
/** 拆解任务的单位和结果文案与镜头素材任务分开。 */
const breakdownTask = computed(() => props.execution?.workflowName === 'breakdown')
/** 执行完成不等于业务校验通过,明确保留待修复状态。 */
const breakdownInvalid = computed(() => {
const validation = result.value.storyboardShotValidation
return (
breakdownTask.value &&
validation &&
typeof validation === 'object' &&
'valid' in validation &&
validation.valid === false
)
})
/** 后端提供的进度单位,避免把抽取完成误报为整个拆解完成。 */
const progressLabel = computed(() =>
props.execution?.metadata?.progressUnit === 'extraction_tasks'
? '抽取任务'
: props.execution?.metadata?.progressUnit === 'storyboard_episodes'
? '分镜剧集'
: '已处理'
)
/** 后端执行终态与业务审核结果共同决定可读状态。 */
const statusLabel = computed(() => {
const labels = { pending: '等待开始', running: '执行中', completed: '已完成', failed: '失败' }
return props.execution ? labels[props.execution.status] : ''
return props.execution
? props.execution.status === 'completed' && breakdownInvalid.value
? '执行结束 · 校验未通过'
: labels[props.execution.status]
: ''
})
const finished = computed(() => ['completed', 'failed'].includes(props.execution?.status ?? ''))
/** 是否为剧本创作任务,避免使用镜头素材的提示文案。 */
@@ -48,7 +74,7 @@ const staleMotionPlanCount = computed(() => {
/** 视频流程结束但含过期候选时使用警告标签,不显示全成功的绿色状态。 */
const statusType = computed(() =>
props.execution?.status === 'completed'
? videoQuality.value && staleMotionPlanCount.value > 0
? breakdownInvalid.value || (videoQuality.value && staleMotionPlanCount.value > 0)
? 'warning'
: 'success'
: props.execution?.status === 'failed'
@@ -162,11 +188,19 @@ function isInputMode(value: unknown, inputMode: string): boolean {
class="mt-4"
/>
<p class="mt-3 text-xs">
<template v-if="execution.total > 0">已处理 {{ execution.current }} / {{ execution.total }}</template>
<template v-if="execution.total > 0"
>{{ progressLabel }} {{ execution.current }} / {{ execution.total }}</template
>
<template v-else>{{
finished ? '本次任务已结束' : scriptCreation ? '正在创作剧本' : '正在准备本次任务'
finished
? '本次任务已结束'
: breakdownTask
? '拆解进行中,等待下一阶段结果'
: scriptCreation
? '正在创作剧本'
: '正在准备本次任务'
}}</template>
<template v-if="execution.currentResourceId && !scriptCreation">
<template v-if="execution.currentResourceId && !scriptCreation && !breakdownTask">
· 当前镜头 <code>{{ execution.currentResourceId }}</code></template
>
</p>
@@ -183,27 +217,31 @@ function isInputMode(value: unknown, inputMode: string): boolean {
<ContextNotice
v-else-if="execution.status === 'completed' && showStatusHint"
:type="
keyframeEdit
? result.passed === true
? 'success'
: result.validationSkipped === true
? 'info'
: 'warning'
: videoQuality && staleMotionPlanCount > 0
? 'warning'
: keyframeQuality &&
(!keyframeCounts || keyframeCounts.repairFailed + keyframeCounts.failed > 0)
breakdownInvalid
? 'warning'
: keyframeEdit
? result.passed === true
? 'success'
: result.validationSkipped === true
? 'info'
: 'warning'
: videoQuality && staleMotionPlanCount > 0
? 'warning'
: 'success'
: keyframeQuality &&
(!keyframeCounts || keyframeCounts.repairFailed + keyframeCounts.failed > 0)
? 'warning'
: 'success'
"
:show-icon="false"
class="mt-3"
>
<p>
{{
scriptCreation
? '剧本创作任务已结束,可查看最新剧本内容。'
: '本轮任务已结束,可查看最新镜头资产状态。'
breakdownTask
? '剧本拆解已结束,请查看候选与校验结果。'
: scriptCreation
? '剧本创作任务已结束,可查看最新剧本内容。'
: '本轮任务已结束,可查看最新镜头资产状态。'
}}
</p>
<p v-if="videoQuality" class="mt-2 text-xs">
@@ -237,12 +275,17 @@ function isInputMode(value: unknown, inputMode: string): boolean {
>
<template v-else>后端首帧质量统计不完整,请查看任务详情并刷新核对。</template>
</p>
<p v-else-if="!videoQuality && !scriptCreation" class="mt-2 text-xs">
<p v-else-if="!videoQuality && !scriptCreation && !breakdownTask" class="mt-2 text-xs">
共 {{ result.total ?? execution.total }} · 生成 {{ result.generated ?? execution.current }} · 跳过
{{ result.skipped ?? 0 }} · 阻塞 {{ result.blocked ?? 0 }} · 失败 {{ result.failed ?? 0 }}
</p>
</ContextNotice>
<ContextNotice v-else-if="execution.status === 'failed'" type="error" :show-icon="false" class="mt-3">
<ContextNotice
v-else-if="execution.status === 'failed' && showStatusHint"
type="error"
:show-icon="false"
class="mt-3"
>
<p>{{ execution.error || '制作任务执行失败。' }}</p>
<p class="mt-2 text-xs">
{{
+113
View File
@@ -0,0 +1,113 @@
import { onScopeDispose, ref, watch, type Ref } from 'vue'
import { workflowExecutionApi } from './execution-api'
import type { WorkflowExecution } from './execution.types'
import { errorMessage } from '../../lib/http'
/**
* 进入项目时读取最新任务,并订阅任务变化;不定时刷新页面或完整快照。
* @param projectId 当前项目编号
* @param workflowName 需要发现的工作流
* @param enabled 是否由当前观察器承担任务发现
* @param receive 接收属于当前项目的真实任务
* @returns 发现状态、错误及手动重读入口
*/
export function useWorkflowDiscovery(
projectId: Ref<string>,
workflowName: string,
enabled: boolean,
receive: (record: WorkflowExecution) => void
) {
/** 首次任务发现尚未结束。 */
const loading = ref(false)
/** 发现或订阅读取错误。 */
const error = ref('')
/** 当前项目订阅,项目切换和卸载时关闭。 */
let source: EventSource | undefined
/** 当前只读查询的取消控制器。 */
let controller: AbortController | undefined
/** 项目版本,拒绝旧项目与卸载后的迟到消息。 */
let version = 0
/** 组件是否已销毁。 */
let disposed = false
/**
* 接收前验证身份与必需状态字段,空结果不伪造任务。
* @param value 后端响应或事件内容
* @param id 本次观察的项目编号
*/
function accept(value: unknown, id: string) {
if (value === null) return
const record = value as WorkflowExecution | undefined
if (
!record ||
typeof record.id !== 'string' ||
!record.id ||
record.projectId !== id ||
record.workflowName !== workflowName ||
!['pending', 'running', 'completed', 'failed'].includes(record.status)
)
throw new Error('后台任务发现结果与当前项目或工作流不匹配。')
receive(record)
}
/** 重新发现服务端任务,不创建或重试任何生成任务。 */
async function refresh() {
if (disposed || !enabled || !projectId.value) return
const current = version
const id = projectId.value
controller?.abort()
controller = new AbortController()
const signal = controller.signal
loading.value = true
try {
const record = await workflowExecutionApi.latest(id, workflowName, signal)
if (disposed || signal.aborted || current !== version) return
accept(record, id)
error.value = ''
} catch (cause) {
if (!disposed && !signal.aborted && current === version) error.value = errorMessage(cause)
} finally {
if (!disposed && !signal.aborted && current === version) loading.value = false
}
}
watch(
projectId,
id => {
version++
source?.close()
controller?.abort()
source = undefined
loading.value = false
error.value = ''
if (!enabled || !id) return
const current = version
void refresh()
if (typeof EventSource === 'undefined') return
source = new EventSource(workflowExecutionApi.eventsUrl(id, workflowName))
source.addEventListener('message', event => {
if (disposed || current !== version) return
try {
accept(JSON.parse(event.data), id)
error.value = ''
loading.value = false
} catch (cause) {
error.value = errorMessage(cause)
}
})
source.addEventListener('error', () => {
if (disposed || current !== version) return
error.value = '后台任务状态订阅暂时断开,正在重新连接。'
loading.value = false
})
},
{ immediate: true }
)
onScopeDispose(() => {
disposed = true
version++
controller?.abort()
source?.close()
})
return { loading, error, refresh }
}
+20
View File
@@ -3,6 +3,26 @@ import type { WorkflowExecution } from './execution.types'
/** WorkflowExecution 查询接口;数据库状态是任务进度的权威来源。 */
export const workflowExecutionApi = {
/**
* 按项目发现最新后台任务,不依赖本地保存的句柄。
* @param projectId 当前正式项目编号
* @param workflowName 工作流名称
* @param signal 取消过期查询
* @returns 服务端最新任务,无记录时为 null
*/
latest: (projectId: string, workflowName: string, signal?: AbortSignal) =>
request<WorkflowExecution | null>(
`/projects/${encodeURIComponent(projectId)}/workflow-executions/latest?${new URLSearchParams({ workflowName })}`,
{ signal }
),
/**
* 项目任务发现事件地址,连接只观察状态,不启动任务。
* @param projectId 当前正式项目编号
* @param workflowName 工作流名称
* @returns 同源或已配置 API 服务的 SSE 地址
*/
eventsUrl: (projectId: string, workflowName: string) =>
`${(import.meta.env.VITE_API_BASE_URL || '/api').replace(/\/$/, '')}/projects/${encodeURIComponent(projectId)}/workflow-executions/events?${new URLSearchParams({ workflowName })}`,
get: (executionId: string, signal?: AbortSignal) =>
request<WorkflowExecution>(`/workflow-executions/${encodeURIComponent(executionId)}`, { signal })
}
+123 -13
View File
@@ -2,6 +2,8 @@ import { computed, onScopeDispose, reactive, ref, watch, type Ref } from 'vue'
import { usePolling } from '../../composables/usePolling'
import { workflowExecutionApi } from './execution-api'
import { useActionMessage } from '../../components/ui/useActionMessage'
import { useWorkflowDiscovery } from './discovery'
import type { WorkflowExecution } from './execution.types'
const storagePrefix = 'short-drama:workflow-execution'
@@ -18,8 +20,14 @@ interface ExecutionActivity {
}
/** 活动状态按项目和工作流共同隔离。 */
const executionActivity = reactive<Record<string, ExecutionActivity>>({})
/** 同项目布局与页面共用最近的真实记录,终态到达时同步解除旧运行提示。 */
const executionRecords = reactive<Record<string, WorkflowExecution>>({})
/** 同任务可能有页面和弹窗多个观察器,真实终态仅通知一次。 */
const announcedExecutions = new Set<string>()
/** 同项目页面共享发现状态,避免未挂载发现器的子页误认为没有后台任务。 */
const discoveryActivity = reactive<Record<string, { loading: boolean; error: string }>>({})
/** 子页重读入口复用项目布局的发现器,避免额外建立订阅。 */
const discoveryReaders = new Map<string, () => Promise<void>>()
/**
* 检查项目是否仍有已跟踪且未结束的后台任务。
@@ -45,6 +53,14 @@ export function executionStageLabel(stage: string | null) {
resumeGeneration: '恢复分集剧本生成',
resumeRewrite: '恢复剧本改写',
breakdown: '拆解剧本',
subject_ready: '主体已整理完成',
subject_candidate_ready: '主体候选已就绪',
storyboard_plan_ready: '分镜规划已生成',
storyboard_shots_progress: '分镜镜头生成进度',
storyboard_shots_pending_quality: '分镜镜头等待质量审核',
storyboard_ready: '分镜已通过结构检查',
storyboard_persisted: '正式分镜已保存',
storyboard_quality_blocked: '分镜质量需要处理',
storyboardRegenerate: '重生成单集镜头',
storyboardDirection: '生成导演设计',
storyboardVisualState: '生成即时状态',
@@ -96,8 +112,18 @@ function savedExecutionId(projectId: string, workflowName: string) {
return localStorage.getItem(storageKey(projectId, workflowName)) ?? ''
}
/** 跟踪一个项目最近的持久化任务;刷新页面后从本地句柄恢复,状态仍从后端读取。 */
export function useWorkflowExecution(projectId: Ref<string>, workflowName: string) {
/**
* 跟踪持久化任务,项目布局可开启服务端发现并在其它页面共享句柄。
* @param projectId 正式项目编号
* @param workflowName 工作流名称
* @param options 当前观察器是否承担服务端任务发现
* @returns 任务记录、活动锁和读取入口
*/
export function useWorkflowExecution(
projectId: Ref<string>,
workflowName: string,
options: { discover?: boolean } = {}
) {
/** 状态反馈与应用其它操作共用消息层。 */
const message = useActionMessage()
/** 仅通知本会话观察到运行或主动启动的任务,不重放旧完成记录。 */
@@ -137,12 +163,19 @@ export function useWorkflowExecution(projectId: Ref<string>, workflowName: strin
const key = computed(() => executionId.value)
const query = usePolling(
key,
async (id, signal) => {
async (id, signal): Promise<WorkflowExecution | null> => {
if (!id) return null
const targetProjectId = projectId.value
const record = await workflowExecutionApi.get(id, signal)
if (record.projectId !== targetProjectId || record.workflowName !== workflowName || record.id !== id)
throw new Error('后台任务与当前项目或工作流不匹配,请刷新核对。')
const known = query.data.value
if (
known?.id === id &&
(['completed', 'failed'].includes(known.status) ||
Date.parse(known.updatedAt) > Date.parse(record.updatedAt))
)
return known
const activity = executionActivity[storageKey(targetProjectId, workflowName)]
if (
!signal.aborted &&
@@ -153,10 +186,19 @@ export function useWorkflowExecution(projectId: Ref<string>, workflowName: strin
) {
activity.terminal = ['completed', 'failed'].includes(record.status)
activity.active = !activity.terminal
executionRecords[storageKey(targetProjectId, workflowName)] = record
}
return record
},
computed(() => (executionId.value && !terminal.value ? 1_500 : false))
computed(() => (executionId.value && !terminal.value && !options.discover ? 1_500 : false))
)
/** 其它观察器读取到新阶段或终态时同步本地展示,拒绝不同任务的迟到结果。 */
watch(
() => executionRecords[storageKey(projectId.value, workflowName)],
record => {
if (record?.id === executionId.value) query.data.value = record
},
{ flush: 'sync' }
)
watch(
() => query.data.value?.status,
@@ -204,14 +246,15 @@ export function useWorkflowExecution(projectId: Ref<string>, workflowName: strin
)
return
}
const failures = [
'staleMotionPlan',
'failed',
'repairFailed',
'exhausted',
'providerFailed',
'submissionFailed'
].some(field => typeof result[field] === 'number' && Number(result[field]) > 0)
const storyboardValidation = result.storyboardShotValidation
const failures =
(storyboardValidation &&
typeof storyboardValidation === 'object' &&
'valid' in storyboardValidation &&
storyboardValidation.valid === false) ||
['staleMotionPlan', 'failed', 'repairFailed', 'exhausted', 'providerFailed', 'submissionFailed'].some(
field => typeof result[field] === 'number' && Number(result[field]) > 0
)
message[failures ? 'warning' : 'info'](
failures
? '本轮任务已结束,部分结果未通过或执行失败,请查看任务记录。'
@@ -255,11 +298,78 @@ export function useWorkflowExecution(projectId: Ref<string>, workflowName: strin
function dismiss() {
if (active.value) return
delete executionActivity[storageKey(projectId.value, workflowName)]
delete executionRecords[storageKey(projectId.value, workflowName)]
if (projectId.value && typeof localStorage !== 'undefined')
localStorage.removeItem(storageKey(projectId.value, workflowName))
executionId.value = ''
terminal.value = false
}
return { executionId, query, active, track, dismiss }
/**
* 服务端消息立即恢复项目活动锁,终态与旧版本消息不得被迟到响应覆盖。
* @param record 当前项目的后台任务记录
*/
function receiveDiscovered(record: WorkflowExecution) {
const known = query.data.value
if (
known &&
(Date.parse(record.createdAt) < Date.parse(known.createdAt) ||
(record.id === known.id &&
(['completed', 'failed'].includes(known.status) ||
Date.parse(record.updatedAt) < Date.parse(known.updatedAt))))
)
return
const activityKey = storageKey(record.projectId, workflowName)
const finished = ['completed', 'failed'].includes(record.status)
const activity = executionActivity[activityKey]
if (activity?.id === record.id && activity.terminal && !finished) return
executionActivity[activityKey] = {
projectId: record.projectId,
id: record.id,
active: !finished,
terminal: finished
}
if (typeof localStorage !== 'undefined') localStorage.setItem(activityKey, record.id)
executionId.value = record.id
terminal.value = finished
query.data.value = record
executionRecords[activityKey] = record
}
/** 由项目布局负责一条发现连接,子页继续共享真实任务句柄。 */
const discovery = useWorkflowDiscovery(projectId, workflowName, options.discover === true, receiveDiscovered)
if (options.discover) {
watch(
projectId,
(id, previous) => {
if (previous) discoveryReaders.delete(storageKey(previous, workflowName))
discoveryReaders.set(storageKey(id, workflowName), discovery.refresh)
},
{ immediate: true }
)
onScopeDispose(() => {
const discoveryKey = storageKey(projectId.value, workflowName)
if (discoveryReaders.get(discoveryKey) === discovery.refresh) {
discoveryReaders.delete(discoveryKey)
delete discoveryActivity[discoveryKey]
}
})
}
if (options.discover)
watch(
[discovery.loading, discovery.error],
([loading, error]) => {
discoveryActivity[storageKey(projectId.value, workflowName)] = { loading, error }
},
{ immediate: true, flush: 'sync' }
)
/** 当前项目的任务发现是否仍在读取。 */
const discovering = computed(() => discoveryActivity[storageKey(projectId.value, workflowName)]?.loading ?? false)
/** 当前项目发现错误,由子页提供明确重读入口。 */
const discoveryError = computed(() => discoveryActivity[storageKey(projectId.value, workflowName)]?.error ?? '')
/** 手动重读复用项目级发现连接,不重发生成请求。 */
async function discover() {
await discoveryReaders.get(storageKey(projectId.value, workflowName))?.()
}
return { executionId, query, active, track, dismiss, discovering, discoveryError, discover }
}
+8
View File
@@ -26,6 +26,8 @@
--app-selected: #e4f4e9;
--app-shadow: #00000018;
--app-danger: #a93232;
/* 问题和待修复区域使用浅红底色,与普通选中状态区分。 */
--app-danger-soft: #fff1f0;
--app-success: #087c42;
}
:root[data-theme='dark'] {
@@ -46,6 +48,8 @@
--app-selected: #173527;
--app-shadow: #00000055;
--app-danger: #fa7373;
/* 深色主题保留柔和红色提示,避免亮色块打断页面层级。 */
--app-danger-soft: #3a2323;
--app-success: #5cd693;
}
html,
@@ -204,6 +208,10 @@ body {
.workspace-panel + .workspace-panel {
margin-top: 20px;
}
/* 错误详情、问题摘要和定位目标共用相同的问题底色。 */
.problem-surface {
background: var(--app-danger-soft);
}
/* 弹窗主流程优先平铺并与标题共用水平基线;仅靠垂直间距区分区块。 */
.dialog-flat-stack > .workspace-panel,
.dialog-section {
+6 -1
View File
@@ -1,7 +1,7 @@
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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NConfigProvider, NMenu, NModal, NPopover, NScrollbar, NTooltip } from 'naive-ui'
import App from '@/App.vue'
import WorkspacePage from '@/components/ui/WorkspacePage.vue'
@@ -11,11 +11,16 @@ import ProjectLayout from '@/features/projects/ProjectLayout.vue'
import ConfirmAction from '@/features/workflows/ConfirmAction.vue'
import ThemeToggle from '@/components/ui/ThemeToggle.vue'
import { projectsApi } from '@/features/projects/api'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import { readFileSync } from 'node:fs'
import { drawerPanel } from '@/testing/naive'
import { readAllStyles } from '@/testing/styles'
let wrapper: VueWrapper | undefined
/** 导航布局测试没有后台任务,明确模拟项目级只读任务发现。 */
beforeEach(() => {
vi.spyOn(workflowExecutionApi, 'latest').mockResolvedValue(null)
})
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
+61 -2
View File
@@ -10,13 +10,62 @@ import type { Checkpoint } from '@/features/workflows/types'
import type { BreakdownModule, EpisodePlan } from '@/features/breakdown/types'
import { drawerPanel } from '@/testing/naive'
import { readAllStyles } from '@/testing/styles'
import { effectScope } from 'vue'
import { useWorkflowExecution } from '@/features/workflows/execution'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
let wrapper: VueWrapper | undefined
/** 跨组件后台任务观察器,验证结束时释放。 */
let taskScope: ReturnType<typeof effectScope> | undefined
afterEach(() => {
taskScope?.stop()
taskScope = undefined
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
vi.restoreAllMocks()
localStorage.clear()
})
it('后台重新拆解时显示真实运行状态并隐藏所有诊断入口,终态后恢复', async () => {
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async () => diagnosisResultsResponse())
)
const provided = mountPage()
await selectTab('分镜')
const record = {
id: 'external-breakdown-ui',
projectId: 'breakdown-scroll-test',
workflowName: 'breakdown',
status: 'running' as 'running' | 'completed',
stage: 'storyboard_plan_ready',
current: 1,
total: 3,
currentResourceId: null,
metadata: { progressUnit: 'storyboard_episodes' },
result: null,
error: null,
startedAt: '2026-10-17T00:00:00Z',
completedAt: null,
createdAt: '2026-10-17T00:00:00Z',
updatedAt: '2026-10-17T00:01:00Z'
}
vi.spyOn(workflowExecutionApi, 'get').mockImplementation(async () => ({ ...record }))
taskScope = effectScope()
const tracker = taskScope.run(() => useWorkflowExecution(ref(record.projectId), 'breakdown'))!
await tracker.track(record.id)
await flushPromises()
expect(wrapper!.text()).toContain('拆解进行中')
expect(wrapper!.find('.storyboard-diagnosis-summary').exists()).toBe(false)
expect(wrapper!.find('.diagnose-hover-action').exists()).toBe(false)
record.status = 'completed'
await tracker.query.refresh()
await flushPromises()
expect(wrapper!.find('.storyboard-diagnosis-summary').exists()).toBe(true)
expect(provided.refresh).toHaveBeenCalled()
tracker.dismiss()
})
/** 长主体、长分镜与长任务列表,用真实 Naive 滚动组件验证内容边界。 */
@@ -495,7 +544,7 @@ describe('拆解页内容滚动', () => {
expect(fetcher).not.toHaveBeenCalled()
})
it('关闭设置时保留问题入口,详细校验与恢复在面板内,不挤占结果高度', async () => {
it('问题入口打开独立错误弹窗,拆解设置不再包含详细错误', async () => {
const record = checkpoint()
record.state.workflowExecution!.status = 'failed'
record.state.workflowExecution!.errorMessage = '工作流中断'
@@ -509,7 +558,17 @@ describe('拆解页内容滚动', () => {
const action = wrapper!.findAll('button').find(item => item.text() === '查看拆解问题')!
await action.trigger('click')
await flushPromises()
expect(drawerPanel().text()).toContain('缺少形态绑定')
const issues = document.querySelector<HTMLElement>('.app-dialog[aria-label="拆解问题"]')
expect(issues?.textContent).toContain('缺少形态绑定')
expect(issues?.textContent).toContain('工作流中断')
expect(issues?.textContent).not.toContain('重试失败抽取')
await new DOMWrapper(issues!).get('.n-card-header__close').trigger('click')
await flushPromises()
await wrapper!.get('[data-workspace-tools]').trigger('click')
await flushPromises()
expect(drawerPanel().text()).not.toContain('缺少形态绑定')
expect(drawerPanel().text()).not.toContain('工作流中断')
expect(drawerPanel().text()).toContain('查看问题')
expect(drawerPanel().text()).toContain('重试失败抽取')
})
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, it } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import BreakdownIssuesDialog from '@/features/breakdown/components/BreakdownIssuesDialog.vue'
import AppDialog from '@/components/ui/AppDialog.vue'
/** 独立问题弹窗实例,验证后移除 Teleport。 */
let wrapper: VueWrapper | undefined
afterEach(() => {
wrapper?.unmount()
document.body.innerHTML = ''
})
describe('拆解问题弹窗', () => {
it('同镜头问题合并展示并去重,定位等待弹窗离场后发出', async () => {
wrapper = mount(BreakdownIssuesDialog, {
attachTo: document.body,
props: {
open: true,
locatable: true,
issues: [
{ episodeNo: 1, beatNo: 2, shotNo: 3, message: '缺少场景' },
{ episodeNo: 1, beatNo: 2, shotNo: 3, message: '缺少道具' },
{ episodeNo: 1, beatNo: 2, shotNo: 3, message: '缺少场景' },
{ episodeNo: 2, beatNo: 1, shotNo: 1, message: '缺少人物' }
]
}
})
await flushPromises()
expect(document.querySelectorAll('.breakdown-issue-group')).toHaveLength(2)
expect(document.body.textContent).toContain('3 项校验问题 · 2 个位置')
const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
item => item.textContent?.trim() === '定位分镜'
)!
button.click()
await flushPromises()
expect(wrapper.emitted('locate')).toBeUndefined()
wrapper.getComponent(AppDialog).vm.$emit('closed')
expect(wrapper.emitted('locate')?.[0]?.[0]).toMatchObject({ episodeNo: 1, beatNo: 2, shotNo: 3 })
})
})
+2
View File
@@ -8,6 +8,7 @@ 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 { workflowExecutionApi } from '@/features/workflows/execution-api'
import { getOperation } from '@/features/workflows/operations'
import type { ProjectDetail, ProjectStageReadiness, ProjectStatus } from '@/features/projects/types'
import { readAllStyles } from '@/testing/styles'
@@ -34,6 +35,7 @@ function readiness(id: string, ready = true): ProjectStageReadiness {
}
beforeEach(() => {
vi.spyOn(workflowExecutionApi, 'latest').mockResolvedValue(null)
vi.spyOn(projectsApi, 'stageReadiness').mockImplementation(async id => readiness(id))
})
let wrapper: VueWrapper | undefined
+113
View File
@@ -0,0 +1,113 @@
import { effectScope, ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useWorkflowExecution } from '@/features/workflows/execution'
import { getOperation } from '@/features/workflows/operations'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
/** 后端自行启动的拆解任务,本地没有保存过句柄。 */
function record(projectId: string, status: WorkflowExecution['status'] = 'running'): WorkflowExecution {
return {
id: `external-${projectId}`,
projectId,
workflowName: 'breakdown',
status,
stage: 'breakdown',
current: 0,
total: 0,
currentResourceId: null,
metadata: {},
result: null,
error: null,
startedAt: '2026-10-17T00:00:00Z',
completedAt: null,
createdAt: '2026-10-17T00:00:00Z',
updatedAt: '2026-10-17T00:00:00Z'
}
}
afterEach(() => {
localStorage.clear()
vi.unstubAllGlobals()
})
describe('服务端任务发现', () => {
it('页面保持打开时通过事件接上新任务,终态不被迟到运行消息重新激活', async () => {
const task = record('discovery-stream')
/** 仅模拟浏览器事件连接,所有任务仍来自测试响应。 */
class TestEventSource extends EventTarget {
static last: TestEventSource
close = vi.fn<() => void>()
constructor() {
super()
TestEventSource.last = this
}
}
vi.stubGlobal('EventSource', TestEventSource)
vi.stubGlobal(
'fetch',
vi
.fn<typeof fetch>()
.mockImplementation(
async url => new Response(JSON.stringify({ data: String(url).includes('/latest?') ? null : task }))
)
)
const scope = effectScope()
const tracker = scope.run(() => useWorkflowExecution(ref(task.projectId), 'breakdown', { discover: true }))!
await flushPromises()
expect(tracker.executionId.value).toBe('')
TestEventSource.last.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(task) }))
await flushPromises()
expect(tracker.active.value).toBe(true)
task.status = 'completed'
TestEventSource.last.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(task) }))
await flushPromises()
TestEventSource.last.dispatchEvent(
new MessageEvent('message', { data: JSON.stringify({ ...task, status: 'running' }) })
)
await flushPromises()
expect(tracker.active.value).toBe(false)
expect(tracker.query.data.value?.status).toBe('completed')
scope.stop()
expect(TestEventSource.last.close).toHaveBeenCalledOnce()
})
it('没有本地句柄时发现后台任务并立即锁住项目操作', async () => {
const id = ref('discovery-active')
const task = record(id.value)
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: task })))
)
const scope = effectScope()
const tracker = scope.run(() => useWorkflowExecution(id, 'breakdown', { discover: true }))!
await flushPromises()
expect(tracker.executionId.value).toBe(task.id)
expect(tracker.active.value).toBe(true)
expect(getOperation(id.value).pending).toBe(true)
scope.stop()
})
it('切换项目后忽略旧项目迟到的发现响应', async () => {
let resolveOld!: (value: Response) => void
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).includes('/discovery-old/'))
return new Promise(resolve => {
resolveOld = resolve
})
return new Response(JSON.stringify({ data: null }))
})
)
const id = ref('discovery-old')
const scope = effectScope()
const tracker = scope.run(() => useWorkflowExecution(id, 'breakdown', { discover: true }))!
await flushPromises()
id.value = 'discovery-new'
await flushPromises()
resolveOld(new Response(JSON.stringify({ data: record('discovery-old') })))
await flushPromises()
expect(tracker.executionId.value).toBe('')
expect(getOperation('discovery-new').pending).toBe(false)
scope.stop()
})
})
@@ -30,6 +30,26 @@ afterEach(() => {
})
describe('WorkflowExecution 前端契约', () => {
it('拆解进度区分抽取计数与工作流完成,校验失败不显示全成功', () => {
const wrapper = mount(WorkflowExecutionPanel, {
props: {
execution: execution({
workflowName: 'breakdown',
status: 'completed',
current: 3,
total: 3,
metadata: { progressUnit: 'extraction_tasks' },
result: { storyboardShotValidation: { valid: false, issues: [] } }
}),
loading: false,
error: ''
}
})
expect(wrapper.text()).toContain('抽取任务 3 / 3')
expect(wrapper.text()).toContain('校验未通过')
expect(wrapper.text()).not.toContain('最新镜头资产状态')
wrapper.unmount()
})
it('保留未知阶段并限制真实进度范围', () => {
expect(executionStageLabel('repairing')).toBe('自动修复')
expect(executionStageLabel('new_backend_stage')).toBe('new_backend_stage')