diff --git a/src/features/production/api.ts b/src/features/production/api.ts index f6263c1..65d3f18 100644 --- a/src/features/production/api.ts +++ b/src/features/production/api.ts @@ -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(`${shotPath(shotId)}/keyframes`, { signal }), - keyframeSpec: (shotId: string, signal?: AbortSignal) => - request(`${shotPath(shotId)}/keyframe-spec`, { signal }), + keyframeSpec: (shotId: string, signal?: AbortSignal, projectId?: string) => + request(keyframeScope(`${shotPath(shotId)}/keyframe-spec`, projectId), { signal }), /** 按本次请求选择的图片模型与参数预览最终输入,不创建首帧任务。 */ previewKeyframe: ( shotId: string, diff --git a/src/features/production/components/KeyframeCard.vue b/src/features/production/components/KeyframeCard.vue index bc89b6f..ebf7d03 100644 --- a/src/features/production/components/KeyframeCard.vue +++ b/src/features/production/components/KeyframeCard.vue @@ -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) => { diff --git a/src/features/production/components/KeyframeDialog.vue b/src/features/production/components/KeyframeDialog.vue index 6bcad42..50abf65 100644 --- a/src/features/production/components/KeyframeDialog.vue +++ b/src/features/production/components/KeyframeDialog.vue @@ -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 }>() -/** 只读提供当次正式预览,候选必须匹配输入指纹才能展示。 */ -const emit = defineEmits<{ previewed: [preview: KeyframeGenerationPreview] }>() /** 当前候选生成窗口。 */ const open = defineModel('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 }) diff --git a/src/features/production/components/KeyframeInputDetails.vue b/src/features/production/components/KeyframeInputDetails.vue new file mode 100644 index 0000000..23f7717 --- /dev/null +++ b/src/features/production/components/KeyframeInputDetails.vue @@ -0,0 +1,89 @@ + + + diff --git a/src/features/production/components/KeyframeValidationHistory.vue b/src/features/production/components/KeyframeValidationHistory.vue index b89d168..7c53f88 100644 --- a/src/features/production/components/KeyframeValidationHistory.vue +++ b/src/features/production/components/KeyframeValidationHistory.vue @@ -26,6 +26,8 @@ const props = defineProps<{ disabled?: boolean /** 在独立弹窗内直接展示内容,并隐藏内部标题、说明与操作栏。 */ initialOpen?: boolean + /** 已有审核弹窗的观察器,可共享同一订阅。 */ + observation?: ReturnType }>() /** 通知候选重新读取当前质量状态。 */ 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, '审核结果或费用待核查,请勿重复提交。') }}

审核{{ execution.data.value?.status === 'pending' ? '等待开始' : '在后台进行' }},关闭页面后仍会保存记录。 @@ -254,9 +262,19 @@ const records = computed(() => : '未取得完整视觉结论' }}

+

+ 原文字授权:{{ + record.allowedTexts === null + ? '无记录' + : record.allowedTexts.length + ? record.allowedTexts.join('、') + : '无额外授权文字' + }} +

+

{{ userFacingText(record.recoveryReason) }}

{{ userFacingText(record.error) }}

