import { computed, ref, watch } from 'vue' import { usePolling } from '../../composables/usePolling' import { useProjectContext } from '../projects/context' import { mergeDesignedShots } from '../storyboard/model' import { storyboardApi } from '../storyboard/api' import { breakdownSnapshot } from '../workflows/selectors' import { getOperation, runOperation } from '../workflows/operations' import { useWorkflowExecution } from '../workflows/execution' import { productionApi } from './api' import { getProductionSession, validOptionalSize } from './model' /** 项目级生产动作;每次请求都由统一项目锁防止重复提交。 */ export type ProductionCommand = 'prompts' | 'keyframes' | 'videos' | 'retry-videos' /** 镜头生产页的查询、筛选、就绪状态与批量操作。 */ export function useProduction() { const context = useProjectContext() const id = computed(() => context.project.value?.id ?? '') const selectedEpisode = ref() const selectedShot = ref('') const concurrency = ref(2) const force = ref(false) const keyframeLimit = ref('') const keyframeWidth = ref('') const keyframeHeight = ref('') const promptLimit = ref(1) const videoLimit = ref(1) const videoRepairAttempts = ref(2) const snapshot = computed(() => breakdownSnapshot(context.checkpoints.value)) const sourceEpisodes = computed( () => snapshot.value?.storyboardEpisodeShots ?? snapshot.value?.breakdownResult?.storyboardEpisodeShots ?? [] ) const episodeOptions = computed(() => { const entries = new Map(context.project.value?.episodes.map(episode => [episode.episode, episode.title]) ?? []) for (const episode of sourceEpisodes.value) { if (!entries.has(episode.episodeNo)) entries.set(episode.episodeNo, episode.episodePlan.episodeTitle) } return [...entries] .map(([episodeNo, title]) => ({ episodeNo, title })) .toSorted((a, b) => a.episodeNo - b.episodeNo) }) const episodeNo = computed( () => episodeOptions.value.find(item => item.episodeNo === selectedEpisode.value)?.episodeNo ?? episodeOptions.value[0]?.episodeNo ?? 0 ) const queryKey = computed(() => JSON.stringify([id.value, episodeNo.value, force.value])) /** 生产页已有刷新按钮,就绪状态改为手动更新。 */ const query = usePolling( queryKey, async (key, signal) => { const [projectId, number, overwrite] = JSON.parse(key) as [string, number, boolean] if (!projectId || !number) return null const [directions, prompts, keyframes, videos, videoStatus] = await Promise.all([ storyboardApi.directions(projectId, number, signal), productionApi.promptReadiness(projectId, overwrite, signal), productionApi.keyframeReadiness(projectId, overwrite, signal), productionApi.videoReadiness(projectId, overwrite, signal), productionApi.projectVideoStatus(projectId, signal) ]) if (directions.projectId !== projectId || directions.episodeNo !== number) throw new Error('镜头生产查询返回了不匹配的项目或剧集,请刷新后重试。') return { directions, prompts, keyframes, videos, videoStatus } }, false ) const source = computed(() => sourceEpisodes.value.find(item => item.episodeNo === episodeNo.value)) const shots = computed(() => mergeDesignedShots(query.data.value?.directions ?? null, null, source.value)) const shot = computed(() => shots.value.find(item => item.shotId === selectedShot.value) ?? shots.value[0]) const promptItem = computed(() => query.data.value?.prompts.items.find(item => item.shotId === shot.value?.shotId)) const keyframeItem = computed(() => query.data.value?.keyframes.items.find(item => item.shotId === shot.value?.shotId) ) const videoItem = computed(() => query.data.value?.videos.items.find(item => item.shotId === shot.value?.shotId)) const videoStatusItem = computed(() => query.data.value?.videoStatus.items.find(item => item.shotId === shot.value?.shotId) ) const operation = computed(() => getOperation(id.value)) const session = computed(() => getProductionSession(id.value)) const promptExecution = useWorkflowExecution(id, 'video-prompt') const videoExecution = useWorkflowExecution(id, 'video-quality') const batchValid = computed(() => Number.isSafeInteger(concurrency.value) && concurrency.value > 0) const promptValid = computed(() => Number.isSafeInteger(promptLimit.value) && (promptLimit.value ?? 0) > 0) const keyframeValid = computed( () => (keyframeLimit.value === '' || (Number.isSafeInteger(keyframeLimit.value) && keyframeLimit.value > 0)) && validOptionalSize(keyframeWidth.value, keyframeHeight.value) ) /** 视频质量流水线要求有限的提交范围和至少一次自动修复额度。 */ const videoQualityValid = computed( () => Number.isSafeInteger(videoLimit.value) && (videoLimit.value ?? 0) > 0 && Number.isSafeInteger(videoRepairAttempts.value) && (videoRepairAttempts.value ?? 0) > 0 ) const blocked = computed( () => operation.value.pending || promptExecution.active.value || videoExecution.active.value || !!context.error.value || !!query.error.value || !query.data.value || context.project.value?.status !== 'completed' ) /** 后台质量任务收口后重新读取资产;失败也要保留已经成功的镜头状态。 */ watch( () => videoExecution.query.data.value?.status, (status, previous) => { if ((status === 'completed' || status === 'failed') && status !== previous) void query.refresh() } ) watch( () => promptExecution.query.data.value?.status, (status, previous) => { if ((status === 'completed' || status === 'failed') && status !== previous) void query.refresh() } ) /** 批量操作只向就绪镜头提交;最终资产状态由轮询查询确认。 */ async function run(command: ProductionCommand) { if ( blocked.value || !batchValid.value || (command === 'prompts' && !promptValid.value) || (command === 'keyframes' && !keyframeValid.value) || (command === 'videos' && !videoQualityValid.value) ) return const projectId = id.value const input = { concurrency: concurrency.value, force: force.value } const target = getProductionSession(projectId) target.receipt = null const staleKeyframes = query.data.value?.keyframes.stalePrimaryKeyframe ?? 0 const staleVideos = query.data.value?.videos.stalePrimaryVideo ?? 0 const labels: Record = { prompts: force.value ? '重生成项目视频提示词' : '补齐项目视频提示词', keyframes: force.value ? '新增项目首帧候选' : staleKeyframes > 0 ? `更新 ${staleKeyframes} 个过期主首帧` : `补齐第 ${episodeNo.value} 集主首帧`, videos: force.value ? '新增项目质量视频候选' : staleVideos > 0 ? `更新 ${staleVideos} 个过期主视频` : '提交视频质量任务', 'retry-videos': '重试失败视频任务' } await runOperation(projectId, labels[command], async () => { if (command === 'prompts') { const started = await productionApi.startPromptExecution(projectId, { ...input, episodeNo: episodeNo.value, limit: promptLimit.value ?? undefined }) await promptExecution.track(started.executionId) } else if (command === 'keyframes') { target.receipt = { kind: 'keyframes', title: labels[command], result: await productionApi.generateKeyframes(projectId, { ...input, // 有 stale 时由后端优先处理全部 stale;否则只补当前剧集,避免误跑整个项目。 ...(force.value || staleKeyframes > 0 ? {} : { episodeNo: episodeNo.value }), ...(keyframeLimit.value === '' ? {} : { limit: keyframeLimit.value }), ...(keyframeWidth.value === '' || keyframeHeight.value === '' ? {} : { width: keyframeWidth.value, height: keyframeHeight.value }) }) } } else if (command === 'videos') { const started = await productionApi.startQualityVideoExecution(projectId, { ...input, limit: videoLimit.value ?? undefined, maxRepairAttempts: videoRepairAttempts.value ?? 0 }) await videoExecution.track(started.executionId) } else { target.receipt = { kind: 'retry', title: labels[command], result: await productionApi.retryVideos(projectId, concurrency.value) } } }) await query.refresh() } return { id, selectedEpisode, selectedShot, episodeNo, episodeOptions, shots, shot, promptItem, keyframeItem, videoItem, videoStatusItem, query, operation, session, concurrency, force, keyframeLimit, keyframeWidth, keyframeHeight, promptLimit, videoLimit, videoRepairAttempts, keyframeValid, promptValid, videoQualityValid, batchValid, blocked, run, promptExecution, videoExecution } }