feat(short-drama-agent-front): 接入正式审核执行历史

This commit is contained in:
GJ committed 2026-11-07 14:03:38 +08:00
1 parent 518b630a46
commit c808a58a3f
17 files changed
+1129 -175

No files matched your search

+16 -7
View File
@@ -1,6 +1,6 @@
# 首帧审核与固定几何连续性接入
日期:2026-11-07。前端起点 `dbf97e6f`,只读核对后端 `6721a4df`,本轮不修改后端。
日期:2026-11-07。前端起点 `dbf97e6f`,只读核对后端 `6721a4df`;完整执行历史增量对接后端 `b254cfca`,本轮不修改后端。
## 已接入
@@ -8,7 +8,7 @@
- 候选历史展示 `legacyTermination` 的原状态、终止时间、审计编号、费用结论和新授权要求。终止不改写原始审核,不解除 Primary 门禁。
- 独立新审核只传 `legacyVisionAuthorizationId`;物理专项补跑同时传原任务、请求指纹和 `physicalRetryAuthorizationId`。均须手动输入已有授权、明确勾选费用并从弹窗底栏提交,不提供签发入口,不自动重试。
- 202 只观察已受理执行。200 按实际质量与来源结果展示;409 刷新历史并保留任务及费用门禁。执行完成、质量通过和正式 Primary 分别表达。
- 多次执行保持审核任务身份,采用历史返回的最新执行,保留本机曾观察到的旧执行编号。已被更新执行取代的本机旧提交不会永久保留未知状态锁。
- 多次执行保持原审核任务身份,按需读取正式分页接口;不再读写本机执行历史缓存。当前执行只按服务端指针标记,逐次步骤、复用来源与计量分别展示。已有未结提交的会话保护继续保留。
- 分镜设计与生产页复用一个全屏连续性审核抽屉,当前集正式顺序连续选择两到三镜,并从正式生成规格求共同 Scene Form。展示 Primary、原图、摄影设计、布局母版、场景形态当前性及原始来源依据。
- 人工分别填写观察面、地标顺序、固定结构位置或数量及其证据。未知明确保留;不把开关门即时状态自动投影成固定结构变化。免费诊断支持 passed、failed、needs_review、insufficient_evidence、stale。
- 审核保存绑定本次已诊断观察的来源指纹,编辑后须重新诊断。刷新可恢复本机最近审核编号,也可手动读取其他正式编号。回读分别展示审核人、时间、原始结论和当前失效原因,不修改 Primary。
@@ -18,15 +18,15 @@
## 后端契约限制
### 同一审核任务的完整执行历史尚无公开读取能力
### 完整执行历史已接入正式分页接口
`GET /storyboard-shots/:shotId/keyframes/:keyframeId/validations` 经 `shot-keyframe-asset.service.ts` 与 `readVisionRecovery()` 仅投影任务当前 `executionId`。项目工作流路由只有 latest 与 events,单执行路由需要已知编号,没有按 `validationTaskId` 枚举全部执行的接口。物理专项授权的旧执行及旧回执虽保存在内部审计记录,当前历史 DTO 未公开。
后端 `b254cfca` 新增 `GET /storyboard-shots/:shotId/keyframes/:keyframeId/validations/:validationTaskId/executions`。前端按原审核任务展开读取,显式传项目和每页 20 条,原样传回 nextCursor;刷新首屏或切换范围废弃旧游标及迟到响应。不以 total 推断下一页。
因此本轮实现的是:正式最新执行恢复 + 本机已实际观察到的执行记录。不能宣称从新浏览器完整找回未曾观察到的旧执行。后续需要后端正式提供任务执行列表及其公开摘要;本轮未猜测 URL,也未新增后端接口。
本机历史模块已移除。当前执行仅依据正式 currentExecutionId/isCurrent;关联未记录或不可用、旧执行缺步骤快照时明确显示未知,不把第一条当当前执行。General 复用的原用量和来源与本次新调用分开,不重复计量。旧失败不覆盖当前执行,执行完成与质量待复核、失败、通过分别表达。
### 专项补跑入口按公开证据提供,最终资格由后端确认
无法恢复的旧证据仍按后端契约返回 unknown/null/not_recorded。历史 metadata 缺少完整关联的行不会被猜测纳入;这属于历史证据边界,不能依靠当前任务结果补齐。
步骤摘要含完成状态、issues、用量,但没有 General 的独立 passed 字段及完整 Physical 原始失败回执。前端仅在最新任务 General 已完成且无硬问题、Physical 失败且有计量时提供已有授权输入,文案明确为“补跑要求”。正式授权受理后才能确认原 General 通过并显示本次单步范围。实际原图、来源、模型、原费用回执与一次性授权继续由后端核对;不向用户伪造缺失证据。
新页与原候选摘要共用步骤组件;后台摘要刷新不卸载已展开的执行列表。现有 GET/SSE 仅更新相同执行,逐次步骤始终由正式历史接口读取;没有新增列表 SSE 或改变授权、费用和 Primary 门禁。
## 验证边界
@@ -35,3 +35,12 @@
本地 Chrome 复用已有 `localhost:4312` 标签页:真实项目只读核对三张 Primary、正式设计、当前布局与来源失效;写入交互使用临时隔离页面拦截全部 API,验证布局正式确认与审核失效保留原结论。检查桌面、390 × 844 手机、长内容滚动、固定底栏、深浅主题及授权按钮禁用/确认状态。临时验收文件在提交前移除。
真实付费 Provider 调用为 0,未提交真实授权、连续性审核或布局修改,未改动正式数据。
## 完整执行历史增量验证
本轮使用正式 DTO 的 Mock 补充 API、分页状态和真实 Vue 组件回归,覆盖按需读取、缓存失效、游标原样传回、同时间顺序、翻页取消、资源切换迟到 404、当前指针不在本页、证据缺失、复用计量、终态刷新、400/404/409、人工终止旧任务和摘要刷新保留展开状态。所有读取均为 GET,没有触发新审核、授权消费或 Primary 修改。
Chrome 复用 localhost:4312 标签页,在临时隔离页面检查桌面及 iPhone SE 375×667、长内容滚动、固定关闭入口、分页结束、深浅主题和指针不可用/旧任务空历史/证据冲突状态。临时页面在提交前删除。
常驻本机服务的只读核对:候选原历史可读,但新 executions 路由返回 Cannot GET 的 404,说明该进程尚未加载新路由;未重启服务,未写正式数据。页面新接口成功、翻页和异常状态由隔离 Mock 验收,正式运行需后端服务加载已推送的版本。
@@ -0,0 +1,191 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import { formatDate } from '../../../lib/format'
import { useValidationExecutions } from '../useValidationExecutions'
import type { WorkflowExecution } from '../../workflows/execution.types'
import type { ValidationExecutionHistoryItem, ValidationStepName } from '../validation-executions.types'
import { validationStatusLabels, validationStepNames } from '../validation-execution-labels'
import KeyframeExecutionStatus from './KeyframeExecutionStatus.vue'
import KeyframeValidationSteps from './KeyframeValidationSteps.vue'
/** 单个审核任务的正式分页历史,关闭时中止请求,不使用本机历史缓存。 */
const props = defineProps<{
/** 当前项目,兼容没有项目参数的历史调用方。 */ projectId?: string
/** 正式镜头。 */ shotId: string
/** 当前候选。 */ keyframeId: string
/** 原审核任务,多个任务分别加载。 */ validationTaskId: string
/** 原轻量历史更新时仅作为刷新信号,不替代正式指针。 */ latestExecutionId?: string
/** 外部现有 GET/SSE 的观察结果,不创建额外订阅。 */ liveExecution?: WorkflowExecution | null
}>()
/** 统一使用 Naive 折叠组件,只有明确展开才读取。 */
const expanded = ref<string[]>([])
/** 查询身份固定全部资源,游标不跨资源复用。 */
const key = computed(() =>
expanded.value.includes('executions') && props.shotId && props.keyframeId && props.validationTaskId
? JSON.stringify([props.projectId, props.shotId, props.keyframeId, props.validationTaskId])
: ''
)
const query = useValidationExecutions(key)
/** 外部事件必须属于此任务及同一项目、镜头和候选。 */
const live = computed(() => {
const record = props.liveExecution
return record &&
(!props.projectId || record.projectId === props.projectId) &&
record.workflowName === 'shot-keyframe-validation' &&
record.metadata?.validationTaskId === props.validationTaskId &&
record.metadata?.shotId === props.shotId &&
record.metadata?.keyframeId === props.keyframeId
? record
: null
})
/** 同一终态或新执行信号只刷新一次,避免延迟同步时形成读取循环。 */
let refreshedSignal = ''
watch(
key,
() => {
refreshedSignal = ''
},
{ flush: 'sync' }
)
watch([() => props.latestExecutionId, live, query.loading], () => {
if (!key.value || !query.data.value || query.loading.value) return
const record = live.value
const known = query.items.value.find(item => item.execution.id === record?.id)?.execution
const changed =
query.data.value.integrity.currentExecution === 'valid' &&
props.latestExecutionId &&
props.latestExecutionId !== query.data.value.currentExecutionId
const terminal = record && ['completed', 'failed'].includes(record.status) && record.status !== known?.status
const signal = JSON.stringify([key.value, props.latestExecutionId, record?.id, record?.status, record?.updatedAt])
if ((changed || terminal) && refreshedSignal !== signal) {
refreshedSignal = signal
void query.refresh()
}
})
/**
* 只将更新的相同执行事件用于它自己的记录,不改写其他执行的结果或步骤。
* @param item 正式逐次记录
* @returns 此次执行的最新公开状态
*/
function displayExecution(item: ValidationExecutionHistoryItem) {
const record = live.value
const original = item.execution
return record?.id === original.id &&
!['completed', 'failed'].includes(original.status) &&
Date.parse(record.updatedAt) >= Date.parse(original.updatedAt)
? record
: original
}
/**
* 区分未记录范围与明确没有计划的新提交步骤。
* @param steps 服务保存的本次范围
* @returns 中文步骤或未记录说明
*/
function stepScope(steps: ValidationStepName[] | null) {
return steps === null ? '未记录' : steps.length ? steps.map(step => validationStepNames[step]).join('、') : '无'
}
/** 服务保存的模式只在展示层转为中文。 */
const modeLabels = {
initial: '首次审核',
resume: '继续原审核',
physical_retry: '仅补跑物理专项',
unknown: '执行范围未记录'
}
/** 正式逐次步骤的证据来源。 */
const evidenceLabels = {
execution_snapshot: '本次执行记录',
archived_audit: '已核对的历史审计',
not_recorded: '未记录本次步骤证据'
}
</script>
<template>
<!-- 以下是当前审核任务的执行记录按需读取模块 -->
<NCollapse v-model:expanded-names="expanded" class="mt-3">
<NCollapseItem name="executions" title="执行记录">
<section
class="space-y-3"
:aria-label="`审核任务 ${validationTaskId} 的执行记录`"
:aria-busy="query.loading.value"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<p v-if="query.data.value" class="text-xs text-muted">
任务状态:{{ validationStatusLabels[query.data.value.taskStatus] ?? '待确认' }} · 已读取
{{ query.items.value.length }} 条,当前共 {{ query.data.value.total }} 条
</p>
<NButton
size="small"
:loading="query.loading.value && !query.loadingMore.value"
@click="query.refresh"
>刷新记录</NButton
>
</div>
<p v-if="query.error.value" class="text-sm text-muted" role="status">{{ query.error.value }}</p>
<p v-if="query.loading.value && !query.loadingMore.value" role="status" class="text-sm text-muted">
正在读取执行记录…
</p>
<template v-if="query.data.value">
<p v-if="query.data.value.integrity.currentExecution === 'unavailable'" class="text-sm text-muted">
当前执行关联需要核查,以下仅展示已保存的执行记录。
</p>
<p
v-else-if="query.data.value.integrity.currentExecution === 'not_recorded'"
class="text-sm text-muted"
>
原审核未记录当前执行关联。
</p>
<p v-else class="wrap-anywhere text-xs text-muted">
当前执行:{{ query.data.value.currentExecutionId
}}<span v-if="!query.items.value.some(item => item.isCurrent)">(尚未在已加载记录中)</span>
</p>
<p v-if="!query.items.value.length" class="text-sm text-muted">此审核任务暂无已保存的执行记录。</p>
</template>
<!-- 以下是逐次执行状态、质量与独立步骤证据,不以旧失败覆盖当前任务 -->
<article v-for="item in query.items.value" :key="item.execution.id" class="space-y-2 pt-2">
<p class="font-semibold text-sm">
{{ item.isCurrent ? '当前执行' : '历史执行' }} · {{ modeLabels[item.mode] }}
</p>
<KeyframeExecutionStatus
:execution="displayExecution(item)"
:title="item.isCurrent ? '当前执行状态' : '历史执行状态'"
:loading="false"
:refreshable="false"
/>
<p class="text-xs text-muted">
本次新提交步骤:{{ stepScope(item.scheduledSteps) }};复用已有步骤:{{
stepScope(item.reusedSteps)
}}
</p>
<p class="text-xs text-muted">{{ evidenceLabels[item.stepsEvidence] }}</p>
<KeyframeValidationSteps v-if="item.steps" :steps="item.steps" />
<!-- 以下是该执行自己的公开起止时间,不读取其他任务结果补齐 -->
<NCollapse
><NCollapseItem name="execution-details" title="执行详情"
><dl class="space-y-1 text-xs text-muted">
<div>创建:{{ formatDate(item.execution.createdAt) }}</div>
<div>
开始:{{
item.execution.startedAt ? formatDate(item.execution.startedAt) : '未记录'
}}
</div>
<div>
结束:{{
item.execution.completedAt ? formatDate(item.execution.completedAt) : '未记录'
}}
</div>
</dl></NCollapseItem
></NCollapse
>
</article>
<NButton
v-if="query.nextCursor.value"
:loading="query.loadingMore.value"
:disabled="query.loading.value && !query.loadingMore.value"
@click="query.loadMore"
>加载更多</NButton
>
</section>
</NCollapseItem>
</NCollapse>
</template>
@@ -8,10 +8,15 @@ import { userFacingText } from '../../../lib/user-facing-text'
import { formatDate } from '../../../lib/format'
/** 单次视觉审核执行状态,完成和质量通过分别表达。 */
const props = defineProps<{
/** 正式执行记录。 */ execution: WorkflowExecution
/** 只读刷新状态。 */ loading: boolean
}>()
const props = withDefaults(
defineProps<{
/** 正式执行记录。 */ execution: WorkflowExecution
/** 只读刷新状态。 */ loading: boolean
/** 历史记录与当前观察使用不同标题。 */ title?: string
/** 历史列表统一刷新,不对每行重复放置按钮。 */ refreshable?: boolean
}>(),
{ title: '当前审核执行', refreshable: true }
)
/** 仅触发只读刷新。 */
const emit = defineEmits<{ refresh: [] }>()
/** 只有明确质量通过且未标记恢复才使用成功语义。 */
@@ -26,26 +31,40 @@ const passed = computed(
const label = computed(() => {
if (passed.value) return '审核质量通过'
if (props.execution.status === 'failed') return '执行失败,质量未确认'
if (props.execution.status === 'completed')
return props.execution.result?.passed === false ? '执行完成,质量未通过' : '执行完成,质量待核对'
return props.execution.status === 'pending' ? '等待审核' : '审核进行中'
if (props.execution.status === 'completed') {
const quality = props.execution.result?.qualityDecision
const labels: Record<string, string> = {
failed: '质量未通过',
needs_review: '质量待复核',
stale: '审核来源已失效',
blocked: '质量受阻',
insufficient_evidence: '证据不足'
}
return `执行完成,${typeof quality === 'string' && labels[quality] ? labels[quality] : props.execution.result?.passed === false ? '质量未通过' : '质量待核对'}`
}
return props.execution.status === 'pending'
? '等待审核'
: props.execution.status === 'running'
? '审核进行中'
: '状态待确认'
})
</script>
<template>
<!-- 以下是正式执行与实际质量结论模块,不用满格绿色进度暗示通过 -->
<section class="mt-4 space-y-2 text-sm" role="status" :class="passed ? 'bg-(--app-success-soft) p-3' : ''">
<WorkspaceSectionHeading title="当前审核执行"
<WorkspaceSectionHeading :title="title"
><template #actions
><NButton :loading="loading" @click="emit('refresh')">刷新进度</NButton></template
><NButton v-if="refreshable" :loading="loading" @click="emit('refresh')">刷新进度</NButton></template
></WorkspaceSectionHeading
>
<p>{{ label }} · {{ executionStageLabel(execution.stage) }}</p>
<p v-if="execution.total > 0">已处理步骤:{{ execution.current }} / {{ execution.total }}</p>
<p v-if="execution.total > 0">审核计划进度:{{ execution.current }} / {{ execution.total }}</p>
<p v-else>尚无可确认的步骤进度。</p>
<p class="wrap-anywhere text-xs text-muted">
执行编号:{{ execution.id }} · {{ formatDate(execution.updatedAt) }}
</p>
<p v-if="typeof execution.result?.summary === 'string'">{{ userFacingText(execution.result.summary) }}</p>
<p v-if="execution.error">{{ userFacingText(execution.error) }}</p>
</section>
</template>
@@ -5,13 +5,15 @@ import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { computed, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem, NInput } from 'naive-ui'
import { NButton, NInput } from 'naive-ui'
import { errorMessage } from '../../../lib/http'
import ReadonlyInspection from '../../../components/ui/ReadonlyInspection.vue'
import { useQuery } from '../../../composables/useQuery'
import { formatDate } from '../../../lib/format'
import { physicalRetryTarget, submitKeyframeVision, useKeyframeVision } from '../keyframe-vision'
import KeyframeExecutionStatus from './KeyframeExecutionStatus.vue'
import KeyframeExecutionHistory from './KeyframeExecutionHistory.vue'
import KeyframeValidationSteps from './KeyframeValidationSteps.vue'
import { validationStatusLabels as stepLabels } from '../validation-execution-labels'
import { useActionMessage, showActionFeedback } from '../../../components/ui/useActionMessage'
import { qualityApi } from '../quality-api'
import { parseKeyframeValidationOutput, keyframeValidationPassed } from '../quality'
@@ -54,7 +56,6 @@ const {
execution,
state,
uncertain,
observedExecutions,
submissionMode
} = props.observation ?? useKeyframeVision(visionKey)
/** 后台结束时同步刷新人工复核与候选状态。 */
@@ -67,19 +68,6 @@ watch(
}
}
)
/** 公开步骤状态的中文名称。 */
const stepLabels: Record<string, string> = {
pending: '等待',
running: '执行中',
received: '已收到回执',
completed: '完成',
failed: '失败',
needs_review: '需要人工核查'
}
/** 不显示内部模型名称作为审核步骤。 */
const stepNames = { general: '通用画面', physical: '物理关系', gaze: '视线' }
/** 仅显示公开词元计量。 */
const usageLabels = { inputTokens: '输入', outputTokens: '输出', totalTokens: '合计', reasoningTokens: '推理' }
/** 复核证据仅在展开历史时读取,不触发 Vision 或写入审核结论。 */
const reviewQuery = useQuery(key, (value, signal) => {
if (!value) return Promise.resolve(null)
@@ -296,7 +284,7 @@ const records = computed(() =>
:collapsible="!initialOpen"
:show-header="!initialOpen"
title="首帧校验历史"
:loading="query.loading.value"
:loading="query.loading.value && !query.data.value"
:error="query.error.value"
@refresh="
() => {
@@ -395,26 +383,9 @@ const records = computed(() =>
<section v-if="submissionMode === 'physical'" class="mt-3 space-y-2 text-sm" role="status">
<h3 class="font-semibold">仅补跑物理专项</h3>
<p>原通用检查已通过,原费用已记录;本次仅补跑一个物理步骤,不重复提交通用检查。</p>
<p>当前审核状态以以下正式执行及最新质量结论为准。</p>
<p>当前状态以审核结果及执行记录为准。</p>
</section>
<KeyframeExecutionStatus
v-if="execution.data.value"
:execution="execution.data.value"
:loading="execution.loading.value"
@refresh="execution.refresh"
/>
<p v-if="execution.error.value" class="mt-3 text-sm text-muted">{{ execution.error.value }}</p>
<NCollapse v-if="observedExecutions.length" class="mt-3">
<NCollapseItem name="executions" title="历史执行记录">
<p class="text-xs text-muted">
显示本机已观察到的执行;刷新会读取服务保存的最新执行。较早且未观察到的执行暂不可查询。
</p>
<p v-for="item in observedExecutions" :key="item.executionId" class="mt-2 wrap-anywhere text-xs">
审核任务:{{ item.taskId }} · 执行:{{ item.executionId
}}{{ item.status ? ` · 观察时状态:${stepLabels[item.status] ?? '待确认'}` : '' }}
</p>
</NCollapseItem>
</NCollapse>
<!-- 以下是当前审核任务和费用核查状态 -->
<p
v-if="state.unknown || uncertain || (state.active && !state.active.executionId)"
@@ -441,10 +412,7 @@ const records = computed(() =>
: '暂无结论'
}}
</p>
<p class="mt-2 wrap-anywhere text-xs text-muted">
审核任务:{{ record.id
}}<template v-if="record.executionId"> · 最新执行:{{ record.executionId }}</template>
</p>
<p class="mt-2 wrap-anywhere text-xs text-muted">审核任务:{{ record.id }}</p>
<section v-if="record.legacyTermination" class="mt-2 space-y-1 text-sm">
<p>历史审核已人工终止,原任务状态:{{ stepLabels[record.status] ?? '待确认' }};未标记通过。</p>
<p>人工终止时间:{{ formatDate(record.legacyTermination.terminatedAt) }}</p>
@@ -483,39 +451,16 @@ const records = computed(() =>
{{ userFacingText(issue.description) }}
</p>
</template>
<!-- 以下是公开步骤进度和计量,不展示模型回执 -->
<NCollapse v-if="record.steps?.length" class="mt-2">
<NCollapseItem
v-for="step in record.steps"
:key="step.name"
:name="step.name"
:title="`${stepNames[step.name]} · ${stepLabels[step.status]}`"
>
<NCollapse>
<NCollapseItem name="diagnostics" title="高级详情">
<dl class="grid gap-1 wrap-anywhere text-xs text-muted">
<div v-if="step.startedAt">开始:{{ formatDate(step.startedAt) }}</div>
<div v-if="step.finishedAt">完成:{{ formatDate(step.finishedAt) }}</div>
<div v-if="step.requestId">请求编号:{{ step.requestId }}</div>
<div v-if="step.providerRequestId">模型服务请求编号:{{ step.providerRequestId }}</div>
<div v-for="(count, unit) in step.usage" :key="unit">
{{ usageLabels[unit] }}词元:{{ count }}
</div>
</dl>
</NCollapseItem>
</NCollapse>
<ul v-if="step.issues?.length" class="mt-2 space-y-1 text-xs">
<li v-for="(issue, index) in step.issues" :key="index" class="text-danger">
{{ issue.subjectRef ? issue.subjectRef + ' · ' : ''
}}{{ userFacingText(issue.description) }}
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">
{{ step.issues ? '未发现问题。' : '暂无问题记录。' }}
</p>
<p v-if="step.error" class="mt-2 text-danger">{{ userFacingText(step.error) }}</p>
</NCollapseItem>
</NCollapse>
<!-- 以下是原任务的最新步骤摘要和按任务读取的正式执行历史 -->
<KeyframeValidationSteps v-if="record.steps?.length" :steps="record.steps" />
<KeyframeExecutionHistory
:project-id="projectId"
:shot-id="shotId"
:keyframe-id="keyframeId"
:validation-task-id="record.id"
:latest-execution-id="record.executionId"
:live-execution="execution.data.value"
/>
</article>
</ReadonlyInspection>
</template>
@@ -0,0 +1,91 @@
<script setup lang="ts">
import { NCollapse, NCollapseItem } from 'naive-ui'
import { formatDate } from '../../../lib/format'
import { userFacingText } from '../../../lib/user-facing-text'
import type { KeyframeValidationStep } from '../quality.types'
import type { ValidationExecutionStep } from '../validation-executions.types'
import {
validationQualityLabels,
validationStatusLabels,
validationStepNames,
validationUsageLabels
} from '../validation-execution-labels'
/** 原任务摘要与逐次执行共用公开步骤展示,复用用量不重复归入本次。 */
defineProps<{
/** 原有摘要没有逐次归属时,不从缺省值推断新调用。 */ steps: readonly (
| KeyframeValidationStep
| ValidationExecutionStep
)[]
}>()
/**
* 将执行状态与质量结论分开标示,保留复用语义。
* @param step 本条公开步骤
* @returns 可读标题
*/
function stepTitle(step: KeyframeValidationStep | ValidationExecutionStep) {
return (
`${validationStepNames[step.name]} · ${validationStatusLabels[step.status] ?? '状态待确认'}` +
('quality' in step
? ` · ${validationQualityLabels[step.quality]}${step.executionKind === 'reused' ? '(复用)' : ''}`
: '')
)
}
</script>
<template>
<!-- 以下是各步骤自己的结论、问题与计量模块 -->
<NCollapse v-if="steps.length" class="mt-3">
<NCollapseItem v-for="step in steps" :key="step.name" :name="step.name" :title="stepTitle(step)">
<template v-if="'executionKind' in step">
<p>
{{
step.executionKind === 'executed'
? '本次执行步骤'
: step.executionKind === 'reused'
? '复用已有步骤,不重复提交'
: '执行方式未记录'
}}
</p>
<p v-if="step.usageAttribution === 'reused'" class="text-muted">以下为原调用计量,不重复计入本次。</p>
<p v-else-if="step.usageAttribution === 'unknown'" class="text-muted">
计量归属未记录,不能推算本次费用。
</p>
</template>
<ul v-if="step.issues?.length" class="mt-2 space-y-1 text-xs">
<li v-for="(issue, index) in step.issues" :key="index">
{{ issue.subjectRef ? issue.subjectRef + ' · ' : '' }}{{ userFacingText(issue.description) }}
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">{{ step.issues ? '未记录问题。' : '未记录问题证据。' }}</p>
<p v-if="step.error" class="mt-2 text-sm">{{ userFacingText(step.error) }}</p>
<!-- 以下是必要的原始请求、时间和计量,默认收起 -->
<NCollapse class="mt-2"
><NCollapseItem name="diagnostics" title="高级详情">
<dl class="space-y-1 wrap-anywhere text-xs text-muted">
<div v-if="step.startedAt">开始:{{ formatDate(step.startedAt) }}</div>
<div v-if="step.finishedAt">完成:{{ formatDate(step.finishedAt) }}</div>
<div v-if="step.requestId">请求编号:{{ step.requestId }}</div>
<div v-if="step.providerRequestId">模型服务请求编号:{{ step.providerRequestId }}</div>
<div v-if="'sourceExecutionId' in step && step.sourceExecutionId">
复用来源执行:{{ step.sourceExecutionId }}
</div>
<div v-if="'usageAttribution' in step">
计量归属:{{
step.usageAttribution === 'this_execution'
? '本次新调用'
: step.usageAttribution === 'reused'
? '原调用复用'
: '未记录'
}}
</div>
<div v-for="(count, unit) in step.usage" :key="unit">
{{ validationUsageLabels[unit] }}词元:{{ count }}
</div>
<div v-if="!step.usage || !Object.keys(step.usage).length">未记录计量。</div>
</dl>
</NCollapseItem></NCollapse
>
</NCollapseItem>
</NCollapse>
</template>
+1 -37
View File
@@ -3,7 +3,6 @@ import { useQuery } from '../../composables/useQuery'
import { ApiError } from '../../lib/http'
import type { WorkflowExecution } from '../workflows/execution.types'
import { workflowExecutionApi } from '../workflows/execution-api'
import { rememberVisionExecutions, type ObservedVisionExecution } from './vision-execution-history'
import { qualityApi } from './quality-api'
import { isVisualValidation } from './quality'
import type { KeyframeValidationHistoryItem, ResumeKeyframeValidation, KeyframeVisionInput } from './quality.types'
@@ -225,11 +224,6 @@ export function useKeyframeVision(key: Ref<string>, observeExecution = true) {
)
watch(history.data, records => {
if (records && key.value)
rememberVisionExecutions(
key.value,
records.flatMap(item => (item.executionId ? [{ taskId: item.id, executionId: item.executionId }] : []))
)
const saved = submission.value
if (!records || !saved || saved.settled) return
const latest = records[0]
@@ -262,30 +256,6 @@ export function useKeyframeVision(key: Ref<string>, observeExecution = true) {
}
}, 2500)
onScopeDispose(() => clearInterval(timer))
/** 公开最新任务与本机已知的多次执行,读取不提交审核。 */
const observedExecutions = ref<ObservedVisionExecution[]>([])
watch(
[history.data, execution.data, key],
([records, current, target]) => {
observedExecutions.value = target
? rememberVisionExecutions(
target,
(records ?? []).flatMap(item =>
item.executionId
? [
{
taskId: item.id,
executionId: item.executionId,
...(current?.id === item.executionId ? { status: current.status } : {})
}
]
: []
)
)
: []
},
{ immediate: true }
)
/** 本机已提交且仍对应当前正式任务的授权范围。 */
const submissionMode = computed(() => {
const saved = submission.value
@@ -296,7 +266,7 @@ export function useKeyframeVision(key: Ref<string>, observeExecution = true) {
? saved.mode
: undefined
})
return { history, state, execution, uncertain, blocked, resume, observedExecutions, submissionMode }
return { history, state, execution, uncertain, blocked, resume, submissionMode }
}
/**
@@ -364,12 +334,6 @@ export async function submitKeyframeVision(
if (result.shotId !== shotId || result.keyframeId !== assetId || !result.validationTaskId)
throw new Error('审核回执与当前候选不一致,请刷新审核记录。')
if ('executionId' in result && result.status === 'pending' && result.executionId) {
rememberVisionExecutions(key, [
...records.flatMap(item =>
item.executionId ? [{ taskId: item.id, executionId: item.executionId }] : []
),
{ taskId: result.validationTaskId, executionId: result.executionId, status: 'pending' }
])
saveSubmission(key, { ...pending, taskId: result.validationTaskId, executionId: result.executionId })
return null
}
+24
View File
@@ -1,3 +1,4 @@
import type { ValidationExecutionHistory, ValidationExecutionQuery } from './validation-executions.types'
import { keyframeScope } from './keyframe-scope'
import { request } from '../../lib/http'
import type {
@@ -58,6 +59,29 @@ export const qualityApi = {
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframe-provider-capability${provider ? `?provider=${encodeURIComponent(provider)}` : ''}`,
{ signal }
),
/**
* 按原审核任务读取正式执行历史,游标原样传递,不调用模型。
* @param shotId 正式镜头
* @param keyframeId 当前候选
* @param validationTaskId 原审核任务
* @param query 当前项目、分页大小与原始游标
* @param signal 取消旧范围读取
* @returns 本页执行及当前指针完整性
*/
keyframeExecutions: (
shotId: string,
keyframeId: string,
validationTaskId: string,
query: ValidationExecutionQuery = {},
signal?: AbortSignal
) => {
const params = new URLSearchParams()
if (query.projectId !== undefined) params.set('projectId', query.projectId)
if (query.limit !== undefined) params.set('limit', String(query.limit))
if (query.cursor !== undefined) params.set('cursor', query.cursor)
const path = `/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/validations/${encodeURIComponent(validationTaskId)}/executions`
return request<ValidationExecutionHistory>(path + (params.size ? '?' + params : ''), { signal })
},
/**
* 显式请求一次审核,互斥提交新文字、原任务继续或独立授权。
* @param shotId 正式镜头编号
@@ -0,0 +1,166 @@
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import { ApiError, errorMessage } from '../../lib/http'
import { useFeedbackMessage } from '../../composables/useFeedbackMessage'
import { qualityApi } from './quality-api'
import type { ValidationExecutionHistory, ValidationExecutionHistoryItem } from './validation-executions.types'
/**
* 验证本页完整归属及当前指针,不能把排序第一条当成当前执行。
* @param page 正式接口的本页数据
* @param target 固定的项目、镜头、候选、审核任务
* @param cursor 本次请求的原始游标
*/
function assertPage(
page: ValidationExecutionHistory,
target: [string | undefined, string, string, string],
cursor?: string
) {
const [projectId, shotId, keyframeId, taskId] = target
if (
!page ||
!page.projectId ||
(projectId && page.projectId !== projectId) ||
page.shotId !== shotId ||
page.keyframeId !== keyframeId ||
page.validationTaskId !== taskId ||
!Number.isSafeInteger(page.total) ||
page.total < 0 ||
!Array.isArray(page.items) ||
page.items.length > 20 ||
!['valid', 'not_recorded', 'unavailable'].includes(page.integrity?.currentExecution) ||
(page.integrity.currentExecution === 'valid' ? !page.currentExecutionId : page.currentExecutionId !== null) ||
!(
page.nextCursor === null ||
(typeof page.nextCursor === 'string' && page.nextCursor.length > 0 && page.nextCursor !== cursor)
) ||
new Set(page.items.map(item => item.execution?.id)).size !== page.items.length ||
page.items.some(
item =>
!item.execution?.id ||
item.execution.projectId !== page.projectId ||
item.execution.workflowName !== 'shot-keyframe-validation' ||
item.execution.metadata?.validationTaskId !== taskId ||
item.execution.metadata?.shotId !== shotId ||
item.execution.metadata?.keyframeId !== keyframeId ||
item.isCurrent !== (item.execution.id === page.currentExecutionId)
)
) {
throw new Error('执行记录与当前审核范围不匹配,请刷新核对。')
}
}
/**
* 按任务按需读取正式分页,不读取或写入任何本机执行历史缓存。
* @param key 展开时的项目、镜头、候选、任务 JSON,收起时为空
* @returns 当前页信息、已加载记录及只读刷新入口
*/
export function useValidationExecutions(key: Ref<string>) {
/** 最新一页的正式任务状态、指针和游标。 */
const data = ref<ValidationExecutionHistory | null>(null)
/** 本次展开已加载的执行,刷新首屏时重新建立。 */
const records = ref<ValidationExecutionHistoryItem[]>([])
/** 当前请求状态,防止连续点击重复翻页。 */
const loading = ref(false)
/** 区分首屏与后续页,保留已加载内容的滚动位置。 */
const loadingMore = ref(false)
/** 只显示当前范围的可读错误。 */
const error = ref('')
useFeedbackMessage(error)
/** 下一页仅由正式游标决定,不以实时 total 计算。 */
const nextCursor = computed(() => data.value?.nextCursor ?? null)
/** 每页可返回更新后的当前指针,同步已加载旧页的标记。 */
const items = computed(() =>
records.value.map(item => ({ ...item, isCurrent: item.execution.id === data.value?.currentExecutionId }))
)
/** 请求代次覆盖取消失效的底层实现。 */
let generation = 0
/** 当前分页请求,切换或关闭时中止。 */
let controller: AbortController | undefined
/** 卸载后不更新状态或展示迟到错误。 */
let disposed = false
/** 取消旧页并清空旧范围,保留提交保护由原观察器负责。 */
function clear() {
generation++
controller?.abort()
data.value = null
records.value = []
error.value = ''
loading.value = false
loadingMore.value = false
}
/**
* 固定当前资源和游标读取一页,错误不启动审核或探测其他项目。
* @param cursor 正式下一页游标,省略时读取首屏
* @returns 本页读取结束
*/
async function read(cursor?: string) {
if (disposed || !key.value) return
const identity = key.value
const current = ++generation
controller?.abort()
controller = new AbortController()
const signal = controller.signal
loading.value = true
loadingMore.value = cursor !== undefined
error.value = ''
try {
const target = JSON.parse(identity) as [string | undefined, string, string, string]
const [projectId, shotId, keyframeId, taskId] = target
const page = await qualityApi.keyframeExecutions(
shotId,
keyframeId,
taskId,
{ ...(projectId ? { projectId } : {}), limit: 20, ...(cursor ? { cursor } : {}) },
signal
)
if (disposed || signal.aborted || current !== generation || identity !== key.value) return
assertPage(page, target, cursor)
const merged = new Map((cursor ? records.value : []).map(item => [item.execution.id, item]))
for (const item of page.items) merged.set(item.execution.id, item)
records.value = [...merged.values()]
data.value = page
} catch (cause) {
if (disposed || signal.aborted || current !== generation || identity !== key.value) return
error.value = errorMessage(cause)
if (cause instanceof ApiError && cause.status === 400 && data.value)
data.value = { ...data.value, nextCursor: null }
else if (!(cause instanceof ApiError) || [404, 409].includes(cause.status)) {
data.value = null
records.value = []
}
} finally {
if (!disposed && current === generation) {
loading.value = false
loadingMore.value = false
}
}
}
/**
* 刷新首屏并废弃旧游标,使新执行进入新的分页序列。
* @returns 首屏查询完成
*/
async function refresh() {
clear()
await read()
}
/**
* 明确点击后原样读取下一页,同一时刻只允许一个请求。
* @returns 下一页查询完成
*/
async function loadMore() {
if (!loading.value && nextCursor.value) await read(nextCursor.value)
}
watch(
key,
() => {
void refresh()
},
{ immediate: true, flush: 'sync' }
)
onScopeDispose(() => {
disposed = true
clear()
})
return { data, items, loading, loadingMore, error, nextCursor, refresh, loadMore }
}
@@ -0,0 +1,25 @@
/** 审核步骤共用中文名称,内部枚举不变。 */
export const validationStepNames = { general: '通用画面', physical: '物理关系', gaze: '视线' }
/** 执行和步骤的公开状态,仅完成不能推断质量通过。 */
export const validationStatusLabels: Record<string, string> = {
pending: '等待',
running: '执行中',
received: '已收到回执',
completed: '完成',
failed: '失败',
needs_review: '需要人工核查'
}
/** 已记录的质量结论。 */
export const validationQualityLabels = {
passed: '质量通过',
failed: '质量未通过',
needs_review: '质量待复核',
unknown: '质量未确认'
}
/** 原始计量单位,不显示缺失项或补零。 */
export const validationUsageLabels: Record<string, string> = {
inputTokens: '输入',
outputTokens: '输出',
totalTokens: '合计',
reasoningTokens: '推理'
}
@@ -0,0 +1,45 @@
import type { WorkflowExecution } from '../workflows/execution.types'
import type { KeyframeValidationStep, KeyframeStepIssue } from './quality.types'
/** 视觉审核的三个正式步骤名称。 */
export type ValidationStepName = KeyframeValidationStep['name']
/** 单次执行独立存证的公开步骤,不以完成状态推断通过。 */
export interface ValidationExecutionStep extends Omit<KeyframeValidationStep, 'issues' | 'error'> {
/** 已解析证据的真实质量结论。 */ quality: 'passed' | 'failed' | 'needs_review' | 'unknown'
/** 公开问题;没有解析结果时为空值。 */ issues: KeyframeStepIssue[] | null
/** 安全的失败原因。 */ error: string | null
/** 本次实际执行、复用或无法确认。 */ executionKind: 'executed' | 'reused' | 'unknown'
/** 有可靠证据时的复用来源执行。 */ sourceExecutionId: string | null
/** 用量归属,只有本次调用可计为新增计量。 */ usageAttribution: 'this_execution' | 'reused' | 'unknown'
}
/** 原审核任务的一次正式执行及其独立证据。 */
export interface ValidationExecutionHistoryItem {
/** 复用单执行接口的公开记录。 */ execution: WorkflowExecution
/** 依据原任务正式当前指针判断。 */ isCurrent: boolean
/** 已保存的本次执行模式。 */ mode: 'initial' | 'resume' | 'physical_retry' | 'unknown'
/** 本次需新提交的步骤,未记录时为 null。 */ scheduledSteps: ValidationStepName[] | null
/** 本次复用或解析已有回执的步骤,未记录时为 null。 */ reusedSteps: ValidationStepName[] | null
/** 本次自己的步骤,不使用任务当前 output 补齐。 */ steps: ValidationExecutionStep[] | null
/** 公开证据来源。 */ stepsEvidence: 'execution_snapshot' | 'archived_audit' | 'not_recorded'
}
/** 同一审核任务的正式分页结果。 */
export interface ValidationExecutionHistory {
/** 正式项目。 */ projectId: string
/** 正式镜头。 */ shotId: string
/** 镜头候选。 */ keyframeId: string
/** 原审核任务。 */ validationTaskId: string
/** 原任务状态,独立于执行和质量。 */ taskStatus: string
/** 经核对的当前执行,可以不在当前页。 */ currentExecutionId: string | null
/** 每次请求时的实时合法记录总数。 */ total: number
/** 当前页,按正式创建顺序倒序。 */ items: ValidationExecutionHistoryItem[]
/** 正式当前指针是否完整。 */ integrity: {
/** 有效、未保存或当前不可用。 */ currentExecution: 'valid' | 'not_recorded' | 'unavailable'
}
/** 原样传回的不透明游标,为 null 时停止。 */ nextCursor: string | null
}
/** 正式接口仅接受明确的项目、分页大小和原始游标。 */
export interface ValidationExecutionQuery {
/** 当前项目,历史调用允许省略。 */ projectId?: string
/** 一次读取的条数,默认 20。 */ limit?: number
/** 后端返回的下一页位置。 */ cursor?: string
}
@@ -1,45 +0,0 @@
/** 客户端曾实际观察到的执行,仅用于补充正式历史的最新执行编号。 */
export interface ObservedVisionExecution {
/** 原审核任务编号。 */ taskId: string
/** 已实际取得的执行编号。 */ executionId: string
/** 最近观察到的公开执行状态。 */ status?: string
}
/**
* 读取本机曾观察到的执行,不推断服务端未公开的历史。
* @param key 项目和候选范围
* @returns 已知执行记录
*/
export function readVisionExecutions(key: string): ObservedVisionExecution[] {
try {
const parsed: unknown = JSON.parse(localStorage.getItem('vision-executions:' + key) || '[]')
return Array.isArray(parsed)
? parsed.filter(item => item && typeof item.taskId === 'string' && typeof item.executionId === 'string')
: []
} catch {
return []
}
}
/**
* 合并真实编号,同一任务的新执行不会覆盖旧执行。
* @param key 项目和候选范围
* @param entries 正式响应或事件中取得的记录
* @returns 合并后的已知记录
*/
export function rememberVisionExecutions(key: string, entries: ObservedVisionExecution[]) {
const records = readVisionExecutions(key)
for (const item of entries) {
const existing = records.find(
record => record.executionId === item.executionId && record.taskId === item.taskId
)
if (existing) Object.assign(existing, item)
else records.push(item)
}
try {
localStorage.setItem('vision-executions:' + key, JSON.stringify(records))
} catch {
/* 存储不可用不影响正式查询。 */
}
return records
}
+4
View File
@@ -95,6 +95,10 @@ export function executionStageLabel(stage: string | null) {
submitting: '提交视频候选',
generating: '生成视频',
validating: '质量校验',
vision: '视觉审核',
general: '通用画面审核',
physical: '物理关系审核',
gaze: '视线审核',
repairing: '自动修复',
passed: '校验通过',
exhausted: '修复次数已用完',
+1
View File
@@ -1,5 +1,6 @@
/** 项目配置的确定性业务状态说明,不将配置限制显示为系统故障。 */
const configurationErrorLabels: Record<string, string> = {
KEYFRAME_VALIDATION_EXECUTION_CONFLICT: '执行关联或历史证据需要核查,请刷新记录后核对。',
KEYFRAME_VALIDATION_ACTIVE: '已有审核正在进行,请查看当前执行进度。',
KEYFRAME_VALIDATION_RECOVERY_REQUIRED: '原审核结果或费用待核查,请刷新历史并核对,勿重复提交。',
KEYFRAME_VALIDATION_AUTHORIZATION_INVALID: '授权无效、已使用或不适用于当前候选,请核对授权编号。',
@@ -0,0 +1,181 @@
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import KeyframeExecutionHistory from '@/features/production/components/KeyframeExecutionHistory.vue'
import KeyframeValidationHistory from '@/features/production/components/KeyframeValidationHistory.vue'
import ReadonlyInspection from '@/components/ui/ReadonlyInspection.vue'
import {
physicalHistoryFixture,
validationExecutionFixture,
validationHistoryFixture
} from '../../fixtures/validation-executions'
/** 只操作隔离挂载,浏览器布局另在本地 Chrome 验收。 */
let wrapper: VueWrapper
/**
* 通过实际折叠标题触发按需查询,不直接调用组件私有方法。
* @param label 可见折叠标题
*/
async function expand(label: string) {
const heading = wrapper.findAll('.n-collapse-item__header-main').find(item => item.text().includes(label))
expect(heading).toBeDefined()
await heading!.trigger('click')
await flushPromises()
}
/**
* 包装正式响应。
* @param data 公开返回值
* @returns Mock HTTP
*/
function response(data: unknown) {
return new Response(JSON.stringify({ data }))
}
afterEach(() => {
wrapper?.unmount()
localStorage.clear()
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('按任务读取执行历史的页面流程', () => {
it('无缓存按需分页,原 General 计量只标复用;旧失败和未记录步骤独立展示', async () => {
const fetcher = vi.fn<typeof fetch>(async input =>
response(
String(input).includes('cursor=opaque')
? validationHistoryFixture([validationExecutionFixture('old-run')])
: validationHistoryFixture([physicalHistoryFixture], { nextCursor: 'opaque' })
)
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(KeyframeExecutionHistory, {
props: { projectId: 'project', shotId: 'shot', keyframeId: 'keyframe', validationTaskId: 'task' }
})
await flushPromises()
expect(fetcher).not.toHaveBeenCalled()
await expand('执行记录')
expect(wrapper.text()).toContain('仅补跑物理专项')
expect(wrapper.text()).toContain('执行完成,质量待复核')
expect(wrapper.text()).toContain('本次新提交步骤:物理关系;复用已有步骤:通用画面')
await expand('通用画面')
expect(wrapper.text()).toContain('原调用计量,不重复计入本次')
await expand('高级详情')
expect(wrapper.text()).toContain('输入词元:100')
expect(wrapper.text()).toContain('复用来源执行:old-run')
expect(wrapper.text()).not.toContain('合计词元:0')
await wrapper
.findAll('button')
.find(item => item.text() === '加载更多')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('历史执行') // 显示历史行,具体错误由该执行本身提供
expect(wrapper.text()).toContain('未记录本次步骤证据')
expect(wrapper.text()).not.toContain('加载更多')
expect(fetcher).toHaveBeenCalledTimes(2)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('当前关联不可用不选择第一条;归档步骤的未知范围不补成空计划', async () => {
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async () =>
response(
validationHistoryFixture(
[validationExecutionFixture('archive', { stepsEvidence: 'archived_audit' })],
{ currentExecutionId: null, integrity: { currentExecution: 'unavailable' } }
)
)
)
)
wrapper = mount(KeyframeExecutionHistory, {
props: { projectId: 'project', shotId: 'shot', keyframeId: 'keyframe', validationTaskId: 'task' }
})
await expand('执行记录')
expect(wrapper.text()).toContain('当前执行关联需要核查')
expect(wrapper.text()).toContain('执行范围未记录')
expect(wrapper.text()).toContain('本次新提交步骤:未记录')
expect(wrapper.text()).toContain('已核对的历史审计')
expect(wrapper.text()).not.toContain('当前执行 ·')
})
it('只接收同一范围的实时变化,终态只刷新首屏一次,不新建 SSE', async () => {
const fetcher = vi.fn<typeof fetch>(async () => response(validationHistoryFixture([physicalHistoryFixture])))
vi.stubGlobal('fetch', fetcher)
const source = vi.fn<() => void>()
vi.stubGlobal('EventSource', source)
wrapper = mount(KeyframeExecutionHistory, {
props: { projectId: 'project', shotId: 'shot', keyframeId: 'keyframe', validationTaskId: 'task' }
})
await expand('执行记录')
await wrapper.setProps({
liveExecution: {
...physicalHistoryFixture.execution,
id: 'foreign-run',
metadata: { validationTaskId: 'other-task', shotId: 'shot', keyframeId: 'keyframe' }
}
})
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(1)
await wrapper.setProps({ latestExecutionId: 'new-run' })
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(2)
await flushPromises()
expect(fetcher).toHaveBeenCalledTimes(2)
expect(source).not.toHaveBeenCalled()
})
it('人工终止旧任务可读空列表,刷新候选摘要不卸载已展开的正式执行记录', async () => {
let pending = false
let resolveHistory!: (value: Response) => void
const task = {
id: 'task',
status: 'running',
output: null,
error: null,
createdAt: '2026-11-07',
legacyTermination: {
auditId: 'audit',
terminatedAt: '2026-11-07',
billingFinding: 'unresolved',
requiresNewAuthorization: true
}
}
const fetcher = vi.fn<typeof fetch>(async input => {
const path = String(input)
if (path.includes('/executions?'))
return response(
validationHistoryFixture([], {
total: 0,
currentExecutionId: null,
taskStatus: 'running',
integrity: { currentExecution: 'not_recorded' }
})
)
if (path.includes('/validations'))
return pending
? new Promise(resolve => {
resolveHistory = resolve
})
: response([task])
return response({
validationTaskId: 'task',
qualityDecision: 'unknown',
effectiveQualityStatus: 'unknown',
historicalGazePreview: [],
manualReviewAvailable: false
})
})
vi.stubGlobal('fetch', fetcher)
wrapper = mount(KeyframeValidationHistory, {
props: { projectId: 'project', shotId: 'shot', keyframeId: 'keyframe', initialOpen: true }
})
await flushPromises()
await expand('执行记录')
expect(wrapper.text()).toContain('暂无已保存的执行记录')
expect(wrapper.text()).toContain('历史审核已人工终止')
const original = wrapper.findComponent(KeyframeExecutionHistory).vm.$.uid
pending = true
wrapper.findComponent(ReadonlyInspection).vm.$emit('refresh')
await flushPromises()
expect(wrapper.findComponent(KeyframeExecutionHistory).vm.$.uid).toBe(original)
expect(wrapper.text()).toContain('暂无已保存的执行记录')
resolveHistory(response([task]))
await flushPromises()
expect(fetcher.mock.calls.filter(([input]) => String(input).includes('/executions?'))).toHaveLength(1)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
})
@@ -0,0 +1,230 @@
import { effectScope, ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useValidationExecutions } from '@/features/production/useValidationExecutions'
import { qualityApi } from '@/features/production/quality-api'
import type { ValidationExecutionHistory } from '@/features/production/validation-executions.types'
/** 隔离范围包含完整资源路径,不能复用其他任务的游标。 */
const target = ['project', 'shot', 'keyframe', 'task'] as const
/** 创建单页正式响应,旧执行保持自己的失败结果。 */
function page(ids: string[], current = 'new', cursor: string | null = null): ValidationExecutionHistory {
return {
projectId: target[0],
shotId: target[1],
keyframeId: target[2],
validationTaskId: target[3],
taskStatus: 'running',
currentExecutionId: current,
total: 3,
integrity: { currentExecution: 'valid' },
nextCursor: cursor,
items: ids.map(id => ({
execution: {
id,
projectId: target[0],
workflowName: 'shot-keyframe-validation',
status: id === 'new' ? 'running' : 'failed',
stage: 'vision',
current: 1,
total: 2,
currentResourceId: null,
metadata: { validationTaskId: target[3], shotId: target[1], keyframeId: target[2] },
result: null,
error: id === 'new' ? null : '旧执行失败',
startedAt: null,
completedAt: null,
createdAt: '2026-11-07T00:00:00Z',
updatedAt: '2026-11-07T00:00:00Z'
},
isCurrent: id === current,
mode: 'unknown',
scheduledSteps: null,
reusedSteps: null,
steps: null,
stepsEvidence: 'not_recorded'
}))
}
}
/** 解包模拟响应,不调用任何真实 API。 */
function response(data: unknown, status = 200) {
return new Response(
JSON.stringify(
status === 200 ? { data } : { message: '读取失败', code: 'KEYFRAME_VALIDATION_EXECUTION_CONFLICT' }
),
{ status }
)
}
let scope = effectScope()
afterEach(() => {
scope.stop()
scope = effectScope()
localStorage.clear()
vi.unstubAllGlobals()
})
describe('正式首帧执行分页', () => {
it('API 编码完整目标,显式传项目、limit 与原样游标', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(response(page([])))
vi.stubGlobal('fetch', fetcher)
await qualityApi.keyframeExecutions(
's/a',
'k/b',
't/c',
{ projectId: 'p/d', limit: 20, cursor: 'opaque_A-1' },
new AbortController().signal
)
expect(String(fetcher.mock.calls[0]![0])).toBe(
'/api/storyboard-shots/s%2Fa/keyframes/k%2Fb/validations/t%2Fc/executions?projectId=p%2Fd&limit=20&cursor=opaque_A-1'
)
expect(fetcher.mock.calls[0]![1]?.method).toBe('GET')
})
it('默认关闭不读取,不读本机缓存;打开后按游标加载并去重,不按 total 猜测页数', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async input =>
response(
String(input).includes('cursor=opaque')
? { ...page(['new', 'old'], 'later'), total: 9 }
: page(['new'], 'new', 'opaque')
)
)
vi.stubGlobal('fetch', fetcher)
const key = ref('')
localStorage.setItem(
'vision-executions:' + JSON.stringify(['shot', 'keyframe', 'project']),
JSON.stringify([{ taskId: 'fake', executionId: 'fake' }])
)
const history = scope.run(() => useValidationExecutions(key))!
await flushPromises()
expect(fetcher).not.toHaveBeenCalled()
key.value = JSON.stringify(target)
await flushPromises()
expect(history.items.value.map(item => item.execution.id)).toEqual(['new'])
await Promise.all([history.loadMore(), history.loadMore()])
await flushPromises()
expect(history.items.value.map(item => item.execution.id)).toEqual(['new', 'old'])
expect(history.data.value?.currentExecutionId).toBe('later')
expect(history.items.value.some(item => item.isCurrent)).toBe(false)
expect(history.nextCursor.value).toBeNull()
await history.loadMore()
expect(fetcher).toHaveBeenCalledTimes(2)
})
it('切项目或任务清空旧页并取消旧请求,迟到 404 不影响新范围', async () => {
let resolveOld!: (value: Response) => void
let oldSignal: AbortSignal | undefined
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
if (String(input).includes('/task/')) {
oldSignal = init?.signal as AbortSignal
return new Promise(resolve => {
resolveOld = resolve
})
}
return response({ ...page(['new']), validationTaskId: 'other-task', items: [] })
})
vi.stubGlobal('fetch', fetcher)
const key = ref(JSON.stringify(target))
const history = scope.run(() => useValidationExecutions(key))!
await flushPromises()
key.value = JSON.stringify(['project', 'shot', 'keyframe', 'other-task'])
await flushPromises()
resolveOld(response(null, 404))
await flushPromises()
expect(oldSignal?.aborted).toBe(true)
expect(history.data.value?.validationTaskId).toBe('other-task')
expect(history.error.value).toBe('')
})
it('切项目时同时更换完整资源身份,旧页回执和游标不能进入新项目', async () => {
let resolveOld!: (value: Response) => void
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async input => {
if (new URL(String(input), 'http://localhost').searchParams.get('projectId') === 'project')
return new Promise(resolve => {
resolveOld = resolve
})
return response({
...page([]),
projectId: 'new-project',
shotId: 'new-shot',
keyframeId: 'new-keyframe',
validationTaskId: 'new-task',
currentExecutionId: null,
integrity: { currentExecution: 'not_recorded' }
})
})
)
const key = ref(JSON.stringify(target))
const history = scope.run(() => useValidationExecutions(key))!
await flushPromises()
key.value = JSON.stringify(['new-project', 'new-shot', 'new-keyframe', 'new-task'])
await flushPromises()
resolveOld(response(page(['new'], 'new', 'old-cursor')))
await flushPromises()
expect(history.data.value?.projectId).toBe('new-project')
expect(history.items.value).toEqual([])
expect(history.nextCursor.value).toBeNull()
})
it('刷新首屏中止旧翻页,新当前指针不被旧页回填,当前不在本页也不选第一条', async () => {
let resolveMore!: (value: Response) => void
let refreshed = false
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async input => {
if (String(input).includes('cursor='))
return new Promise(resolve => {
resolveMore = resolve
})
return response(refreshed ? page(['old'], 'outside') : page(['new'], 'new', 'opaque'))
})
)
const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))!
await flushPromises()
const more = history.loadMore()
await flushPromises()
refreshed = true
await history.refresh()
resolveMore(response(page(['older'])))
await more
expect(history.items.value.map(item => item.execution.id)).toEqual(['old'])
expect(history.items.value[0]?.isCurrent).toBe(false)
expect(history.data.value?.currentExecutionId).toBe('outside')
})
it.each([400, 404, 409])('翻页 %i 明确结束旧游标,不自动重试或 POST', async status => {
const fetcher = vi.fn<typeof fetch>(async input =>
String(input).includes('cursor=') ? response(null, status) : response(page(['new'], 'new', 'opaque'))
)
vi.stubGlobal('fetch', fetcher)
const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))!
await flushPromises()
await history.loadMore()
await history.loadMore()
expect(history.nextCursor.value).toBeNull()
expect(history.error.value).not.toBe('')
expect(fetcher).toHaveBeenCalledTimes(2)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
expect(history.items.value).toHaveLength(status === 400 ? 1 : 0)
})
it('损坏的归属和当前标记不进入列表;旧审核空列表合法', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
response({ ...page(['old']), items: page(['old']).items.map(item => ({ ...item, isCurrent: true })) })
)
.mockResolvedValueOnce(
response({
...page([]),
total: 0,
currentExecutionId: null,
integrity: { currentExecution: 'not_recorded' }
})
)
vi.stubGlobal('fetch', fetcher)
const history = scope.run(() => useValidationExecutions(ref(JSON.stringify(target))))!
await flushPromises()
expect(history.items.value).toEqual([])
expect(history.error.value).not.toBe('')
await history.refresh()
expect(history.error.value).toBe('')
expect(history.data.value?.integrity.currentExecution).toBe('not_recorded')
})
})
@@ -167,10 +167,7 @@ describe('审核 GET 与 SSE 项目隔离', () => {
)
expect(vision.execution.data.value?.id).toBe('new-execution')
expect(vision.state.value.active?.id).toBe('same-task')
expect(vision.observedExecutions.value.map(item => item.executionId)).toEqual([
'old-execution',
'new-execution'
])
expect(localStorage.getItem('vision-executions:' + JSON.stringify(['s', 'k', 'multi']))).toBeNull()
const state = visionState([
task('new-execution', 'completed'),
{ ...task('old-execution', 'failed'), id: 'older-task', recoveryRequired: true }
+107
View File
@@ -0,0 +1,107 @@
import type {
ValidationExecutionHistory,
ValidationExecutionHistoryItem
} from '@/features/production/validation-executions.types'
/** 隔离任务的完整正式路径身份。 */
export const executionHistoryTarget = ['project', 'shot', 'keyframe', 'task'] as const
/**
* 创建逐次证据的隔离执行,不调用 Provider。
* @param id 正式执行编号
* @param patch 本次已保存证据覆盖
* @returns 执行公开 DTO
*/
export function validationExecutionFixture(
id: string,
patch: Partial<ValidationExecutionHistoryItem> = {}
): ValidationExecutionHistoryItem {
return {
execution: {
id,
projectId: 'project',
workflowName: 'shot-keyframe-validation',
status: 'failed',
stage: 'vision',
current: 1,
total: 2,
currentResourceId: null,
metadata: { validationTaskId: 'task', shotId: 'shot', keyframeId: 'keyframe' },
result: null,
error: '物理步骤回执尚待核查',
startedAt: '2026-11-07T00:00:00Z',
completedAt: '2026-11-07T00:01:00Z',
createdAt: '2026-11-07T00:00:00Z',
updatedAt: '2026-11-07T00:01:00Z'
},
isCurrent: false,
mode: 'unknown',
scheduledSteps: null,
reusedSteps: null,
steps: null,
stepsEvidence: 'not_recorded',
...patch
}
}
/**
* 构造正式分页响应,当前指针独立于页内排序。
* @param items 本页独立执行证据
* @param patch 分页及当前指针覆盖
* @returns 隔离接口响应数据
*/
export function validationHistoryFixture(
items: ValidationExecutionHistoryItem[],
patch: Partial<ValidationExecutionHistory> = {}
): ValidationExecutionHistory {
return {
projectId: 'project',
shotId: 'shot',
keyframeId: 'keyframe',
validationTaskId: 'task',
taskStatus: 'completed',
currentExecutionId: 'current-run',
total: 2,
items,
integrity: { currentExecution: 'valid' },
nextCursor: null,
...patch
}
}
/** 带通用复用与本次物理调用的正式证据。 */
export const physicalHistoryFixture = validationExecutionFixture('current-run', {
execution: {
...validationExecutionFixture('current-run').execution,
status: 'completed',
current: 2,
result: { passed: false, qualityDecision: 'needs_review' },
error: null
},
isCurrent: true,
mode: 'physical_retry',
scheduledSteps: ['physical'],
reusedSteps: ['general'],
stepsEvidence: 'execution_snapshot',
steps: [
{
name: 'general',
status: 'completed',
quality: 'passed',
issues: [],
error: null,
usage: { inputTokens: 100, outputTokens: 10 },
executionKind: 'reused',
sourceExecutionId: 'old-run',
usageAttribution: 'reused'
},
{
name: 'physical',
status: 'completed',
quality: 'needs_review',
issues: [{ code: 'visibility', description: '固定部件部分遮挡', severity: 'warning' }],
error: null,
usage: { inputTokens: 80 },
executionKind: 'executed',
sourceExecutionId: null,
usageAttribution: 'this_execution'
}
]
})