feat(short-drama-agent-front): 接入草案、首帧证据与审核继续

This commit is contained in:
GJ committed 2026-11-06 18:21:31 +08:00
1 parent 751106985e
commit d0264c08ce
23 files changed
+990 -170

No files matched your search

+3 -2
View File
@@ -1,3 +1,4 @@
import { keyframeScope } from './keyframe-scope'
import { request } from '../../lib/http'
import type { PromptBatchResult, StoryboardBatchInput } from '../storyboard/types'
import type {
@@ -156,8 +157,8 @@ export const productionApi = {
}),
listKeyframes: (shotId: string, signal?: AbortSignal) =>
request<ShotKeyframe[]>(`${shotPath(shotId)}/keyframes`, { signal }),
keyframeSpec: (shotId: string, signal?: AbortSignal) =>
request<KeyframeSpec>(`${shotPath(shotId)}/keyframe-spec`, { signal }),
keyframeSpec: (shotId: string, signal?: AbortSignal, projectId?: string) =>
request<KeyframeSpec>(keyframeScope(`${shotPath(shotId)}/keyframe-spec`, projectId), { signal }),
/** 按本次请求选择的图片模型与参数预览最终输入,不创建首帧任务。 */
previewKeyframe: (
shotId: string,
@@ -16,6 +16,8 @@ import type { ShotKeyframe } from '../types'
/** 首帧卡片统一主图标识、质量结论和晋升限制。 */
const props = defineProps<{
item: ShotKeyframe
/** 正式项目归属,用于查询候选审核。 */
projectId?: string
shotId: string
/** 审核后递增以刷新持久化质量状态。 */
reviewRevision?: number
@@ -42,9 +44,13 @@ const emit = defineEmits<{
}>()
/** 每张可见候选可独立找回自己的审核任务。 */
const visionKey = computed(() =>
props.item.status === 'completed' ? JSON.stringify([props.shotId, props.item.id]) : ''
props.item.status === 'completed'
? JSON.stringify(
props.projectId ? [props.shotId, props.item.id, props.projectId] : [props.shotId, props.item.id]
)
: ''
)
const vision = useKeyframeVision(visionKey)
const vision = useKeyframeVision(visionKey, false)
watch(
() => vision.state.value.active,
(active, previous) => {
@@ -20,7 +20,7 @@ import { errorMessage } from '../../../lib/http'
import { productionApi } from '../api'
import { directionLabel } from '../../storyboard/model'
import type { ShotDirection, ShotVisualState } from '../../storyboard/types'
import type { GenerateKeyframeInput, KeyframeGenerationPreview } from '../types'
import type { GenerateKeyframeInput } from '../types'
/** 单镜头首帧表单;所有新图先生成候选,通过质量检查后再人工晋升。 */
const props = defineProps<{
@@ -38,8 +38,6 @@ const props = defineProps<{
/** 仅发送已经确认的当前快照。 */
submitGeneration: (input: GenerateKeyframeInput) => Promise<ImageGenerationSubmission>
}>()
/** 只读提供当次正式预览,候选必须匹配输入指纹才能展示。 */
const emit = defineEmits<{ previewed: [preview: KeyframeGenerationPreview] }>()
/** 当前候选生成窗口。 */
const open = defineModel<boolean>('open', { default: false })
/** 生成参数表单,用于复用字段校验。 */
@@ -86,7 +84,6 @@ const {
const shotId = props.shotId
const result = await productionApi.previewKeyframe(shotId, input, signal)
if (result?.shotId !== shotId) throw new Error('预览结果与当前镜头不匹配。')
if (!signal.aborted && shotId === props.shotId) emit('previewed', result)
return result
},
generate: input => props.submitGeneration({ ...input, setPrimary: false })
@@ -0,0 +1,89 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import { useQuery } from '../../../composables/useQuery'
import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import { historicalReferenceUrl, loadKeyframeInput } from '../keyframe-input'
import type { ImageGenerationPreview as ImagePreview } from '../../subject-images/generation-preview'
/** 只在展开后读取所选候选的实际生成输入。 */
const props = defineProps<{
/** 当前项目。 */ projectId: string
/** 当前镜头。 */ shotId: string
/** 当前候选。 */ keyframeId: string
}>()
/** 生成证据默认收起。 */
const expanded = ref<string[]>([])
/** 包含完整归属,切换候选即取消前一个请求。 */
const key = computed(() =>
expanded.value.includes('generation') ? JSON.stringify([props.projectId, props.shotId, props.keyframeId]) : ''
)
/** 从保存快照读取;不调用免费预览重建历史。 */
const query = useQuery(key, async (value, signal) => {
if (!value) return null
const [projectId, shotId, keyframeId] = JSON.parse(value) as [string, string, string]
const result = await loadKeyframeInput(projectId, shotId, keyframeId, signal)
if (result.shotId !== shotId || result.keyframeId !== keyframeId) throw new Error('生成记录与当前候选不一致。')
return result
})
/** 只有完整历史证据才能进入现有图片预览组件。 */
const snapshot = computed(() =>
query.data.value?.inputSnapshotStatus === 'recorded' ? query.data.value.providerInputSnapshot : null
)
/** 使用正式原件地址和真实模型参数展示历史快照。 */
const display = computed<ImagePreview | null>(() => {
const input = snapshot.value
if (!input) return null
return {
provider: input.provider,
model: input.model ?? '模型未记录',
providerPrompt: input.providerPrompt,
previewFingerprint: input.fingerprint,
generationConfig: { options: input.generationOptions, width: input.width, height: input.height },
providerInputSnapshot: input,
referenceImages: input.references.map(
reference => historicalReferenceUrl(reference, props.projectId, props.shotId, props.keyframeId) ?? ''
)
}
})
</script>
<template>
<!-- 以下是当前候选生成输入的按需详情 -->
<NCollapse v-model:expanded-names="expanded" class="mb-4">
<NCollapseItem name="generation" title="当次参考图和画面描述">
<p v-if="query.loading.value" role="status" class="text-xs text-muted">正在读取生成记录…</p>
<NButton
v-if="query.error.value || query.data.value"
size="small"
:disabled="query.loading.value"
class="mb-3"
@click="query.refresh"
>刷新生成记录</NButton
>
<template v-if="display && snapshot">
<p class="text-xs text-muted">
快照版本 {{ snapshot.version
}}<template v-if="snapshot.width && snapshot.height">
· {{ snapshot.width }} × {{ snapshot.height }}</template
>
</p>
<ImageGenerationPreview
:preview="display"
:historical-references="snapshot.references"
:loading="false"
error=""
stale-notice=""
display-only
/>
</template>
<p v-else-if="query.data.value" class="text-xs text-muted">
{{
query.data.value.inputSnapshotStatus === 'not-recorded'
? '这张首帧没有保存当次生成输入。'
: '这张首帧的生成证据已损坏,无法读取。'
}}
</p>
</NCollapseItem>
</NCollapse>
</template>
@@ -26,6 +26,8 @@ const props = defineProps<{
disabled?: boolean
/** 在独立弹窗内直接展示内容,并隐藏内部标题、说明与操作栏。 */
initialOpen?: boolean
/** 已有审核弹窗的观察器,可共享同一订阅。 */
observation?: ReturnType<typeof useKeyframeVision>
}>()
/** 通知候选重新读取当前质量状态。 */
const emit = defineEmits<{ reviewed: [] }>()
@@ -38,8 +40,14 @@ const key = computed(() =>
: ''
)
/** 独立打开历史后恢复后台观察。 */
const visionKey = computed(() => (key.value ? JSON.stringify([props.shotId, props.keyframeId]) : ''))
const { history: query, execution, state, uncertain } = useKeyframeVision(visionKey)
const visionKey = computed(() =>
key.value
? JSON.stringify(
props.projectId ? [props.shotId, props.keyframeId, props.projectId] : [props.shotId, props.keyframeId]
)
: ''
)
const { history: query, execution, state, uncertain } = props.observation ?? useKeyframeVision(visionKey)
/** 后台结束时同步刷新人工复核与候选状态。 */
watch(
() => state.value.active,
@@ -234,7 +242,7 @@ const records = computed(() =>
role="status"
class="text-sm text-muted"
>
审核结果或费用待核查,请勿重复提交。
{{ userFacingText(state.unknown?.recoveryReason, '审核结果或费用待核查,请勿重复提交。') }}
</p>
<p v-else-if="state.active" role="status" class="text-sm text-muted">
审核{{ execution.data.value?.status === 'pending' ? '等待开始' : '在后台进行' }},关闭页面后仍会保存记录。
@@ -254,9 +262,19 @@ const records = computed(() =>
: '未取得完整视觉结论'
}}
</p>
<p v-if="record.allowedTexts !== undefined" class="text-muted">
原文字授权:{{
record.allowedTexts === null
? '无记录'
: record.allowedTexts.length
? record.allowedTexts.join('、')
: '无额外授权文字'
}}
</p>
<p v-if="record.recoveryReason" class="text-muted">{{ userFacingText(record.recoveryReason) }}</p>
<p v-if="record.error" class="text-danger">{{ userFacingText(record.error) }}</p>
<template v-if="record.validation">
<p>{{ record.validation.summary }}</p>
<p>合并结论:{{ userFacingText(record.validation.summary) }}</p>
<p v-for="(issue, index) in record.validation.issues" :key="index" class="text-danger">
{{ userFacingText(issue.description) }}
</p>
@@ -278,6 +296,15 @@ const records = computed(() =>
{{ usageLabels[unit] }}词元:{{ count }}
</div>
</dl>
<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>
@@ -54,14 +54,18 @@ const { key, session, operation, execution, blocked, run } = useQuality(
)
/** 打开首帧质量弹窗时读取正式审核状态。 */
const visionKey = computed(() =>
open.value && props.target?.kind === 'keyframe' ? JSON.stringify([props.target.shotId, props.target.assetId]) : ''
open.value && props.target?.kind === 'keyframe'
? JSON.stringify([props.target.shotId, props.target.assetId, props.projectId])
: ''
)
const vision = useKeyframeVision(visionKey)
/** 有原参数时继续;没有原参数时保留只读核查。 */
const visionBlocked = computed(() => !!visionKey.value && vision.blocked.value)
/** 质量弹窗重新读取所选候选自身的权限,不以会话历史代替后端事实。 */
const videoKey = computed(() =>
open.value && props.target?.kind === 'video' ? JSON.stringify([props.target.shotId, props.target.assetId]) : ''
open.value && props.target?.kind === 'video'
? JSON.stringify([props.target.shotId, props.target.assetId, props.projectId])
: ''
)
/** 按正式镜头和候选 ID 查询公开权限。 */
const videoQuery = useQuery(videoKey, async (value, signal) => {
@@ -143,7 +147,7 @@ const input = computed<QualityInput>(() => ({
maxRepairAttempts: action.value === 'validate' ? 0 : (attempts.value ?? -1),
force: force.value,
episodeNo: props.target?.kind === 'batch' ? props.target.episodeNo : 1,
allowedTexts: vision.resumeTexts.value ?? allowedTextLines(texts.value),
allowedTexts: allowedTextLines(texts.value),
...(action.value === 'validate' || width.value === null ? {} : { width: width.value }),
...(action.value === 'validate' || height.value === null ? {} : { height: height.value })
}))
@@ -243,11 +247,21 @@ async function submit() {
blocked.value ||
visionBlocked.value ||
!repairAvailable.value ||
(!!vision.resumeTexts.value && action.value !== 'validate')
!!vision.state.value.resumable
)
return
acknowledged.value = false
await run(action.value, input.value)
if (visionKey.value) void vision.history.refresh()
}
/** 只用已确认的原任务身份继续;不会退回普通审核。 */
async function submitResume() {
const resume = vision.resume.value
if (!resume || !acknowledged.value || blocked.value || visionBlocked.value || action.value !== 'validate') return
acknowledged.value = false
await run('validate', input.value, resume)
if (visionKey.value) void vision.history.refresh()
}
/** 质量面板的formModel状态,随目标更新。 */
const formModel = computed(() => ({
@@ -374,9 +388,9 @@ const optionsExpanded = ref<string[]>(['options'])
</div>
<NFormItem class="mt-4 block" path="texts" label="额外允许的画面文字(一行一项,可留空)"
><NInput
:value="vision.resumeTexts.value?.join('\n') ?? texts"
:value="texts"
@update:value="texts = $event"
:disabled="pending || !!vision.resumeTexts.value"
:disabled="pending || !!vision.state.value.resumable"
type="textarea"
:autosize="{ minRows: 2, maxRows: 5 }"
:input-props="{ 'aria-label': '额外允许的画面文字' }"
@@ -444,8 +458,8 @@ const optionsExpanded = ref<string[]>(['options'])
@refresh="execution.query.refresh"
@dismiss="execution.dismiss"
/>
<p v-if="vision.state.value.resumable && !vision.resumeTexts.value" class="mt-3 text-xs text-muted">
此窗口没有原审核参数,暂不能安全继续。
<p v-if="vision.state.value.resumable && !vision.resume.value" class="mt-3 text-xs text-muted">
原审核缺少可核对的请求版本,暂不能安全继续。
</p>
<KeyframeValidationHistory
v-if="open && target?.kind === 'keyframe'"
@@ -453,6 +467,7 @@ const optionsExpanded = ref<string[]>(['options'])
:shot-id="target.shotId"
:key="target.assetId"
:keyframe-id="target.assetId"
:observation="vision"
:disabled="disabled || pending"
initial-open
@reviewed="emit('changed')"
@@ -479,17 +494,22 @@ const optionsExpanded = ref<string[]>(['options'])
<div class="quality-dialog-actions">
<NButton @click="open = false">关闭</NButton>
<NButton
v-if="vision.state.value.resumable"
type="primary"
:loading="pending"
:disabled="
blocked ||
visionBlocked ||
!acknowledged ||
!repairAvailable ||
(!!vision.resumeTexts.value && action !== 'validate')
blocked || visionBlocked || !acknowledged || !vision.resume.value || action !== 'validate'
"
@click="submitResume"
>继续原审核</NButton
>
<NButton
v-else
type="primary"
:loading="pending"
:disabled="blocked || visionBlocked || !acknowledged || !repairAvailable"
@click="formRef?.validate(submit)"
>{{ vision.resumeTexts.value && action === 'validate' ? '继续原审核' : label }}</NButton
>{{ label }}</NButton
>
</div>
</div>
@@ -28,7 +28,6 @@ import type {
GenerateKeyframeInput,
KeyframeReadinessItem,
KeyframeSpec,
KeyframeGenerationPreview,
PromptReadinessItem,
VideoGenerationSpec,
VideoReadinessItem
@@ -48,7 +47,7 @@ import KeyframeValidationHistory from './KeyframeValidationHistory.vue'
import { AppDialog } from '../../../components/ui'
import ModelCapabilities from './ModelCapabilities.vue'
import type { QualityTarget } from '../quality.types'
import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import KeyframeInputDetails from './KeyframeInputDetails.vue'
import { visionState } from '../keyframe-vision'
import { clearVideoConflict, clearVideoQualification, sessionKeyframePassed, sessionVideoValidation } from '../quality'
import { useProjectGenerationRevision } from '../../generation-config/context'
@@ -348,19 +347,6 @@ function openShotKeyframeQuality() {
}
/** 当前查看历史的候选 ID;历史记录在独立弹窗内按候选隔离。 */
const historyKeyframeId = ref('')
/** 当前会话保留最近一次真实正式预览,只用于相同候选输入的证据展示。 */
const latestKeyframePreview = ref<KeyframeGenerationPreview | null>(null)
/** 历史候选的实际输入只有指纹完全一致时才能显示。 */
const historyInput = computed(() => {
const preview = latestKeyframePreview.value
const item = keyframes.value.find(candidate => candidate.id === historyKeyframeId.value)
return preview &&
item &&
item.shotId === preview.shotId &&
preview.previewFingerprint === item.providerInputFingerprint
? preview
: null
})
/** 历史候选画幅或来源失效时保留浏览、禁止人工采用。 */
const historyBlocked = computed(() => {
const item = keyframes.value.find(candidate => candidate.id === historyKeyframeId.value)
@@ -587,7 +573,7 @@ async function setPrimaryKeyframe() {
// 晋升前重新读取持久化质量结论,刷新页面后也认可真实历史通过。
const [review, history] = await Promise.all([
qualityApi.keyframeQualityReview(shotId, keyframeId),
qualityApi.keyframeHistory(shotId, keyframeId)
qualityApi.keyframeHistory(shotId, keyframeId, undefined, props.projectId)
])
const vision = visionState(history)
if (vision.active || vision.unknown || vision.resumable) throw new Error('审核尚未结算,暂不能设为主首帧。')
@@ -760,6 +746,7 @@ defineExpose({ inspectSpecs, inspecting })
<!-- 以下是主首帧卡片模块,校验历史通过卡片入口在弹窗内查看 -->
<div v-if="currentKeyframe" class="keyframe-grid mt-4">
<KeyframeCard
:project-id="projectId"
:shot-id="shot.shotId"
:review-revision="reviewRevision"
:item="currentKeyframe"
@@ -1093,6 +1080,7 @@ defineExpose({ inspectSpecs, inspecting })
<div v-if="keyframeCandidates.length" class="asset-candidate-grid mt-4">
<div v-for="item in keyframeCandidates" :key="item.id" class="min-w-0">
<KeyframeCard
:project-id="projectId"
:shot-id="shot.shotId"
:review-revision="reviewRevision"
:item="item"
@@ -1170,22 +1158,14 @@ defineExpose({ inspectSpecs, inspecting })
description="核对当前候选的生成输入、视觉审核与人工复核。"
wide
>
<!-- 以下是同指纹的实际输入,历史无法取得时如实说明 -->
<NCollapse v-if="historyOpen" class="mb-4">
<NCollapseItem name="generation" title="当次参考图和画面描述">
<ImageGenerationPreview
v-if="historyInput"
:preview="historyInput"
:loading="false"
error=""
stale-notice=""
display-only
/>
<p v-else class="text-xs text-muted">
当前无法读取这张图的原始生成输入。可查看候选原图和已有审核记录。
</p>
</NCollapseItem>
</NCollapse>
<!-- 以下是按需读取的候选生成证据 -->
<KeyframeInputDetails
v-if="historyOpen && historyKeyframeId"
:key="historyKeyframeId"
:project-id="projectId"
:shot-id="shot.shotId"
:keyframe-id="historyKeyframeId"
/>
<KeyframeValidationHistory
v-if="historyOpen && historyKeyframeId"
:key="historyKeyframeId"
@@ -1208,7 +1188,6 @@ defineExpose({ inspectSpecs, inspecting })
:disabled="!canGenerateKeyframe"
:previous-candidate-ids="keyframes.map(item => item.id)"
:submit-generation="generateKeyframe"
@previewed="latestKeyframePreview = $event"
/>
</section>
</template>
+84
View File
@@ -0,0 +1,84 @@
import { request } from '../../lib/http'
import type { ProviderImageInputSnapshot } from '../subject-images/generation-preview'
import { keyframeScope } from './keyframe-scope'
/** 历史实际参考图保留顺序和证据,独立报告原件可用性。 */
export type HistoricalKeyframeReference = ProviderImageInputSnapshot['references'][number] & {
/** 当次实际文件字节指纹。 */ sha256: string
/** 当次解码像素指纹。 */ pixelFingerprint: string
/** 图像类型。 */ mimeType: string
/** 文件大小。 */ byteLength: number
/** 像素宽度。 */ width: number
/** 像素高度。 */ height: number
/** 服务端原件核验结果。 */
availability: 'available' | 'unavailable' | 'changed'
/** 经过同一候选校验的相对 API 地址。 */
imageUrl: string | null
}
/** 候选的历史输入证据,缺失时不重新编译。 */
export interface HistoricalKeyframeInput {
/** 所属镜头。 */ shotId: string
/** 所属候选。 */ keyframeId: string
/** 已保存输入的完整性。 */ inputSnapshotStatus: 'recorded' | 'not-recorded' | 'invalid'
/** 当次输入版本。 */ providerInputFingerprint: string | null
/** 实际模型输入。 */
providerInputSnapshot:
| (Omit<ProviderImageInputSnapshot, 'references'> & {
/** 当次图片模型服务。 */ provider: string
/** 当次具体模型。 */ model: string | null
/** 当次完整提示词。 */ providerPrompt: string
/** 快照格式。 */ version: number
/** 旧参数中记录的宽度。 */ width?: number
/** 旧参数中记录的高度。 */ height?: number
/** 实际参考图顺序。 */ references: HistoricalKeyframeReference[]
})
| null
}
/**
* 构造候选独立的正式证据路径。
* @param shotId 正式镜头
* @param keyframeId 候选
* @returns 不含 API 前缀的路径
*/
function inputPath(shotId: string, keyframeId: string) {
return `/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/generation-input`
}
/**
* 只读加载指定候选的历史输入。
* @param projectId 当前项目
* @param shotId 正式镜头
* @param keyframeId 候选
* @param signal 取消已离开候选的请求
* @returns 该候选的历史证据
*/
export function loadKeyframeInput(projectId: string, shotId: string, keyframeId: string, signal?: AbortSignal) {
return request<HistoricalKeyframeInput>(keyframeScope(inputPath(shotId, keyframeId), projectId), { signal })
}
/**
* 只允许访问同项目同候选的正式参考原件,保留服务返回的范围参数。
* @param reference 当前参考图
* @param projectId 当前项目
* @param shotId 正式镜头
* @param keyframeId 候选
* @returns 可安全浏览的绝对地址,或空
*/
export function historicalReferenceUrl(
reference: HistoricalKeyframeReference,
projectId: string,
shotId: string,
keyframeId: string
) {
if (reference.availability !== 'available' || !reference.imageUrl?.startsWith('/api/')) return null
try {
const api = new URL(import.meta.env.VITE_API_BASE_URL || '/api', window.location.origin)
const url = new URL(reference.imageUrl, api.origin)
const expected = '/api' + inputPath(shotId, keyframeId) + '/references/' + reference.imageNumber
return url.pathname === expected && url.searchParams.get('projectId') === projectId ? url.href : null
} catch {
return null
}
}
@@ -0,0 +1,9 @@
/**
* 为镜头级正式接口附带项目归属;已有查询参数也保留。
* @param path 不含统一 API 前缀的路径
* @param projectId 当前项目
* @returns 附带项目范围的路径
*/
export function keyframeScope(path: string, projectId?: string) {
return projectId ? path + (path.includes('?') ? '&' : '?') + new URLSearchParams({ projectId }) : path
}
+84 -41
View File
@@ -1,15 +1,14 @@
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
import { useQuery } from '../../composables/useQuery'
import { ApiError } from '../../lib/http'
import type { WorkflowExecution } from '../workflows/execution.types'
import { workflowExecutionApi } from '../workflows/execution-api'
import { qualityApi } from './quality-api'
import { isVisualValidation } from './quality'
import type { KeyframeValidationHistoryItem } from './quality.types'
import type { KeyframeValidationHistoryItem, ResumeKeyframeValidation } from './quality.types'
/** 当前候选的最近一次客户端提交,用于断线后只读恢复。 */
interface Submission {
/** 本次确认的文字授权。 */
texts: string[]
/** 请求前已存在的最近记录。 */
before: string | null
/** 同一任务继续时,原执行编号用于识别新一轮。 */
@@ -18,9 +17,7 @@ interface Submission {
taskId?: string
/** 服务确认的执行编号。 */
executionId?: string
/** 任务属于其他提交,当前文字不能用于继续。 */
external?: boolean
/** 已明确结算,仅保留原参数供显式继续。 */
/** 已明确结算,可解除断线保护。 */
settled?: boolean
}
@@ -66,8 +63,12 @@ function saveSubmission(key: string, value?: Submission) {
*/
export function visionState(records: KeyframeValidationHistoryItem[]) {
const active = records.find(item => item.status === 'pending' || item.status === 'running')
const unknown = records.find(item => item.status === 'failed' && visionOutput(item).recoveryRequired !== false)
const resumable = records.find(item => item.status === 'failed' && visionOutput(item).resumeAvailable === true)
const unknown = records.find(
item => item.recoveryRequired ?? (item.status === 'failed' && visionOutput(item).recoveryRequired !== false)
)
const resumable = records.find(
item => item.status === 'failed' && (item.resumeAvailable ?? visionOutput(item).resumeAvailable) === true
)
return { active, unknown, resumable }
}
@@ -88,22 +89,27 @@ function visionOutput(record: KeyframeValidationHistoryItem): Record<string, unk
/**
* 按候选发现后台任务,轮询仅查询历史和正式执行记录。
* @param key 镜头和候选 ID 的 JSON 查询键
* @param observeExecution 是否订阅执行事件(候选卡片只读历史)
* @returns 观察状态和一次性提交凭据操作
*/
export function useKeyframeVision(key: Ref<string>) {
export function useKeyframeVision(key: Ref<string>, observeExecution = true) {
/** 当前候选的客户端凭据。 */
const submission = computed(() => readSubmission(key.value))
/** 公开审核记录是刷新恢复的正式来源。 */
const history = useQuery(key, (value, signal) => {
if (!value) return Promise.resolve([])
const [shotId, keyframeId] = JSON.parse(value) as [string, string]
return qualityApi.keyframeHistory(shotId, keyframeId, signal)
const [shotId, keyframeId, projectId] = JSON.parse(value) as [string, string, string?]
return qualityApi.keyframeHistory(shotId, keyframeId, signal, projectId)
})
/** 当前活跃、未结或可继续的记录。 */
const state = computed(() => visionState(history.data.value ?? []))
/** 旧版活跃记录没有执行编号,仍只能观察和核查。 */
const executionKey = computed(
() => state.value.active?.executionId ?? (submission.value?.settled ? '' : submission.value?.executionId) ?? ''
const executionKey = computed(() =>
observeExecution
? (state.value.active?.executionId ??
(submission.value?.settled ? '' : submission.value?.executionId) ??
'')
: ''
)
/** 只读取执行状态,不展示工作流内部原始结果。 */
const execution = useQuery(executionKey, (id, signal) =>
@@ -111,25 +117,59 @@ export function useKeyframeVision(key: Ref<string>) {
)
/** 未明确结算的断线状态禁止再次写入。 */
const uncertain = computed(() => !!submission.value && !submission.value.settled && !state.value.active)
/** 只有本次会话确知原文字授权时才能安全继续。 */
const resumeTexts = computed(() => {
const saved = submission.value
return saved?.settled && !saved.external && saved.taskId && saved.taskId === state.value.resumable?.id
? saved.texts
/** 继续完全依赖同一条正式历史的任务和指纹。 */
const resume = computed<ResumeKeyframeValidation | null>(() => {
const task = state.value.resumable
return task?.requestFingerprint && /^[a-f0-9]{64}$/.test(task.requestFingerprint)
? { resumeValidationTaskId: task.id, expectedRequestFingerprint: task.requestFingerprint }
: null
})
/** 初次读取或失败时不允许盲目启动,轮询期间不清空旧状态。 */
/** 初次读取或失败时不允许盲目启动,轮询期间保留旧状态。 */
const blocked = computed(
() =>
!history.data.value ||
!!history.error.value ||
!!state.value.active ||
!!state.value.unknown ||
uncertain.value ||
(!!state.value.resumable && !resumeTexts.value)
uncertain.value
)
/** SSE 断开时回到只读轮询。 */
let live = false
watch(
executionKey,
(id, _, onCleanup) => {
live = false
if (!id || typeof EventSource === 'undefined') return
const source = new EventSource(workflowExecutionApi.executionEventsUrl(id))
onCleanup(() => {
source.close()
live = false
})
source.addEventListener('message', event => {
if (id !== executionKey.value) return
try {
const payload = JSON.parse(event.data) as
| WorkflowExecution
| { done: true; result?: WorkflowExecution }
const record = 'done' in payload ? payload.result : payload
if (!record || record.id !== id) return
live = true
execution.data.value = record
if (!history.loading.value) void history.refresh()
if (record.status === 'completed' || record.status === 'failed') source.close()
} catch {
live = false
}
})
source.addEventListener('error', () => {
live = false
})
},
{ immediate: true }
)
watch([history.data, submission], ([records, saved]) => {
watch(history.data, records => {
const saved = submission.value
if (!records || !saved || saved.settled) return
const latest = records[0]
const found = saved.taskId
@@ -145,48 +185,51 @@ export function useKeyframeVision(key: Ref<string>) {
const timer = setInterval(() => {
if (key.value && (state.value.active || uncertain.value)) {
if (!history.loading.value) void history.refresh()
if (executionKey.value && !execution.loading.value) void execution.refresh()
if (executionKey.value && !live && !execution.loading.value) void execution.refresh()
}
}, 2500)
onScopeDispose(() => clearInterval(timer))
return { history, state, execution, uncertain, blocked, resumeTexts }
return { history, state, execution, uncertain, blocked, resume }
}
/**
* 只提交一次审核;冲突和断线回到只读观察。
* @param shotId 正式镜头
* @param assetId 当前候选
* @param texts 已明确确认的文字授权
* @param input 已明确确认的新文字,或原任务继续凭据
* @param records 提交前读取的审核历史
* @param projectId 当前正式项目
* @returns 已复用的质量结论,或后台受理时返回空
*/
export async function submitKeyframeVision(
shotId: string,
assetId: string,
texts: string[],
records: KeyframeValidationHistoryItem[]
input: string[] | ResumeKeyframeValidation,
records: KeyframeValidationHistoryItem[],
projectId?: string
) {
const key = JSON.stringify([shotId, assetId])
const key = JSON.stringify(projectId ? [shotId, assetId, projectId] : [shotId, assetId])
const previous = readSubmission(key)
const current = visionState(records)
if (current.active || current.unknown || (previous && !previous.settled))
throw new Error('已有审核或费用待核查,请查看审核记录。')
if (
current.resumable &&
(!previous ||
previous.external ||
previous.taskId !== current.resumable.id ||
JSON.stringify(texts) !== JSON.stringify(previous.texts))
)
throw new Error('继续审核需要原审核参数,请核对原操作记录。')
if (Array.isArray(input)) {
if (current.resumable) throw new Error('有可继续的审核,请通过继续原审核操作处理。')
} else if (
!current.resumable ||
current.resumable.id !== input.resumeValidationTaskId ||
current.resumable.requestFingerprint !== input.expectedRequestFingerprint ||
!/^[a-f0-9]{64}$/.test(input.expectedRequestFingerprint)
) {
throw new Error('原审核参数或任务状态已变化,请刷新记录。')
}
const pending: Submission = {
texts: [...texts],
before: records[0]?.id ?? null,
beforeExecutionId: records[0]?.executionId
}
saveSubmission(key, pending)
try {
const result = await qualityApi.validateKeyframe(shotId, assetId, texts)
const result = await qualityApi.validateKeyframe(shotId, assetId, input, projectId)
if (result.shotId !== shotId || result.keyframeId !== assetId || !result.validationTaskId)
throw new Error('审核回执与当前候选不一致,请刷新审核记录。')
if ('executionId' in result && result.status === 'pending' && result.executionId) {
@@ -206,13 +249,13 @@ export async function submitKeyframeVision(
saveSubmission(key, {
...pending,
taskId: details?.taskId,
executionId: details?.executionId,
external: true
executionId: details?.executionId
})
return null
}
if (code === 'KEYFRAME_VALIDATION_RECOVERY_REQUIRED') {
saveSubmission(key, { ...pending, taskId: details?.taskId, external: true })
// 在一次新的历史读取确认结算或可继续前,保持写入阻断。
saveSubmission(key, { ...pending, taskId: details?.taskId })
throw new Error('原审核结果或费用待核查,请查看审核记录。', { cause })
}
saveSubmission(key, previous)
+18 -5
View File
@@ -1,9 +1,11 @@
import { keyframeScope } from './keyframe-scope'
import { request } from '../../lib/http'
import type {
ImageProviderCapability,
KeyframeRepair,
KeyframeValidation,
KeyframeValidationAccepted,
ResumeKeyframeValidation,
KeyframeQualityStart,
KeyframeValidationHistoryItem,
QualityInput,
@@ -57,10 +59,18 @@ export const qualityApi = {
{ signal }
),
/** 显式请求一次审核,返回后台受理或既有质量结果。 */
validateKeyframe: (shotId: string, assetId: string, allowedTexts: string[]) =>
validateKeyframe: (
shotId: string,
assetId: string,
input: string[] | ResumeKeyframeValidation,
projectId?: string
) =>
request<KeyframeValidation | KeyframeValidationAccepted>(
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(assetId)}/validate`,
{ method: 'POST', body: { allowedTexts } }
keyframeScope(
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(assetId)}/validate`,
projectId
),
{ method: 'POST', body: Array.isArray(input) ? { allowedTexts: input } : input }
),
repair: (
shotId: string,
@@ -124,9 +134,12 @@ export const qualityApi = {
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/quality-review/reject`,
{ method: 'POST', body }
),
keyframeHistory: (shotId: string, keyframeId: string, signal?: AbortSignal) =>
keyframeHistory: (shotId: string, keyframeId: string, signal?: AbortSignal, projectId?: string) =>
request<KeyframeValidationHistoryItem[]>(
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/validations`,
keyframeScope(
`/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/validations`,
projectId
),
{ signal }
),
/**
+26
View File
@@ -219,6 +219,20 @@ export interface KeyframeValidationAccepted {
status: 'pending'
}
/** 通过正式任务身份继续,不能同时发送新的文字授权。 */
export interface ResumeKeyframeValidation {
/** 原审核任务编号。 */ resumeValidationTaskId: string
/** 同一任务保存的请求版本。 */ expectedRequestFingerprint: string
}
/** 单一步骤已解析并公开的问题。 */
export interface KeyframeStepIssue {
/** 问题分类。 */ code: string
/** 对用户可读的问题。 */ description: string
/** 有证据时的严重程度。 */ severity?: string
/** 对应主体。 */ subjectRef?: string
}
/** 审核历史中公开的步骤证据。 */
export interface KeyframeValidationStep {
/** 审核范围。 */
@@ -235,6 +249,8 @@ export interface KeyframeValidationStep {
finishedAt?: string
/** 可取得的词元计量。 */
usage?: Partial<Record<'inputTokens' | 'outputTokens' | 'totalTokens' | 'reasoningTokens', number>>
/** 未产出为 null,已完成且无问题为 []。 */
issues?: KeyframeStepIssue[] | null
/** 公开错误说明。 */
error?: string
}
@@ -247,6 +263,16 @@ export interface KeyframeValidationHistoryItem {
status: string
/** 数据库保存的 JSON 输出 */
output: string | Record<string, unknown> | null
/** 原审核的文字授权,空数组与未记录分开。 */
allowedTexts?: string[] | null
/** 继续时需要的请求指纹。 */
requestFingerprint?: string | null
/** 服务端判定是否需要核查。 */
recoveryRequired?: boolean
/** 服务端明确允许继续。 */
resumeAvailable?: boolean
/** 服务端核查原因。 */
recoveryReason?: string | null
/** 新版工作流执行编号。 */
executionId?: string
/** 公开步骤进度。 */
+24 -6
View File
@@ -18,7 +18,14 @@ import {
qualityTargets,
validQualityInput
} from './quality'
import type { QualityAction, QualityInput, QualityReceipt, QualityTarget, RepairAttempt } from './quality.types'
import type {
QualityAction,
QualityInput,
QualityReceipt,
QualityTarget,
RepairAttempt,
ResumeKeyframeValidation
} from './quality.types'
/** 校验有限修复回执的每轮结论,避免结构缺失时误报成功。 */
function validAttempts(attempts: RepairAttempt[]) {
@@ -106,11 +113,13 @@ export function useQuality(
* 确认之后重读状态并只提交一次,固定原目标与费用范围。
* @param action 已确认的质量操作
* @param input 已确认的参数
* @param resume 显式继续的原任务身份,可省略
* @returns 操作结束通知,后台生成由持久化任务继续跟踪
*/
async function run(action: QualityAction, input: QualityInput) {
async function run(action: QualityAction, input: QualityInput, resume?: ResumeKeyframeValidation) {
if (blocked.value || !visible() || !props.target || !validQualityInput(input)) return
const target = { ...props.target }
if (resume && (target.kind !== 'keyframe' || action !== 'validate')) return
if (
(target.kind === 'batch') !== (action === 'batch') ||
(target.kind === 'video' && action === 'repair' && input.maxRepairAttempts <= 0)
@@ -210,7 +219,7 @@ export function useQuality(
if (target.kind === 'keyframe' && action === 'validate') {
const [images, history] = await Promise.all([
productionApi.listKeyframes(target.shotId),
qualityApi.keyframeHistory(target.shotId, target.assetId)
qualityApi.keyframeHistory(target.shotId, target.assetId, undefined, projectId)
])
const image = images.find(item => item.id === target.assetId && item.shotId === target.shotId)
if (
@@ -225,8 +234,9 @@ export function useQuality(
const result = await submitKeyframeVision(
target.shotId,
target.assetId,
input.allowedTexts ?? [],
history
resume ?? input.allowedTexts ?? [],
history,
projectId
)
if (result) receiptTarget.receipt = { kind: 'keyframe', result }
return
@@ -331,7 +341,15 @@ export function useQuality(
}
}
receiptTarget.receipt = receipt
}
},
target.kind === 'keyframe' && action === 'validate'
? () => ({
type: 'info',
content: receiptTarget.receipt
? '已读取已有审核结论。'
: '审核任务已受理或正在执行,可查看后台进度。'
})
: undefined
)
if (!ok) receiptTarget.error = getOperation(projectId).error
// 已提交请求即使切换页面也归原会话;只刷新仍在查看的原项目。