diff --git a/src/features/production/keyframe-input.ts b/src/features/production/keyframe-input.ts new file mode 100644 index 0000000..360faa6 --- /dev/null +++ b/src/features/production/keyframe-input.ts @@ -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 & { + /** 当次图片模型服务。 */ 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(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 + } +} diff --git a/src/features/production/keyframe-scope.ts b/src/features/production/keyframe-scope.ts new file mode 100644 index 0000000..4a2483a --- /dev/null +++ b/src/features/production/keyframe-scope.ts @@ -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 +} diff --git a/src/features/production/keyframe-vision.ts b/src/features/production/keyframe-vision.ts index 4e8d4a4..2ed704c 100644 --- a/src/features/production/keyframe-vision.ts +++ b/src/features/production/keyframe-vision.ts @@ -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) { +export function useKeyframeVision(key: Ref, 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) { ) /** 未明确结算的断线状态禁止再次写入。 */ 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(() => { + 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) { 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) diff --git a/src/features/production/quality-api.ts b/src/features/production/quality-api.ts index 41cadde..66e5f2e 100644 --- a/src/features/production/quality-api.ts +++ b/src/features/production/quality-api.ts @@ -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( - `/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( - `/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/validations`, + keyframeScope( + `/storyboard-shots/${encodeURIComponent(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/validations`, + projectId + ), { signal } ), /** diff --git a/src/features/production/quality.types.ts b/src/features/production/quality.types.ts index 746fb1f..538f52b 100644 --- a/src/features/production/quality.types.ts +++ b/src/features/production/quality.types.ts @@ -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> + /** 未产出为 null,已完成且无问题为 []。 */ + issues?: KeyframeStepIssue[] | null /** 公开错误说明。 */ error?: string } @@ -247,6 +263,16 @@ export interface KeyframeValidationHistoryItem { status: string /** 数据库保存的 JSON 输出 */ output: string | Record | null + /** 原审核的文字授权,空数组与未记录分开。 */ + allowedTexts?: string[] | null + /** 继续时需要的请求指纹。 */ + requestFingerprint?: string | null + /** 服务端判定是否需要核查。 */ + recoveryRequired?: boolean + /** 服务端明确允许继续。 */ + resumeAvailable?: boolean + /** 服务端核查原因。 */ + recoveryReason?: string | null /** 新版工作流执行编号。 */ executionId?: string /** 公开步骤进度。 */ diff --git a/src/features/production/useQuality.ts b/src/features/production/useQuality.ts index f4a6b14..8ab4fb6 100644 --- a/src/features/production/useQuality.ts +++ b/src/features/production/useQuality.ts @@ -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 // 已提交请求即使切换页面也归原会话;只刷新仍在查看的原项目。 diff --git a/src/features/storyboard/api.ts b/src/features/storyboard/api.ts index 0c93c09..29e0173 100644 --- a/src/features/storyboard/api.ts +++ b/src/features/storyboard/api.ts @@ -1,3 +1,4 @@ +import { keyframeScope } from '../production/keyframe-scope' import type { WorkflowExecutionStart } from '../workflows/execution.types' import { request } from '../../lib/http' import type { @@ -83,8 +84,8 @@ export const storyboardApi = { timeoutMs: 0 }), references: (id: string, signal?: AbortSignal) => request(`${shotPath(id)}/references`, { signal }), - generationSpec: (id: string, signal?: AbortSignal) => - request(`${shotPath(id)}/generation-spec`, { signal }), + generationSpec: (id: string, signal?: AbortSignal, projectId?: string) => + request(keyframeScope(`${shotPath(id)}/generation-spec`, projectId), { signal }), /** 只读获取已保存的视频提示词,不要求首帧已就绪。 */ videoPrompt: (id: string, signal?: AbortSignal) => request(`${shotPath(id)}/video-prompt`, { signal }), diff --git a/src/features/storyboard/components/ShotDerivedReview.vue b/src/features/storyboard/components/ShotDerivedReview.vue index 9c43977..90ffe02 100644 --- a/src/features/storyboard/components/ShotDerivedReview.vue +++ b/src/features/storyboard/components/ShotDerivedReview.vue @@ -5,6 +5,7 @@ import { AppDrawer, WorkspaceSectionHeading } from '../../../components/ui' import { useActionMessage } from '../../../components/ui/useActionMessage' import { useQuery } from '../../../composables/useQuery' import { ApiError, errorMessage } from '../../../lib/http' +import { formatDate } from '../../../lib/format' import { userFacingText } from '../../../lib/user-facing-text' import { productionApi } from '../../production/api' import KeyframePreviewChecks from '../../production/components/KeyframePreviewChecks.vue' @@ -17,7 +18,12 @@ import type { GenerationOptions } from '../../generation-config/types' import { storyboardApi } from '../api' import { derivedReviewApi } from '../derived-review-api' import { draftFromFormal } from '../derived-review' -import type { DerivedReviewSelection, ShotDraftPreview, ShotReviewDraft } from '../derived-review.types' +import type { + DerivedReviewSelection, + DraftProviderInput, + ShotDraftPreview, + ShotReviewDraft +} from '../derived-review.types' import { directionLabel } from '../model' import type { DesignedShot } from '../types' @@ -56,7 +62,31 @@ const saving = ref(false) /** 当前消息层。 */ const message = useActionMessage() /** 关闭或切换镜头后撤销旧读取。 */ -const key = computed(() => (open.value ? props.shot.shotId : '')) +const key = computed(() => (open.value ? JSON.stringify([props.projectId, props.shot.shotId]) : '')) +/** 服务端草案单独读取,不阻塞外部草案的免费预览。 */ +const savedDraft = useQuery(key, async (value, signal) => { + if (!value) return null + const [projectId, shotId] = JSON.parse(value) as [string, string] + const result = await derivedReviewApi.draft(projectId, shotId, signal) + if (result && result.shotId !== shotId) throw new Error('已保存草案与当前镜头不一致。') + return result +}) +/** 区分已保存原稿与当前表单内容。 */ +const useSaved = ref(false) +/** 保存冲突后必须由用户重新读取,不自动覆盖。 */ +const draftConflict = ref(false) +/** 草案保存使用独立的短请求状态。 */ +const savingDraft = ref(false) +/** 用户主动修改模型后不再使用保存时的参数。 */ +const providerEdited = ref(false) +/** 编辑保存的原稿时,保留其模型参数和显式尺寸。 */ +const editingSavedInput = ref() +/** 当前可查看的原稿,保留过期草案的全部内容。 */ +const savedDraftText = computed(() => + savedDraft.data.value ? JSON.stringify(savedDraft.data.value.draft, null, 2) : '' +) +/** 原稿与编辑状态的来源分离,重读草案不替换用户输入。 */ +const draftLoaded = ref(false) /** 已有正式设计时仅允许受控修改。 */ const formal = computed(() => !!props.shot.direction && !!props.shot.visualState) /** 读取服务端正式审核状态和版本。 */ @@ -64,11 +94,12 @@ const preflight = useQuery(key, (id, signal) => id ? preparationApi.qualityPreflight(props.projectId, signal) : Promise.resolve(null) ) /** 受控修改前重新读取镜头规格、实际参考与新鲜摄影记录。 */ -const formalQuery = useQuery(key, async (id, signal) => { - if (!id || !formal.value) return null +const formalQuery = useQuery(key, async (value, signal) => { + if (!value || !formal.value) return null + const [projectId, id] = JSON.parse(value) as [string, string] const [keyframe, generation, directions, visuals] = await Promise.all([ - productionApi.keyframeSpec(id, signal), - storyboardApi.generationSpec(id, signal), + productionApi.keyframeSpec(id, signal, projectId), + storyboardApi.generationSpec(id, signal, projectId), storyboardApi.directions(props.projectId, props.episodeNo, signal), storyboardApi.visualStates(props.projectId, props.episodeNo, signal) ]) @@ -137,6 +168,8 @@ onScopeDispose(clearPreview) watch( [ key, + useSaved, + providerEdited, mode, composition, cameraPosition, @@ -151,32 +184,119 @@ watch( { flush: 'sync' } ) watch(key, () => { + useSaved.value = false + draftConflict.value = false + providerEdited.value = false + draftLoaded.value = false + editingSavedInput.value = undefined mode.value = 'camera' selectedScene.value = null imported.value = '' reviewer.value = '' }) +watch( + savedDraft.updatedAt, + updatedAt => { + if (!key.value || !updatedAt || draftLoaded.value) return + const value = savedDraft.data.value + if ( + value && + !imported.value.trim() && + !providerEdited.value && + (!composition.value || composition.value === formalQuery.data.value?.shot.direction?.composition) && + (!cameraPosition.value || cameraPosition.value === formalQuery.data.value?.shot.direction?.cameraPosition) + ) + useSaved.value = true + draftLoaded.value = true + }, + { flush: 'post' } +) + +/** 用最新修订作为下一次显式保存的基准,保留现有表单。 */ +async function reloadSavedDraft() { + clearPreview() + await savedDraft.refresh() + if (!savedDraft.error.value) draftConflict.value = false +} + +/** 从原稿返回当前正式来源编辑,已有表单不被覆盖。 */ +function editCurrentDraft() { + const saved = savedDraft.data.value + useSaved.value = false + providerEdited.value = false + editingSavedInput.value = saved?.providerInput + if (saved?.providerInput?.provider) provider.value = saved.providerInput.provider + if (saved?.providerInput?.generationOptions) { + options.value = Object.fromEntries( + Object.entries(saved.providerInput.generationOptions).filter( + (entry): entry is [string, string | number | boolean] => + ['string', 'number', 'boolean'].includes(typeof entry[1]) + ) + ) + } + if (!saved) return + if (saved.status === 'stale') { + void preflight.refresh() + void formalQuery.refresh() + return + } + if (!formal.value) { + imported.value = savedDraftText.value + return + } + if (saved.draft.sceneStateCarryForward) { + mode.value = 'scene' + selectedScene.value = saved.draft.sceneStateCarryForward.subjectRef + } else { + mode.value = 'camera' + composition.value = saved.draft.direction.composition + cameraPosition.value = saved.draft.direction.cameraPosition + } +} + +/** 显式复制已保存原稿,包含过期稿件。 */ +async function copySavedDraft() { + try { + await navigator.clipboard.writeText(savedDraftText.value) + message?.success('已复制草案原稿') + } catch (cause) { + message?.error(errorMessage(cause)) + } +} + +watch( + savedDraft.data, + () => { + if (useSaved.value) clearPreview() + }, + { flush: 'sync' } +) watch(formalQuery.data, value => { composition.value = value?.shot.direction?.composition ?? '' cameraPosition.value = value?.shot.direction?.cameraPosition ?? '' }) watch(configuration.data, value => { const model = value?.catalog.images.find(item => item.enabled && item.provider === value.profile.imageProvider) + if (providerEdited.value || editingSavedInput.value !== undefined) return provider.value = model?.provider ?? '' options.value = value?.profile.imageOptions ?? {} }) /** 是否具备提交免费预览的实际输入。 */ const canPreview = computed( () => - !!provider.value && !!preflight.data.value?.current.evidence.shotFingerprint && !preflight.error.value && - !configuration.error.value && - (formal.value - ? !!formalQuery.data.value && - !formalQuery.error.value && - (mode.value === 'scene' ? !!scene.value : !!composition.value.trim() && !!cameraPosition.value.trim()) - : !!imported.value.trim()) + (useSaved.value + ? savedDraft.data.value?.status === 'current' && !savedDraft.error.value + : (!!provider.value || (!providerEdited.value && editingSavedInput.value !== undefined)) && + !configuration.error.value && + (formal.value + ? !!formalQuery.data.value && + !formalQuery.error.value && + (mode.value === 'scene' + ? !!scene.value + : !!composition.value.trim() && !!cameraPosition.value.trim()) + : !!imported.value.trim())) ) /** 展示已预览输入,草案指纹只用于只读公共组件。 */ const previewDisplay = computed(() => @@ -194,6 +314,12 @@ const previewDisplay = computed(() => */ function buildDraft(): ShotReviewDraft { const fingerprint = preflight.data.value!.current.evidence.shotFingerprint + if (useSaved.value) { + const original = savedDraft.data.value + if (!original || original.status !== 'current' || original.draft.expectedShotFingerprint !== fingerprint) + throw new Error('草案来源已变化,请刷新正式分镜并重新核对。') + return JSON.parse(JSON.stringify(original.draft)) as ShotReviewDraft + } if (!formal.value) { let draft: ShotReviewDraft try { @@ -233,6 +359,68 @@ function buildDraft(): ShotReviewDraft { return draft } +/** + * 固定本次预览或保存的参数,保留原稿中未指定的模型字段。 + * @returns 真实模型参数和受控修订来源 + */ +function draftParameters() { + const original = useSaved.value ? savedDraft.data.value : null + const storedInput = original ? original.providerInput : !providerEdited.value ? editingSavedInput.value : undefined + const providerInput: DraftProviderInput | undefined = + storedInput === undefined + ? { provider: provider.value, generationOptions: { ...options.value } } + : storedInput + ? (JSON.parse(JSON.stringify(storedInput)) as DraftProviderInput) + : undefined + const expectedCurrentFormalSourceFingerprint = original + ? (original.expectedCurrentFormalSourceFingerprint ?? undefined) + : formalQuery.data.value?.keyframe.formalSourceFingerprint + return { providerInput, expectedCurrentFormalSourceFingerprint } +} + +/** 保存是显式整份替换,不触发免费预览或采用。 */ +async function saveDraft() { + if ( + !canPreview.value || + props.disabled || + savingDraft.value || + saving.value || + savedDraft.loading.value || + !savedDraft.updatedAt.value || + savedDraft.error.value || + draftConflict.value + ) + return + const target = key.value + clearPreview() + savingDraft.value = true + try { + const result = await derivedReviewApi.saveDraft(props.projectId, props.shot.shotId, { + expectedRevision: savedDraft.data.value?.revision ?? null, + draft: buildDraft(), + ...draftParameters() + }) + if (target !== key.value) return + if (result.shotId !== props.shot.shotId) throw new Error('保存回执与当前镜头不一致。') + savedDraft.data.value = result + message?.success('已保存待审草案') + } catch (cause) { + if (target !== key.value) return + if (cause instanceof ApiError && cause.status === 409) { + draftConflict.value = true + const details = cause.details as { code?: string; currentRevision?: number | null } | null + const revisionConflict = + (details?.code ?? cause.code ?? cause.message.split(':')[0]) === + 'KEYFRAME_REVIEW_DRAFT_REVISION_CONFLICT' + message?.warning( + revisionConflict ? '草案已被更新。当前输入已保留,请重新读取后核对。' : errorMessage(cause) + ) + } else message?.error(errorMessage(cause)) + } finally { + savingDraft.value = false + } +} + /** 免费编译并冻结本次输入,只有同一快照可正式采用。 */ async function loadPreview() { if (!canPreview.value || previewing.value || saving.value) return @@ -243,9 +431,14 @@ async function loadPreview() { try { const draft = buildDraft() const shotId = props.shot.shotId - const parameters = { provider: provider.value, generationOptions: { ...options.value } } - const expectedCurrentFormalSourceFingerprint = formalQuery.data.value?.keyframe.formalSourceFingerprint - const preview = await derivedReviewApi.preview(shotId, draft, parameters, controller.signal) + const { providerInput: parameters, expectedCurrentFormalSourceFingerprint } = draftParameters() + const preview = await derivedReviewApi.preview( + shotId, + draft, + parameters ?? {}, + controller.signal, + props.projectId + ) if (controller.signal.aborted) return if (preview.shotId !== shotId || !preview.draftFingerprint || preview.productionReady !== false) throw new Error('没有收到本镜头的有效草案预览。') @@ -312,7 +505,7 @@ async function adopt() { 摄影草案与审核 @@ -344,8 +537,58 @@ async function adopt() {

正在读取正式审核状态…

重新读取审核状态 + +
+ +

正在读取草案…

+ +

+ 此镜头还没有已保存的待审草案。 +

+

当前输入已保留。请重新读取保存记录,核对后再保存。

+ 重新读取草案 +
+ -
+
-
+
-
+
重新读取模型配置 - 免费预览摄影草案 @@ -532,7 +790,22 @@ async function adopt() {