import { computed, ref, watch, onScopeDispose, type Ref } from 'vue' import { usePolling } from '../../composables/usePolling' import { motionApi } from './motion-api' import { productionApi } from '../production/api' import { useWorkflowExecution } from '../workflows/execution' import { getOperation, runOperation } from '../workflows/operations' import { ApiError, errorMessage } from '../../lib/http' import { motionEvidenceCurrent, type MotionPlan, type MotionRevisionPreview, type FailedMotionCandidate } from './motion-revision' /** * 管理一个镜头的完整草稿、免费预检、保存和付费视觉任务;切镜后丢弃迟到 UI 更新。 * @param props 当前镜头与项目 * @param open 编辑面板可见状态 * @param changed 激活成功后通知外层刷新资产和就绪状态 * @returns 表单状态与明确操作入口 */ export function useMotionRevision( props: { projectId: string; shotId: string; disabled?: boolean }, open: Ref, changed: () => void ) { /** 任务观察按项目隔离,真实状态来自持久化接口。 */ const project = computed(() => props.projectId) const execution = useWorkflowExecution(project, 'motion-plan-start-state-validation') /** 原目标身份同时用于废弃迟到响应。 */ const identity = computed(() => JSON.stringify([props.projectId, props.shotId])) /** 面板关闭后不发起普通查询;活动任务仍由任务观察器恢复。 */ const key = computed(() => (open.value ? identity.value : '')) /** 查询期间显示已有后端数据,但出错时禁用所有写入。 */ const context = usePolling( key, async (value, signal) => { if (!value) return null const [, shotId] = JSON.parse(value) as [string, string] const [history, preview, keyframes] = await Promise.all([ motionApi.revisions(shotId, signal), motionApi.preview(shotId, signal), productionApi.listKeyframes(shotId, signal) ]) if ( history.shotId !== shotId || preview.shotId !== shotId || keyframes.some(item => item.shotId !== shotId) ) throw new Error('动作修订或首帧与当前镜头不匹配。') return { history, preview, primary: keyframes.find( item => item.isPrimary && item.status === 'completed' && item.source !== 'provider_variant' ) ?? null } }, computed(() => (open.value ? 5000 : false)) ) /** 当前选择的已保存版本;空值表示从历史 AI 预览开始。 */ const selectedId = ref('') /** 全字段动作草稿,不允许自动生成占位阶段。 */ const draft = ref({ beats: [], globalMotionConstraints: [] }) /** 人工修改原因。 */ const reason = ref('') /** 原失败Task可由正式免费计划发现,也可粘贴真实ID只读核对。 */ const failedTaskId = ref('') /** 原模型候选、质量和Workflow公开回执,始终与人工草稿分开。 */ const failedCandidate = ref(null) /** 用户确认承接原失败,而不是将其改为通过。 */ const failedAcknowledged = ref(false) /** 只读候选查询就地加载,不启动原Workflow。 */ const candidateLoading = ref(false) /** 完整交互JSON的输入错误保留在编辑器中。 */ const interactionError = ref('') /** 只保留当前草稿的免费预检查。 */ const preview = ref(null) /** 明确确认视觉模型费用。 */ const acknowledged = ref(false) /** 草稿或输入变化后不再认可旧视觉证据。 */ const invalidated = ref(false) /** 本次请求错误独立于只读查询。 */ const error = ref('') /** 激活成功的提示词更新说明。 */ const notice = ref('') /** 拷贝历史时不误判为用户修改。 */ let copying = false /** 卸载后不更新当前界面。 */ let disposed = false onScopeDispose(() => { disposed = true }) /** 当前后端保存版本,不以草稿代替不可变修订。 */ const revision = computed( () => context.data.value?.history.revisions.find(item => item.revisionId === selectedId.value) ?? null ) /** 沿真实父版本追溯失败根,重新打开人工子版本后仍可核对原任务,不改写原质量。 */ const candidateOrigin = computed(() => { const rows = context.data.value?.history.revisions ?? [], seen = new Set() let row = revision.value while (row && !seen.has(row.revisionId)) { if (row.candidateOrigin) return row.candidateOrigin seen.add(row.revisionId) row = rows.find(parent => parent.revisionId === row?.parentRevisionId) ?? null } return null }) /** 草稿与所选修订内容保持一致才可校验或激活。 */ const saved = computed( () => !!revision.value && JSON.stringify(draft.value) === JSON.stringify(revision.value.motionPlan) ) /** 无正式原计划且尚无历史时,必须显式承接当前失败候选。 */ const requiresCandidate = computed( () => context.data.value?.preview.motionPlanAvailable === false && context.data.value.history.revisions.length === 0 ) /** 原Task必须仍属于同项目同镜头、当前Motion阶段失败且有完整原候选。 */ const candidateReady = computed( () => failedCandidate.value?.shotId === props.shotId && failedCandidate.value.taskId === failedTaskId.value.trim() && failedCandidate.value.plan?.projectId === props.projectId && failedCandidate.value.current && failedCandidate.value.status === 'failed' && failedCandidate.value.qualityFailure?.phase === 'motion_plan' && !!failedCandidate.value.observations?.motion_plan ) /** 项目已有请求或后台任务时禁止重复发起。 */ const pending = computed(() => getOperation(props.projectId).pending) /** 自动核对输入期间允许继续填写草稿,不让定时查询打断输入焦点。 */ const formBlocked = computed( () => !!props.disabled || pending.value || !!context.error.value || !context.data.value ) /** 后端查询缺失或失败时不使用旧数据提交。 */ const blocked = computed( () => !!props.disabled || pending.value || context.loading.value || !!context.error.value || !context.data.value ) /** 当前任务只展示本镜头记录,其他镜头任务不充当证据。 */ const record = computed(() => { const item = execution.query.data.value return item?.metadata?.shotId === props.shotId || item?.result?.shotId === props.shotId ? item : null }) /** 完成、通过、未失效且所有绑定匹配才开放激活。 */ const evidenceValid = computed( () => saved.value && !invalidated.value && revision.value?.source !== 'failed_candidate' && !!preview.value?.sourceFingerprint && !!record.value?.result?.plan && (record.value.result.plan as { sourceFingerprint?: string }).sourceFingerprint === preview.value.sourceFingerprint && motionEvidenceCurrent( record.value, revision.value, context.data.value?.primary ?? null, context.data.value?.history.activeRevisionId ?? null ) ) /** 查询与请求进行中临时禁用提交,不把有效证据误显示为失效。 */ const canActivate = computed(() => !blocked.value && evidenceValid.value) /** 保存与正式采用独立;缺候选证据或交互输入不合法时不写入。 */ const canSave = computed( () => !blocked.value && !interactionError.value && preview.value?.valid === true && (!requiresCandidate.value || (candidateReady.value && failedAcknowledged.value && !!reason.value.trim() && /^[a-f0-9]{64}$/.test(preview.value.sourceFingerprint ?? '') && /^[a-f0-9]{64}$/.test(preview.value.previewFingerprint ?? ''))) ) /** 只能启动已保存的非失败根版本,且必须有当前精确起点计划。 */ const canValidate = computed( () => !blocked.value && saved.value && revision.value?.source !== 'failed_candidate' && !!preview.value?.valid && !!preview.value.startStatePlan && preview.value.source?.projectId === props.projectId && preview.value.source.primaryKeyframeId === context.data.value?.primary?.id && /^[a-f0-9]{64}$/.test(preview.value.sourceFingerprint ?? '') && preview.value.startStatePlan.version === 1 && preview.value.startStatePlan.sourceFingerprint === preview.value.sourceFingerprint && preview.value.startStatePlan.primaryKeyframeId === context.data.value?.primary?.id && preview.value.startStatePlan.expectedRevisionId === context.data.value?.history.activeRevisionId && preview.value.startStatePlan.motionPlanFingerprint === revision.value?.fingerprint && /^[a-f0-9]{64}$/.test(preview.value.startStatePlan.fingerprint) && ['ready', 'reusable'].includes(preview.value.startStatePlan.status) && (preview.value.startStatePlan.status === 'reusable' || preview.value.startStatePlan.executionAvailable) ) /** 当前版本和主首帧输入变化也撤销费用确认及旧证据。 */ const binding = computed(() => JSON.stringify([ context.data.value?.history.activeRevisionId ?? null, context.data.value?.primary?.id ?? null, context.data.value?.primary?.imageUrl ?? null ]) ) watch(binding, (_value, old) => { if (old && old !== '[null,null,null]') invalidated.value = true acknowledged.value = false }) /** 更换待核对Task只撤销承接确认,保留人工草稿等待新来源。 */ watch( failedTaskId, () => { failedAcknowledged.value = false preview.value = null invalidated.value = true }, { flush: 'sync' } ) watch( draft, () => { preview.value = null failedAcknowledged.value = false acknowledged.value = false if (!copying) invalidated.value = true }, { deep: true, flush: 'sync' } ) watch([identity, open], () => { selectedId.value = '' draft.value = { beats: [], globalMotionConstraints: [] } preview.value = null reason.value = '' error.value = '' notice.value = '' acknowledged.value = false failedTaskId.value = '' failedCandidate.value = null failedAcknowledged.value = false interactionError.value = '' }) /** * 复制所选版本或真实 AI 规划;改变来源后须重新取得视觉证据。 * @param id 所选版本 ID,空值使用预览 * @param initial 首次恢复允许核对已持久化任务 */ function select(id: string, initial = false) { const value = context.data.value if (!value) return const source = value.history.revisions.find(item => item.revisionId === id)?.motionPlan ?? (id ? null : { beats: value.preview.beats, globalMotionConstraints: value.preview.globalMotionConstraints }) if (!source) return copying = true selectedId.value = id draft.value = JSON.parse(JSON.stringify(source)) as MotionPlan copying = false preview.value = null reason.value = '' acknowledged.value = false invalidated.value = !initial notice.value = '' } watch( () => context.data.value, value => { if (value && !selectedId.value && draft.value.beats.length === 0) select( value.history.activeRevisionId ?? value.history.originalRevisionId ?? value.history.revisions.findLast(row => row.source === 'manual')?.revisionId ?? value.history.revisions.at(-1)?.revisionId ?? '', true ) } ) /** 刷新或重开时恢复同镜头的真实任务版本;用户修改后不恢复旧资格。 */ watch([() => context.data.value, record], ([value, task]) => { const id = task?.metadata?.revisionId if ( value && typeof id === 'string' && !invalidated.value && !preview.value && value.history.revisions.some(item => item.revisionId === id) && selectedId.value !== id && (saved.value || draft.value.beats.length === 0) ) select(id, true) }) /** * 发起一次明确操作;冲突后刷新绑定,成功也校验响应目标。 * @param label 操作说明 * @param action 固定原镜头操作 */ async function perform(label: string, action: () => Promise) { if (blocked.value) return const target = identity.value error.value = '' notice.value = '' await runOperation(props.projectId, label, async () => { try { await action() } catch (cause) { if (!disposed && identity.value === target) { error.value = errorMessage(cause) if (cause instanceof ApiError && cause.status === 409) { invalidated.value = true preview.value = null acknowledged.value = false await context.refresh() changed() } } throw cause } }) } /** 免费检查本次完整草稿;编辑或切镜后丢弃迟到回执。 */ async function precheck() { if (interactionError.value) return const shotId = props.shotId const plan = JSON.parse(JSON.stringify(draft.value)) as MotionPlan const signature = JSON.stringify(plan) await perform('免费检查动作修订', async () => { const result = await motionApi.previewRevision( shotId, { ...plan, interactions: plan.interactions ?? [] }, preview.value?.sourceFingerprint ) if (!disposed && props.shotId === shotId && signature === JSON.stringify(draft.value)) { if (result.shotId !== shotId || (result.source && result.source.projectId !== props.projectId)) throw new Error('预检查回执与当前项目或镜头不匹配。') preview.value = result } }) } /** 保存必须先获得当前草稿的结构通过结果,不激活或调用模型。 */ async function save() { if (!canSave.value) return const target = identity.value const shotId = props.shotId const plan = { ...JSON.parse(JSON.stringify(draft.value)), interactions: draft.value.interactions ?? [] } as MotionPlan const parentRevisionId = selectedId.value || null const failed = requiresCandidate.value ? { taskId: failedCandidate.value!.taskId, expectedSourceFingerprint: preview.value!.sourceFingerprint!, expectedPreviewFingerprint: preview.value!.previewFingerprint!, acknowledgeFailedCandidate: true as const } : undefined await perform('保存动作修订', async () => { const result = await motionApi.saveRevision(shotId, { motionPlan: plan, parentRevisionId, reason: reason.value.trim() || null, ...(failed ? { failedCandidate: failed } : {}) }) if (result.shotId !== shotId || result.source !== 'manual' || result.isActive || !result.revisionId) throw new Error('保存回执不是当前镜头的未生效人工版本。') if (disposed || identity.value !== target) return await context.refresh() select(result.revisionId) failedAcknowledged.value = false notice.value = '人工修订已保存,尚未采用。重新免费预检后,可另行确认起点视觉费用;未自动启动任何模型。' }) } /** 用户确认费用后重新读取首帧与生效指针,再启动视觉模型。 */ async function validate() { if ( !acknowledged.value || !canValidate.value || !revision.value || !context.data.value?.primary || !preview.value?.startStatePlan ) return const target = identity.value const selected = revision.value const originalProjectId = props.projectId const expectedBinding = binding.value const frozenPlan = preview.value.startStatePlan.fingerprint, sourceFingerprint = preview.value.sourceFingerprint acknowledged.value = false await perform('校验动作修订起点', async () => { await context.refresh() if ( disposed || identity.value !== target || context.error.value || expectedBinding !== binding.value || !saved.value ) throw new Error('主首帧或生效版本已变化,请刷新并重新确认费用。') const primary = context.data.value?.primary if (!primary?.imageUrl) throw new Error('尚无有效主首帧,不能启动视觉校验。') const latest = await motionApi.previewRevision(selected.shotId, selected.motionPlan, sourceFingerprint) if (disposed || identity.value !== target) return if ( !latest.valid || latest.startStatePlan?.fingerprint !== frozenPlan || !['ready', 'reusable'].includes(latest.startStatePlan.status) || (latest.startStatePlan.status === 'ready' && !latest.startStatePlan.executionAvailable) ) { preview.value = latest throw new Error('精确起点计划已变化或尚不可执行,请重新核对并确认费用。') } preview.value = latest const result = await motionApi.validateRevision(selected.shotId, selected.revisionId, { primaryKeyframeId: primary.id, expectedRevisionId: context.data.value!.history.activeRevisionId, expectedPlanFingerprint: frozenPlan }) if ( !result.executionId || (result.willCallModel !== true && !(result.willCallModel === false && result.reused === true)) ) throw new Error('未返回有效视觉校验任务,请刷新,勿重复提交。') if (!disposed && identity.value === target) invalidated.value = false await execution.track(result.executionId, originalProjectId) }) } /** 激活前再次刷新并核对全部证据,成功后通知两个工作区同步。 */ async function activate() { if (!canActivate.value || !revision.value || !record.value) return const target = identity.value const selected = revision.value const taskId = record.value.id await perform('激活动作修订', async () => { await context.refresh() if ( disposed || identity.value !== target || context.error.value || !saved.value || invalidated.value || !motionEvidenceCurrent( record.value, selected, context.data.value?.primary ?? null, context.data.value?.history.activeRevisionId ?? null ) ) throw new Error('视觉证据已失效,请重新校验当前修订。') const result = await motionApi.activateRevision(props.shotId, selected.revisionId, { expectedRevisionId: context.data.value!.history.activeRevisionId, validationExecutionId: taskId }) if ( result.shotId !== selected.shotId || result.activeRevisionId !== selected.revisionId || result.motionPlanFingerprint !== selected.fingerprint ) throw new Error('激活回执与目标版本不匹配,请刷新核对。') if (disposed || identity.value !== target) return await context.refresh() changed() notice.value = result.videoPromptStale ? '修订已生效。请重新生成视频提示词;旧视频候选仍保留,未自动提交生成任务。' : '此版本已生效。' }) } /** 主动读取原候选,只展示原失败证据,不自动载入或保存。 */ async function readCandidate() { if (blocked.value || candidateLoading.value) return const target = identity.value, shotId = props.shotId, projectId = props.projectId candidateLoading.value = true error.value = '' failedAcknowledged.value = false failedCandidate.value = null try { let taskId = failedTaskId.value.trim() if (!taskId) { const plan = await motionApi.candidatePlan(shotId) if (plan.shotId !== shotId || plan.projectId !== projectId || !plan.latestTask?.taskId) throw new Error('当前镜头没有可核对的原任务。') taskId = plan.latestTask.taskId } const original = await motionApi.candidate(shotId, taskId) if (disposed || identity.value !== target) return if (original.taskId !== taskId || original.shotId !== shotId || original.plan?.projectId !== projectId) throw new Error('原任务不属于当前项目或镜头。') failedCandidate.value = original failedTaskId.value = taskId if (!candidateReady.value) error.value = '原任务不是当前可承接的动作质量失败候选,仅保留只读记录。' } catch (cause) { if (!disposed && target === identity.value) error.value = errorMessage(cause) } finally { if (target === identity.value) candidateLoading.value = false } } /** 从已保存失败根读取原公开回执,不将历史候选重新载入人工草稿或恢复模型执行。 */ async function readOriginCandidate() { if (!candidateOrigin.value || blocked.value || candidateLoading.value) return failedTaskId.value = candidateOrigin.value.taskId await readCandidate() } /** 将原失败候选显式载入人工草稿,原Task/质量/回执保持失败。 */ function useCandidate() { if (!candidateReady.value || !failedCandidate.value?.observations.motion_plan || blocked.value) return copying = true selectedId.value = '' draft.value = JSON.parse(JSON.stringify(failedCandidate.value.observations.motion_plan)) copying = false preview.value = null reason.value = '' acknowledged.value = false failedAcknowledged.value = false invalidated.value = true notice.value = '已载入人工草稿,原候选仍为失败;请修改并免费预检。' } return { context, canSave, canValidate, failedTaskId, failedCandidate, failedAcknowledged, candidateLoading, requiresCandidate, candidateReady, candidateOrigin, readOriginCandidate, interactionError, readCandidate, useCandidate, selectedId, draft, reason, preview, acknowledged, error, notice, revision, saved, pending, blocked, formBlocked, record, execution, canActivate, evidenceValid, invalidated, select, precheck, save, validate, activate } }