feat(short-drama-agent-front): 接入空间母版恢复与修订

This commit is contained in:
GJ committed 2026-11-07 16:38:26 +08:00
1 parent c808a58a3f
commit 7e149a10c0
18 files changed
+2732 -12

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
# F04 空间母版恢复与修订接入
## 基线与范围
- 前端从 `c808a58` 开始,根目录 `dev` 开发;既有 Vision 完整执行历史已在该基线接入,本轮保留并回归,不再建立本机执行历史缓存。
- 本轮核对后端 `758b07e4` 的正式路由、Schema、服务、响应和 `docs/audits/b04-09-layout-master-recovery-2026-11-07.md`;未修改后端。
- 沿用“形态图片 → 查看图片与记录 → 场景几何与机位参考”,增加空间母版管理入口。先关闭图库并等待离场,再打开母版抽屉。
## 已接入
- 布局及完整母版列表、正式当前全局确认母版、生成任务记录;完成任务不等于质量通过。
- `GET .../masters/recovery-impact`:当前版本/母版、关联镜头、历史 Primary、Anchor、Form,以及独立的图片完整性与来源当前性。原审核通过不等于当前来源通过。
- `POST .../masters/generation-preflight`:明确选择历史确认母版;当前草稿仅在显式修订模式及同版本下可选。展示原图、最终提示词、参数、参考摘要和指纹。
- `POST .../masters/generate`:完整复用同次预检输入,强制传 `expectedPreviewFingerprint` 与独立费用确认。结果仅为草稿,不自动审核、确认或重生下游素材。
- 原有 `review` / `validate` / `confirm`:资产、人工审核、机器审核及来源版本分别呈现;逐项人工证据和真实确认人必须显式填写。AI 审核另行确认费用,不能填成人工通过。
- 原任务记录展示原模型、参数、提示词及 `referenceSnapshot`,不使用当前素材反推原输入。
## 切换与费用保护
- 关闭、项目、布局、母版或预检参数变化取消旧免费请求,并拒绝迟到响应。再次进入同一范围也有请求代次保护。
- 同步母版任务通过正式只读 GET 观察;保留既有 Vision WorkflowExecution / SSE 实现,不为同步接口伪造 SSE 或进度。
- 输入或原件变化撤销旧预检和费用勾选;提交中锁定重复点击、标签切换和关闭。普通查询允许关闭。
- 网络中断、畸形回执、Provider 后保存冲突继续保留未知费用保护;不会自动重发。400/409 只有在正式任务列表证明未创建新任务后才能解除本次保护。
- 不自动恢复 interrupted 任务,不触发 General 重跑,不改历史 Primary。
## 验证
- 新增隔离 Mock 契约、表单与组件测试:历史参考、草稿修订、独立人工/机器结论、来源影响、指纹、参数变更、范围切换、断线、400/409 的付费前后区分和畸形回执。
- 回归既有 Vision 多执行、分页、Physical Retry、复用步骤计量和任务切换测试。
- 全量检查通过:104 个测试文件、774 项测试;lint、格式检查、类型检查与生产构建通过。
- 本地 Chrome 复用已有标签页、`localhost:4312`。隔离页面验收免费预检、Mock 生成及独立审核;深浅主题、375×667 窄屏、长内容滚动、固定底栏均已检查。临时验收文件已移除。
- 真实项目仅只读核对图库到母版抽屉的交接、当前/历史母版、人工确认与机器结论、来源影响、原任务参考摘要。未提交正式数据,真实 Provider 调用为 0。
## 真实后端缺口
母版 generation-preflight 和模型目录目前没有预计金额及货币字段。页面显示“预检接口未提供报价”,保留明确收费确认,不硬编码金额;后端提供正式报价契约后才能展示数值预计费用。
+144
View File
@@ -0,0 +1,144 @@
import { request } from '../../lib/http'
import type {
MasterGenerationInput,
MasterGenerationReceipt,
MasterHumanResult,
MasterJob,
MasterPreflight,
MasterRecoveryImpact,
MasterReview,
MasterVisionReceipt,
SceneMaster,
SpatialLayout
} from './types'
/**
* 布局路径统一编码,不用场景身份或 Form ID 代替布局。
* @param projectId 正式项目
* @param layoutId 正式布局
* @returns 布局范围路径
*/
function path(projectId: string, layoutId: string) {
return `/projects/${encodeURIComponent(projectId)}/shared-spatial-layouts/${encodeURIComponent(layoutId)}/masters`
}
/** 正式母版路由,免费读取与付费操作分开,不自动重试任何写入。 */
export const spatialMasterApi = {
/**
* 读取项目布局供现有来源入口和管理页复用。
* @param projectId 项目编号
* @param signal 取消信号
* @returns 正式布局列表
*/
layouts: (projectId: string, signal?: AbortSignal) =>
request<SpatialLayout[]>(`/projects/${encodeURIComponent(projectId)}/shared-spatial-layouts`, { signal }),
/**
* 保留历史确认和草稿的完整母版列表。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param signal 取消信号
* @returns 母版资产
*/
masters: (projectId: string, layoutId: string, signal?: AbortSignal) =>
request<SceneMaster[]>(path(projectId, layoutId), { signal }),
/**
* 读取真正当前已确认的全局母版,空值为尚无记录。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param signal 取消信号
* @returns 当前母版或 null
*/
confirmed: (projectId: string, layoutId: string, signal?: AbortSignal) =>
request<SceneMaster | null>(path(projectId, layoutId) + '/confirmed', { signal }),
/**
* 免费读取来源影响。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param signal 取消信号
* @returns 原件与来源独立诊断
*/
impact: (projectId: string, layoutId: string, signal?: AbortSignal) =>
request<MasterRecoveryImpact>(path(projectId, layoutId) + '/recovery-impact', { signal, timeoutMs: 0 }),
/**
* 免费预检最终修订输入,不创建任务。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param input 本次完整参数
* @param signal 取消信号
* @returns 正式最终预览
*/
preflight: (projectId: string, layoutId: string, input: MasterGenerationInput, signal?: AbortSignal) =>
request<MasterPreflight>(path(projectId, layoutId) + '/generation-preflight', {
method: 'POST',
body: input,
signal,
timeoutMs: 0
}),
/**
* 明确付费后只生成一次,必须绑定本次预检指纹。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param input 已确认的完整参数和指纹
* @returns 仅为草稿的回执
*/
generate: (
projectId: string,
layoutId: string,
input: MasterGenerationInput & { expectedPreviewFingerprint: string; confirmPaidGeneration: true }
) =>
request<MasterGenerationReceipt>(path(projectId, layoutId) + '/generate', {
method: 'POST',
body: input,
timeoutMs: 0
}),
/**
* 只读任务状态,不自动恢复或再生成。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param signal 取消信号
* @returns 服务保存的任务
*/
jobs: (projectId: string, layoutId: string, signal?: AbortSignal) =>
request<MasterJob[]>(path(projectId, layoutId) + '/generation-jobs', { signal }),
/**
* 免费读取逐项人工与独立机器证据。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param masterId 母版编号
* @param signal 取消信号
* @returns 正式审核材料
*/
review: (projectId: string, layoutId: string, masterId: string, signal?: AbortSignal) =>
request<MasterReview>(path(projectId, layoutId) + '/' + encodeURIComponent(masterId) + '/review', { signal }),
/**
* 仅在用户独立确认本次 Vision 费用后调用,不自动确认母版。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param masterId 母版编号
* @returns 独立机器证据
*/
validate: (projectId: string, layoutId: string, masterId: string) =>
request<MasterVisionReceipt>(path(projectId, layoutId) + '/' + encodeURIComponent(masterId) + '/validate', {
method: 'POST',
body: { confirmPaidValidation: true },
timeoutMs: 0
}),
/**
* 正式人工确认,传真实身份和每项证据,不冒充 Vision 通过。
* @param projectId 项目编号
* @param layoutId 布局编号
* @param masterId 母版编号
* @param input 当前版本及人工依据
* @returns 已确认母版
*/
confirm: (
projectId: string,
layoutId: string,
masterId: string,
input: { expectedVersion: string; evidence: string; confirmedBy: string; reviewResults: MasterHumanResult[] }
) =>
request<SceneMaster>(path(projectId, layoutId) + '/' + encodeURIComponent(masterId) + '/confirm', {
method: 'POST',
body: input,
timeoutMs: 0
})
}
@@ -0,0 +1,149 @@
<script setup lang="ts">
import { formatDate } from '../../../lib/format'
import { computed } from 'vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NInput, NSelect } from 'naive-ui'
import { AssetImage } from '../../../components/ui'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import GenerationModelControls from '../../generation-config/components/GenerationModelControls.vue'
import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import { useMasterGeneration } from '../useMasterGeneration'
import type { MasterGenerationReceipt, SceneMaster, SpatialLayout } from '../types'
/** 正式母版免费预检与单次生成表单,主要操作由抽屉固定底栏提供。 */
const props = defineProps<{
/** 当前项目。 */ projectId: string
/** 当前正式布局。 */ layout: SpatialLayout
/** 保留的历史及草稿资产。 */ masters: SceneMaster[]
/** 上游任务或活动任务锁。 */ disabled: boolean
}>()
/** 生成只登记草稿,来源冲突只通知刷新。 */
const emit = defineEmits<{ generated: [receipt: MasterGenerationReceipt]; stale: [] }>()
const form = useMasterGeneration(
props,
receipt => emit('generated', receipt),
() => emit('stale')
)
/** 固定底栏共用同一套生成门禁。 */
defineExpose({
canSubmit: form.canSubmit,
submitting: form.submitting,
acknowledged: form.acknowledged,
submit: form.submit
})
/** 选项明确区分旧版确认图和当前草稿,用户自定义名称不翻译。 */
const options = computed(() =>
form.references.value.map(master => ({
value: master.id,
label: `${master.status === 'draft' ? '当前草稿' : master.spatialLayoutVersion === props.layout.version ? '当前版本已确认参考' : '历史版本已确认参考'} · ${master.subjectFormId ? '形态专属机位' : '全局布局'} · ${formatDate(master.createdAt)}`
}))
)
</script>
<template>
<!-- 以下是同布局的历史原件选择与显式图片修订,不改变正式布局 -->
<section class="space-y-4">
<WorkspaceSectionHeading
title="历史母版恢复与图片修订"
description="历史母版仅作参考;当前版本草稿须填写明确修订要求。生成结果仍是草稿,不会自动确认。"
/>
<NCheckbox v-model:checked="form.revisionMode.value" :disabled="form.submitting.value"
>显式修订参考图片</NCheckbox
>
<NSelect
v-model:value="form.referenceId.value"
:options="options"
clearable
:disabled="form.submitting.value"
aria-label="母版历史参考"
placeholder="选择已有母版;留空时使用正式共享参考"
/>
<section v-if="form.selectedReference.value" class="space-y-2">
<AssetImage
class="max-w-sm aspect-square"
:src="form.selectedReference.value.imageUrl"
alt="本次选中的母版原始图片"
preview
object-fit="contain"
/>
<p class="wrap-anywhere text-xs text-muted">
参考母版:{{ form.selectedReference.value.id }} · 原版本:{{
form.selectedReference.value.spatialLayoutVersion
}}
</p>
<p class="text-sm">
{{
form.selectedReference.value.status === 'draft'
? '待修订草稿,尚未确认'
: '历史确认图,仅作本次恢复参考'
}}
</p>
</section>
<NInput
v-if="form.revisionMode.value"
v-model:value="form.instruction.value"
type="textarea"
:maxlength="2000"
:disabled="form.submitting.value"
placeholder="填写本次限定图片修订;其余结构沿用参考"
:input-props="{ 'aria-label': '母版修订要求' }"
/>
<!-- 以下是复用现有真实模型目录和本次参数的控件模块 -->
<GenerationModelControls
v-if="form.config.data.value?.profile"
v-model:provider="form.provider.value"
v-model:options="form.options.value"
type="image"
:catalog="form.config.data.value.catalog"
:aspect-ratio="form.config.data.value.profile.aspectRatio"
:disabled="form.submitting.value"
/>
<p v-else class="text-sm text-muted">
{{ form.config.loading.value ? '正在读取项目图片模型配置…' : '请先保存有效的项目图片模型配置。' }}
</p>
<NButton
:loading="form.loading.value"
:disabled="!form.valid.value || form.submitting.value"
@click="form.loadPreview"
>免费预检母版输入</NButton
>
<!-- 以下是实际 Prompt、参数、原始参考和版本指纹,只展示最终输入 -->
<ImageGenerationPreview
:preview="form.preview.value"
:loading="form.loading.value"
display-only
error=""
stale-notice=""
/>
<section v-if="form.preview.value" class="space-y-2 text-sm">
<p>预计费用:预检接口未提供报价,请在提交前核对所选模型报价;本次仅生成 1 张图片,可能收费。</p>
<p>
已核对 {{ form.preview.value.preflight.verifiedSceneCount }} 个场景,实际参考
{{ form.preview.value.preflight.referenceCount }} 张。
</p>
<NCollapse
><NCollapseItem name="reference-evidence" title="参考图摘要与预览指纹"
><p class="wrap-anywhere text-xs">预览指纹:{{ form.preview.value.previewFingerprint }}</p>
<dl
v-for="reference in form.preview.value.preflight.references"
:key="reference.imageId"
class="mt-3 space-y-1 wrap-anywhere text-xs text-muted"
>
<div>参考编号:{{ reference.imageId }}</div>
<div>角色:{{ reference.role === 'layout-master' ? '布局母版参考' : '共享主体身份参考' }}</div>
<div v-if="reference.sourceMasterStatus">
原状态:{{ reference.sourceMasterStatus === 'draft' ? '待修订草稿' : '历史已确认' }}
</div>
<div v-if="reference.sourceLayoutVersion">原布局版本:{{ reference.sourceLayoutVersion }}</div>
<div v-if="reference.sha256">原件摘要:{{ reference.sha256 }}</div>
</dl></NCollapseItem
></NCollapse
>
</section>
<p v-if="form.recoveryNotice.value" class="text-sm text-muted" role="status">
{{ form.recoveryNotice.value }}只读刷新任务记录,不要再次生图。
</p>
<p v-if="form.submitting.value" class="text-sm text-muted" role="status">
正在生成一张母版草稿,请勿重复提交。
</p>
</section>
</template>
@@ -0,0 +1,192 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import { AssetImage } from '../../../components/ui'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import { useQuery } from '../../../composables/useQuery'
import { userFacingText } from '../../../lib/user-facing-text'
import { impactVisionLabel } from '../model'
import { spatialMasterApi } from '../api'
/** 来源影响只在所属标签被打开后读取,原件可读不等于来源当前。 */
const props = defineProps<{
/** 当前项目。 */ projectId: string
/** 当前布局。 */ layoutId: string
}>()
/** 项目与布局共同构成查询身份。 */
const key = computed(() => JSON.stringify([props.projectId, props.layoutId]))
/** 正式只读影响分析,不创建修复任务或清除 Primary。 */
const query = useQuery(key, async (value, signal) => {
const [projectId, layoutId] = JSON.parse(value) as [string, string]
const result = await spatialMasterApi.impact(projectId, layoutId, signal)
if (result.projectId !== projectId || result.layoutId !== layoutId) throw new Error('来源影响与当前布局不匹配。')
return result
})
/** 原件证据与旧审核的字节关系。 */
const imageLabels = {
matches_review: '原件与原审核一致',
readable_unbound: '原件可读,缺少审核字节绑定',
changed: '原件与原审核不一致',
unavailable: '原件不可读取'
}
/** 来源当前性不由像素完整推断。 */
const sourceLabels = {
current: '来源当前',
layout_version_changed: '布局版本已变化',
stale_or_unverified: '来源过期或未核实',
unknown: '来源当前性待核验'
}
/** 汇总按正式结果显示,不在客户端估算待重生数量。 */
const summaries = computed(() =>
query.data.value
? [
['关联镜头', query.data.value.summary.affectedShots],
['历史主图镜头', query.data.value.summary.primaryShots],
['历史候选', query.data.value.summary.candidateCount],
['主图待重新核验', query.data.value.summary.primaryRevalidationShots],
['无首帧镜头', query.data.value.summary.shotsWithoutAssets]
]
: []
)
</script>
<template>
<!-- 以下是布局当前母版及真实恢复范围,不将图片完整性当来源有效 -->
<section class="space-y-4">
<WorkspaceSectionHeading
title="母版恢复与来源影响"
description="图片原件有效 ≠ 来源当前有效。历史主图和旧审核保留,来源变化不等于图片损坏。"
><template #actions
><NButton :loading="query.loading.value" @click="query.refresh">重新读取影响</NButton></template
></WorkspaceSectionHeading
>
<p v-if="query.loading.value && !query.data.value" class="text-sm text-muted" role="status">
正在逐项核对图片原件与来源…
</p>
<p v-if="query.error.value" class="text-sm text-muted">{{ query.error.value }}</p>
<template v-if="query.data.value">
<p class="wrap-anywhere text-xs text-muted">当前布局版本:{{ query.data.value.layoutVersion }}</p>
<p class="text-sm">
当前母版:{{
query.data.value.currentMaster
? '当前版本已人工确认;机器结论请在母版审核中另行核对'
: '暂无当前版本已确认母版'
}}
</p>
<AssetImage
v-if="query.data.value.currentMaster"
class="max-w-sm"
:src="query.data.value.currentMaster.imageUrl"
alt="当前布局母版"
object-fit="contain"
preview
/>
<dl class="grid gap-4 sm:grid-cols-3 lg:grid-cols-5">
<div v-for="[label, count] in summaries" :key="label">
<dt class="text-xs text-muted">{{ label }}</dt>
<dd class="mt-1 text-lg font-semibold">{{ count }}</dd>
</div>
</dl>
<p class="text-sm text-muted">
是否重新生图须结合画面证据判断;此处仅列出需核验资产,不安排批量重生或修改主图。
</p>
<!-- 以下是旧身份锚图和旧形态主图,原图可读与当前来源分别呈现 -->
<NCollapse
><NCollapseItem
v-for="scene in query.data.value.assets"
:key="scene.subjectId"
:name="scene.subjectId"
:title="`${scene.ref} ${scene.name} · 旧身份锚图与形态`"
>
<div class="grid gap-(--app-content-gap) sm:grid-cols-2 lg:grid-cols-3">
<article v-for="anchor in scene.anchors" :key="anchor.id" class="space-y-2">
<h4 class="text-sm font-medium">原身份锚图(Anchor)</h4>
<AssetImage :src="anchor.imageUrl" alt="历史场景身份锚图" object-fit="contain" preview />
<p class="text-sm">
图片完整性:{{ anchor.fileStatus === 'readable' ? '原件可读取' : '原件不可读取' }}
</p>
<p class="text-sm text-muted">来源当前性:需重新核验;接口未给出当前通过结论。</p>
</article>
<template v-for="form in scene.forms" :key="form.id"
><article v-for="image in form.primaryImages" :key="image.id" class="space-y-2">
<h4 class="text-sm font-medium">原形态主图 · {{ form.name }}</h4>
<AssetImage
:src="image.imageUrl"
:alt="`${form.name} 原形态主图`"
object-fit="contain"
preview
/>
<p class="text-sm">
图片完整性:{{ image.fileStatus === 'readable' ? '原件可读取' : '原件不可读取' }}
</p>
<p class="text-sm">
来源当前性:{{
image.currentness.current
? '当前有效'
: userFacingText(image.currentness.reason, '来源待重新核验')
}}
</p>
</article>
<p v-if="!form.primaryImages.length" class="text-sm text-muted">
{{ form.name }} 暂无原形态主图。
</p></template
>
</div>
</NCollapseItem></NCollapse
>
<!-- 以下是正式镜头历史 Primary 和候选,仅展示只读核验建议 -->
<NCollapse
><NCollapseItem
v-for="shot in query.data.value.shots"
:key="shot.shotId"
:name="shot.shotId"
:title="`第 ${shot.episodeNo} 集 · ${shot.beatNo}.${shot.shotNo} ${shot.title} · ${shot.primaryCount ? '有历史主图' : '无历史主图'}`"
>
<p v-if="!shot.candidates.length" class="text-sm text-muted">暂无首帧资产,不代表图片损坏。</p>
<div class="grid gap-(--app-content-gap) sm:grid-cols-2 lg:grid-cols-3">
<article v-for="candidate in shot.candidates" :key="candidate.id" class="space-y-2">
<p class="font-medium text-sm">
{{ candidate.isPrimary ? '历史主首帧(Primary)' : '历史候选' }} ·
{{ candidate.action === 'retain' ? '可保留' : '需要重新核验' }}
</p>
<AssetImage
:src="candidate.imageUrl"
:style="{
aspectRatio:
candidate.width && candidate.height
? `${candidate.width}/${candidate.height}`
: '1/1'
}"
alt="历史镜头首帧"
object-fit="contain"
preview
/>
<p class="text-sm">图片完整性:{{ imageLabels[candidate.imageIntegrity] }}</p>
<p class="text-sm">来源当前性:{{ sourceLabels[candidate.sourceStatus] }}</p>
<p v-if="candidate.sourceReason" class="text-xs text-muted">
{{ userFacingText(candidate.sourceReason) }}
</p>
<p v-if="candidate.latestVision" class="text-sm">
{{ candidate.latestVision.historical ? '历史审核' : '当前审核' }}:{{
impactVisionLabel(candidate.latestVision)
}}{{ candidate.latestVision.historical ? ',不等于当前来源通过' : '' }}
</p>
<NCollapse
><NCollapseItem name="evidence" title="高级来源详情"
><p class="wrap-anywhere text-xs">
候选编号:{{ candidate.id }} · 生成指纹:{{
candidate.providerInputFingerprint || '未记录'
}}
</p>
<pre class="whitespace-pre-wrap break-words text-xs">{{
JSON.stringify(candidate.referenceEvidence, null, 2)
}}</pre>
</NCollapseItem></NCollapse
>
</article>
</div>
</NCollapseItem></NCollapse
>
</template>
</section>
</template>
@@ -0,0 +1,301 @@
<script setup lang="ts">
import { computed, onScopeDispose, ref, watch } from 'vue'
import { NCollapse, NCollapseItem, NInput, NSelect } from 'naive-ui'
import { useQuery } from '../../../composables/useQuery'
import { useActionMessage, showActionFeedback } from '../../../components/ui/useActionMessage'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import { ApiError } from '../../../lib/http'
import { getOperation, runOperation } from '../../workflows/operations'
import { imageRequestNotice, runGuardedImageRequest } from '../../subject-images/image-request-guard'
import { spatialMasterApi } from '../api'
import { masterReviewLabels } from '../model'
import type { MasterHumanResult, SceneMaster, SpatialLayout } from '../types'
/** 当前母版的正式人工审核和独立 Vision,不把确认状态混成 AI 通过。 */
const props = defineProps<{
/** 正式项目。 */ projectId: string
/** 当前布局版本。 */ layout: SpatialLayout
/** 当前用户选中母版。 */ master: SceneMaster
/** 上游活动任务或来源限制。 */ disabled: boolean
}>()
/** 只通知刷新来源,不自动生成后续素材。 */
const emit = defineEmits<{ changed: []; stale: [] }>()
/** 同一原件和版本的审核材料身份。 */
const key = computed(() =>
JSON.stringify([
props.projectId,
props.layout.id,
props.master.id,
props.layout.version,
props.master.imageUrl,
props.master.status
])
)
/** 免费正式审核清单,切母版会中止旧请求。 */
const query = useQuery(key, async (value, signal) => {
const [projectId, layoutId, masterId] = JSON.parse(value) as string[]
const result = await spatialMasterApi.review(projectId!, layoutId!, masterId!, signal)
if (!result || result.masterId !== masterId || result.layoutId !== layoutId)
throw new Error('审核材料与当前母版不匹配。')
return result
})
/** 人工逐项结果,不能从 Vision 通过自动填成通过。 */
const results = ref<MasterHumanResult[]>([])
/** 人工总依据。 */
const evidence = ref('')
/** 真实确认人,打开不默认填充。 */
const confirmedBy = ref('')
/** 单独确认本次 Vision 可能收费。 */
const visionAcknowledged = ref(false)
/** 当前正式操作,本地加载不会误锁关闭。 */
const pending = ref<'vision' | 'confirm' | null>(null)
/** 未知 Vision 结果保留独立费用保护。 */
const guardTarget = computed(
() => `scene-layout-master-vision:${props.projectId}:${props.layout.id}:${props.master.id}`
)
/** 未知回执不可盲目重审。 */
const recoveryNotice = computed(() => (pending.value ? '' : imageRequestNotice(guardTarget.value)))
/** 四类状态分别展示,不把人工作为机器证据。 */
const labels = computed(() => (query.data.value ? masterReviewLabels(query.data.value) : null))
/** 当前原件和正式版本均允许发起操作。 */
const current = computed(
() =>
!!query.data.value?.currentVersion &&
query.data.value.layoutVersion === props.layout.version &&
props.master.spatialLayoutVersion === props.layout.version &&
query.data.value.imageUrl === props.master.imageUrl
)
/** 独立 Vision 不要求人工表单先填完,但必须单独确认费用。 */
const canValidate = computed(
() =>
current.value &&
props.master.status === 'draft' &&
visionAcknowledged.value &&
!props.disabled &&
!pending.value &&
!query.loading.value &&
!query.error.value &&
!recoveryNotice.value
)
/** 逐项人工证据完整后才能正式确认,Vision 不能代填。 */
const canConfirm = computed(
() =>
current.value &&
!!query.data.value?.canConfirm &&
!!evidence.value.trim() &&
!!confirmedBy.value.trim() &&
results.value.length === query.data.value.checklist.length &&
results.value.every(item => item.result === 'passed' && !!item.evidence.trim()) &&
!props.disabled &&
!pending.value &&
!query.loading.value &&
!query.error.value
)
/** 抽屉固定底栏复用同一门禁与局部 loading。 */
defineExpose({ canValidate, canConfirm, visionAcknowledged, pending, validate, confirm, refresh: query.refresh })
/** 短反馈统一走 NMessage。 */
const message = useActionMessage()
/** 卸载后忽略旧操作的结果。 */
let disposed = false
/** 离开并返回相同目标后,也拒绝旧预读结果提交。 */
let cycle = 0
onScopeDispose(() => {
disposed = true
})
watch(
key,
() => {
cycle++
results.value = []
evidence.value = ''
confirmedBy.value = ''
visionAcknowledged.value = false
},
{ flush: 'sync' }
)
watch(
() => query.data.value,
review => {
if (!review) return
if (results.value.length !== review.checklist.length)
results.value = review.checklist.map(item => ({ index: item.index, result: 'needs_review', evidence: '' }))
}
)
/**
* 单独提交一次 Vision,回执只保存机器结论,不确认母版。
* @returns 付费请求结算及只读刷新通知
*/
async function validate() {
if (!canValidate.value) return
const identity = key.value
const requestCycle = cycle
const projectId = props.projectId
const layoutId = props.layout.id
const masterId = props.master.id
const target = guardTarget.value
pending.value = 'vision'
visionAcknowledged.value = false
const ok = await runOperation(projectId, '空间母版 AI 视觉审核', async () => {
const review = await spatialMasterApi.review(projectId, layoutId, masterId)
if (
disposed ||
identity !== key.value ||
requestCycle !== cycle ||
!review.currentVersion ||
review.status !== 'draft' ||
review.layoutVersion !== props.layout.version
)
throw new Error('母版或布局已变化,本次未提交 AI 审核。')
return runGuardedImageRequest(target, async () => {
const receipt = await spatialMasterApi.validate(projectId, layoutId, masterId)
if (
!receipt ||
receipt.masterId !== masterId ||
receipt.layoutId !== layoutId ||
typeof receipt.persisted !== 'boolean' ||
typeof receipt.automatedVisionPassed !== 'boolean'
)
throw new Error('审核回执不完整,请只读刷新记录,勿重复审核。')
return receipt
})
})
pending.value = null
if (disposed || identity !== key.value || requestCycle !== cycle) return
if (ok) {
showActionFeedback(message, 'AI 审核已结束,请查看独立机器结论;仍须人工逐项确认。', 'info')
void query.refresh()
emit('changed')
} else {
showActionFeedback(message, getOperation(projectId).error, 'error')
void query.refresh()
emit('stale')
}
}
/**
* 正式确认只发送当前人工逐项结果,版本变化时不自动套用新版。
* @returns 人工确认完成通知
*/
async function confirm() {
if (!canConfirm.value) return
const identity = key.value
const requestCycle = cycle
const projectId = props.projectId
const layoutId = props.layout.id
const masterId = props.master.id
const input = {
expectedVersion: props.layout.version,
evidence: evidence.value.trim(),
confirmedBy: confirmedBy.value.trim(),
reviewResults: results.value.map(item => ({ ...item, evidence: item.evidence.trim() }))
}
pending.value = 'confirm'
const ok = await runOperation(projectId, '正式确认空间母版', async () => {
const review = await spatialMasterApi.review(projectId, layoutId, masterId)
if (disposed || identity !== key.value || requestCycle !== cycle) return
if (!review.currentVersion || review.layoutVersion !== input.expectedVersion || !review.canConfirm)
throw new ApiError('母版来源或状态已变化,请重新核对。', 409)
const result = await spatialMasterApi.confirm(projectId, layoutId, masterId, input)
if (
result.id !== masterId ||
result.projectId !== projectId ||
result.spatialLayoutId !== layoutId ||
result.status !== 'confirmed'
)
throw new Error('未取得正式确认回执,请刷新来源核对。')
})
pending.value = null
if (disposed || identity !== key.value || requestCycle !== cycle) return
if (ok) {
showActionFeedback(message, '母版已人工确认,AI 原审核结论保持独立。请重新核对相关来源。', 'success')
void query.refresh()
emit('changed')
} else {
showActionFeedback(message, getOperation(projectId).error, 'error')
emit('stale')
}
}
</script>
<template>
<!-- 以下是独立的资产、人工、机器及来源状态模块 -->
<section class="space-y-4">
<WorkspaceSectionHeading
title="母版质量与正式确认"
description="人工确认不会代做 AI 审核;AI 通过也不会自动确认母版。"
/>
<p v-if="query.loading.value && !query.data.value" class="text-sm text-muted" role="status">
正在读取审核清单…
</p>
<p v-if="query.error.value" class="text-sm text-muted">{{ query.error.value }}</p>
<div v-if="labels" class="flex flex-wrap gap-x-6 gap-y-2 text-sm" role="status">
<span>资产:{{ labels.asset }}</span
><span>人工:{{ labels.human }}</span
><span>机器:{{ labels.vision }}</span
><span>来源:{{ current ? '当前版本' : '版本已变化,需重新核对' }}</span>
</div>
<template v-if="query.data.value">
<p v-if="!query.data.value.currentVersion" class="text-sm text-muted">
此图绑定旧布局版本,不能按当前版本确认或重新运行 AI 审核。可在恢复与修订中显式选择为历史参考。
</p>
<!-- 以下是原有逐项规则的人工核对表单,初始不默认通过 -->
<section v-if="query.data.value.canConfirm && current" class="space-y-4">
<div v-for="(item, index) in query.data.value.checklist" :key="item.index" class="space-y-2">
<p class="text-sm font-medium">{{ item.index }}. {{ item.requirement }}</p>
<p class="text-xs text-muted">验收依据:{{ item.acceptance }}</p>
<NSelect
v-if="results[index]"
v-model:value="results[index]!.result"
:disabled="disabled || !!pending"
:aria-label="`第 ${item.index} 项人工结论`"
:options="[
{ label: '待核对', value: 'needs_review' },
{ label: '通过', value: 'passed' },
{ label: '未通过', value: 'failed' }
]"
/>
<NInput
v-if="results[index]"
v-model:value="results[index]!.evidence"
:disabled="disabled || !!pending"
type="textarea"
placeholder="填写本项实际看到的画面依据"
:input-props="{ 'aria-label': `第 ${item.index} 项人工依据` }"
/>
</div>
<NInput
v-model:value="evidence"
type="textarea"
:disabled="disabled || !!pending"
placeholder="填写本次人工确认的完整依据"
:input-props="{ 'aria-label': '母版人工确认依据' }"
/>
<NInput
v-model:value="confirmedBy"
:disabled="disabled || !!pending"
placeholder="填写真实确认人"
:input-props="{ 'aria-label': '母版确认人' }"
/>
</section>
<NCollapse v-if="query.data.value.humanReviewEvidence || query.data.value.automatedVisionReview"
><NCollapseItem name="review-record" title="已有审核记录"
><p v-if="query.data.value.humanReviewEvidence" class="whitespace-pre-wrap text-sm">
{{ query.data.value.humanReviewEvidence.summary }}
</p>
<p
v-for="item in query.data.value.humanReviewEvidence?.compositionReviews"
:key="item.index"
class="mt-2 text-sm"
>
第 {{ item.index }} 项:{{ item.evidence }}
</p>
<p v-if="typeof query.data.value.automatedVisionReview?.summary === 'string'" class="mt-2 text-sm">
AI 摘要:{{ query.data.value.automatedVisionReview.summary }}
</p></NCollapseItem
></NCollapse
>
</template>
<p v-if="recoveryNotice" class="text-sm text-muted" role="status">
{{ recoveryNotice }}请读取已有审核记录,不要重复付费。
</p>
</section>
</template>
@@ -0,0 +1,366 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NTab, NTabs } from 'naive-ui'
import AppDrawer from '../../../components/ui/AppDrawer.vue'
import { AssetImage } from '../../../components/ui'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import { useActionMessage, showActionFeedback } from '../../../components/ui/useActionMessage'
import { useQuery } from '../../../composables/useQuery'
import { usePolling } from '../../../composables/usePolling'
import { formatDate } from '../../../lib/format'
import { getOperation } from '../../workflows/operations'
import { spatialMasterApi } from '../api'
import type { MasterGenerationReceipt } from '../types'
import MasterGenerationForm from './MasterGenerationForm.vue'
import MasterReviewForm from './MasterReviewForm.vue'
import MasterRecoveryImpact from './MasterRecoveryImpact.vue'
/** 从原场景几何入口增量展开的正式母版管理,不另建生成或质量体系。 */
const props = withDefaults(
defineProps<{
/** 当前项目。 */ projectId: string
/** 用户从已有场景选择的布局。 */ layoutId: string
/** 上游活动操作仅限制写入,读取仍可使用。 */ disabled?: boolean
}>(),
{ disabled: false }
)
/** 全屏内容级滚动,正式操作由固定底栏提供。 */
const open = defineModel<boolean>('open', { default: false })
/** 母版正式操作反馈沿用应用消息层。 */
const message = useActionMessage()
/** 正式资产变化后通知原图库只读刷新。 */
const emit = defineEmits<{ changed: [] }>()
/** 关闭时取消全部读取,切换项目/布局拒绝旧结果。 */
const key = computed(() =>
open.value && props.projectId && props.layoutId ? JSON.stringify([props.projectId, props.layoutId]) : ''
)
/** 当前真实布局、完整母版历史与正式已确认母版。 */
const query = useQuery(key, async (value, signal) => {
if (!value) return null
const [projectId, layoutId] = JSON.parse(value) as [string, string]
const [layouts, masters, confirmed] = await Promise.all([
spatialMasterApi.layouts(projectId, signal),
spatialMasterApi.masters(projectId, layoutId, signal),
spatialMasterApi.confirmed(projectId, layoutId, signal)
])
const layout = layouts.find(item => item.id === layoutId)
if (
!layout ||
(layout.projectId && layout.projectId !== projectId) ||
masters.some(item => item.projectId !== projectId || item.spatialLayoutId !== layoutId) ||
(confirmed &&
(confirmed.projectId !== projectId ||
confirmed.spatialLayoutId !== layoutId ||
confirmed.spatialLayoutVersion !== layout.version ||
confirmed.status !== 'confirmed'))
)
throw new Error('母版或布局与当前项目不匹配,请重新读取。')
return { layout, masters, confirmed }
})
/** 后端为同步持久化母版任务,使用正式 GET 观察,不伪造 SSE 或百分比。 */
const jobs = usePolling(
key,
async (value, signal) => {
if (!value) return []
const [projectId, layoutId] = JSON.parse(value) as [string, string]
const rows = await spatialMasterApi.jobs(projectId, layoutId, signal)
if (rows.some(item => item.projectId !== projectId || item.spatialLayoutId !== layoutId))
throw new Error('任务记录与当前布局不匹配。')
return rows
},
computed(() => (key.value ? 5000 : false))
)
/** 当前功能标签;未打开恢复影响时不发全布局检查。 */
const tab = ref('masters')
/** 用户主动查看审核时定位到对应表单,不让长图库挡住正文。 */
const reviewSection = ref<HTMLElement | null>(null)
/** 用户选择的正式母版;默认仅查看服务端当前记录。 */
const selectedId = ref('')
/** 选中图片只来自当前列表。 */
const selected = computed(() => query.data.value?.masters.find(item => item.id === selectedId.value))
/** 生成表单公开底栏操作。 */
const generationRef = ref<InstanceType<typeof MasterGenerationForm> | null>(null)
/** 审核表单公开底栏操作。 */
const reviewRef = ref<InstanceType<typeof MasterReviewForm> | null>(null)
/** 仅真正提交期间锁定关闭,普通查询不锁定。 */
const busy = computed(() => !!generationRef.value?.submitting || !!reviewRef.value?.pending)
/** 已有任务或未知费用阻止新付费/正式确认,不影响只读。 */
const activeJob = computed(() => jobs.data.value?.some(item => !['completed', 'failed'].includes(item.status)))
/** 复用项目全局活动锁,防止从另一入口并行写入。 */
const blocked = computed(
() =>
props.disabled ||
getOperation(props.projectId).pending ||
!!activeJob.value ||
!jobs.data.value ||
!!jobs.error.value ||
!!query.error.value
)
/** 最近任务公开状态。 */
const jobLabels: Record<string, string> = {
pending: '等待执行',
running: '执行中',
interrupted: '结果或费用待核查',
completed: '已生成草稿',
failed: '执行失败'
}
watch(
key,
() => {
tab.value = 'masters'
selectedId.value = ''
},
{ flush: 'sync' }
)
watch(
() => query.data.value,
data => {
if (data && !data.masters.some(item => item.id === selectedId.value))
selectedId.value = data.confirmed?.id ?? data.masters[0]?.id ?? ''
}
)
/** 任务在其他入口完成后,只读恢复母版列表,旧项目事件不会回填。 */
watch(
() => jobs.data.value,
(rows, previous) => {
if (!key.value || !rows || !previous) return
if (
rows.some(
item =>
['completed', 'failed', 'interrupted'].includes(item.status) &&
previous.some(old => old.id === item.id && ['pending', 'running'].includes(old.status))
)
)
void query.refresh()
}
)
/**
* 同步读取当前布局与任务;失败保持数据但暂停写入。
* @returns 当前刷新完成
*/
async function refresh() {
await Promise.all([query.refresh(), jobs.refresh(), reviewRef.value?.refresh()])
}
/**
* 在同一只读范围选择母版并定位审核表单,不触发审核或确认。
* @param masterId 用户选中的正式资产编号
* @returns 正文定位完成
*/
async function selectMaster(masterId: string) {
if (busy.value) return
const target = key.value
selectedId.value = masterId
await nextTick()
if (target === key.value) reviewSection.value?.scrollIntoView({ block: 'start' })
}
/**
* 新草稿回执仅定位展示,不自动审核或确认。
* @param receipt 已验证的正式生成回执
*/
function generated(receipt: MasterGenerationReceipt) {
showActionFeedback(message, '已生成母版草稿,尚未完成质量审核与人工确认。', 'info')
selectedId.value = receipt.masterId
tab.value = 'masters'
void query.refresh()
void jobs.refresh()
emit('changed')
}
/** 人工确认或机器审核后只读回查正式来源,不生成下游素材。 */
function reviewed() {
void query.refresh()
void jobs.refresh()
emit('changed')
}
</script>
<template>
<!-- 以下是母版历史、独立质量、恢复影响和任务的全屏管理模块 -->
<AppDrawer
v-model:open="open"
title="空间母版管理"
description="历史原图、来源版本与人工/机器审核分别核对。所有生成和 AI 审核均须独立确认费用。"
:busy="busy"
>
<div class="space-y-(--app-content-gap)">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 class="text-base font-semibold">{{ query.data.value?.layout.name || '当前空间布局' }}</h3>
<p v-if="query.data.value" class="mt-2 wrap-anywhere text-xs text-muted">
当前布局版本:{{ query.data.value.layout.version }}
</p>
</div>
<NButton :loading="query.loading.value || jobs.loading.value" :disabled="busy" @click="refresh"
>刷新母版与任务</NButton
>
</div>
<p v-if="query.loading.value && !query.data.value" class="text-sm text-muted" role="status">
正在读取布局与母版记录…
</p>
<p v-if="query.error.value" class="text-sm text-muted">{{ query.error.value }}</p>
<p v-if="activeJob" class="text-sm text-muted" role="status">
已有生成任务执行中或结果待核查,请在任务记录中核对;不会自动再次生图。
</p>
<NTabs v-model:value="tab" type="line" aria-label="空间母版功能"
><NTab :disabled="busy" name="masters">母版与审核</NTab
><NTab :disabled="busy" name="generate">恢复与修订</NTab
><NTab :disabled="busy" name="impact">来源影响</NTab
><NTab :disabled="busy" name="jobs">任务记录</NTab></NTabs
>
<template v-if="query.data.value">
<!-- 以下是保留原图的全部母版历史,确认状态不冒充机器通过 -->
<section v-if="tab === 'masters'" class="space-y-(--app-content-gap)">
<WorkspaceSectionHeading
title="母版历史"
:description="
query.data.value.confirmed
? '当前版本已有正式确认母版;旧图和草稿继续保留。'
: '暂无当前版本已确认母版。历史确认图不能自动作为当前母版。'
"
/>
<p v-if="!query.data.value.masters.length" class="text-sm text-muted">
暂无母版记录,可在恢复与修订中免费预检。
</p>
<div
class="grid grid-cols-1 items-start gap-(--app-content-gap) sm:grid-cols-[repeat(auto-fill,minmax(220px,260px))]"
>
<article v-for="master in query.data.value.masters" :key="master.id" class="min-w-0 space-y-2">
<AssetImage
:src="master.imageUrl"
:style="{ aspectRatio: '1/1' }"
alt="空间母版原图"
object-fit="contain"
preview
/>
<p class="text-sm font-semibold">
{{
master.status === 'confirmed'
? '已确认'
: master.status === 'draft'
? '草稿'
: '状态待核对'
}}{{ master.id === query.data.value.confirmed?.id ? ' · 当前全局母版' : '' }}
</p>
<p class="text-xs text-muted">
{{
master.spatialLayoutVersion === query.data.value.layout.version
? '绑定当前布局'
: '绑定历史布局'
}}
· {{ master.subjectFormId ? '形态专属机位' : '全局布局' }} ·
{{ formatDate(master.createdAt) }}
</p>
<p v-if="master.confirmedBy" class="text-xs text-muted">
人工确认:{{ master.confirmedBy }} ·
{{ master.confirmedAt ? formatDate(master.confirmedAt) : '时间未记录' }}
</p>
<NButton
class="workspace-action-button"
:disabled="busy"
@click="selectMaster(master.id)"
>{{ selectedId === master.id ? '正在查看审核' : '查看审核与确认' }}</NButton
>
</article>
</div>
<section v-if="selected" ref="reviewSection">
<MasterReviewForm
ref="reviewRef"
:key="selected.id"
:project-id="projectId"
:layout="query.data.value.layout"
:master="selected"
:disabled="blocked"
@changed="reviewed"
@stale="refresh"
/>
</section>
</section>
<!-- 以下是独立的免费输入预检与单次生成表单,结果只登记草稿 -->
<MasterGenerationForm
v-if="tab === 'generate'"
ref="generationRef"
:project-id="projectId"
:layout="query.data.value.layout"
:masters="query.data.value.masters"
:disabled="blocked"
@generated="generated"
@stale="refresh"
/>
<MasterRecoveryImpact v-if="tab === 'impact'" :project-id="projectId" :layout-id="layoutId" />
<!-- 以下是真实任务状态,无本次请求也可发现,不自动恢复或重复生图 -->
<section v-if="tab === 'jobs'" class="space-y-4">
<WorkspaceSectionHeading
title="母版生成任务"
description="完成仅代表草稿生成;中断可能已计费,应先核对原结果,不自动重试。"
/>
<p v-if="jobs.error.value" class="text-sm text-muted">{{ jobs.error.value }}</p>
<p v-if="!jobs.data.value?.length" class="text-sm text-muted">暂无生成任务。</p>
<article v-for="job in jobs.data.value" :key="job.id" class="space-y-2">
<p class="text-sm font-semibold">
{{ jobLabels[job.status] || '状态待核查' }} · {{ formatDate(job.updatedAt) }}
</p>
<p class="wrap-anywhere text-xs text-muted">
任务编号:{{ job.id }} · {{ job.provider }} / {{ job.model }}
</p>
<p v-if="job.status === 'interrupted'" class="text-sm">原结果或费用待核查,请勿重新生图。</p>
<NCollapse
><NCollapseItem name="job" title="任务输入详情"
><p class="wrap-anywhere text-xs">布局版本:{{ job.spatialLayoutVersion }}</p>
<pre class="mt-2 whitespace-pre-wrap break-words text-xs">{{ job.prompt }}</pre>
<pre class="mt-2 whitespace-pre-wrap break-words text-xs">{{
JSON.stringify(job.generationOptions, null, 2)
}}</pre>
<p class="mt-2 text-xs">原任务参考摘要</p>
<pre class="whitespace-pre-wrap break-words text-xs">{{
job.referenceSnapshot ? JSON.stringify(job.referenceSnapshot, null, 2) : '未记录'
}}</pre>
</NCollapseItem></NCollapse
>
</article>
</section>
</template>
</div>
<!-- 以下是固定底栏中的独立费用确认、人工确认与关闭入口 -->
<template #footer>
<div class="flex w-full flex-wrap items-center justify-end gap-3">
<NCheckbox
v-if="tab === 'generate' && generationRef"
v-model:checked="generationRef.acknowledged"
:disabled="busy || blocked"
class="mr-auto"
>已核对本次费用,确认仅生成一张草稿</NCheckbox
>
<NCheckbox
v-if="tab === 'masters' && selected?.status === 'draft' && reviewRef"
v-model:checked="reviewRef.visionAcknowledged"
:disabled="busy || blocked"
class="mr-auto"
>单独确认本次 AI 视觉审核可能收费</NCheckbox
>
<NButton :disabled="busy" @click="open = false">关闭</NButton>
<NButton
v-if="tab === 'generate' && generationRef"
type="primary"
:loading="generationRef.submitting"
:disabled="!generationRef.canSubmit"
@click="generationRef.submit()"
>确认费用并生成一张草稿</NButton
>
<NButton
v-if="tab === 'masters' && selected?.status === 'draft' && reviewRef"
:loading="reviewRef.pending === 'vision'"
:disabled="!reviewRef.canValidate"
@click="reviewRef.validate()"
>AI 视觉审核</NButton
>
<NButton
v-if="tab === 'masters' && selected?.status === 'draft' && reviewRef"
type="primary"
:loading="reviewRef.pending === 'confirm'"
:disabled="!reviewRef.canConfirm"
@click="reviewRef.confirm()"
>正式人工确认母版</NButton
>
</div>
</template>
</AppDrawer>
</template>
+76
View File
@@ -0,0 +1,76 @@
import type { MasterPreflight, MasterPreview, MasterReview, SceneMaster, ImpactCandidate } from './types'
/**
* 历史确认母版可恢复;当前版草稿只有明确图片修订时可引用。
* @param master 正式资产状态
* @param version 当前几何版本
* @param revision 是否有明确修订意图
* @returns 本次是否可以选择为参考
*/
export function canUseMasterReference(
master: Pick<SceneMaster, 'status' | 'spatialLayoutVersion'>,
version: string,
revision: boolean
) {
return (
master.status === 'confirmed' ||
(revision && master.status === 'draft' && master.spatialLayoutVersion === version)
)
}
/**
* 人工、机器及资产状态分别展示,不从 confirmed 推断 Vision。
* @param review 正式审核摘要
* @returns 独立状态标签
*/
export function masterReviewLabels(
review: Pick<MasterReview, 'status' | 'currentVersion' | 'reviewStatus' | 'automatedVisionPassed'>
) {
return {
asset: review.status === 'confirmed' ? '已确认' : review.status === 'draft' ? '草稿' : '状态待核对',
human: review.reviewStatus === 'human_passed' ? '人工审核通过' : '人工审核待核对',
vision: review.currentVersion && review.automatedVisionPassed ? 'AI 视觉审核通过' : 'AI 视觉审核未通过或未运行'
}
}
/**
* 将正式预检适配现有图片输入组件,显示原图而不把 Base64 放进页面。
* @param preflight 本次服务端完整预检
* @returns 共用展示组件所需预览
*/
export function toMasterPreview(preflight: MasterPreflight): MasterPreview {
return {
preflight,
provider: preflight.provider,
model: preflight.model,
previewFingerprint: preflight.previewFingerprint,
providerPrompt: preflight.prompt,
referenceImages: preflight.references.map(item => item.imageUrl),
generationConfig: preflight.generationOptions,
actualProviderReferenceCount: preflight.referenceCount,
references: preflight.references.map((item, index) => ({
imageNumber: index + 1,
role: item.role ?? 'identity-anchor',
imageId: item.imageId,
imageUrl: item.imageUrl
}))
}
}
/**
* 原任务执行完成与原质量结论分开,历史通过也不代表当前来源有效。
* @param vision 正式影响分析保留的原审核摘要
* @returns 只描述可核实的原始结论
*/
export function impactVisionLabel(vision: NonNullable<ImpactCandidate['latestVision']>) {
if (vision.status !== 'completed') return '原审核未完成'
const labels: Record<string, string> = {
failed: '原结论未通过',
needs_review: '原结论待人工复核',
stale: '原审核来源已失效',
blocked: '原质量受阻',
insufficient_evidence: '原审核证据不足'
}
if (vision.qualityDecision && labels[vision.qualityDecision]) return labels[vision.qualityDecision]!
if (vision.passed === true && vision.qualityDecision === 'passed')
return vision.evidenceComplete ? '原结论通过' : '原结论通过,完整证据待核验'
return vision.passed === false ? '原结论未通过' : '原质量结论待核验'
}
+232
View File
@@ -0,0 +1,232 @@
import type { ImageGenerationPreview } from '../subject-images/generation-preview'
import type { GenerationOptions } from '../generation-config/types'
/** 空间布局的正式身份与当前几何版本。 */
export interface SpatialLayout {
/** 布局编号。 */ id: string
/** 所属项目。 */ projectId: string
/** 用户定义的布局名称。 */ name: string
/** 当前布局版本。 */ version: string
/** 正式关联场景。 */ sceneSubjectIds: string[]
}
/** 草稿或已确认的母版原始资产;确认不等于 Vision 通过。 */
export interface SceneMaster {
/** 母版编号。 */ id: string
/** 正式项目。 */ projectId: string
/** 正式布局。 */ spatialLayoutId: string
/** 本图绑定版本。 */ spatialLayoutVersion: string
/** 原始图片。 */ imageUrl: string
/** 数据库原状态。 */ status: string
/** 特定形态机位,空值为全局母版。 */ subjectFormId: string | null
/** 人工机位描述。 */ viewDescription: string | null
/** 原始确认依据。 */ evidence: string | null
/** 人工确认人。 */ confirmedBy: string | null
/** 人工确认时间。 */ confirmedAt: string | null
/** 机器审核时间,不表示通过。 */ visionReviewedAt: string | null
/** 创建时间。 */ createdAt: string
/** 最近更新。 */ updatedAt: string
}
/** 单次母版生成参数,原样复用预检到生成。 */
export interface MasterGenerationInput {
/** 本次布局版本。 */ expectedVersion: string
/** 明确选择的历史或草稿母版。 */ referenceMasterId?: string
/** 仅有此字段时才允许当前版本 draft 作修订参考。 */ revisionInstruction?: string
/** 本次明确的模型供应方。 */ providerName?: string
/** 本次模型选项。 */ generationOptions?: GenerationOptions
}
/** 预检返回的实际参考职责和原件证据。 */
export interface MasterReference {
/** 正式参考编号。 */ imageId: string
/** 持久化原图。 */ imageUrl: string
/** 真实送图地址,可能为大体积 Base64,不展示或存储。 */ providerImageUrl: string
/** 送图是否解析成功。 */ providerInputResolved: boolean
/** 布局母版具有独立角色。 */ role?: 'layout-master'
/** 共享主体编号。 */ subjectId?: string
/** 共享主体引用。 */ subjectRef?: string
/** 历史几何版本。 */ sourceLayoutVersion?: string
/** 历史确认或待修订草稿。 */ sourceMasterStatus?: 'draft' | 'confirmed'
/** 原件字节摘要。 */ sha256?: string
/** 像素摘要。 */ pixelFingerprint?: string
/** 原始宽度。 */ width?: number
/** 原始高度。 */ height?: number
}
/** 免费预检的正式 DTO;接口没有报价字段。 */
export interface MasterPreflight {
/** 布局编号。 */ layoutId: string
/** 本次当前版本。 */ layoutVersion: string
/** 实际供应方。 */ provider: string
/** 实际模型。 */ model: string
/** 最终实际参数。 */ generationOptions: GenerationOptions
/** 最终画面描述。 */ prompt: string
/** 按真实顺序的参考。 */ references: MasterReference[]
/** 同次输入指纹。 */ previewFingerprint: string
/** 用户选择的参考。 */ referenceMasterId: string | null
/** 同次明确修订文字。 */ revisionInstruction: string | null
/** 实际参考数。 */ referenceCount: number
/** 已核对的场景数量。 */ verifiedSceneCount: number
/** 模型上限,空值表示无公开上限。 */ maxReferenceImages: number | null
/** 免费请求不会启动生成。 */ generationAllowed: false
/** 公开业务原因。 */ reason: string
}
/** 适配既有实际输入展示组件,不改变正式参数或推断报价。 */
export interface MasterPreview extends ImageGenerationPreview {
/** 母版原始预检,保留数据层的真实返回值。 */ preflight: MasterPreflight
}
/** 正式单次生图回执,只说明草稿已登记。 */
export interface MasterGenerationReceipt {
/** 原持久化任务。 */ jobId: string
/** 新生成的草稿。 */ masterId: string
/** 已保存原图。 */ imageUrl: string
/** 同步执行结束,不表示质量通过。 */ status: 'completed'
}
/** 母版持久化生成任务;中断可能已经计费,不能自动重发。 */
export interface MasterJob {
/** 正式任务。 */ id: string
/** 原项目。 */ projectId: string
/** 原布局。 */ spatialLayoutId: string
/** 任务绑定版本。 */ spatialLayoutVersion: string
/** 原执行状态。 */ status: string
/** 本次模型供应方。 */ provider: string
/** 本次模型。 */ model: string
/** 本次实际提示词。 */ prompt: string
/** 原任务实际选项。 */ generationOptions: GenerationOptions
/** 原任务不可变参考摘要,不用当前素材反推。 */ referenceSnapshot: Array<
Pick<
MasterReference,
'imageId' | 'subjectId' | 'role' | 'sourceLayoutVersion' | 'sourceMasterStatus' | 'sha256'
>
>
/** 已存远程或本地结果。 */ imageUrl: string | null
/** 原错误保留数据层。 */ errorMessage: string | null
/** 创建时间。 */ createdAt: string
/** 更新时间。 */ updatedAt: string
}
/** 必须由用户逐项核对的正式人工证据。 */
export interface MasterHumanResult {
/** 一基审核项。 */ index: number
/** 用户明确选择,打开不默认通过。 */ result: 'passed' | 'failed' | 'needs_review'
/** 人工依据。 */ evidence: string
}
/** 人工审核预览,不消耗 Vision 费用。 */
export interface MasterReview {
/** 原母版。 */ masterId: string
/** 当前图像。 */ imageUrl: string
/** 当前布局。 */ layoutId: string
/** 当前几何版本。 */ layoutVersion: string
/** 图像是否仍绑定当前版本。 */ currentVersion: boolean
/** 原资产状态。 */ status: string
/** 已保存的逐项人工审核状态。 */ reviewStatus: 'human_passed' | 'needs_review'
/** 独立机器结论,不能从 confirmed 推断。 */ automatedVisionPassed: boolean
/** 原始自动审核摘要,普通区域不直接展示内部对象。 */ automatedVisionReview: Record<string, unknown> | null
/** 适用场景。 */ sceneSubjectIds: string[]
/** 机位形态。 */ subjectFormId: string | null
/** 机位描述。 */ viewDescription: string | null
/** 逐项真实规则。 */ checklist: Array<{
/** 一基索引。 */ index: number
/** 规则类别。 */ kind: string
/** 关联主体。 */ subjectId: string
/** 参照主体。 */ referenceSubjectId: string | null
/** 要求。 */ requirement: string
/** 验收准则。 */ acceptance: string
/** 服务已保存结果。 */ result: MasterHumanResult['result']
}>
/** 只说明版本和 draft 允许发起人工确认。 */ canConfirm: boolean
/** 已保存人工证据,不能在 draft 上伪造。 */ humanReviewEvidence: {
/** 人工总依据。 */ summary: string
/** 逐项人工结果。 */ compositionReviews: MasterHumanResult[]
} | null
/** 公开边界。 */ note: string
}
/** 自动 Vision 回执,顶层 passed=false 保留正式人工门禁。 */
export interface MasterVisionReceipt {
/** 所属母版。 */ masterId: string
/** 所属布局。 */ layoutId: string
/** 本次版本。 */ layoutVersion: string
/** 推理后来源是否仍一致。 */ currentVersion: boolean
/** 本次结果是否已存证。 */ persisted: boolean
/** 机器独立通过,不代表人工确认。 */ automatedVisionPassed: boolean
/** 实际检查状态。 */ reviewStatus: string
/** 结果摘要。 */ summary: string
}
/** 来源影响中的历史候选,原件完整性和来源当前性独立。 */
export interface ImpactCandidate {
/** 历史候选。 */ id: string
/** 保留的历史主图。 */ isPrimary: boolean
/** 原执行状态。 */ status: string
/** 原始图片。 */ imageUrl: string | null
/** 原件宽度。 */ width: number | null
/** 原件高度。 */ height: number | null
/** 原件与原审核的关系。 */ imageIntegrity: 'matches_review' | 'readable_unbound' | 'changed' | 'unavailable'
/** 来源当前性,不由原件可读推断。 */ sourceStatus:
| 'current'
| 'layout_version_changed'
| 'stale_or_unverified'
| 'unknown'
/** 来源说明。 */ sourceReason: string | null
/** 应保留或重新核验,不自动重生。 */ action: 'retain' | 'revalidate'
/** 原始不可变生成输入。 */ providerInputFingerprint: string | null
/** 历史审核,不等于当前通过。 */ latestVision: {
/** 原记录编号。 */ id: string
/** 原执行状态。 */ status: string
/** 原审核是否通过。 */ passed: boolean | null
/** 原质量结论。 */ qualityDecision: string | null
/** 原审核证据是否完整。 */ evidenceComplete: boolean
/** 是否为历史来源结论。 */ historical: boolean
} | null
/** 原参考证据,只在高级详情展开。 */ referenceEvidence: Array<{
/** 参考图片序号。 */ imageNumber: number
/** 原参考内容校验值。 */ recordedSha256: string
/** 原参考绑定与完整性。 */ bindings: Array<
Record<string, unknown> & { imageIntegrity: 'matches_input' | 'changed' | 'unavailable' }
>
}>
}
/** 正式布局范围的免费恢复影响,不授予生成或晋升资格。 */
export interface MasterRecoveryImpact {
/** 当前项目。 */ projectId: string
/** 当前布局。 */ layoutId: string
/** 当前布局版本。 */ layoutVersion: string
/** 真正当前已确认母版。 */ currentMaster: SceneMaster | null
/** 真实汇总。 */ summary: {
/** 关联镜头数量。 */ affectedShots: number
/** 保留历史主图的镜头数。 */ primaryShots: number
/** 存在审核任务的镜头数。 */ shotsWithVision: number
/** 暂无首帧的镜头数。 */ shotsWithoutAssets: number
/** 历史候选数量。 */ candidateCount: number
/** 主图待重新核验的镜头数。 */ primaryRevalidationShots: number
}
/** 逐镜头历史及原主图。 */ shots: Array<{
/** 正式镜头编号。 */ shotId: string
/** 剧集序号。 */ episodeNo: number
/** 节拍序号。 */ beatNo: number
/** 镜头序号。 */ shotNo: number
/** 镜头标题。 */ title: string
/** 历史主图数量。 */ primaryCount: number
/** 原主图记录。 */ primary: ImpactCandidate | null
/** 审核任务数量。 */ visionTaskCount: number
/** 全部历史候选。 */ candidates: ImpactCandidate[]
}>
/** 按正式场景关联的旧 Anchor 与 Form。 */ assets: Array<{
/** 场景身份。 */ subjectId: string
/** 场景引用。 */ ref: string
/** 场景名称。 */ name: string
/** 原形态和主图。 */ forms: Array<{
/** 原记录编号。 */ id: string
/** 正式名称。 */ name: string
/** 形态原主图。 */ primaryImages: Array<{
/** 原记录编号。 */ id: string
/** 原图片地址。 */ imageUrl: string | null
/** 原件可读取状态。 */ fileStatus: 'readable' | 'unavailable'
/** 来源当前性及原因。 */ currentness: { current: boolean; reason?: string | null }
}>
}>
/** 原身份锚图,只给出待重验,不能假定来源已通过。 */ anchors: Array<{
/** 原记录编号。 */ id: string
/** 原图片地址。 */ imageUrl: string | null
/** 原件可读取状态。 */ fileStatus: 'readable' | 'unavailable'
/** 需重新核验,不自动重生。 */ action: 'revalidate'
}>
}>
/** 不允许直接生成。 */ generationAllowed: false
/** 公开限制。 */ limitation: string
}
@@ -0,0 +1,316 @@
import { computed, onScopeDispose, ref, shallowRef, watch } from 'vue'
import { useQuery } from '../../composables/useQuery'
import { ApiError, errorMessage } from '../../lib/http'
import { useActionMessage, showActionFeedback } from '../../components/ui/useActionMessage'
import { generationConfigApi } from '../generation-config/api'
import type { GenerationOptions } from '../generation-config/types'
import { getOperation, runOperation } from '../workflows/operations'
import { imageRequestNotice, runGuardedImageRequest } from '../subject-images/image-request-guard'
import { spatialMasterApi } from './api'
import { canUseMasterReference, toMasterPreview } from './model'
import type { MasterGenerationReceipt, MasterPreview, SceneMaster, SpatialLayout } from './types'
/**
* 免费预检和单次付费生成,版本或输入变化必须重新确认;断线不重发。
* @param props 当前项目、布局、母版和活动锁
* @param changed 原范围内成功生成后的刷新通知
* @param stale 原范围来源冲突时的只读刷新通知
* @returns 表单、实际预览和受费用保护的提交入口
*/
export function useMasterGeneration(
props: { projectId: string; layout: SpatialLayout; masters: SceneMaster[]; disabled: boolean },
changed: (receipt: MasterGenerationReceipt) => void,
stale: () => void
) {
/** 用户明确选择的参考,不默认选取旧图。 */
const referenceId = ref('')
/** 显式图片修订模式,不修改正式布局。 */
const revisionMode = ref(false)
/** 用户本次限定修订。 */
const instruction = ref('')
/** 本次选择的模型。 */
const provider = ref('')
/** 本次明确参数。 */
const options = ref<GenerationOptions>({})
/** 原项目配置查询身份。 */
const context = computed(() => JSON.stringify([props.projectId, props.layout.id]))
/** 复用现有目录和配置,切项目取消旧请求。 */
const config = useQuery(
computed(() => props.projectId),
async (projectId, signal) => {
const [catalog, profile] = await Promise.all([
generationConfigApi.catalog(signal),
generationConfigApi.profile(projectId, signal)
])
if (profile && profile.projectId !== projectId) throw new Error('生成配置不属于当前项目。')
return { catalog, profile }
}
)
/** 已取得有效的启用图片模型,不猜测默认模型。 */
const modelReady = computed(
() =>
!!config.data.value?.profile &&
!config.error.value &&
!!config.data.value.catalog.images.find(item => item.provider === provider.value && item.enabled)
)
/** 当前模式真正允许选择的正式参考。 */
const references = computed(() =>
props.masters.filter(
item =>
item.projectId === props.projectId &&
item.spatialLayoutId === props.layout.id &&
canUseMasterReference(item, props.layout.version, revisionMode.value)
)
)
/** 用户选中的原始母版。 */
const selectedReference = computed(() =>
props.masters.find(
item =>
item.id === referenceId.value &&
item.projectId === props.projectId &&
item.spatialLayoutId === props.layout.id
)
)
/** 同一参数对象贯穿预检和正式提交。 */
const input = computed(() => ({
expectedVersion: props.layout.version,
...(referenceId.value ? { referenceMasterId: referenceId.value } : {}),
...(revisionMode.value ? { revisionInstruction: instruction.value.trim() } : {}),
providerName: provider.value,
generationOptions: { ...options.value }
}))
/** 校验只控制操作,不在打开空表单时显示红色错误。 */
const valid = computed(
() =>
modelReady.value &&
(!referenceId.value || references.value.some(item => item.id === referenceId.value)) &&
(!revisionMode.value ||
(!!referenceId.value && !!instruction.value.trim() && instruction.value.trim().length <= 2000))
)
/** 只有本次参数和原件状态完全相同时才保留预览。 */
const identity = computed(() =>
JSON.stringify([
context.value,
input.value,
props.masters.map(item => [item.id, item.status, item.updatedAt, item.imageUrl, item.spatialLayoutVersion])
])
)
/** 只在内存保存本次免费预检,不持久化 Base64。 */
const preview = shallowRef<MasterPreview | null>(null)
/** 独立确认一次生成费用和范围。 */
const acknowledged = ref(false)
/** 免费预览加载不锁关闭。 */
const loading = ref(false)
/** 同步长请求进行中不重复提交。 */
const submitting = ref(false)
/** 原任务的未知费用保护不随选项变化解除。 */
const recoveryTarget = computed(() => `scene-layout-master:${props.projectId}:${props.layout.id}`)
/** 同项目活动任务和来源限制沿用既有操作锁。 */
const canSubmit = computed(
() =>
valid.value &&
!!preview.value &&
acknowledged.value &&
!loading.value &&
!submitting.value &&
!props.disabled &&
!getOperation(props.projectId).pending &&
!imageRequestNotice(recoveryTarget.value)
)
/** 只在请求结束后显示未知结果提示。 */
const recoveryNotice = computed(() => (submitting.value ? '' : imageRequestNotice(recoveryTarget.value)))
/** 消息层统一反馈。 */
const message = useActionMessage()
/** 取消旧预检并拒绝相同参数的迟到结果。 */
let revision = 0
/** 免费请求可取消,付费提交保持观察。 */
let controller: AbortController | undefined
/** 组件卸载后不回填。 */
let disposed = false
/** 清除本次预览与费用勾选,保留未知费用标记。 */
function invalidate() {
revision++
controller?.abort()
preview.value = null
acknowledged.value = false
loading.value = false
}
watch(identity, invalidate, { flush: 'sync' })
watch(
context,
() => {
referenceId.value = ''
revisionMode.value = false
instruction.value = ''
provider.value = ''
options.value = {}
},
{ flush: 'sync' }
)
watch(
[() => config.data.value, context],
([data]) => {
if (!data?.profile || data.profile.projectId !== props.projectId) return
const model = data.catalog.images.find(
item => item.enabled && item.provider === data.profile!.imageProvider
)
if (model) {
provider.value = model.provider
options.value = { ...model.defaults, ...data.profile.imageOptions }
}
},
{ immediate: true }
)
watch(
references,
items => {
if (referenceId.value && !items.some(item => item.id === referenceId.value)) referenceId.value = ''
},
{ flush: 'sync' }
)
onScopeDispose(() => {
disposed = true
invalidate()
})
/**
* 只读编译实际生成输入,并验证版本、参考和完整指纹。
* @returns 当前预检结束
*/
async function loadPreview() {
if (!valid.value || submitting.value || loading.value) return
invalidate()
const current = revision
const target = identity.value
const projectId = props.projectId
const layoutId = props.layout.id
const snapshot = JSON.parse(JSON.stringify(input.value)) as typeof input.value
controller = new AbortController()
loading.value = true
try {
const result = await spatialMasterApi.preflight(projectId, layoutId, snapshot, controller.signal)
if (disposed || target !== identity.value || current !== revision) return
if (
!result ||
result.layoutId !== layoutId ||
result.layoutVersion !== snapshot.expectedVersion ||
result.referenceMasterId !== (snapshot.referenceMasterId ?? null) ||
result.revisionInstruction !== (snapshot.revisionInstruction ?? null) ||
result.provider !== snapshot.providerName ||
!result.model ||
!result.prompt?.trim() ||
!/^[a-f0-9]{64}$/.test(result.previewFingerprint) ||
!Array.isArray(result.references) ||
result.referenceCount !== result.references.length ||
result.references.some(item => !item.providerInputResolved)
)
throw new Error('母版预检与当前输入不一致,请重新核对。')
preview.value = toMasterPreview(result)
} catch (cause) {
if (!disposed && target === identity.value && current === revision)
showActionFeedback(message, errorMessage(cause), 'error')
} finally {
if (current === revision) loading.value = false
}
}
/**
* 固定同次免费输入,只提交一个生成请求,未知费用永不自动重发。
* @returns 单次请求与必要只读核查完成
*/
async function submit() {
if (!canSubmit.value || !preview.value) return
const target = identity.value
const requestRevision = revision
const projectId = props.projectId
const layoutId = props.layout.id
const version = props.layout.version
const guard = recoveryTarget.value
const snapshot = JSON.parse(
JSON.stringify({
...input.value,
expectedPreviewFingerprint: preview.value.previewFingerprint,
confirmPaidGeneration: true as const
})
) as typeof input.value & { expectedPreviewFingerprint: string; confirmPaidGeneration: true }
acknowledged.value = false
submitting.value = true
const ok = await runOperation(projectId, '生成一张空间母版草稿', async () => {
const before = await spatialMasterApi.jobs(projectId, layoutId)
if (
before.some(
job =>
job.projectId !== projectId ||
job.spatialLayoutId !== layoutId ||
!['completed', 'failed'].includes(job.status)
)
)
throw new Error('已有母版任务进行中或结果待核查,请刷新任务记录。')
if (disposed || target !== identity.value || requestRevision !== revision)
throw new Error('已离开原母版输入,本次未提交。')
return runGuardedImageRequest(
guard,
async () => {
const receipt = await spatialMasterApi.generate(projectId, layoutId, snapshot)
if (
!receipt ||
receipt.status !== 'completed' ||
!receipt.jobId ||
!receipt.masterId ||
!receipt.imageUrl
)
throw new Error('生成回执不完整,请先读取任务记录,勿再次生图。')
if (!disposed && target === identity.value && requestRevision === revision) {
preview.value = null
changed(receipt)
}
return receipt
},
{
confirmRejection: async cause => {
if (!(cause instanceof ApiError) || ![400, 409].includes(cause.status)) return false
const after = await spatialMasterApi.jobs(projectId, layoutId)
return after.every(
job =>
job.projectId === projectId &&
job.spatialLayoutId === layoutId &&
before.some(old => old.id === job.id)
)
}
}
)
})
submitting.value = false
if (disposed || target !== identity.value || requestRevision !== revision) return
if (ok) showActionFeedback(message, '已生成母版草稿,尚未完成质量审核与人工确认。', 'info')
else {
const operation = getOperation(projectId)
showActionFeedback(message, operation.error, 'error')
preview.value = null
if (
operation.cause instanceof ApiError &&
operation.cause.status === 409 &&
props.layout.version === version
)
stale()
}
}
return {
referenceId,
revisionMode,
instruction,
provider,
options,
config,
modelReady,
references,
selectedReference,
valid,
preview,
acknowledged,
loading,
submitting,
canSubmit,
recoveryNotice,
loadPreview,
submit
}
}
@@ -1,4 +1,5 @@
<script setup lang="ts">
import SceneMasterManager from '../spatial-layouts/components/SceneMasterManager.vue'
import { userFacingText } from '../../lib/user-facing-text'
import { isOperationRunning } from '../workflows/operations'
@@ -67,6 +68,27 @@ const {
generate,
generateProject
} = useSubjectImages()
/** 母版管理复用原场景来源入口,图库关闭后再打开。 */
const masterOpen = ref(false)
/** 用户从真实来源布局选择的范围。 */
const masterLayoutId = ref('')
/**
* 在原图库释放焦点后打开同项目布局母版管理。
* @param layoutId 已读取的正式布局
*/
function manageLayout(layoutId: string) {
masterLayoutId.value = layoutId
masterOpen.value = true
}
/** 项目切换不能保留旧布局抽屉。 */
watch(
id,
() => {
masterOpen.value = false
masterLayoutId.value = ''
},
{ flush: 'sync' }
)
const sourceShotId = computed(() => queryText(route.query.sourceShotId))
const targetFormId = computed(() => queryText(route.query.subjectFormId))
const targetForm = computed(() => forms.value.find(form => form.id === targetFormId.value))
@@ -755,8 +777,16 @@ const rules = { concurrency: integerRule('批量并发'), limit: integerRule('
:project-id="id"
:form="galleryForm"
:disabled="blocked || !galleryForm"
@changed="refreshAssets" /></template
@changed="refreshAssets"
@manage-layout="manageLayout" /></template
></WorkspacePage>
<!-- 以下是从场景来源入口展开的空间母版管理模块 -->
<SceneMasterManager
v-model:open="masterOpen"
:project-id="id"
:layout-id="masterLayoutId"
@changed="refreshAssets"
/>
<!-- 以下是免费图片准备计划全屏模块 -->
<ImagePreparationDrawer v-model:open="preparationOpen" :project-id="id" />
</template>
@@ -18,6 +18,8 @@ const props = defineProps<{
/** 正式形态。 */ form: SubjectFormAsset
/** 当前项目编号。 */ projectId: string
}>()
/** 交给所属图库在关闭离场后打开母版管理,避免叠加主界面。 */
const emit = defineEmits<{ manageLayout: [layoutId: string] }>()
/** 来源折叠区域的打开状态。 */
const expanded = ref<string[]>([])
/** 只按当前形态和项目读取,关闭取消旧请求。 */
@@ -218,7 +220,12 @@ function episodeLabel(id: string) {
此场景有多个布局,请先选定适用范围。
</p>
<section v-for="layout in query.data.value.layouts" :key="layout.id" class="space-y-3">
<h3 class="font-medium">{{ layout.name }}</h3>
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="font-medium">{{ layout.name }}</h3>
<NButton class="workspace-action-button" size="small" @click="emit('manageLayout', layout.id)"
>空间母版管理</NButton
>
</div>
<p class="text-muted break-all">当前几何版本 {{ layout.version }}</p>
<p v-if="!layout.masters.length" class="text-muted">尚无当前形态的机位或全局空间参考。</p>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
@@ -25,7 +25,24 @@ const props = defineProps<{ projectId: string; form: SubjectFormAsset | null; di
/** 全屏图库开关。 */
const open = defineModel<boolean>('open', { default: false })
/** 成功保存质量或主图后刷新外部列表。 */
const emit = defineEmits<{ changed: [] }>()
const emit = defineEmits<{ changed: []; manageLayout: [layoutId: string] }>()
/** 关闭离场后再移交焦点到母版管理,只保留当前项目目标。 */
const pendingLayout = ref<{ projectId: string; layoutId: string } | null>(null)
/**
* 来源入口请求打开母版管理,先关闭当前全屏图库。
* @param layoutId 正式布局编号
*/
function manageLayout(layoutId: string) {
if (pending.value) return
pendingLayout.value = { projectId: props.projectId, layoutId }
open.value = false
}
/** 图库焦点约束释放后才进入另一个全屏工作区。 */
function galleryClosed() {
const target = pendingLayout.value
pendingLayout.value = null
if (target && target.projectId === props.projectId && !open.value) emit('manageLayout', target.layoutId)
}
/** 当前查看的图片编号。 */
const selectedId = ref('')
/** 当前底栏确认操作,打开图库时不会自动调用审核。 */
@@ -287,6 +304,7 @@ async function confirmAction() {
<template>
<AppDrawer
v-model:open="open"
@closed="galleryClosed"
:title="`${form?.subject.name || ''} · ${form?.name || '形态图片'}`"
description="切换主图后,请复核已有视频提示词。"
:busy="!!pending"
@@ -549,6 +567,7 @@ async function confirmAction() {
</p>
<!-- 以下是道具与场景的上游来源检查,可独立于候选图片阅读 -->
<FormSourceDiagnostics
@manage-layout="manageLayout"
v-if="open && form && (form.subject.module === 'prop' || form.subject.module === 'scene')"
:key="form.id"
:form="form"
@@ -15,6 +15,8 @@ interface ImageRequestGuardOptions {
evidence?: ImageRequestEvidence
/** 对该入口可证明在付费前拒绝的 HTTP 状态。 */
rejectionStatuses?: readonly number[]
/** 明确错误后可通过正式只读任务证据确认未受理;查证失败继续保留费用保护。 */
confirmRejection?: (cause: unknown) => Promise<boolean>
}
/** 当前标签页的提交记录,与表单关闭和页面刷新独立。 */
@@ -112,9 +114,16 @@ export async function runGuardedImageRequest<T>(
clearMarker(target, marker.id)
return result
} catch (cause) {
// 断线、网关超时、畸形回执或审核后保存冲突继续待核查。
if (cause instanceof ApiError && options.rejectionStatuses?.includes(cause.status))
clearMarker(target, marker.id)
// 断线、网关超时和付费后的保存冲突不能仅凭 HTTP 状态解锁。
let rejected = cause instanceof ApiError && options.rejectionStatuses?.includes(cause.status)
if (!rejected && options.confirmRejection) {
try {
rejected = await options.confirmRejection(cause)
} catch {
/* 无法查证时继续保留保护。 */
}
}
if (rejected) clearMarker(target, marker.id)
throw cause
}
}
@@ -1,3 +1,4 @@
import { spatialMasterApi } from '../spatial-layouts/api'
import { request } from '../../lib/http'
/** 服务端提供的道具当前规格及来源证据。 */
@@ -97,17 +98,21 @@ export const sourceDiagnosticsApi = {
* @param signal 关闭诊断时取消
* @returns 按布局分组的实际参考及其记录状态
*/
async scene(projectId: string, subjectId: string, formId: string, signal?: AbortSignal) {
const path = `/projects/${encodeURIComponent(projectId)}/shared-spatial-layouts`
const layouts = (await request<SceneLayout[]>(path, { signal })).filter(layout =>
async scene(
projectId: string,
subjectId: string,
formId: string,
signal?: AbortSignal
): Promise<Array<SceneLayout & { masters: SceneMaster[] }>> {
const layouts = (await spatialMasterApi.layouts(projectId, signal)).filter(layout =>
layout.sceneSubjectIds.includes(subjectId)
)
return Promise.all(
layouts.map(async layout => ({
...layout,
masters: (
await request<SceneMaster[]>(`${path}/${encodeURIComponent(layout.id)}/masters`, { signal })
).filter(master => master.subjectFormId === null || master.subjectFormId === formId)
masters: (await spatialMasterApi.masters(projectId, layout.id, signal)).filter(
master => master.subjectFormId === null || master.subjectFormId === formId
)
}))
)
}
@@ -0,0 +1,230 @@
import { effectScope, reactive } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useMasterGeneration } from '@/features/spatial-layouts/useMasterGeneration'
import { createMasterMock, spatialLayoutFixture } from '../../fixtures/spatial-masters'
/** 每个测试使用独立作用域与费用标记,不连接任何 Provider。 */
let scope = effectScope()
afterEach(() => {
scope.stop()
scope = effectScope()
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('母版输入来源与重复付费保护', () => {
it('明确 Draft 修订后绑定同次指纹;输入改变撤销费用勾选,成功只生成一次草稿', async () => {
const mock = createMasterMock()
vi.stubGlobal('fetch', mock.fetcher)
const generated = vi.fn<() => void>()
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const form = scope.run(() => useMasterGeneration(props, generated, () => {}))!
await flushPromises()
expect(mock.calls.every(call => call.method === 'GET')).toBe(true)
form.revisionMode.value = true
form.referenceId.value = 'draft'
form.instruction.value = '只调整转轴方向'
await form.loadPreview()
expect(form.preview.value?.preflight.referenceMasterId).toBe('draft')
form.acknowledged.value = true
form.instruction.value = '只调整门扇方向'
await flushPromises()
expect(form.preview.value).toBeNull()
expect(form.acknowledged.value).toBe(false)
await form.loadPreview()
form.acknowledged.value = true
await Promise.all([form.submit(), form.submit()])
const writes = mock.calls.filter(call => call.url.endsWith('/generate'))
expect(writes).toHaveLength(1)
expect(writes[0]!.body).toMatchObject({
referenceMasterId: 'draft',
revisionInstruction: '只调整门扇方向',
expectedPreviewFingerprint: 'f'.repeat(64),
confirmPaidGeneration: true,
expectedVersion: spatialLayoutFixture.version
})
expect(generated).toHaveBeenCalledTimes(1)
expect(mock.calls.some(call => call.url.endsWith('/validate') || call.url.endsWith('/confirm'))).toBe(false)
})
it('费用前 409 且任务未创建可重新免费预检;费用后冲突存在新任务则持续阻断', async () => {
const mock = createMasterMock()
vi.stubGlobal('fetch', mock.fetcher)
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const form = scope.run(() =>
useMasterGeneration(
props,
() => {},
() => {}
)
)!
await flushPromises()
form.referenceId.value = 'old'
await form.loadPreview()
form.acknowledged.value = true
mock.state.generationConflict = true
await form.submit()
expect(form.recoveryNotice.value).toBe('')
expect(form.preview.value).toBeNull()
mock.state.generationConflict = false
mock.state.afterPaidConflict = true
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(form.recoveryNotice.value).toContain('费用待核对')
form.instruction.value = '修改也不能绕过费用保护'
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(mock.calls.filter(call => call.url.endsWith('/generate'))).toHaveLength(2)
})
it('付费阶段的 400 不能当成未收费,必须按新任务证据保持阻断', async () => {
const mock = createMasterMock()
mock.state.afterPaidConflict = true
mock.state.generationErrorStatus = 400
vi.stubGlobal('fetch', mock.fetcher)
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const form = scope.run(() =>
useMasterGeneration(
props,
() => {},
() => {}
)
)!
await flushPromises()
form.referenceId.value = 'old'
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(form.recoveryNotice.value).toContain('费用待核对')
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(mock.calls.filter(call => call.url.endsWith('/generate'))).toHaveLength(1)
})
it('200 畸形回执不当作成功,保留未知费用且不自动重发', async () => {
const mock = createMasterMock()
const fetcher = vi.fn<typeof fetch>(async (input, init) =>
String(input).endsWith('/generate')
? new Response(JSON.stringify({ data: null }))
: mock.fetcher(input, init)
)
vi.stubGlobal('fetch', fetcher)
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const generated = vi.fn<() => void>()
const form = scope.run(() => useMasterGeneration(props, generated, () => {}))!
await flushPromises()
form.referenceId.value = 'old'
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(form.recoveryNotice.value).toContain('费用待核对')
expect(generated).not.toHaveBeenCalled()
await form.submit()
expect(fetcher.mock.calls.filter(([input]) => String(input).endsWith('/generate'))).toHaveLength(1)
})
it('连接中断保持费用保护;关闭并刷新观察器不自动重发', async () => {
const mock = createMasterMock()
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async (input, init) => {
if (String(input).endsWith('/generate')) throw new TypeError('网络中断')
return mock.fetcher(input, init)
})
)
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const form = scope.run(() =>
useMasterGeneration(
props,
() => {},
() => {}
)
)!
await flushPromises()
form.referenceId.value = 'old'
await form.loadPreview()
form.acknowledged.value = true
await form.submit()
expect(form.recoveryNotice.value).toContain('费用待核对')
scope.stop()
scope = effectScope()
const restored = scope.run(() =>
useMasterGeneration(
props,
() => {},
() => {}
)
)!
await flushPromises()
expect(restored.recoveryNotice.value).toContain('费用待核对')
expect(restored.canSubmit.value).toBe(false)
})
it('切项目和同项目切布局都清除旧参考与预检,迟到响应不回填', async () => {
const mock = createMasterMock()
let resolveOld!: (response: Response) => void
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async (input, init) =>
String(input).endsWith('/generation-preflight')
? new Promise(resolve => {
resolveOld = resolve
})
: mock.fetcher(input, init)
)
)
const props = reactive({
projectId: 'p',
layout: { ...spatialLayoutFixture },
masters: mock.state.masters,
disabled: false
})
const form = scope.run(() =>
useMasterGeneration(
props,
() => {},
() => {}
)
)!
await flushPromises()
form.referenceId.value = 'old'
const loading = form.loadPreview()
await flushPromises()
props.projectId = 'p2'
props.layout = { ...spatialLayoutFixture, id: 'layout2', projectId: 'p2' }
await flushPromises()
resolveOld(
new Response(JSON.stringify({ data: { layoutId: 'layout', layoutVersion: spatialLayoutFixture.version } }))
)
await loading
expect(form.preview.value).toBeNull()
expect(form.referenceId.value).toBe('')
expect(form.provider.value).toBe('mock')
props.layout = { ...props.layout, id: 'layout3' }
await flushPromises()
expect(form.provider.value).toBe('mock')
})
})
@@ -0,0 +1,108 @@
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { NCheckbox, NInput, NSelect, NTabs } from 'naive-ui'
import { afterEach, describe, expect, it, vi } from 'vitest'
import SceneMasterManager from '@/features/spatial-layouts/components/SceneMasterManager.vue'
import { createMasterMock } from '../../fixtures/spatial-masters'
/** 固定栏与长内容在 Chrome 验收,组件层使用实际表单和正式接口 Mock。 */
let wrapper: VueWrapper
/**
* 点击可见业务按钮,保留实际提交门禁。
* @param label 完整按钮名称
*/
async function click(label: string) {
const button = wrapper.findAll('button').find(item => item.text() === label)
expect(button).toBeDefined()
await button!.trigger('click')
await flushPromises()
}
/**
* 创建隔离管理页,不把初始读取变成审核或生成。
* @returns 请求 Mock 状态
*/
async function setup() {
const mock = createMasterMock()
vi.stubGlobal('fetch', mock.fetcher)
wrapper = mount(SceneMasterManager, {
props: { open: true, projectId: 'p', layoutId: 'layout' },
global: { stubs: { AppDrawer: { template: '<div><slot/><slot name="footer"/></div>' }, AssetImage: true } }
})
await flushPromises()
return mock
}
afterEach(() => {
wrapper?.unmount()
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('F04 空间母版管理增量流程', () => {
it('打开不调用 Provider,确认历史不冒充当前母版,预检没有报价不伪造金额', async () => {
const mock = await setup()
expect(wrapper.text()).toContain('暂无当前版本已确认母版')
expect(wrapper.text()).toContain('机器:AI 视觉审核未通过或未运行')
expect(mock.calls.every(call => call.method === 'GET')).toBe(true)
expect(wrapper.findAll('.n-form-item--error')).toHaveLength(0)
wrapper.findComponent(NTabs).vm.$emit('update:value', 'generate')
await flushPromises()
await click('免费预检母版输入')
expect(wrapper.text()).toContain('预检接口未提供报价')
expect(wrapper.text()).not.toContain('¥0.60')
expect(mock.calls.filter(call => call.url.endsWith('/generate'))).toHaveLength(0)
})
it('人工逐项确认使用真实身份和版本,独立保存 Human Passed,不自动 Vision', async () => {
const mock = await setup()
const select = wrapper
.findAllComponents(NSelect)
.find(item => item.attributes('aria-label') === '第 1 项人工结论')!
select.vm.$emit('update:value', 'passed')
for (const input of wrapper.findAllComponents(NInput)) {
const placeholder = input.props('placeholder')
input.vm.$emit('update:value', placeholder === '填写真实确认人' ? 'goujun' : '清晰可见固定连接位置')
}
await flushPromises()
await click('正式人工确认母版')
expect(mock.calls.filter(call => call.url.endsWith('/confirm'))).toHaveLength(1)
expect(mock.calls.filter(call => call.url.endsWith('/validate'))).toHaveLength(0)
expect(wrapper.text()).toContain('人工:人工审核通过')
expect(wrapper.text()).toContain('机器:AI 视觉审核未通过或未运行')
const body = mock.calls.find(call => call.url.endsWith('/confirm'))!.body
expect(body.confirmedBy).toBe('goujun')
expect(body.reviewResults).toEqual([{ index: 1, result: 'passed', evidence: '清晰可见固定连接位置' }])
})
it('AI 通过仍为 Draft,不自动填人工通过或确认;必须独立勾选费用', async () => {
const mock = await setup()
const button = wrapper.findAll('button').find(item => item.text() === 'AI 视觉审核')!
expect(button.attributes('disabled')).toBeDefined()
wrapper
.findAllComponents(NCheckbox)
.find(item => item.text().includes('单独确认'))!
.vm.$emit('update:checked', true)
await flushPromises()
await click('AI 视觉审核')
expect(wrapper.text()).toContain('机器:AI 视觉审核通过')
expect(wrapper.text()).toContain('资产:草稿')
expect(mock.calls.filter(call => call.url.endsWith('/confirm'))).toHaveLength(0)
expect(
wrapper
.findAll('button')
.find(item => item.text() === '正式人工确认母版')!
.attributes('disabled')
).toBeDefined()
})
it('按需读取来源影响,原件可读与过期独立展示,不改历史 Primary', async () => {
const mock = await setup()
expect(mock.calls.filter(call => call.url.endsWith('/recovery-impact'))).toHaveLength(0)
wrapper.findComponent(NTabs).vm.$emit('update:value', 'impact')
await flushPromises()
expect(wrapper.text()).toContain('图片原件有效 ≠ 来源当前有效')
expect(wrapper.text()).toContain('关联镜头8')
const headings = wrapper.findAll('.n-collapse-item__header-main')
await headings.find(item => item.text().includes('星港相遇'))!.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('原件与原审核一致')
expect(wrapper.text()).toContain('布局版本已变化')
expect(wrapper.text()).toContain('历史主首帧(Primary)')
expect(wrapper.text()).toContain('需要重新核验')
expect(mock.calls.every(call => call.method === 'GET')).toBe(true)
})
})
@@ -0,0 +1,151 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { spatialMasterApi } from '@/features/spatial-layouts/api'
import {
canUseMasterReference,
masterReviewLabels,
toMasterPreview,
impactVisionLabel
} from '@/features/spatial-layouts/model'
import { runGuardedImageRequest, imageRequestNotice } from '@/features/subject-images/image-request-guard'
/** 所有请求均由隔离 Mock 接收,禁止连接真实 Provider。 */
afterEach(() => {
sessionStorage.clear()
vi.unstubAllGlobals()
})
describe('F04 母版正式契约与独立证据', () => {
it('历史及草稿修订预检、生成复用同一参数与指纹', async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ data: {} })))
vi.stubGlobal('fetch', fetcher)
const input = {
expectedVersion: 'a'.repeat(64),
referenceMasterId: 'draft',
revisionInstruction: '仅调整活动方向',
providerName: 'provider',
generationOptions: { size: '2048x2048' }
}
await spatialMasterApi.preflight('p/a', 'l/b', input)
await spatialMasterApi.generate('p/a', 'l/b', {
...input,
expectedPreviewFingerprint: 'f'.repeat(64),
confirmPaidGeneration: true
})
expect(String(fetcher.mock.calls[0]![0])).toBe(
'/api/projects/p%2Fa/shared-spatial-layouts/l%2Fb/masters/generation-preflight'
)
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual(input)
expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual({
...input,
expectedPreviewFingerprint: 'f'.repeat(64),
confirmPaidGeneration: true
})
})
it('来源影响、人工清单和单独 Vision 使用正式路径及独立费用确认', async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ data: {} })))
vi.stubGlobal('fetch', fetcher)
await spatialMasterApi.impact('p', 'l', new AbortController().signal)
await spatialMasterApi.review('p', 'l', 'm')
await spatialMasterApi.validate('p', 'l', 'm')
await spatialMasterApi.confirm('p', 'l', 'm', {
expectedVersion: 'a'.repeat(64),
evidence: '人工依据',
confirmedBy: '审核人',
reviewResults: [{ index: 1, result: 'passed', evidence: '连接位置可见' }]
})
expect(fetcher.mock.calls.map(([url]) => String(url))).toEqual([
'/api/projects/p/shared-spatial-layouts/l/masters/recovery-impact',
'/api/projects/p/shared-spatial-layouts/l/masters/m/review',
'/api/projects/p/shared-spatial-layouts/l/masters/m/validate',
'/api/projects/p/shared-spatial-layouts/l/masters/m/confirm'
])
expect(JSON.parse(String(fetcher.mock.calls[2]![1]?.body))).toEqual({ confirmPaidValidation: true })
})
it('草稿只有明确修订且属于当前布局版本才能作参考,人工通过不冒充 Vision 通过', () => {
expect(canUseMasterReference({ status: 'draft', spatialLayoutVersion: 'old' }, 'now', true)).toBe(false)
expect(canUseMasterReference({ status: 'draft', spatialLayoutVersion: 'now' }, 'now', false)).toBe(false)
expect(canUseMasterReference({ status: 'draft', spatialLayoutVersion: 'now' }, 'now', true)).toBe(true)
expect(canUseMasterReference({ status: 'confirmed', spatialLayoutVersion: 'old' }, 'now', false)).toBe(true)
expect(
masterReviewLabels({
status: 'confirmed',
currentVersion: true,
reviewStatus: 'human_passed',
automatedVisionPassed: false
})
).toMatchObject({ human: '人工审核通过', vision: 'AI 视觉审核未通过或未运行', asset: '已确认' })
})
it('完成但质量待复核不能展示通过,历史分步证据缺失明确保留未知', () => {
expect(
impactVisionLabel({
id: 'v',
status: 'completed',
passed: true,
qualityDecision: 'needs_review',
evidenceComplete: true,
historical: true
})
).toBe('原结论待人工复核')
expect(
impactVisionLabel({
id: 'v',
status: 'running',
passed: true,
qualityDecision: 'passed',
evidenceComplete: true,
historical: false
})
).toBe('原审核未完成')
})
it('适配预检时保留原始参数和参考摘要,不虚构预计费用或正式确认', () => {
const result = toMasterPreview({
layoutId: 'l',
layoutVersion: 'a'.repeat(64),
provider: 'provider',
model: 'model',
generationOptions: { size: '2048x2048' },
prompt: '最终画面描述',
references: [
{
imageId: 'm',
imageUrl: '/storage/m.png',
providerImageUrl: 'data:image/png;base64,AA==',
providerInputResolved: true,
role: 'layout-master',
sourceMasterStatus: 'draft'
}
],
previewFingerprint: 'f'.repeat(64),
referenceMasterId: 'm',
revisionInstruction: '修订',
referenceCount: 1,
verifiedSceneCount: 2,
maxReferenceImages: 10,
generationAllowed: false,
reason: '免费预检'
})
expect(result.providerPrompt).toBe('最终画面描述')
expect(result.referenceImages).toEqual(['/storage/m.png'])
expect(result.previewFingerprint).toBe('f'.repeat(64))
})
it('仅在请求确定被拒绝且只读证据证明没有创建任务时解除费用保护', async () => {
const target = 'master-reject'
const reject = new Error('来源过期')
const proof = vi.fn<() => Promise<boolean>>().mockResolvedValue(true)
await expect(
runGuardedImageRequest(
target,
async () => {
throw reject
},
{ confirmRejection: proof }
)
).rejects.toBe(reject)
expect(imageRequestNotice(target)).toBe('')
const calls = vi.fn<() => Promise<void>>().mockRejectedValue(new Error('连接中断'))
await expect(runGuardedImageRequest(target, calls, { confirmRejection: async () => false })).rejects.toThrow(
'连接中断'
)
await expect(runGuardedImageRequest(target, calls)).rejects.toThrow('费用待核对')
expect(calls).toHaveBeenCalledTimes(1)
})
})
+349
View File
@@ -0,0 +1,349 @@
import type {
MasterRecoveryImpact,
MasterReview,
SceneMaster,
SpatialLayout,
MasterJob
} from '@/features/spatial-layouts/types'
import type { GenerationModelCatalog, CreativeProfile } from '@/features/generation-config/types'
/** 隔离当前几何版本,不引用真实项目。 */
export const masterVersion = 'a'.repeat(64)
/** 正式布局的跨题材夹具。 */
export const spatialLayoutFixture: SpatialLayout = {
id: 'layout',
projectId: 'p',
name: '星港中枢共享空间',
version: masterVersion,
sceneSubjectIds: ['scene']
}
/**
* 构造正式草稿/确认母版,图片仅为隔离地址。
* @param patch 当前测试差异
* @returns 母版资产
*/
export function sceneMasterFixture(patch: Partial<SceneMaster> = {}): SceneMaster {
return {
id: 'draft',
projectId: 'p',
spatialLayoutId: 'layout',
spatialLayoutVersion: masterVersion,
imageUrl: '/storage/mock-master.png',
status: 'draft',
subjectFormId: null,
viewDescription: null,
evidence: null,
confirmedBy: null,
confirmedAt: null,
visionReviewedAt: null,
createdAt: '2026-11-07T00:00:00Z',
updatedAt: '2026-11-07T00:00:00Z',
...patch
}
}
/** 隔离项目已保存的模型配置。 */
export const masterProfile: CreativeProfile = {
projectId: 'p',
aspectRatio: '1:1',
imageProvider: 'mock',
imageModel: 'mock-model',
imageOptions: { size: '2048x2048' },
videoProvider: 'mock-video',
videoModel: 'mock-video',
videoOptions: {}
}
/** 使用正式目录结构,仅暴露一个测试模型。 */
export const masterCatalog: GenerationModelCatalog = {
defaults: { imageProvider: 'mock', videoProvider: 'mock-video' },
images: [
{
type: 'image',
provider: 'mock',
providerLabel: '隔离图片模型',
model: 'mock-model',
modelLabel: '测试模型',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [],
defaults: { size: '2048x2048' },
projectConstraints: []
}
],
videos: []
}
/**
* 独立人工与机器证据,确认不改变机器结论。
* @param master 指定母版
* @param visionPassed 本次正式机器证据
* @returns 正式审核材料
*/
export function masterReviewFixture(master: SceneMaster, visionPassed = false): MasterReview {
const current = master.spatialLayoutVersion === masterVersion
return {
masterId: master.id,
imageUrl: master.imageUrl,
layoutId: 'layout',
layoutVersion: masterVersion,
currentVersion: current,
status: master.status,
reviewStatus: master.status === 'confirmed' && current ? 'human_passed' : 'needs_review',
automatedVisionPassed: visionPassed,
automatedVisionReview: visionPassed ? { summary: '隔离机器审核通过' } : null,
sceneSubjectIds: ['scene'],
subjectFormId: null,
viewDescription: null,
checklist: [
{
index: 1,
kind: 'structural-connection',
subjectId: 'scene',
referenceSubjectId: null,
requirement: '观察面内固定连接位置正确',
acceptance: '连接处可见',
result: 'needs_review'
}
],
canConfirm: current && master.status === 'draft',
humanReviewEvidence:
master.status === 'confirmed' && current
? {
summary: master.evidence || '人工证据',
compositionReviews: [{ index: 1, result: 'passed', evidence: '连接可见' }]
}
: null,
note: '人工与AI证据独立'
}
}
/** 真实影响结构:原件有效但来源过期,不能认定损坏或自动重生。 */
export const masterImpactFixture: MasterRecoveryImpact = {
projectId: 'p',
layoutId: 'layout',
layoutVersion: masterVersion,
currentMaster: null,
summary: {
affectedShots: 8,
primaryShots: 1,
shotsWithVision: 1,
shotsWithoutAssets: 7,
candidateCount: 1,
primaryRevalidationShots: 1
},
generationAllowed: false,
limitation: '不改变主图',
assets: [
{
subjectId: 'scene',
ref: '@SC001',
name: '星港中枢',
anchors: [{ id: 'anchor', imageUrl: '/storage/anchor.png', fileStatus: 'readable', action: 'revalidate' }],
forms: [
{
id: 'form',
name: '基础形态',
primaryImages: [
{
id: 'form-image',
imageUrl: '/storage/form.png',
fileStatus: 'readable',
currentness: { current: false, reason: '母版来源已变化' }
}
]
}
]
}
],
shots: [
{
shotId: 'shot',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
title: '星港相遇',
primaryCount: 1,
visionTaskCount: 1,
primary: null,
candidates: [
{
id: 'primary',
isPrimary: true,
status: 'completed',
imageUrl: '/storage/primary.png',
width: 2048,
height: 2048,
imageIntegrity: 'matches_review',
sourceStatus: 'layout_version_changed',
sourceReason: '布局版本已变化',
action: 'revalidate',
providerInputFingerprint: 'f'.repeat(64),
referenceEvidence: [],
latestVision: {
id: 'old-vision',
status: 'completed',
passed: true,
qualityDecision: 'passed',
evidenceComplete: true,
historical: true
}
}
]
}
]
}
/**
* 所有正式路由均隔离模拟;未匹配请求返回 404,不连接真实服务。
* @returns Mock 请求、调用记录及可调整状态
*/
export function createMasterMock() {
const calls: Array<{ url: string; method: string; body: Record<string, unknown> }> = []
const state = {
masters: [
sceneMasterFixture(),
sceneMasterFixture({ id: 'old', status: 'confirmed', spatialLayoutVersion: 'b'.repeat(64) })
],
jobs: [] as MasterJob[],
visionPassed: false,
visionMasterId: '',
generationConflict: false,
afterPaidConflict: false,
generationErrorStatus: 409 as 400 | 409
}
/**
* 隔离正式路由,不调用 Provider。
* @param input 请求地址
* @param init HTTP 参数
* @returns Mock 响应
*/
const fetcher: typeof fetch = async (input, init) => {
const url = new URL(String(input), 'http://localhost')
const path = url.pathname
const method = init?.method || 'GET'
const body = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
calls.push({ url: String(input), method, body })
let data: unknown
if (path === '/api/generation-models') data = masterCatalog
else if (path.endsWith('/creative-profile')) data = { ...masterProfile, projectId: path.split('/')[3] }
else if (path.endsWith('/shared-spatial-layouts')) data = [spatialLayoutFixture]
else if (path.endsWith('/generation-jobs')) data = state.jobs
else if (path.endsWith('/recovery-impact'))
data = {
...masterImpactFixture,
currentMaster:
state.masters.find(
item => item.status === 'confirmed' && item.spatialLayoutVersion === masterVersion
) ?? null
}
else if (path.endsWith('/confirmed'))
data =
state.masters.find(
item => item.status === 'confirmed' && item.spatialLayoutVersion === masterVersion
) ?? null
else if (path.endsWith('/generation-preflight'))
data = {
layoutId: 'layout',
layoutVersion: body.expectedVersion,
provider: body.providerName,
model: 'mock-model',
generationOptions: body.generationOptions,
prompt: '本次仅修订活动方向,保留星港结构。',
references: body.referenceMasterId
? [
{
imageId: body.referenceMasterId,
imageUrl: '/storage/mock-master.png',
providerImageUrl: 'data:image/png;base64,AA==',
providerInputResolved: true,
role: 'layout-master',
sourceLayoutVersion: state.masters.find(item => item.id === body.referenceMasterId)
?.spatialLayoutVersion,
sha256: 'd'.repeat(64),
pixelFingerprint: 'e'.repeat(64),
width: 800,
height: 800,
sourceMasterStatus: state.masters.find(item => item.id === body.referenceMasterId)?.status
}
]
: [],
referenceCount: body.referenceMasterId ? 1 : 0,
verifiedSceneCount: 2,
maxReferenceImages: 10,
referenceMasterId: body.referenceMasterId ?? null,
revisionInstruction: body.revisionInstruction ?? null,
previewFingerprint: 'f'.repeat(64),
generationAllowed: false,
reason: '免费预检'
}
else if (path.endsWith('/generate')) {
if (state.afterPaidConflict)
state.jobs.push({
id: 'interrupted-job',
projectId: 'p',
spatialLayoutId: 'layout',
spatialLayoutVersion: masterVersion,
status: 'interrupted',
referenceSnapshot: [],
provider: 'mock',
model: 'mock-model',
prompt: '已提交的原输入',
generationOptions: {},
imageUrl: null,
errorMessage: '保存失败',
createdAt: '2026-11-07',
updatedAt: '2026-11-07'
})
if (state.generationConflict || state.afterPaidConflict)
return new Response(JSON.stringify({ message: '空间布局版本已变化,请重新预检' }), {
status: state.generationErrorStatus
})
state.masters.unshift(sceneMasterFixture({ id: 'generated' }))
state.jobs.push({
id: 'job',
projectId: 'p',
spatialLayoutId: 'layout',
spatialLayoutVersion: masterVersion,
status: 'completed',
referenceSnapshot: [],
provider: 'mock',
model: 'mock-model',
prompt: '本次仅修订活动方向,保留星港结构。',
generationOptions: masterProfile.imageOptions,
imageUrl: '/storage/mock-master.png',
errorMessage: null,
createdAt: '2026-11-07',
updatedAt: '2026-11-07'
})
data = { jobId: 'job', masterId: 'generated', imageUrl: '/storage/mock-master.png', status: 'completed' }
} else if (path.endsWith('/review'))
data = masterReviewFixture(
state.masters.find(item => item.id === path.split('/').at(-2))!,
state.visionPassed && state.visionMasterId === path.split('/').at(-2)
)
else if (path.endsWith('/validate')) {
state.visionPassed = true
state.visionMasterId = path.split('/').at(-2)!
data = {
masterId: path.split('/').at(-2),
layoutId: 'layout',
layoutVersion: masterVersion,
currentVersion: true,
persisted: true,
automatedVisionPassed: true,
reviewStatus: 'passed',
summary: '隔离视觉审核通过'
}
} else if (path.endsWith('/confirm')) {
const master = state.masters.find(item => item.id === path.split('/').at(-2))!
Object.assign(master, {
status: 'confirmed',
evidence: body.evidence,
confirmedBy: body.confirmedBy,
confirmedAt: '2026-11-07T01:00:00Z'
})
data = master
} else if (path.endsWith('/masters')) data = state.masters
else return new Response(JSON.stringify({ message: '隔离测试未匹配请求' }), { status: 404 })
return new Response(JSON.stringify({ data }))
}
return { calls, state, fetcher }
}