diff --git a/docs/api-contract-sync.md b/docs/api-contract-sync.md index c29d87f..141d60b 100644 --- a/docs/api-contract-sync.md +++ b/docs/api-contract-sync.md @@ -1,5 +1,28 @@ # 接口数据同步说明 +## 2026-11-16 集中 Git 交付 + +按用户明确授权,将本轮全部52个文件(新增26、修改26、删除0)集中提交并推送到dev,主题为 `feat(short-drama-agent-front): 接入联合修订与图片费用审计`。范围包括环境原文依据、人工图片追加/费用审计、时间语义及分镜界面修复,保留正常提交钩子。以下“未提交/未推送”属于各功能验收时点;实际提交号、全量钩子结果和远端同步状态以本次Git记录为准。 + +## 2026-11-16 Beat6 有据环境修订 + +已按后端 `dev@cde30f09464c152447bb0adcee8c670b6ba917a4` 的环境修订 Prompt、正式 Schema/路由/事务接入原联合审核。环境四字段完整差异可编辑、保存和免费预览;存在环境差异才读取现有项目详情的正式本集 ID、projectId 与完整 content,原字节计算 SHA256,用户逐字引用后携带 jointRevision.environmentSource 免费预检和明确采用。 + +缺证、正文/归属缺失、版本冲突不放行;409保留输入并读取当前原文,不自动重提。原文/版本匹配不代表机器语义通过;原摄影、主体、场景模式和图片费用门禁保持独立。真实仅核对公开 GET,采用和冲突在全请求隔离的 Mock/Chrome 验证,没有正式项目写入或收费。 + +文件、契约、验证及边界见 [环境修订接入交接](audits/beat6-environment-frontend-2026-11-16.md)。本次增量覆盖下文旧基线“环境不可联合修改”的历史边界;既有页面精简、目录避让和工具栏优化保持。 + +## 2026-11-16 V8-9.4~V8-9.9 联合采用与图片费用 + +按指定后端 `dev@2d3abdab5f2656223ab98161dff6388200db281c` 的正式 Schema、路由与服务核对,前端从 `87427d9` 在根目录 `dev` 增量接入。复用原摄影审核抽屉、项目图片授权设置、首帧预览及 Workflow/SSE,不新增业务页面。 + +- 原保存草案增加联合模式:完整字段前后差异、当前摄影/开拍状态、邻镜版本、免费预检、人工确认和冻结请求采用。保存不表示采用;409 重读正式来源并保留输入,不自动重提;采用后刷新正式 Direction、VisualState 和首帧 Preview。 +- 原图片授权 POST 支持人工 `mode=additional`;不预选许可、不增加预算。原首帧入口主动选择许可并重新核对精确计划,只能发送一次明确操作;完整同计划结果优先只读查看。撤销/用尽/来源或范围变化继续阻断,原未知请求和预留保留。 +- 原授权设置内增加图片原请求费用审计,三个正式 API 分别读取、登记和独立复核。完整原身份及三项并发指纹来自 GET;登记不解锁,复核不改变原执行、质量和主图。未知账单保持未知;409 刷新正式 GET、保留表单并撤销确认。 +- VisualState 只按后端四种显式时间标记排版,原主体/环境显示当前开拍状态;规划末态、连续要求与真实视频末态分开。三种时间问题保留 code/severity/field 和镜头位置,待审不表示通过。 + +完整已有能力/缺口、文件职责、API 与 Mock/Chrome 验收、费用边界、未完成项及 Git 状态见 [本轮交接](audits/v8-9-4-9-frontend-integration-2026-11-16.md)。未执行真实收费模型或正式采用/证据登记/核清;未提交或推送。后端工作区另有并行未提交的环境修订,本轮按用户指定已提交基线实施,不修改后端或自动采用该后续扩展。 + ## 2026-11-15 V8-9.1 / V8-9.2 分阶段镜头生产 已在根目录 dev 增量接入正式 shotIds 定向摄影/画面状态、逐镜复用、派生批次停止、原 executionId 刷新恢复观察、独立摄影免费预检与版本绑定采用、原失败及零模型请求恢复展示,以及所选范围的参考素材/计划/资产缺口。默认 force=false、concurrency=1、maxRepairAttempts=0,不自动开始下一阶段或重发未知请求。 diff --git a/docs/audits/beat6-environment-frontend-2026-11-16.md b/docs/audits/beat6-environment-frontend-2026-11-16.md new file mode 100644 index 0000000..5681b76 --- /dev/null +++ b/docs/audits/beat6-environment-frontend-2026-11-16.md @@ -0,0 +1,68 @@ +# Beat6 有据环境修订前端交接 + +Git交付补充:用户已授权本轮全部前端改动集中提交并推送dev,本环境增量随 `feat(short-drama-agent-front): 接入联合修订与图片费用审计` 交付。下文未Commit/Push为功能验收时点,实际SHA和远端同步以本次仓库记录为准。 + +2026-11-16,前端根目录 dev,保留前几轮未提交改动,只增量修改前端,不新建 worktree。后端只读基线为已提交的 `cde30f09464c152447bb0adcee8c670b6ba917a4`,依据 `docs/audits/v02-beat6-environment-review-frontend-prompt.md`、公开 storyboard 契约及真实 Schema/路由/项目事务核对。 + +## 已有实现与新增范围 + +原摄影/开拍状态联合流程已经具备完整草案读取/保存、字段差异、本镜/邻镜版本、免费预检、冻结请求采用、幂等、409保护及固定底栏。此次只补环境四字段和本集原文依据,不创建新编辑器、API服务、任务/SSE、费用或质量流程。此前环境差异被白名单阻止属于旧基线,本轮扩展后不再作为越界;身份、Form、主体集合与正式动作仍不开放。 + +## 正式来源与接口 + +- 环境可变字段为 timeOfDay、weather、atmosphere、transientState,changes[] 使用 target=environment,before/after 均完整保留;天气未知保持空,不补晴天。 +- 沿原 GET/PUT keyframe-review-draft 保存完整原稿及 expectedRevision、expectedCurrentFormalSourceFingerprint。保存不采用,不额外往草案中塞入无契约字段,原 current/stale 与 staleReason 保留。 +- 沿原 POST keyframe/preview 免费取得草案、本镜派生和完整邻镜版本;草案指纹不提交生图。 +- 存在环境差异时,原 confirm 的 jointRevision 另带 environmentSource:episodeId、expectedContentFingerprint、quote。预检与正式采用冻结同一原稿/差异/原文/版本,仅切换 preview;依旧必须分别执行和人工确认。 +- 已核对现有 GET `/api/projects/:projectId` 的正式 ProjectEpisodeDto 及实际响应,确实公开本集 id/projectId/episode/content。按当前项目和集号取唯一正式集,校验 ID、归属、完整字符串正文,再用 TextEncoder + Web Crypto SHA-256 计算完整 content 的原字节版本;不使用 summary、截断正文、换行归一化或人工输入的哈希。 +- Keyframe Spec 同时核对 projectId、shotId、episodeNo;最终 Storyboard 外键与源集、正文版本和引用存在性继续由原采用事务核验,前端不把项目集号匹配冒充外键已通过。 +- 没有环境变化时不额外查询本集正文、不附 environmentSource,原请求形状保持。 +- 新错误前缀 JOINT_REVISION_ENVIRONMENT_SOURCE_STALE 使用中文提示。409读取当前正式 D/VS/草案和本集原文,保留草案、原文片段及审核输入,清除旧预检/确认,不自动重复提交或绑定新版本采用。 + +## UI + +在原“摄影草案与审核 → 联合修订摄影与开拍状态”内,以 NCollapse 默认收起四项环境字段。环境变化后才出现“本集原文依据”;完整正文及技术版本按需展开,引用字段不预填。缺证、片段不匹配或读取失败时禁用联合预检与采用,仍允许单独保存草案。 + +提示明确“原文及版本匹配不等于机器语义审核通过”。原确认勾选复用,不再增加另一套确认或费用授权;任何字段、片段或源读取变化撤销旧确认。长内容只滚动正文,固定关闭/保存/采用底栏,沿用现有主题与表单间距。既有分镜浏览精简、无默认多选/弹窗、目录避让和工具栏布局未改。 + +## 本轮文件职责 + +| 文件 | 变更 | +| --- | --- | +| src/features/storyboard/derived-review.types.ts | 扩展 environment 差异联合类型和有据采用的 environmentSource | +| src/features/storyboard/joint-review.ts | 四环境字段加入完整差异声明,保留其它越界显示/阻断 | +| src/features/storyboard/components/JointDraftFields.vue | 原编辑区内的可选四环境字段,不填默认天气 | +| src/features/storyboard/components/JointDraftReviewPanel.vue | 按需读取源集全文/身份/原字节SHA、逐字片段、预检冻结、冲突刷新和原状态原因 | +| src/features/projects/types.ts | 补充公开 Episode.projectId 可选类型及正式集ID说明,不改变其它项目流程 | +| src/lib/user-facing-text.ts | 环境源版本冲突中文提示,保留原错误码判断 | +| tests/features/storyboard/joint-review.test.ts | 环境字段、精确正文SHA、缺证、源缺失/409、重复点击和旧模式回归 | +| tests/browser/review-billing.ts | 原全请求隔离页增加 environment 场景,模拟原文变更及严格环境证据核对 | +| docs/api-contract-sync.md | 最新环境来源契约索引,说明旧环境边界已扩展 | +| docs/audits/beat6-environment-frontend-2026-11-16.md | 本交接 | + +本轮没有删除文件、没有修改依赖/锁文件、没有修改后端。前几轮文件仍保留为未提交状态,本表只统计本次环境增量职责。 + +## 验证 + +真实只读 GET 项目详情为200:项目 cmw02vpwi000005axrdtus3pa,第1集正式ID cmw02yfyb000505axhlvcp135,所属项目一致,完整content为656字符,UTF-8 SHA256为 `08b58106a9c29cd1dbc5cf42f5cb95c0f0bfd6b4c15f01f5de2f1d4c10bd8f7f`。这只证明读取能力,没有重新采用后端已确认的Beat6草案。 + +自动化:环境联合专项9项通过,原字节SHA用 Node createHash 独立核对 CRLF/换行和中文输入;缺证/他集片段不允许预检、缺正式全文不猜哈希、旧模式不带environmentSource、409保留输入重读、重复点击只发送一次正式采用均覆盖。 + +最终验证:相关5套38项Vitest通过;Vue TypeScript、8个实现/验收文件的Oxlint/Oxfmt、两处Vue组件的ESLint及生产构建通过,git diff --check通过。沿用前几轮其它已通过证据,没有重新执行无关全仓检查。后端工作区仍干净。 + +Chrome复用本地已有标签页,通过 `localhost:4312/tests/browser/review-billing.html?environment=1` 验收,全fetch拦截,未声明路由403且无正式服务回退: + +1. 打开原联合模式显示8项完整差异,四环境字段 before/after 全部保留,天气为空。 +2. 保存第7→8版后明确仍未采用;错误片段即使已免费预览,仍无法联合预检。 +3. 手填本集原样片段/审核人/理由后免费预检,正式采用仍需人工确认。 +4. 模拟预检后源正文变化:正式采用409,草案和片段保留,旧确认与预检失效;源全文刷新显示新增原文,没有自动第二次采用。 +5. 用户明确重读、重新预览/预检及确认后,Mock采用成功,正式D/VS/Preview刷新,完整差异归0,原草案stale和历史保留。 +6. 390×844检查完整原文、原文字段、长内容独立滚动、固定底栏、关闭与按钮禁用状态;验收后恢复桌面和原正式只读页面。全程模拟图片0、真实模型0。 + +截图在 `/Users/goujun/.codex/visualizations/2026/11/15/01a1df1f-2851-7ff2-b840-d1a0f3154f74/environment-review/` 的 mobile.jpg、adopted-desktop.jpg。未使用Playwright。 + +## 交付边界 + +环境接入没有解除原项目图片 billingBlocked,也不改变 unknown、预留、授权余额、质量结果或Primary。未执行真实文字/图片/Vision/Repair/视频,未在正式项目保存草案或采用。没有未接入的必要公开接口,Storyboard外键和最终版本保护仍由服务端权威事务决定。 + +前端保持dev,未Commit、未Push;后端只读且工作区未改动。本轮功能验收不构成后续正式采用或付费生产授权。 diff --git a/docs/audits/v8-9-4-9-frontend-integration-2026-11-16.md b/docs/audits/v8-9-4-9-frontend-integration-2026-11-16.md new file mode 100644 index 0000000..898fadc --- /dev/null +++ b/docs/audits/v8-9-4-9-frontend-integration-2026-11-16.md @@ -0,0 +1,158 @@ +# V8-9.4~V8-9.9 前端接入交接 + +Git交付补充:用户已授权本轮全部52个前端文件集中提交并推送dev,主题为 `feat(short-drama-agent-front): 接入联合修订与图片费用审计`。下文未提交/未Push和旧文件统计保留各验收时点;最新范围含后续环境增量,实际SHA及远端状态以本次仓库记录为准。 + +集中提交检查补充:首次正常钩子已通过全量Lint、488文件格式及类型检查,118套/913项测试中有3项暴露当前新回执被错误归入历史。已在原页面标记本页明确发起的操作,让新回执直接显示,恢复历史仍默认收起且不弹窗;未放宽原生成、费用或校验判断。3项原失败回归及2项浏览回归定向通过(其余59项未选中),本地Chrome原全请求隔离页验证新回执无需展开历史即可查看,截图在同级 `storyboard-cleanup/current-receipt.jpg`。提交钩子保留并重新执行全量,最终结果以此次提交终端为准。 + +日期:2026-11-16。前端根目录 `dev`,起始 `87427d9d4347fcc5535cbe74728ab00bf53ae796`;后端契约基线 `2d3abdab5f2656223ab98161dff6388200db281c`。只修改前端,没有新建工作树,没有提交或推送。 + +## 已有实现与本轮缺口 + +| 范围 | 已有能力 | 本轮补齐 | +| --- | --- | --- | +| 摄影审核 | 原独立摄影、组合草案、视线修订、场景沿用、草案保存/历史、版本保护 | 原抽屉内联合模式、完整字段差异、本镜/邻镜版本、免费预检及冻结请求采用 | +| 图片授权 | OpenAI 有限持续授权、原请求费用/余额、撤销、普通首帧 Preview、未知请求保护 | 人工有限追加登记/显示/撤销、原首帧主动选用、精确计划资格核对与成功后免费复用 | +| 费用审计 | 视频原件登记与独立复核 | 提取共用字段/校验,增加图片域三个正式接口及独立费用投影 | +| VisualState | 原主体/环境/continuityNote、原问题及定位、任务回执 | 正式时间标记分段与开拍说明、三种时间问题中文标题 | +| Workflow | 持久化 WorkflowExecution、GET/SSE、活动任务锁、恢复观察 | 继续复用;联合采用与费用审计为免费同步操作,不新增任务系统 | + +没有第二套摄影编辑器、时间轴、授权服务或业务页面。后端接口缺失没有用其它功能代替。 + +## 联合采用交互及保护 + +1. 从原“摄影草案与审核”切入联合模式,读取正式 Direction、VisualState、质量确认、Keyframe Spec 和原保存草案。项目、剧集、镜头归属不一致时不开放写入。 +2. 展示完整原稿与正式前后差异;身份、Form、环境、主体集合及其它不允许字段也显示,不悄悄过滤后提交。仅开放 composition、cameraPosition、visualIntent、continuityNote 及主体 expression/pose/gaze/position/transientState。 +3. 保存完整原草案使用 expectedRevision 及当前正式来源。保存成功只提示“尚未正式采用”,不变更正式 D/VS。 +4. 免费画面预览读取 draftFingerprint、currentDerivedFingerprint、adjacentDerivedVersions;邻镜必须完整对应同集正式顺序,不可缺漏、重复或伪造。 +5. 原 confirm 路由 `preview:true` 发送 jointRevision 的保存版号、本镜版本、完整邻镜、原因和全部 1~40 项差异。人工勾选后,正式采用提交完全相同快照,仅改 `preview:false`。 +6. 接受 changed 或 reused 的正式回执。409 或未知回执废弃旧预检,重读正式 GET,保留人工输入,等待明确重读/重新预检;不自动覆盖、保存或再次采用。 +7. 采用后读取正式 D/VS 及正式 Keyframe Preview,草案显示 stale 时保留原文与历史。草案指纹不提交生图。没有自动生图、Vision、Repair 或 Primary。 + +原摄影、组合草案、视线修订、场景沿用和草案历史的分支保留。超出40项、字段超过4000字、越界或混入其它修订模式时有简短原因并禁止联合采用。 + +## 追加许可与费用审计 + +- 追加许可表单只接受原 unknown OpenAI 首帧请求,次数、署名和风险确认不预填;POST 只发送正式 additional Schema,不构造新型号、范围、预算或供应方。 +- 显示原请求、原型号/镜头、计划及来源、原预留/未知账单、批准/已用/剩余次数和状态。撤销走原 revoke;撤销后剩余次数不可领取。没有自动创建许可。 +- 首帧入口必须主动选择已有许可并重新读取图片 Preview 与精确费用计划。项目/镜头/型号/来源/计划、原批准预算/有效期、追加剩余及其它在途请求逐项核对,最终领取仍由后端事务裁决。 +- 原 unknown 本地保护不清除;追加使用包含项目、许可和已用次数的独立提交标识。一次提交后停止,不自动用完剩余次数;存在同计划完整结果时,只读核对候选,不再生成或设主图。 +- 追加界面仅适用 OpenAI,其它供应方保留原保护。授权响应结构不完整时显示读取错误,不将其当成空授权或允许重试。 +- 图片审计复用项目设置的同一 AppDrawer/固定 footer。原 project/request/identity 和 taskFingerprint、evidenceSetFingerprint、reviewFingerprint 全部来自正式 GET。 +- 证据登记默认执行/费用未知、金额 null、无供应方编号和空材料;独立复核默认保留阻断。用户另行选择正式材料、填写署名/理由/真实摘要、切换决定并确认后才能提交。 +- 校验 USD 整数微美元精度;零金额必须显式填写,null 不显示为0。本地请求、候选、授权、镜头、项目及材料中的 LangSmith 编号不能冒充供应方请求号。 +- 登记不解除阻断,核清不覆盖原 unknown/账单/预留,也不代表生图成功、质量 Passed 或 Primary 可采用。核清后刷新原授权余额,原同计划没有结果的 unknown 仍不能普通重发。 +- 编辑、GET刷新或409撤销确认;409保留全部表单并重读正式版本,无自动第二次 POST。切项目/请求清空材料、签署和选择,迟到响应不回填。 + +## 正式 API 对接 + +下表的写入流程均由隔离 Mock 验证;正式服务仅进行免费只读核对,没有为验收在真实项目登记证据或采用草案。 + +| API | 用途及结果 | +| --- | --- | +| GET/PUT 原 keyframe-review-draft | 复用原草案保存及 expectedRevision,保留完整原稿与显式 providerInput | +| POST 原 keyframe/preview | 草案与正式模式分离;联合使用本镜/邻镜派生版本,采用后重读正式 Preview | +| POST projects/:projectId/storyboard-derived-reviews/confirm | 原接口新增 jointRevision,免费预检/正式采用/幂等/冲突走同一契约 | +| GET/POST projects/:projectId/image-authorizations | 保留原授权,新增 additional 分支、已用/剩余投影,首帧显式选择使用 | +| POST image-authorizations/:authorizationId/revoke | 原接口撤销持续授权或追加许可,保留历史 | +| GET projects/:projectId/image-requests/:requestId/audit | 原身份、原费用、阻断及证据/复核历史读取 | +| POST 原 audit/evidence | 原完整身份/版本绑定,登记与解除分开 | +| POST 原 audit/reviews | 独立复核携带三项并发版本,409读取正式GET,不自动重提 | +| POST 原 storyboard-shots/:shotId/keyframe | 仅用户操作时附 additionalAuthorizationId 和原项目 scope,Preview 不携带许可字段 | +| GET/SSE 原 WorkflowExecution | 沿用原观察链;刷新、重进或订阅重连不生成 POST | + +真实只读核对的时点结果: + +- `localhost:3412/api` 的保存草案 5.2 返回 revision1/stale,主体 formId 与正式 subjectFormId 相同,未做猜测映射或重存。 +- 项目 `cmw02vpwi000005axrdtus3pa` 的授权 GET 为200:持续授权1、追加许可1、billingBlocked=true、unknown1。原阻断请求 `cmwhxdc0i0003rocjcz80n31v` 保留。 +- 上述原请求 audit GET 为200:unknown、预留 USD1、原实际账单 null、Provider Request ID null、无原成功回执、unreviewed、billingBlocked=true,证据及复核历史均0。没有声称该正式请求已核清。 +- 正式质量确认 GET 为200,valid=true、60镜。本轮观察期间另有后端任务继续生产,正式页面 D/VS 覆盖随之变化,不能把该变化计为本轮执行成果。 + +## 时间语义 + +当前主体/环境显示为本镜0秒开拍状态,允许已经开始的持续动作。continuityNote 仅按后端明确的【输入事实】【规划末态】【连续要求】【视频末态】四种标记排版,旧无标记原文完整保留,不靠动作关键词判定有效性。视频末态明确仍需真实视频证据。 + +VISUAL_STATE_START_CONFLICT 显示开拍状态冲突;VISUAL_STATE_TIME_NEEDS_REVIEW 显示人工待核对;VISUAL_STATE_VIDEO_END_UNSUPPORTED 显示真实视频末态缺证。原 code/severity/field、原回执导出及集/段落/镜头位置保留,不把 needs_review 转为通过。 + +## 文件职责 + +以下路径相对前端根目录。含后续浏览精简及目录/按钮补充,新增25个文件、修改25个文件、删除0个文件;没有修改依赖或锁文件。 + +| 状态 | 文件 | 职责 | +| --- | --- | --- | +| 新增 | src/features/storyboard/joint-review.ts | 完整稳定比较与允许/越界差异声明 | +| 新增 | src/features/storyboard/components/JointDraftFields.vue | 原摄影字段组件复用及有界开拍字段 | +| 新增 | src/features/storyboard/components/JointDraftReviewPanel.vue | 草案读取/保存、版本、邻镜、预检、采用和冲突处理 | +| 新增 | src/features/storyboard/visual-state-time.ts、components/VisualStateContinuity.vue | 统一时间标记及问题标题、共享原文展示 | +| 新增 | src/features/billing-audit/types.ts、labels.ts、evidence.ts、BillingEvidenceFields.vue | 图片/视频共享原件类型、文案、校验、表单 | +| 新增 | src/features/image-authorization/billing-audit.types.ts、billing-audit-api.ts、billing-audit.ts | 图片原身份、正式审计API、金额与核清条件 | +| 新增 | src/features/image-authorization/useImageBillingAudit.ts、ImageBillingAuditPanel.vue | 同一授权抽屉的图片登记/独立复核/历史/409 | +| 新增 | tests/features/storyboard/joint-review.test.ts、tests/fixtures/joint-review.ts | 联合保存/预检/采用/幂等/冲突/时间与完整差异 | +| 新增 | tests/features/storyboard/page-browsing.test.ts | 历史回执恢复不弹窗、目录浏览与生成范围勾选分离 | +| 新增 | tests/features/storyboard/directory-position.test.ts | 真实目录包装结构中的段落吸顶高度避让回归 | +| 新增 | tests/features/image-authorization/additional.test.ts、tests/fixtures/image-additional.ts | 许可范围/次数/撤销/预算、原guard保留及一次主动生成 | +| 新增 | tests/features/image-authorization/billing-audit.test.ts、tests/fixtures/image-billing-audit.ts | 登记/独立复核、精度/null、409、范围隔离与历史 | +| 新增 | tests/browser/review-billing.html、review-billing.ts | 真实组件的内存隔离验收页,全fetch拦截,未知路由403,无真实回退 | +| 新增 | docs/audits/v8-9-4-9-frontend-integration-2026-11-16.md | 本轮交接、验证和边界 | +| 修改 | src/features/storyboard/components/ShotDerivedReview.vue | 原摄影抽屉内的联合模式与固定底栏 | +| 修改 | src/features/storyboard/StoryboardPage.vue、components/StagedShotPreparation.vue | 配置只由用户打开、普通目录无多选、历史按需展开与精简说明 | +| 修改 | src/composables/useDirectorySelection.ts、src/components/ui/ActionMenu.vue | 语义分组定位标题、更多按钮统一默认中性底色 | +| 修改 | src/features/storyboard/derived-review.types.ts、derived-review-api.ts | 联合正式字段、预览/采用回执及原路由 | +| 修改 | src/features/storyboard/components/ShotDesign.vue、GenerationReceipt.vue | 开拍/衔接及时间问题展示 | +| 修改 | src/features/storyboard/types.ts、src/features/workflows/WorkflowExecutionPanel.vue | 保留时间问题码/级别/位置与原逐集回执 | +| 修改 | src/features/image-authorization/types.ts、api.ts、model.ts、ImageAuthorizationSettings.vue | 追加许可、精确资格、原余额/未知、同抽屉图片审计 | +| 修改 | src/features/production/components/KeyframeDialog.vue、ShotProductionAssets.vue | 原首帧选择许可/重新预览/一次提交/免费只读复用 | +| 修改 | src/features/production/types.ts、api.ts | 可选追加许可及原项目请求范围 | +| 修改 | src/features/subject-images/generation-preview.ts | 共用精确费用核对及只读复用回调,原收费保护保留 | +| 修改 | src/features/production/components/VideoAuditPanel.vue、video-audit.ts | 视频原证据字段/校验复用共享实现,保留原视频操作与导出 | +| 修改 | src/lib/billing-errors.ts、user-facing-text.ts | 追加/审计/联合/时间中文原因、网络与Provider配额区别 | +| 修改 | docs/api-contract-sync.md | 本轮契约同步索引 | + +## 自动化与本地 Chrome + +本轮新增3套34项测试;专项测试覆盖完整差异、保存/采用分离、冻结请求、幂等、邻镜409、旧模式、许可次数/撤销/预算/跨项目镜头型号来源计划、原guard、未知历史/null金额、登记与独立复核分离、证据版本409和项目隔离。共享视频原能力及原图片预览/候选恢复由现有回归覆盖。 + +首次全量发现其它图片供应方失败候选也尝试读取追加许可,已收紧到 OpenAI,补正式响应结构核对。原下载恢复和新增追加相关2套25项已通过;最终全量结果见下方验证记录。 + +本地 Chrome 复用原标签页及 `localhost:4312`;所有写入在 `/tests/browser/review-billing.html` 全拦截隔离页面,只用原生AX/键鼠/截图,没有 Playwright。已验证: + +1. 原摄影模式切联合、编辑完整草案、保存7→8版、完整前后差异、邻镜2.1、免费预检、人工勾选后采用;正式 D/VS/Preview 刷新、原草案stale与历史保留,没有生图。 +2. 预检后模拟邻镜变化:正式采用409,输入保留、预检和确认撤销;用户明确重读、再次预检/确认后才采用。 +3. 原 unknown 下手填追加次数2、批准材料与风险确认,登记后未生成;首帧默认不选许可,主动选择并重新预览后仅1次模拟图片请求;再次同计划查看完整候选不增加请求。 +4. 已用1/2、剩余1;撤销后不可领取,原 unknown、预留/null账单及新 completed 两笔均保留。 +5. 手填仅供Mock的执行/账单原件登记后仍阻断;另切独立复核,默认保留,主动选证据/核清/署名/理由/SHA/确认后核清。原 unknown、原预留及未知实际账单仍保留;历史展示登记与第1次独立复核。 +6. 390×844 窄屏检查完整差异、四类时间说明、长表单和审计历史,正文滚动、标题及底栏固定、字段有留白,关闭按钮可见。恢复临时视口到原桌面尺寸。 +7. 刷新隔离页为0模拟同步操作/0模拟图片请求/0真实模型请求;没有刷新触发写入。费用409保留表单与跨项目隔离由自动化覆盖。 + +截图保存在 `/Users/goujun/.codex/visualizations/2026/11/15/01a1df1f-2851-7ff2-b840-d1a0f3154f74/v8-9-4-9/`:joint-adopted-desktop.jpg、joint-diff-mobile.jpg、image-audit-mobile.jpg。 + +最终验证记录: + +- Vitest 全量116个文件、907项通过,0失败/0未处理错误;其中本轮新增34项。 +- Vue TypeScript `vue-tsc --noEmit` 通过。 +- 改动范围 Oxlint、全部修改/新增 Vue 的 ESLint、Oxfmt 检查通过,无警告;文档补齐后只重新检查对应文档和差异。 +- Vite生产构建通过,4964个模块,未把隔离测试页面作为生产构建入口。 +- `git diff --check` 通过;初轮涉及前端44个文件,后续浏览精简共47个文件,没有依赖或锁文件变动。 + +## 分镜浏览精简补充 + +用户反馈普通目录多选、进入页面自动弹出配置和说明过多后,定位并修复以下原因: + +- 目录多选来自页面固定传入 selectable,且生成抽屉已有重复选择器。普通目录改为单纯浏览;完整按段落/镜头勾选保留在“生成与恢复 → 选择镜头”。切换到当前集/全项目范围不再显示不适用的勾选区。 +- 自动弹出来自 useStoryboard 在恢复历史 Workflow 终态后设置 session.receipt,页面 watcher 把任何回执变化都当成打开指令。移除 watcher 中的打开动作,保留回执、状态观察和镜头重生成后的时长刷新;只有主动点击入口打开配置。 +- 默认保留摄影参数/意图与0秒环境摘要,完整构图/机位、连续性和主体状态使用 NCollapse 按需展开,原创作正文完整保留。全项目进度归入生成配置,删去重复介绍;覆盖风险、费用及作用范围继续在原确认流程展示。 +- 已完成任务及原回执默认收起;正在执行、待读取和失败记录仍直接显示,不隐藏费用未知或失败处理入口。 + +先复现两项失败回归,再修复;定向5套35项通过,TypeScript、修改范围 Oxlint/Vue ESLint/格式及生产构建通过。本地 Chrome 复用正式 localhost 页面,只读刷新后不弹窗且无目录多选;验证点击切镜、展开完整摄影原文、生成范围勾选/取消、历史回执保留、390px长内容滚动和固定关闭底栏,未执行生成或正式写入。桌面及移动截图在本轮截图目录的同级 `storyboard-cleanup/`。 + +用户指定的 Leonxlnx/taste-skill 当前为 tasteskill 2.5.1,主要面向公司官网。可借用 references/copy.md 的短文案/一事实一处/按钮动作命名,copy-voice.md 的用户用语与精简确认,SKILL.md 的单一设计系统和实际浏览器验收。营销页的单屏节奏、随机配色、动效和图库模板不适用当前工作台;继续采用项目 Vue/Naive UI/主题变量及本地 Chrome 规则,不复制官网资产或执行其自动浏览器脚本。 + +已通过官方 skill-installer 将固定版本 `f6b76575f949707b4e3c37cd86cb44b0b98643e8` 安装到 `/Users/goujun/.codex/skills/taste-skill`,原有其它技能保留;安装后的1631个文件逐一校验 Git blob SHA 全部一致。初始浮动分支下载受网络影响,最终改用固定版本归档完成,未执行下载 skill 内的代码或修改项目依赖。新安装技能从下一条消息可用。 + +后续目录/工具栏修复:镜头条目新增包装后,原自动定位依赖两层父节点,未找到实际段落标题,导致首行镜号进入吸顶标题下方;现改按最近语义分组查标题并保留真实高度。连续性按钮使用正式 icon 插槽,桌面和手机都显示;更多按钮采用公共默认中性底面并移到三项操作最左侧。新增定位回归先失败(实际滚动160,预期122),修复后相关4套12项通过,类型/Lint/格式及构建检查通过。Chrome复用正式localhost页面,验证段落首镜完整露出、更多菜单保留导出、本组三按钮底色/图标/顺序、390px布局与键盘焦点,未执行生成。截图在同级 `toolbar-directory/desktop.jpg`、`toolbar-directory/mobile.jpg`。当前前端总计50个变动文件,仍未提交或推送。 + +## 未完成项及交付边界 + +- 指定基线内没有已知未接入的前端目标。真实生成、正式采用/追加批准/证据登记/核清及真实质量/Primary没有执行,这是本轮明确禁止或保护正式数据的边界;写入成功/失败由隔离 Mock 验证,不称作正式业务验收。 +- 后端工作区另有并行未提交的 Beat6 当前集正文与环境联合修订扩展。它超出本轮指定已提交基线;当前前端继续将环境视为不可联合修改,不猜测 environmentSource 或自动新增环境编辑,未改动后端文件。 +- 本轮所有真实收费模型调用为0,没有改变正式请求状态或伪造 Provider ID/费用证据。没有自动执行任何图片/文字/Vision/Repair/视频/Primary,也没有历史 unknown 自动重试。 +- 前端保持 `dev@87427d9`,改动未提交、未push;没有切换或合并发布分支。 diff --git a/src/components/ui/ActionMenu.vue b/src/components/ui/ActionMenu.vue index e1ba72e..0cf6e5d 100644 --- a/src/components/ui/ActionMenu.vue +++ b/src/components/ui/ActionMenu.vue @@ -19,13 +19,7 @@ function select(key: string) { diff --git a/src/features/image-authorization/ImageBillingAuditPanel.vue b/src/features/image-authorization/ImageBillingAuditPanel.vue new file mode 100644 index 0000000..e1f8053 --- /dev/null +++ b/src/features/image-authorization/ImageBillingAuditPanel.vue @@ -0,0 +1,207 @@ + + diff --git a/src/features/image-authorization/api.ts b/src/features/image-authorization/api.ts index f8c92e6..1ea090f 100644 --- a/src/features/image-authorization/api.ts +++ b/src/features/image-authorization/api.ts @@ -1,5 +1,6 @@ import { request } from '../../lib/http' import type { + ImageAdditionalAuthorizationInput, ImageAuthorizationInput, ImageAuthorizationList, ImageAuthorizationPreview, @@ -39,7 +40,7 @@ export const imageAuthorizationApi = { * @param input 本次不可变批准 * @returns 原授权标识及状态 */ - create: (projectId: string, input: ImageAuthorizationInput) => + create: (projectId: string, input: ImageAuthorizationInput | ImageAdditionalAuthorizationInput) => request<{ authorizationId: string; status: string }>(root(projectId), { method: 'POST', body: input }), /** * 撤销未来领取并保留原件。 diff --git a/src/features/image-authorization/billing-audit-api.ts b/src/features/image-authorization/billing-audit-api.ts new file mode 100644 index 0000000..abd45ab --- /dev/null +++ b/src/features/image-authorization/billing-audit-api.ts @@ -0,0 +1,47 @@ +import { request } from '../../lib/http' +import type { ImageBillingAuditView, ImageBillingEvidenceInput, ImageBillingReviewInput } from './billing-audit.types' +/** + * 精确绑定原项目和原应用请求,不复用视频任务路径。 + * @param projectId 原项目 + * @param requestId 原应用费用请求 + * @returns 正式图片费用审计路径 + */ +function path(projectId: string, requestId: string) { + return `/projects/${encodeURIComponent(projectId)}/image-requests/${encodeURIComponent(requestId)}/audit` +} +/** 同步、免费图片费用审计;任何动作都不启动生产。 */ +export const imageBillingAuditApi = { + /** + * 读取原身份和并发版本。 + * @param projectId 原项目 + * @param requestId 原应用费用请求 + * @param signal 取消旧范围读取 + * @returns 原请求审计视图 + */ + get: (projectId: string, requestId: string, signal?: AbortSignal) => + request(path(projectId, requestId), { signal }), + /** + * 幂等登记外部原件,不解除阻断。 + * @param projectId 原项目 + * @param requestId 原应用费用请求 + * @param body 正式身份及登记人 + * @returns 新审计视图和登记回执 + */ + evidence: (projectId: string, requestId: string, body: ImageBillingEvidenceInput) => + request( + path(projectId, requestId) + '/evidence', + { method: 'POST', body } + ), + /** + * 独立复核当前完整证据版本,不改变原执行、质量或主图。 + * @param projectId 原项目 + * @param requestId 原应用费用请求 + * @param body 用户明确核对的复核材料 + * @returns 当前正式审计和幂等回执 + */ + review: (projectId: string, requestId: string, body: ImageBillingReviewInput) => + request(path(projectId, requestId) + '/reviews', { + method: 'POST', + body + }) +} diff --git a/src/features/image-authorization/billing-audit.ts b/src/features/image-authorization/billing-audit.ts new file mode 100644 index 0000000..652b5a1 --- /dev/null +++ b/src/features/image-authorization/billing-audit.ts @@ -0,0 +1,86 @@ +import { billingEvidenceIssues } from '../billing-audit/evidence' +import type { BillingFacts } from '../billing-audit/types' +import type { ImageBillingAuditView, ImageBillingEvidenceInput } from './billing-audit.types' + +/** + * 核对USD金额是否可精确表示为整数微美元,零金额必须显式填写。 + * @param amount 原金额或未知 + * @returns 精确整数微美元或null + */ +export function imageBillingAmountMicros(amount: number | null): number | null { + if (amount === null || !Number.isFinite(amount) || amount < 0 || !/^\d+(\.\d{1,6})?$/.test(String(amount))) + return null + const [whole = '0', fraction = ''] = String(amount).split('.') + const micros = Number(whole) * 1_000_000 + Number(fraction.padEnd(6, '0')) + return Number.isSafeInteger(micros) ? micros : null +} +/** + * 校验图片证据格式和本地身份,不把未知材料当成核实结论。 + * @param facts 用户填写的事实 + * @param view 原正式审计身份 + * @returns 可操作校验原因 + */ +export function imageBillingEvidenceIssues(facts: BillingFacts, view: ImageBillingAuditView): string[] { + const identity = view.identity + const issues = billingEvidenceIssues(facts, [ + identity.requestId, + identity.candidateId, + identity.authorizationId, + identity.targetId, + identity.projectId + ]) + if ( + facts.billing.currency !== 'USD' || + (facts.billing.amount !== null && imageBillingAmountMicros(facts.billing.amount) === null) + ) + issues.push('图片账单金额需为可精确表示的USD非负数,最多6位小数;未知请留空。') + return issues +} +/** + * 核清前检查材料是否具备正式条件,最终真实性、唯一认领仍由人工和服务端核验。 + * @param evidence 用户明确选中的已登记证据 + * @param view 原图片费用审计 + * @returns 不能核清的原因 + */ +export function imageBillingReleaseIssues( + evidence: ImageBillingEvidenceInput['evidence'] | undefined, + view: ImageBillingAuditView +): string[] { + if (!evidence) return ['请先选择已登记的证据包。'] + const issues = imageBillingEvidenceIssues(evidence, view) + if ( + Object.entries(view.identity).some( + ([key, value]) => evidence.identity[key as keyof typeof evidence.identity] !== value + ) + ) + issues.push('证据身份与原请求不一致。') + if (!['unknown', 'completed'].includes(view.originalRequestStatus)) issues.push('原请求尚未形成可复核的结束状态。') + if ( + evidence.correlation !== 'unique' || + evidence.execution.outcome === 'unknown' || + evidence.billing.finding === 'unknown' || + evidence.billing.amount === null + ) + issues.push('唯一关联、执行终态或实际费用仍未确认。') + const execution = evidence.artifacts.filter(item => evidence.execution.evidenceIds.includes(item.id)), + billing = evidence.artifacts.filter(item => evidence.billing.evidenceIds.includes(item.id)) + if ( + !execution.some(item => ['provider-execution', 'provider-support'].includes(item.kind)) || + !billing.some(item => ['provider-billing', 'provider-support'].includes(item.kind)) + ) + issues.push('执行与费用分别需要供应方原件,观测记录不能替代。') + if (evidence.billing.finding === 'no-charge' && evidence.billing.amount !== 0) + issues.push('未收费必须有明确零金额依据。') + if (evidence.execution.outcome === 'not-received') { + if ( + evidence.billing.finding !== 'no-charge' || + evidence.billing.amount !== 0 || + !execution.some(item => item.kind === 'provider-support') + ) + issues.push('未接收需要官方支持原件及未收费说明。') + } else if (!evidence.providerRequestId) issues.push('缺少真实供应方请求号。') + if (view.hasOriginalReceipt && evidence.execution.outcome !== 'succeeded') issues.push('外部声明与原成功回执冲突。') + if (view.originalProviderRequestId && view.originalProviderRequestId !== evidence.providerRequestId) + issues.push('供应方编号与原回执不一致。') + return issues +} diff --git a/src/features/image-authorization/billing-audit.types.ts b/src/features/image-authorization/billing-audit.types.ts new file mode 100644 index 0000000..acd899a --- /dev/null +++ b/src/features/image-authorization/billing-audit.types.ts @@ -0,0 +1,70 @@ +import type { BillingFacts } from '../billing-audit/types' +import type { ImageAuthorizationScope } from './types' + +/** 原图片费用请求身份,完整复制GET,不由当前新资产推导。 */ +export interface ImageBillingIdentity { + /** 原项目。 */ projectId: string + /** 原应用费用请求。 */ requestId: string + /** 原批准。 */ authorizationId: string + /** 原业务范围。 */ scope: ImageAuthorizationScope + /** 原主体、形态、镜头或布局。 */ targetId: string + /** 原候选。 */ candidateId: string + /** 原来源版本。 */ sourceFingerprint: string + /** 原精确费用计划。 */ planFingerprint: string + /** 原完整请求版本。 */ requestFingerprint: string + /** 固定供应方。 */ provider: 'openai-image' + /** 原型号。 */ model: string +} +/** 只登记外部事实,不修改原unknown和账单字段。 */ +export interface ImageBillingEvidenceInput { + /** 原请求及原授权完整版本。 */ expectedTaskFingerprint: string + /** 实际登记人。 */ operator: string + /** 身份及待人工核验的材料。 */ evidence: BillingFacts & { /** 原完整身份。 */ identity: ImageBillingIdentity } +} +/** 图片费用的独立人工复核,不改写像素、质量或主图。 */ +export interface ImageBillingReviewInput { + /** 用户选中的正式证据包。 */ evidenceId: string + /** 原请求版本。 */ expectedTaskFingerprint: string + /** 完整证据集合。 */ expectedEvidenceSetFingerprint: string + /** 上一次复核版本。 */ expectedReviewFingerprint: string + /** 用户明确选择的决定。 */ decision: 'keep_blocked' | 'release_future_charges' + /** 实际复核人。 */ reviewer: string + /** 复核原因。 */ reason: string + /** 用户核对材料的真实摘要。 */ confirmationSha256: string +} +/** 不可变审计事件,复核先后以revision为准。 */ +export interface ImageBillingEvent { + /** 正式事件身份。 */ id: string + /** 原请求身份。 */ requestId: string + /** 原请求版本。 */ taskFingerprint: string + /** 原事件正文。 */ body: T + /** 稳定事件摘要。 */ digest: string + /** 服务端可能提供的记录时间。 */ createdAt?: string + /** 复核单调序号。 */ revision?: number +} +/** 图片原请求的权威审计视图。 */ +export interface ImageBillingAuditView { + /** 原项目。 */ projectId: string + /** 原应用费用请求。 */ requestId: string + /** 完整原身份。 */ identity: ImageBillingIdentity + /** 原请求和授权完整版本。 */ taskFingerprint: string + /** 当前证据集合版本。 */ evidenceSetFingerprint: string + /** 当前复核版本。 */ reviewFingerprint: string + /** 原请求执行状态。 */ originalRequestStatus: string + /** 原预留,核清不退回。 */ reservedMicros: number + /** 原用量价,未知为null。 */ originalUsageCostMicros: number | null + /** 原实际账单,未知为null。 */ originalActualBilledMicros: number | null + /** 真实供应方编号,缺失不能补造。 */ originalProviderRequestId: string | null + /** 原成功回执是否存在。 */ hasOriginalReceipt: boolean + /** 原请求的原始阻断。 */ originalBillingBlocked: boolean + /** 有效复核之后的当前阻断。 */ billingBlocked: boolean + /** 当前有效解除。 */ released: boolean + /** 当前审计结论,不是执行结论。 */ status: 'unreviewed' | 'blocked' | 'released' + /** 有效解除的复核。 */ reviewId: string | null + /** 审计核实金额,不覆盖原账单。 */ reviewedAmountMicros: number | null + /** 当前不能解除的正式原因。 */ releaseIssues: string[] + /** 完整不可变历史。 */ history: { + /** 全部登记原件。 */ evidence: ImageBillingEvent[] + /** 全部独立复核。 */ reviews: ImageBillingEvent[] + } +} diff --git a/src/features/image-authorization/model.ts b/src/features/image-authorization/model.ts index ab7fbe0..d5b6834 100644 --- a/src/features/image-authorization/model.ts +++ b/src/features/image-authorization/model.ts @@ -40,6 +40,7 @@ export function formatMicros(value: number | null | undefined): string { * @param targetId 实际目标 * @param model 实际预览型号 * @param planFingerprint 免费计划返回的指纹,仅普通计划可提供 + * @param additional 用户主动选择且需要核对精确来源的有限许可 * @returns 可复用、已授权或阻断说明 */ export function imageChargeEligibility( @@ -47,7 +48,12 @@ export function imageChargeEligibility( scope: ImageAuthorizationScope, targetId: string, model: string, - planFingerprint?: string + planFingerprint?: string, + additional?: { + /** 用户明确选中的许可。 */ id: string + /** 当前正式来源。 */ sourceFingerprint: string + /** 当前原项目。 */ projectId: string + } ) { const reusable = list.requests.find( row => @@ -65,6 +71,35 @@ export function imageChargeEligibility( reusable: true, message: '同计划完整回执可免费复用,不新增请求次数;图片质量仍按原审核结果。' } + if (additional) + return scope === 'keyframe' && planFingerprint + ? additionalImageEligibility( + list, + additional.id, + additional.projectId, + targetId, + model, + additional.sourceFingerprint, + planFingerprint + ) + : { allowed: false, reusable: false, message: '追加许可只适用于已重新核对的原精确首帧计划。' } + if ( + planFingerprint && + list.requests.some( + row => + row.status === 'unknown' && + row.input.scope === scope && + row.input.targetId === targetId && + row.input.model === model && + row.input.planFingerprint === planFingerprint && + !row.output?.result + ) + ) + return { + allowed: false, + reusable: false, + message: '原精确计划仍有结果或费用未知的请求。即使费用已核清,也不能普通重发;需主动核对人工有限追加许可。' + } if (list.billingBlocked) return { allowed: false, @@ -116,3 +151,76 @@ export function imageRequestBlockReason(request: ImageChargeRequest): string { if (usageCost > request.input.reservedMicros) return '公开用量价超过单次预留,后续收费暂停。' return '' } + +/** + * 仅提示原精确首帧计划的追加准入,最终费用领取仍由服务端事务核对。 + * @param list 原项目正式费用投影 + * @param permitId 用户主动选中的许可 + * @param projectId 当前原项目 + * @param targetId 当前镜头 + * @param model 当前预览型号 + * @param sourceFingerprint 当前正式来源 + * @param planFingerprint 当前精确费用计划 + * @returns 当前是否满足追加条件及原因 + */ +export function additionalImageEligibility( + list: ImageAuthorizationList, + permitId: string, + projectId: string, + targetId: string, + model: string, + sourceFingerprint: string, + planFingerprint: string +) { + const permit = list.additionalAuthorizations?.find(row => row.id === permitId) + const parent = list.requests.find(row => row.id === permit?.input.parentRequestId) + const grant = list.authorizations.find(row => row.id === parent?.input.authorizationId) + if ( + !permit || + permit.status !== 'approved' || + !Number.isSafeInteger(permit.remainingRequests) || + permit.remainingRequests < 1 || + !Number.isSafeInteger(permit.usedRequests) || + permit.usedRequests < 0 || + !parent || + parent.status !== 'unknown' || + parent.output?.result || + parent.input.projectId !== projectId || + parent.input.scope !== 'keyframe' || + parent.input.provider !== 'openai-image' || + parent.input.targetId !== targetId || + parent.input.model !== model || + parent.input.sourceFingerprint !== sourceFingerprint || + parent.input.planFingerprint !== planFingerprint || + !grant || + grant.status !== 'approved' || + grant.expired || + !(Date.parse(grant.input.expiresAt) > Date.now()) || + !Number.isSafeInteger(grant.remainingRequests) || + grant.remainingRequests < 1 || + !Number.isSafeInteger(grant.remainingMicros) || + !Number.isSafeInteger(grant.input.perRequestMicros) || + grant.input.perRequestMicros < 1 || + grant.remainingMicros < grant.input.perRequestMicros + ) + return { + allowed: false, + reusable: false, + message: '所选追加许可已撤销、用尽,或原镜头、型号、来源、计划及预算不匹配。请重新核对原请求。' + } + const blockers = list.requests.filter(row => list.blockingRequestIds.includes(row.id)) + if ( + blockers.some( + row => + row.status !== 'unknown' || + row.input.planFingerprint !== planFingerprint || + (row.id !== parent.id && row.input.additionalAuthorizationId !== permit.id) + ) + ) + return { allowed: false, reusable: false, message: '仍有在途或未被本次许可覆盖的原请求,不能追加。' } + return { + allowed: true, + reusable: false, + message: `人工追加许可:已用 ${permit.usedRequests} 次,剩余 ${permit.remainingRequests} 次。原未知请求和预留保持;仅本次主动生成,不会自动用完剩余次数。` + } +} diff --git a/src/features/image-authorization/types.ts b/src/features/image-authorization/types.ts index 6dfe4fb..77ac8e8 100644 --- a/src/features/image-authorization/types.ts +++ b/src/features/image-authorization/types.ts @@ -24,8 +24,15 @@ export interface ImageAuthorizationInput { export interface ImageChargeRequest { /** 原请求标识。 */ id: string /** 原执行状态。 */ status: string + /** 当前有效审计,不覆盖原状态、用量或账单。 */ billingAudit?: { + /** 审计状态。 */ status: 'unreviewed' | 'blocked' | 'released' + /** 有效解除。 */ released: boolean + /** 独立复核。 */ reviewId: string | null + /** 核实金额。 */ reviewedAmountMicros: number | null + } /** 不可变原输入。 */ input: { /** 原项目。 */ projectId: string + /** 用户主动选用的人工追加许可。 */ additionalAuthorizationId?: string /** 原范围。 */ scope: ImageAuthorizationScope /** 原目标。 */ targetId: string /** 原候选。 */ candidateId: string @@ -47,6 +54,16 @@ export interface ImageChargeRequest { /** 项目授权余额与原请求。 */ export interface ImageAuthorizationList { + /** 原始在途或未知记录仍完整保留。 */ originalBlockingRequestIds?: string[] + /** 人工有限追加许可,不增加原预算。 */ additionalAuthorizations?: Array<{ + /** 正式追加许可。 */ id: string + /** approved或revoked等真实状态。 */ status: string + /** 原不可变批准及服务端父输入摘要。 */ input: ImageAdditionalAuthorizationInput & { + /** 原完整输入摘要。 */ parentInputFingerprint: string + } + /** 已领取的模型请求次数。 */ usedRequests: number + /** 尚可人工领取次数。 */ remainingRequests: number + }> /** 服务端计算的授权投影。 */ authorizations: Array<{ /** 原批准记录。 */ id: string /** 原批准状态。 */ status: string @@ -90,3 +107,14 @@ export interface ImageAuthorizationPreview { /** 不承诺实际账单硬上限。 */ hardProviderCostCap: false /** 当前授权与费用状态。 */ authorization: ImageAuthorizationList } + +/** 接受原费用未知风险后的有限人工追加,只允许服务端继承原精确计划。 */ +export interface ImageAdditionalAuthorizationInput { + /** 明确追加模式。 */ mode: 'additional' + /** 本次批准唯一键,同内容重放保持。 */ idempotencyKey: string + /** 原应用费用请求,不能使用候选或Provider编号。 */ parentRequestId: string + /** 明确批准1~100次,不自动用完。 */ maxRequests: number + /** 用户主动接受原费用仍未知。 */ acknowledgeUnknownPriorBilling: true + /** 实际批准人。 */ approvedBy: string + /** 批准说明。 */ approvalNote: string +} diff --git a/src/features/image-authorization/useImageBillingAudit.ts b/src/features/image-authorization/useImageBillingAudit.ts new file mode 100644 index 0000000..0d12c80 --- /dev/null +++ b/src/features/image-authorization/useImageBillingAudit.ts @@ -0,0 +1,250 @@ +import { computed, onScopeDispose, ref, watch } from 'vue' +import { useQuery } from '../../composables/useQuery' +import { ApiError, errorMessage } from '../../lib/http' +import { useActionMessage } from '../../components/ui/useActionMessage' +import type { BillingFacts } from '../billing-audit/types' +import { imageBillingAuditApi } from './billing-audit-api' +import { imageBillingEvidenceIssues, imageBillingReleaseIssues } from './billing-audit' + +/** + * 在原图片授权入口处理原请求的登记和独立复核,不执行生成或质量动作。 + * @param props 原项目与应用费用请求 + * @param changed 写入后刷新原授权余额和请求 + * @returns 当前权威审计、独立表单和固定底栏操作 + */ +export function useImageBillingAudit( + props: { projectId: string; requestId: string; disabled?: boolean }, + changed: () => Promise | void +) { + /** 当前原范围与提交回执隔离。 */ + const key = computed(() => JSON.stringify([props.projectId, props.requestId])) + /** 组件离开后不应用旧提交结果。 */ + let disposed = false + onScopeDispose(() => { + disposed = true + }) + /** 原身份、版本和完整历史只来自正式GET。 */ + const query = useQuery(key, async (value, signal) => { + const [projectId, requestId] = JSON.parse(value) as [string, string] + const result = await imageBillingAuditApi.get(projectId, requestId, signal) + if ( + !result || + result.projectId !== projectId || + result.requestId !== requestId || + result.identity?.projectId !== projectId || + result.identity.requestId !== requestId || + result.identity.provider !== 'openai-image' || + ![result.taskFingerprint, result.evidenceSetFingerprint, result.reviewFingerprint].every(hash => + /^[a-f0-9]{64}$/.test(hash) + ) || + !Array.isArray(result.history?.evidence) || + !Array.isArray(result.history?.reviews) + ) + throw new Error('原图片请求身份或审计版本无法核对,请重新读取。') + return result + }) + /** 登记和复核始终是两个独立用户动作。 */ + const action = ref<'evidence' | 'review'>('evidence') + /** 实际登记署名。 */ + const operator = ref('') + /** 外部事实默认未知,不预填真实Provider号或账单。 */ + const facts = ref({ + correlation: 'unverified', + providerRequestId: null, + artifacts: [], + execution: { outcome: 'unknown', evidenceIds: [] }, + billing: { finding: 'unknown', amount: null, currency: 'USD', evidenceIds: [] } + }) + /** 用户主动选择当前正式证据。 */ + const evidenceId = ref('') + /** 独立复核实际署名。 */ + const reviewer = ref('') + /** 独立复核理由。 */ + const reason = ref('') + /** 人工核对材料的真实摘要,不从本地身份伪造。 */ + const confirmationSha256 = ref('') + /** 默认保留原阻断,解除需用户主动切换。 */ + const decision = ref<'keep_blocked' | 'release_future_charges'>('keep_blocked') + /** 用户确认的是本次当前版本,刷新和编辑均撤销。 */ + const confirmed = ref(false) + /** 同步写入过程防重复操作。 */ + const saving = ref(false) + /** 完整校验只在提交时显示。 */ + const validation = ref('') + /** 当前原请求的有效版本证据,旧历史仍保留展示。 */ + const currentEvidence = computed( + () => + query.data.value?.history.evidence.filter( + row => + row.taskFingerprint === query.data.value?.taskFingerprint && + row.body.expectedTaskFingerprint === query.data.value?.taskFingerprint + ) ?? [] + ) + /** 复核只能使用用户选中的当前正式材料。 */ + const selectedEvidence = computed(() => currentEvidence.value.find(row => row.id === evidenceId.value)) + /** 核清不依据零token、unknown、观测记录或本地编号推断。 */ + const releaseIssues = computed(() => + query.data.value + ? imageBillingReleaseIssues(selectedEvidence.value?.body.evidence, query.data.value) + : ['请先读取原请求审计。'] + ) + /** 固定底栏区分登记、保留和核清。 */ + const submitLabel = computed(() => + action.value === 'evidence' + ? '登记图片费用证据' + : decision.value === 'keep_blocked' + ? '确认保留费用阻断' + : '确认核清原请求费用' + ) + /** 真实版本已读且用户明确确认后才允许提交。 */ + const canSubmit = computed( + () => + !!query.data.value && + !query.loading.value && + !query.error.value && + !saving.value && + !props.disabled && + confirmed.value && + (action.value !== 'review' || + (!!selectedEvidence.value && + (decision.value !== 'release_future_charges' || !releaseIssues.value.length))) + ) + /** 使用原NMessage反馈。 */ + const message = useActionMessage() + watch( + [action, facts, operator, evidenceId, reviewer, reason, confirmationSha256, decision], + () => { + confirmed.value = false + validation.value = '' + }, + { deep: true, flush: 'sync' } + ) + watch( + query.data, + () => { + confirmed.value = false + }, + { flush: 'sync' } + ) + /** 项目或原请求切换不继承证据、签署或人工确认。 */ + watch( + key, + () => { + action.value = 'evidence' + operator.value = '' + facts.value = { + correlation: 'unverified', + providerRequestId: null, + artifacts: [], + execution: { outcome: 'unknown', evidenceIds: [] }, + billing: { finding: 'unknown', amount: null, currency: 'USD', evidenceIds: [] } + } + evidenceId.value = '' + reviewer.value = '' + reason.value = '' + confirmationSha256.value = '' + decision.value = 'keep_blocked' + confirmed.value = false + validation.value = '' + }, + { flush: 'sync' } + ) + /** 免费读取当前GET,保留本次用户表单并要求重新确认。 */ + async function refresh() { + confirmed.value = false + await query.refresh() + } + /** 登记与复核分开提交,409刷新正式GET,保留输入并等待重新确认。 */ + async function submit() { + const view = query.data.value + if (!view || !canSubmit.value) return + const errors = + action.value === 'evidence' + ? [ + ...imageBillingEvidenceIssues(facts.value, view), + ...(!operator.value.trim() || operator.value.trim().length > 120 + ? ['请填写1~120字的实际登记人。'] + : []) + ] + : [ + ...(!selectedEvidence.value ? ['请重新选择当前版本的正式证据。'] : []), + ...(decision.value === 'release_future_charges' ? releaseIssues.value : []), + ...(!reviewer.value.trim() || + reviewer.value.trim().length > 120 || + reason.value.trim().length < 4 || + reason.value.trim().length > 2000 || + !/^[a-f0-9]{64}$/.test(confirmationSha256.value) + ? ['请填写实际复核人、4~2000字理由及真实材料SHA256。'] + : []) + ] + if (errors.length) { + validation.value = [...new Set(errors)].join(' ') + return + } + const target = key.value + const operation = action.value + saving.value = true + confirmed.value = false + try { + const result = + operation === 'evidence' + ? await imageBillingAuditApi.evidence(view.projectId, view.requestId, { + expectedTaskFingerprint: view.taskFingerprint, + operator: operator.value.trim(), + evidence: { + ...JSON.parse(JSON.stringify(facts.value)), + identity: JSON.parse(JSON.stringify(view.identity)) + } + }) + : await imageBillingAuditApi.review(view.projectId, view.requestId, { + evidenceId: evidenceId.value, + expectedTaskFingerprint: view.taskFingerprint, + expectedEvidenceSetFingerprint: view.evidenceSetFingerprint, + expectedReviewFingerprint: view.reviewFingerprint, + decision: decision.value, + reviewer: reviewer.value.trim(), + reason: reason.value.trim(), + confirmationSha256: confirmationSha256.value + }) + if (disposed || target !== key.value) return + if (result?.projectId !== view.projectId || result.requestId !== view.requestId) + throw new Error('费用回执与原请求不一致,请重新读取。') + message?.info( + operation === 'evidence' + ? '证据已登记,仍需独立人工复核。' + : result.billingBlocked + ? '复核已记录,原请求费用仍阻断。' + : '原请求费用已核清;原执行状态、图片质量与主图资格保持独立。' + ) + await refresh() + if (!disposed && target === key.value) await changed() + } catch (cause) { + if (disposed || target !== key.value) return + message?.error(errorMessage(cause)) + if (cause instanceof ApiError && cause.status === 409) await refresh() + } finally { + saving.value = false + } + } + return { + query, + action, + operator, + facts, + evidenceId, + reviewer, + reason, + confirmationSha256, + decision, + confirmed, + saving, + validation, + currentEvidence, + selectedEvidence, + releaseIssues, + submitLabel, + canSubmit, + refresh, + submit + } +} diff --git a/src/features/production/api.ts b/src/features/production/api.ts index 5b3c772..ca0a547 100644 --- a/src/features/production/api.ts +++ b/src/features/production/api.ts @@ -171,7 +171,9 @@ export const productionApi = { /** 按本次请求选择的图片模型与参数预览最终输入,不创建首帧任务。 */ previewKeyframe: ( shotId: string, - input: Pick, + input: Pick & { + /** 已保存草案中的原模型参数。 */ generationOptions?: Record + }, signal?: AbortSignal ) => request(`${shotPath(shotId)}/keyframe/preview`, { @@ -179,8 +181,15 @@ export const productionApi = { signal, body: input }), - generateKeyframe: (shotId: string, input: GenerateKeyframeInput) => - request(`${shotPath(shotId)}/keyframe`, { + /** + * 提交用户确认的单镜首帧,追加许可显式绑定原项目。 + * @param shotId 正式镜头 + * @param input 已核对的模型参数及可选人工许可 + * @param projectId 原项目范围 + * @returns 原候选回执 + */ + generateKeyframe: (shotId: string, input: GenerateKeyframeInput, projectId?: string) => + request(keyframeScope(`${shotPath(shotId)}/keyframe`, projectId), { method: 'POST', body: input, timeoutMs: 0 diff --git a/src/features/production/components/KeyframeDialog.vue b/src/features/production/components/KeyframeDialog.vue index 25a3b3b..1519711 100644 --- a/src/features/production/components/KeyframeDialog.vue +++ b/src/features/production/components/KeyframeDialog.vue @@ -1,4 +1,8 @@ + diff --git a/src/features/storyboard/components/JointDraftReviewPanel.vue b/src/features/storyboard/components/JointDraftReviewPanel.vue new file mode 100644 index 0000000..f048a7f --- /dev/null +++ b/src/features/storyboard/components/JointDraftReviewPanel.vue @@ -0,0 +1,692 @@ + + diff --git a/src/features/storyboard/components/ShotDerivedReview.vue b/src/features/storyboard/components/ShotDerivedReview.vue index f59c119..59aa226 100644 --- a/src/features/storyboard/components/ShotDerivedReview.vue +++ b/src/features/storyboard/components/ShotDerivedReview.vue @@ -1,4 +1,6 @@ + + + +
+
构图
+
{{ shot.direction.composition }}
+
机位
+
{{ shot.direction.cameraPosition }}
+
+
+

此镜头尚无已保存的导演设计。

- + + {{ subject.subjectRef }}{{ subject.formName }} + +
+ +
+ + + -

此镜头还没有画面状态,请先完成镜头设计。

+

+ 此镜头尚无画面状态。请在“生成与恢复”中核对本次摄影范围后补齐。 +

diff --git a/src/features/storyboard/components/StagedShotPreparation.vue b/src/features/storyboard/components/StagedShotPreparation.vue index 0b887bd..7a110ed 100644 --- a/src/features/storyboard/components/StagedShotPreparation.vue +++ b/src/features/storyboard/components/StagedShotPreparation.vue @@ -123,7 +123,7 @@ function referenceAt(index: number) { > -

请先在镜头目录勾选要核对的镜头。

+

请先展开“选择镜头”勾选本次范围。

正在读取正式生产计划和所选镜头参考素材…

diff --git a/src/features/storyboard/components/VisualStateContinuity.vue b/src/features/storyboard/components/VisualStateContinuity.vue new file mode 100644 index 0000000..8c11c2c --- /dev/null +++ b/src/features/storyboard/components/VisualStateContinuity.vue @@ -0,0 +1,18 @@ + + diff --git a/src/features/storyboard/derived-review-api.ts b/src/features/storyboard/derived-review-api.ts index 878b33b..5d1629c 100644 --- a/src/features/storyboard/derived-review-api.ts +++ b/src/features/storyboard/derived-review-api.ts @@ -1,6 +1,7 @@ import { keyframeScope } from '../production/keyframe-scope' import { request } from '../../lib/http' import type { + JointDerivedReviewResult, DirectionReviewInput, DirectionReviewResult, DerivedReviewSelection, @@ -13,6 +14,22 @@ import type { /** 已审摄影草案的正式读写入口。 */ export const derivedReviewApi = { + /** + * 使用原confirm接口免费预检或采用同一完整联合草案。 + * @param projectId 正式项目 + * @param body 冻结的审核人、已保存草案和完整差异 + * @param signal 取消只读预检 + * @returns 整批采用或幂等回执 + */ + joint: ( + projectId: string, + body: { reviewer: string; shots: DerivedReviewSelection[]; preview: boolean }, + signal?: AbortSignal + ) => + request( + `/projects/${encodeURIComponent(projectId)}/storyboard-derived-reviews/confirm`, + { method: 'POST', body, signal } + ), /** * 沿原采用接口免费预检或采用独立摄影,不生成画面状态。 * @param projectId 正式项目 diff --git a/src/features/storyboard/derived-review.types.ts b/src/features/storyboard/derived-review.types.ts index 3e26dfe..a9a037b 100644 --- a/src/features/storyboard/derived-review.types.ts +++ b/src/features/storyboard/derived-review.types.ts @@ -61,6 +61,11 @@ export type DraftProviderInput = Pick { + /** 本镜完整摄影和开拍状态的版本。 */ currentDerivedFingerprint?: string + /** 正式同集紧邻镜头的完整版本,原样用于联合采用。 */ adjacentDerivedVersions?: Array<{ + /** 正式镜头。 */ shotId: string + /** 完整派生版本。 */ derivedFingerprint: string + }> /** 本次草案的确切输入版本。 */ draftFingerprint: string /** 草案始终不能直接生成。 */ productionReady: false /** 项目级制作门禁。 */ @@ -70,6 +75,7 @@ export interface ShotDraftPreview extends Omit } + +/** 联合采用逐字段声明,环境修改另需本集原文,主体身份及形态仍不可编辑。 */ +export type JointDerivedChange = + | { + /** 摄影意图。 */ target: 'direction' + /** 正式允许字段。 */ field: 'composition' | 'cameraPosition' | 'visualIntent' + /** 正式原值。 */ before: string + /** 草案目标值。 */ after: string + } + | { + /** 本镜0秒环境。 */ target: 'environment' + /** 正式允许的四项环境字段。 */ field: 'timeOfDay' | 'weather' | 'atmosphere' | 'transientState' + /** 正式原值,未知可为空。 */ before: string + /** 草案目标值,不猜测未知天气。 */ after: string + } + | { + /** 衔接文字。 */ target: 'visualState' + /** 正式允许字段。 */ field: 'continuityNote' + /** 正式原值。 */ before: string + /** 草案目标值。 */ after: string + } + | { + /** 主体0秒状态。 */ target: 'subject' + /** 正式主体。 */ subjectRef: string + /** 正式允许字段。 */ field: 'expression' | 'pose' | 'gaze' | 'position' | 'transientState' + /** 正式原值。 */ before: string + /** 草案目标值。 */ after: string + } + +/** 联合采用绑定已保存草案、当前派生与完整邻镜版本。 */ +export interface JointDerivedRevision { + /** 仅存在环境差异时提供,由正式项目详情的本集全文及人工片段形成。 */ + environmentSource?: { + /** 当前正式集ID,采用事务最终核对Storyboard外键。 */ episodeId: string + /** 本集完整content原字节SHA256,不使用摘要或截取正文。 */ expectedContentFingerprint: string + /** 人工选择的本集逐字片段。 */ quote: string + } + /** 已保存草案修订。 */ expectedDraftRevision: number + /** 当前摄影及画面状态版本。 */ expectedDerivedFingerprint: string + /** 完整同集紧邻镜头版本。 */ expectedNeighbors: NonNullable + /** 用户确认的修订与剪辑依据。 */ reason: string + /** 全部允许差异,不得漏报或重复。 */ changes: JointDerivedChange[] +} + +/** 联合采用的同步事务回执,不代表生图或质量通过。 */ +export interface JointDerivedReviewResult { + /** 正式项目。 */ projectId: string + /** 是否只读预检。 */ preview: boolean + /** 是否真实写入。 */ changed: boolean + /** 是否复用同一已采用请求。 */ reused: boolean + /** 本次完整请求版本。 */ requestFingerprint: string + /** 整批返回的正式归属。 */ shots: Array<{ + /** 正式镜头。 */ shotId: string + /** 摄影记录。 */ directionId: string + /** 画面状态记录。 */ visualStateId: string + }> +} diff --git a/src/features/storyboard/joint-review.ts b/src/features/storyboard/joint-review.ts new file mode 100644 index 0000000..7c80652 --- /dev/null +++ b/src/features/storyboard/joint-review.ts @@ -0,0 +1,171 @@ +import type { JointDerivedChange, ShotReviewDraft } from './derived-review.types' + +/** 完整差异展示包含不可修改项,不能只列允许字段而隐藏越界变化。 */ +export interface JointDraftDifference { + /** 中文字段或主体位置。 */ label: string + /** 修改前原文。 */ before: string + /** 修改后原文。 */ after: string + /** 是否属于正式联合采用白名单。 */ allowed: boolean + /** 可提交的差异,越界项不构造请求。 */ change?: JointDerivedChange +} +/** 摄影、主体和时间状态共用的中文字段名。 */ +export const jointFieldLabels: Record = { + composition: '构图', + cameraPosition: '摄影机位置', + visualIntent: '摄影意图', + continuityNote: '衔接与时间依据', + expression: '表情', + pose: '姿态', + gaze: '视线', + position: '位置', + transientState: '即时变化', + formId: '形态身份', + formName: '形态名称', + shotNo: '镜头编号', + timeOfDay: '时间', + weather: '天气', + atmosphere: '氛围', + shotSize: '景别', + cameraAngle: '摄影角度', + cameraMovement: '运镜', + lensIntent: '焦段', + depthOfField: '景深' +} +/** + * 稳定比较完整JSON草案,属性顺序不构成修改。 + * @param value 真实字段值 + * @returns 可比较的稳定原文 + */ +export function jointValue(value: unknown): string { + if (typeof value === 'string') return JSON.stringify(value) + if (value === undefined) return '(字段缺失)' + if (value && typeof value === 'object' && !Array.isArray(value)) + return JSON.stringify( + Object.fromEntries( + Object.entries(value) + .toSorted(([a], [b]) => a.localeCompare(b)) + .map(([key, item]) => [key, jointValue(item)]) + ) + ) + if (Array.isArray(value)) return JSON.stringify(value.map(jointValue)) + return JSON.stringify(value) +} +/** + * 比对完整正式内容与待审草案,允许差异与越界差异都完整展示。 + * @param formal 当前正式摄影和0秒状态 + * @param draft 用户完整待审草案 + * @returns 全部逐字段差异,不能从中悄悄删除越界项后采用 + */ +export function jointDraftDifferences(formal: ShotReviewDraft, draft: ShotReviewDraft): JointDraftDifference[] { + const differences: JointDraftDifference[] = [] + /** + * 比对真实值,只为正式允许的字符串字段形成差异声明。 + * @param label 中文字段名 + * @param before 正式原值 + * @param after 完整草案值 + * @param change 允许字段的正式差异 + */ + function compare(label: string, before: unknown, after: unknown, change?: JointDerivedChange) { + if (jointValue(before) === jointValue(after)) return + differences.push({ + label, + before: typeof before === 'string' ? before : jointValue(before), + after: typeof after === 'string' ? after : jointValue(after), + allowed: !!change, + change + }) + } + for (const field of new Set([...Object.keys(formal.direction), ...Object.keys(draft.direction)])) { + const key = field as keyof typeof formal.direction + const before = formal.direction[key], + after = draft.direction[key] + const allowed = + ['composition', 'cameraPosition', 'visualIntent'].includes(field) && + typeof before === 'string' && + typeof after === 'string' + compare( + `摄影 · ${jointFieldLabels[field] ?? field}`, + before, + after, + allowed + ? { + target: 'direction', + field: field as 'composition' | 'cameraPosition' | 'visualIntent', + before: before as string, + after: after as string + } + : undefined + ) + } + compare('画面状态 · 镜头编号', formal.visualState.shotNo, draft.visualState.shotNo) + compare('画面状态 · 衔接与时间依据', formal.visualState.continuityNote, draft.visualState.continuityNote, { + target: 'visualState', + field: 'continuityNote', + before: formal.visualState.continuityNote, + after: draft.visualState.continuityNote + }) + for (const field of new Set([ + ...Object.keys(formal.visualState.environment), + ...Object.keys(draft.visualState.environment) + ])) { + const key = field as keyof typeof formal.visualState.environment + const before = formal.visualState.environment[key], + after = draft.visualState.environment[key] + const allowed = + ['timeOfDay', 'weather', 'atmosphere', 'transientState'].includes(field) && + typeof before === 'string' && + typeof after === 'string' + compare( + `环境 · ${jointFieldLabels[field] ?? field}`, + before, + after, + allowed ? { target: 'environment', field: key, before, after } : undefined + ) + } + const previous = new Map(formal.visualState.subjects.map(subject => [subject.subjectRef, subject])) + const next = new Map(draft.visualState.subjects.map(subject => [subject.subjectRef, subject])) + if (previous.size !== formal.visualState.subjects.length || next.size !== draft.visualState.subjects.length) + compare('主体重复或集合异常', formal.visualState.subjects, draft.visualState.subjects) + for (const subjectRef of new Set([...previous.keys(), ...next.keys()])) { + const before = previous.get(subjectRef), + after = next.get(subjectRef) + if (!before || !after) { + compare(`${subjectRef} · 主体集合`, before, after) + continue + } + for (const field of new Set([...Object.keys(before), ...Object.keys(after)])) { + const key = field as keyof typeof before + const allowed = + ['expression', 'pose', 'gaze', 'position', 'transientState'].includes(field) && + typeof before[key] === 'string' && + typeof after[key] === 'string' + compare( + `${subjectRef} · ${jointFieldLabels[field] ?? field}`, + before[key], + after[key], + allowed + ? { + target: 'subject', + subjectRef, + field: field as 'expression' | 'pose' | 'gaze' | 'position' | 'transientState', + before: before[key], + after: after[key] + } + : undefined + ) + } + } + for (const field of new Set([...Object.keys(formal), ...Object.keys(draft)])) { + if (['direction', 'visualState'].includes(field)) continue + compare( + field === 'expectedShotFingerprint' + ? '正式分镜版本' + : field === 'sceneSources' + ? '场景参考与几何版本' + : '修订模式', + formal[field as keyof ShotReviewDraft], + draft[field as keyof ShotReviewDraft] + ) + } + return differences +} diff --git a/src/features/storyboard/types.ts b/src/features/storyboard/types.ts index 119fc9c..37a3d5a 100644 --- a/src/features/storyboard/types.ts +++ b/src/features/storyboard/types.ts @@ -75,6 +75,9 @@ export interface EpisodeVisualStates { /** 导演设计与视觉状态统一呈现的校验问题。 */ export interface StoryboardIssue { + /** 原时间或其它结构化问题码,不改变业务判断。 */ code?: string + /** 确定性冲突与人工待审分别展示。 */ severity?: 'error' | 'needs_review' + /** 原问题字段用于定位。 */ field?: string episodeNo: number beatNo: number | null shotNo: number | null diff --git a/src/features/storyboard/visual-state-time.ts b/src/features/storyboard/visual-state-time.ts new file mode 100644 index 0000000..e229f28 --- /dev/null +++ b/src/features/storyboard/visual-state-time.ts @@ -0,0 +1,45 @@ +/** 统一时间契约的展示分段,不能作为模型结果有效性的判断。 */ +export interface VisualStateTimeSection { + /** 后端明确提供的分类。 */ kind: 'input' | 'planned' | 'continuity' | 'video' | 'legacy' + /** 普通用户可读标题。 */ title: string + /** 原文字内容,不翻译或改写。 */ text: string +} +/** + * 只按正式四种显式标记排版,旧文字保持原样,不按动作关键词推断时间或审核结果。 + * @param note 原continuityNote + * @returns 可展示的完整原文分段 + */ +export function visualStateTimeSections(note: string): VisualStateTimeSection[] { + const markers = [...note.matchAll(/【(输入事实|规划末态|连续要求|视频末态)】/g)] + if (!markers.length) return [{ kind: 'legacy', title: '原衔接说明(未分段)', text: note }] + const kinds = { 输入事实: 'input', 规划末态: 'planned', 连续要求: 'continuity', 视频末态: 'video' } as const + const titles = { + 输入事实: '已确认的输入事实', + 规划末态: '规划中的镜头结束状态', + 连续要求: '相邻镜头连续性要求', + 视频末态: '视频末态声明(仍需真实视频证据核验)' + } + const sections: VisualStateTimeSection[] = [] + const prefix = note.slice(0, markers[0]!.index).trim() + if (prefix) sections.push({ kind: 'legacy', title: '原补充说明', text: prefix }) + markers.forEach((marker, index) => { + const name = marker[1] as keyof typeof kinds + sections.push({ + kind: kinds[name], + title: titles[name], + text: note.slice(marker.index! + marker[0].length, markers[index + 1]?.index ?? note.length).trim() + }) + }) + return sections +} +/** + * 仅使用后端问题码与severity命名,保留原消息和定位,不自行判定质量。 + * @param issue 原问题 + * @returns 时间问题标题或空值 + */ +export function visualStateTimeIssueLabel(issue: { code?: string; severity?: string }) { + if (issue.code === 'VISUAL_STATE_START_CONFLICT') return '开拍状态冲突' + if (issue.code === 'VISUAL_STATE_TIME_NEEDS_REVIEW') return '时间语义待人工核对' + if (issue.code === 'VISUAL_STATE_VIDEO_END_UNSUPPORTED') return '真实视频末态缺少证据' + return issue.severity === 'needs_review' ? '需要人工核对' : '' +} diff --git a/src/features/subject-images/generation-preview.ts b/src/features/subject-images/generation-preview.ts index c6bf413..05dd861 100644 --- a/src/features/subject-images/generation-preview.ts +++ b/src/features/subject-images/generation-preview.ts @@ -101,6 +101,10 @@ interface PreviewOptions string | undefined + /** 已有完整同计划候选时只读查看,不能新增请求。 */ + reuseResult?: (preview: Preview) => Promise /** 当前完整生成参数。 */ input: () => Input /** 当前是否允许提交。 */ @@ -139,6 +143,8 @@ export function useImageGenerationPreview preview.value?.provider !== 'openai-image' || !options.chargeContext ) + /** 只有正式费用计划证明完整回执可复用时才允许只读查看。 */ + const reusableResult = computed(() => charge.value?.reusable === true && !!options.reuseResult) /** 授权与未知费用显示在当前生成入口。 */ const chargeNotice = computed(() => charge.value?.message ?? '') /** 输入快照同时绑定界面目标和显隐周期。 */ @@ -160,7 +166,7 @@ export function useImageGenerationPreview - let list, planFingerprint: string | undefined + let list, planFingerprint: string | undefined, sourceFingerprint: string | undefined if (context.exactPreview && ['identity', 'form', 'keyframe'].includes(context.scope)) { const plan = await imageAuthorizationApi.preview( context.projectId, @@ -238,6 +244,7 @@ export function useImageGenerationPreview +import { visualStateTimeIssueLabel } from '../storyboard/visual-state-time' import WorkspaceActionTooltip from '../../components/ui/WorkspaceActionTooltip.vue' import ConfirmAction from './ConfirmAction.vue' import { useQuery } from '../../composables/useQuery' @@ -112,6 +113,9 @@ const derivedEpisodes = computed(() => { ( issue ): issue is { + code?: string + severity?: 'error' | 'needs_review' + field?: string episodeNo: number beatNo: number | null shotNo: number | null @@ -639,7 +643,9 @@ function isInputMode(value: unknown, inputMode: string): boolean { : '状态待确认' }}:{{ derivedErrorSummary(item.error) }}

- 段落 {{ issue.beatNo ?? '待确认' }} · 镜头 {{ issue.shotNo ?? '待确认' }}:{{ + {{ visualStateTimeIssueLabel(issue) }} · 段落 {{ issue.beatNo ?? '待确认' }} · 镜头 {{ issue.shotNo ?? '待确认' }}:{{ userFacingText(issue.message) }}

diff --git a/src/lib/billing-errors.ts b/src/lib/billing-errors.ts index e132dd5..34e82ea 100644 --- a/src/lib/billing-errors.ts +++ b/src/lib/billing-errors.ts @@ -1,5 +1,12 @@ /** 用户可操作的图片授权及视频费用审计错误,保留原码用于业务判断。 */ const messages: Record = { + IMAGE_ADDITIONAL_AUTHORIZATION_INVALID: '人工追加许可无效、已撤销、用尽,或原精确计划与预算已变化,请重新核对。', + IMAGE_BILLING_AUDIT_CONFLICT: '原图片请求或批准版本冲突,请重新读取审计。', + IMAGE_BILLING_AUDIT_IDENTITY_MISMATCH: '材料与原图片请求身份不匹配,或供应方编号已归属其它请求。', + IMAGE_BILLING_AUDIT_STALE: '原请求或完整证据集合已变化,请重新核对并确认。', + IMAGE_BILLING_AUDIT_REVIEW_CONFLICT: '另一项图片费用复核已先完成,请刷新后重新核对。', + IMAGE_BILLING_AUDIT_RELEASE_REJECTED: '尚不具备费用核清条件,请核对原执行、真实账单及唯一关联。', + IMAGE_BILLING_AUDIT_EVIDENCE_INVALID: '图片审计历史或摘要无法核实,费用继续阻断。', IMAGE_AUTHORIZATION_REQUIRED: '当前模型或范围没有有效图片授权,授权可能已到期或撤销。请核对项目生成设置。', IMAGE_AUTHORIZATION_EXPIRED: '到期时间已过,请重新填写未来时间。', IMAGE_AUTHORIZATION_BUDGET_EXCEEDED: '图片授权剩余预算不足整次预留,或请求次数已用尽。', @@ -35,10 +42,34 @@ const failureMessages: Record = { * @returns 可操作说明或空值 */ export function billingErrorText(code: string | undefined, details: unknown): string | undefined { - const record = details && typeof details === 'object' ? (details as Record) : {} + const outer = details && typeof details === 'object' ? (details as Record) : {} + const nested = outer.details && typeof outer.details === 'object' ? (outer.details as Record) : {} + const record = { ...outer, ...nested } const actualCode = code ?? (typeof record.code === 'string' ? record.code : undefined) if (actualCode && messages[actualCode]) return messages[actualCode] - if (actualCode?.startsWith('OPENAI_IMAGE_')) - return failureMessages[String(record.failureType)] ?? '图片请求结果或费用尚未核实,请查看原请求,禁止自动重发。' + if (actualCode?.startsWith('OPENAI_IMAGE_')) { + const cause = + record.causeCode === 'UND_ERR_CONNECT_TIMEOUT' + ? '底层连接超时' + : record.causeCode === 'ECONNREFUSED' + ? '底层连接被拒绝' + : record.causeCode === 'ETIMEDOUT' + ? '底层请求超时' + : '' + const transport = + record.transportMode === 'proxy' + ? '应用通过代理连接' + : record.transportMode === 'direct' + ? '应用直接连接' + : '' + return [ + failureMessages[String(record.failureType)] ?? '图片请求结果或费用尚未核实,请查看原请求,禁止自动重发。', + ...(['network_error', 'timeout_unknown', 'receipt_unknown'].includes(String(record.failureType)) + ? [transport, cause] + : []) + ] + .filter(Boolean) + .join(';') + } return undefined } diff --git a/src/lib/user-facing-text.ts b/src/lib/user-facing-text.ts index 52f6387..4eddbe1 100644 --- a/src/lib/user-facing-text.ts +++ b/src/lib/user-facing-text.ts @@ -152,6 +152,17 @@ export function userFacingText(value: string | null | undefined, fallback = '暂 STORYBOARD_DERIVED_STALE: '摄影或画面来源已变化,请重新预检,不能覆盖旧版本。', STORYBOARD_DERIVED_REQUEST_UNRESOLVED: '原请求结果尚未核清,请核对原任务和费用,不要重复生成。', STORYBOARD_DIRECTION_SCOPE_MISMATCH: '本镜摄影的可见范围与正式绑定冲突,请核对对应段落和镜头。', + VISUAL_STATE_START_CONFLICT: '开拍状态与已确认的输入事实冲突,请核对对应镜头。', + VISUAL_STATE_TIME_NEEDS_REVIEW: '开拍与结束时点存在歧义,需要人工核对,尚未通过。', + VISUAL_STATE_VIDEO_END_UNSUPPORTED: '缺少真实视频末态证据,不能把规划结束状态当作已验证结果。', + JOINT_REVISION_DRAFT_STALE: '已保存联合草案或修订号已变化,请重新读取并免费预检。', + JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: '本集原文依据缺失或版本已变化,请保留草案,重新读取原文并人工核对。', + JOINT_REVISION_NEIGHBOR_STALE: '相邻镜头版本已变化,请重新核对连续性依据。', + JOINT_REVISION_STALE: '本镜摄影或开拍状态已变化,请保留草案并重新核对。', + JOINT_REVISION_SCOPE: '联合草案超出允许字段或存在未声明差异,请核对完整修改。', + JOINT_REVISION_ACTIVE: '本次范围有活动任务,暂不能联合采用。', + JOINT_REVISION_DOWNSTREAM: '本镜已有下游生产结果或执行记录,请使用原受控修订流程。', + JOINT_REVISION_HISTORY_INVALID: '联合采用历史无法核对,请保留原稿并检查正式记录。', STORYBOARD_SOURCE_MISMATCH: '镜头与已提交分镜不一致,请刷新后核对。' } const code = Object.keys(codeLabels).find( diff --git a/tests/browser/review-billing.html b/tests/browser/review-billing.html new file mode 100644 index 0000000..d284f40 --- /dev/null +++ b/tests/browser/review-billing.html @@ -0,0 +1,12 @@ + + + + + + 联合摄影与图片费用 · 隔离验收 + + +
+ + + diff --git a/tests/browser/review-billing.ts b/tests/browser/review-billing.ts new file mode 100644 index 0000000..0cba563 --- /dev/null +++ b/tests/browser/review-billing.ts @@ -0,0 +1,456 @@ +import { createApp, defineComponent, h, ref } from 'vue' +import { NButton, NConfigProvider, NGlobalStyle, NMessageProvider, dateZhCN, zhCN } from 'naive-ui' +import ActionMessageProvider from '../../src/components/ui/ActionMessageProvider.vue' +import { useTheme } from '../../src/composables/useTheme' +import ShotDerivedReview from '../../src/features/storyboard/components/ShotDerivedReview.vue' +import ProjectSettingsDialog from '../../src/features/generation-config/components/ProjectSettingsDialog.vue' +import KeyframeDialog from '../../src/features/production/components/KeyframeDialog.vue' +import { jointReviewFixture } from '../fixtures/joint-review' +import { imageAuditFixture } from '../fixtures/image-billing-audit' +import { additionalImageFixture } from '../fixtures/image-additional' +import { imagePreviewFixture } from '../fixtures/image-preview' +import { billingCatalog, billingProfile } from '../fixtures/billing' +import type { + ImageBillingEvidenceInput, + ImageBillingReviewInput +} from '../../src/features/image-authorization/billing-audit.types' +import type { ImageAdditionalAuthorizationInput } from '../../src/features/image-authorization/types' +import '../../src/styles/styles.css' +import '../../src/styles/admin.css' + +/** 隔离数据只存在本页面,未知接口403,无任何正式项目或模型连接。 */ +const joint = jointReviewFixture('mock-joint-project') +/** 可选环境验收仅修改内存草案;完整源集正文保留原始换行。 */ +const environmentMode = new URLSearchParams(location.search).has('environment') +/** 模拟正式项目详情公开的本集身份和全文,不使用摘要。 */ +const environmentEpisode = { + id: 'mock-source-episode', + projectId: 'mock-joint-project', + episode: 1, + title: '当前源集', + content: '第一行\r\n午后,维修间透入日光。\n天气未指定。' +} +if (environmentMode) { + joint.saved.draft.visualState.environment = { + timeOfDay: '午后', + weather: '', + atmosphere: '自然日光', + transientState: '' + } +} +/** 原unknown与账单始终保留的隔离费用账本。 */ +const images = additionalImageFixture() +images.additionalAuthorizations = [] +/** 原图片审计身份与费用父请求一致,所有原件必须由测试操作者填写。 */ +const audit = imageAuditFixture('billing-project', 'original-image-request') +audit.identity.candidateId = 'original-image' +audit.reservedMicros = images.requests[0]!.input.reservedMicros +/** 只统计模拟同步操作,不是真实模型调用。 */ +const writes = ref(0) +/** 隔离模型请求计数,已成功后同计划不再增加。 */ +const mockGenerations = ref(0) +/** 精确保存当前页面发出的请求,帮助验收无隐式生成。 */ +const calls: Array<{ path: string; method: string; body: unknown }> = [] +/** 模拟并发仅作用于下一次正式联合采用,不改变预检。 */ +let neighborConflict = false +/** 下一次采用时模拟本集正文版本变化,预检仍可通过。 */ +let environmentConflict = false +/** 模拟审计409后保留表单。 */ +let auditConflict = false +/** 只读结果是否已有完整同计划候选。 */ +let hasImage = false +/** + * 返回隔离的正式接口响应形状。 + * @param data 当前模拟数据 + * @returns 不连接网络的响应 + */ +function ok(data: unknown) { + return new Response(JSON.stringify({ data }), { headers: { 'Content-Type': 'application/json' } }) +} +/** + * 全请求隔离处理,任何未声明路由都拒绝,不回退真实fetch。 + * @param input 原请求地址 + * @param init 原请求参数 + * @returns 正式接口形状的Mock响应 + */ +window.fetch = async (input, init) => { + const path = String(input), + method = init?.method ?? 'GET', + body = init?.body ? JSON.parse(String(init.body)) : undefined + calls.push({ path, method, body }) + if (method === 'POST' || method === 'PUT') writes.value++ + if (path === '/api/projects/mock-joint-project') + return ok({ id: 'mock-joint-project', episodes: [environmentEpisode] }) + if (path.endsWith('/generation-models')) return ok(billingCatalog) + if (path.endsWith('/creative-profile')) return ok(billingProfile) + if (path.endsWith('/resolve')) return ok({ provider: 'openai-image', model: 'gpt-image-2.5-flare', options: {} }) + if (path.includes('/keyframe-review-draft')) { + if (method === 'PUT') { + if (body.expectedRevision !== joint.saved.revision) + return new Response(JSON.stringify({ message: '草案版本已变化' }), { status: 409 }) + joint.saved.draft = body.draft + joint.saved.providerInput = body.providerInput ?? null + joint.saved.expectedCurrentFormalSourceFingerprint = body.expectedCurrentFormalSourceFingerprint + joint.saved.revision++ + joint.saved.status = 'current' + } + return ok(joint.saved) + } + if (path.endsWith('/storyboard-quality-confirmation')) + return ok({ ...joint.approval.approval, valid: true, confirmation: joint.approval.record }) + if (path.endsWith('/storyboard-quality-confirmation/preflight')) + return ok({ + current: { ...joint.approval.approval, valid: true, confirmation: joint.approval.record }, + quality: joint.approval.quality + }) + if (path.includes('/storyboard-directions?')) return ok(joint.directions) + if (path.includes('/storyboard-visual-states?')) return ok(joint.visuals) + if (path.includes('/keyframe-spec')) return ok(joint.keyframe) + if (path.includes('/generation-spec')) + return ok({ shotId: joint.shot.shotId, projectId: 'mock-joint-project', subjects: [] }) + if (path.endsWith('/storyboard-derived-reviews/confirm')) { + if (body.shots[0]?.jointRevision) { + if (!body.preview && environmentConflict) { + environmentConflict = false + environmentEpisode.content += '\n另一位编辑已更新源正文。' + } + if (body.shots[0].jointRevision.changes.some((row: { target: string }) => row.target === 'environment')) { + const source = body.shots[0].jointRevision.environmentSource + const digest = await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(environmentEpisode.content) + ) + const fingerprint = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join( + '' + ) + if ( + !source || + source.episodeId !== environmentEpisode.id || + source.expectedContentFingerprint !== fingerprint || + !environmentEpisode.content.includes(source.quote) + ) + return new Response( + JSON.stringify({ + message: 'JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: 本集原文已变化,请重新核对。' + }), + { status: 409 } + ) + } + if (!body.preview && neighborConflict) { + neighborConflict = false + return new Response( + JSON.stringify({ message: 'JOINT_REVISION_NEIGHBOR_STALE: 相邻镜头已经更新,请重新读取。' }), + { status: 409 } + ) + } + if (!body.preview) { + const draft = body.shots[0].draft + joint.saved.status = 'stale' + joint.directions.beats[0]!.shots[0]!.direction = { + ...draft.direction, + rawJson: JSON.stringify({ + jointRevisionHistory: [ + { + originalDirection: joint.shot.direction, + changes: body.shots[0].jointRevision.changes, + environmentSource: body.shots[0].jointRevision.environmentSource, + reviewer: body.reviewer + } + ] + }) + } + joint.visuals.beats[0]!.shots[0]!.visualState = { + timeOfDay: draft.visualState.environment.timeOfDay, + weather: draft.visualState.environment.weather, + atmosphere: draft.visualState.environment.atmosphere, + environmentTransientState: draft.visualState.environment.transientState, + continuityNote: draft.visualState.continuityNote, + subjects: draft.visualState.subjects.map((subject: Record) => ({ + ...subject, + subjectId: 'mock-subject', + subjectFormId: subject.formId + })) + } + } + return ok({ + projectId: 'mock-joint-project', + preview: body.preview, + changed: !body.preview, + reused: false, + requestFingerprint: 'f'.repeat(64), + shots: [{ shotId: joint.shot.shotId, directionId: 'mock-direction', visualStateId: 'mock-visual' }] + }) + } + return ok({ shots: [{ shotId: joint.shot.shotId }] }) + } + if (path.includes('/keyframe/preview')) { + const image = { + ...imagePreviewFixture(), + provider: body.provider ?? 'openai-image', + model: 'gpt-image-2.5-flare', + shotId: path.includes('/audit-shot/') ? 'audit-shot' : joint.shot.shotId + } + return body.draft + ? ok({ + ...image, + draftFingerprint: 'a'.repeat(64), + productionReady: false, + productionGate: { ready: false, reason: '隔离项目尚未完整生产' }, + currentDerivedFingerprint: 'c'.repeat(64), + adjacentDerivedVersions: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }], + sceneSources: [] + }) + : ok(image) + } + if (path.endsWith('/image-authorizations/preview')) + return ok({ + provider: 'openai-image', + model: 'gpt-image-2.5-flare', + context: { + projectId: 'billing-project', + targetId: 'audit-shot', + scope: 'keyframe', + sourceFingerprint: 'c'.repeat(64) + }, + planFingerprint: 'b'.repeat(64), + authorization: images + }) + if (path.endsWith('/image-authorizations') && method === 'GET') return ok(images) + if (path.endsWith('/image-authorizations') && method === 'POST') { + if (body.mode === 'additional') { + const previous = images.additionalAuthorizations!.find( + row => row.input.idempotencyKey === body.idempotencyKey + ) + if (previous) return ok({ authorizationId: previous.id, status: previous.status }) + const approvalInput = body as ImageAdditionalAuthorizationInput + const permit = { + id: `mock-permit-${images.additionalAuthorizations!.length + 1}`, + status: 'approved', + input: { ...approvalInput, parentInputFingerprint: 'd'.repeat(64) }, + usedRequests: 0, + remainingRequests: approvalInput.maxRequests + } + images.additionalAuthorizations!.push(permit) + return ok({ authorizationId: permit.id, status: permit.status, parentAuthorizationId: 'grant' }) + } + return ok({ authorizationId: 'mock-standing', status: 'approved' }) + } + if (path.endsWith('/revoke')) { + const id = path.split('/').at(-2)!, + row = + images.authorizations.find(item => item.id === id) ?? + images.additionalAuthorizations!.find(item => item.id === id) + if (row) row.status = 'revoked' + return ok({ authorizationId: id, status: 'revoked' }) + } + if (path.endsWith('/audit')) return ok(audit) + if (path.endsWith('/audit/evidence')) { + const previous = audit.history.evidence.find(row => JSON.stringify(row.body) === JSON.stringify(body)) + const row = previous ?? { + id: `mock-evidence-${audit.history.evidence.length + 1}`, + requestId: audit.requestId, + taskFingerprint: audit.taskFingerprint, + body: body as ImageBillingEvidenceInput, + digest: '1'.repeat(64) + } + if (!previous) audit.history.evidence.push(row) + audit.evidenceSetFingerprint = '2'.repeat(64) + audit.released = false + audit.billingBlocked = true + audit.status = 'unreviewed' + return ok({ ...audit, evidenceId: row.id, reused: !!previous }) + } + if (path.endsWith('/audit/reviews')) { + if (auditConflict) { + auditConflict = false + audit.reviewFingerprint = '3'.repeat(64) + return new Response( + JSON.stringify({ + code: 'IMAGE_BILLING_AUDIT_REVIEW_CONFLICT', + message: '另一项隔离复核已先完成,请重新核对。' + }), + { status: 409 } + ) + } + const review = body as ImageBillingReviewInput + audit.history.reviews.push({ + id: `mock-review-${audit.history.reviews.length + 1}`, + requestId: audit.requestId, + taskFingerprint: audit.taskFingerprint, + body: review, + digest: '4'.repeat(64), + revision: audit.history.reviews.length + 1 + }) + audit.released = review.decision === 'release_future_charges' + audit.status = audit.released ? 'released' : 'blocked' + audit.billingBlocked = !audit.released + audit.reviewedAmountMicros = audit.released ? 1 : null + images.billingBlocked = audit.billingBlocked + images.blockingRequestIds = audit.billingBlocked ? ['original-image-request'] : [] + images.requests[0]!.billingAudit = { + status: audit.status, + released: audit.released, + reviewId: audit.released ? 'mock-review' : null, + reviewedAmountMicros: audit.reviewedAmountMicros + } + return ok({ ...audit, reused: false }) + } + if (/\/audit-shot\/keyframe(?:\?|$)/.test(path)) { + if (!hasImage) { + const permit = images.additionalAuthorizations!.find(row => row.id === body.additionalAuthorizationId) + if ( + !permit || + permit.status !== 'approved' || + !permit.remainingRequests || + body.provider !== 'openai-image' + ) + return new Response( + JSON.stringify({ + code: 'IMAGE_ADDITIONAL_AUTHORIZATION_INVALID', + message: '缺少当前精确计划人工许可' + }), + { status: 409 } + ) + permit.usedRequests++ + permit.remainingRequests-- + mockGenerations.value++ + hasImage = true + const grant = images.authorizations.find(row => row.id === images.requests[0]!.input.authorizationId) + if (grant) { + grant.usedRequests++ + grant.remainingRequests = Math.max(0, grant.remainingRequests - 1) + grant.accountedMicros += images.requests[0]!.input.reservedMicros + grant.remainingMicros = Math.max(0, grant.input.budgetMicros - grant.accountedMicros) + } + images.requests.push({ + ...structuredClone(images.requests[0]!), + id: 'mock-image-completed', + status: 'completed', + input: { ...images.requests[0]!.input, additionalAuthorizationId: permit.id }, + output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'mock-existing-result' } } + }) + } + return ok({ + id: 'mock-existing-candidate', + shotId: 'audit-shot', + status: 'completed', + recoveryRequired: false, + providerInputFingerprint: 'a'.repeat(64) + }) + } + return new Response(JSON.stringify({ message: '隔离页面拒绝未声明接口;不会连接正式服务。' }), { status: 403 }) +} +/** 原组件与原全屏抽屉组成的本地验收页,不进入正式构建入口。 */ +const Preview = defineComponent({ + setup() { + const theme = useTheme(), + settings = ref(false), + keyframe = ref(false) + return () => + h( + NConfigProvider, + { theme: theme.theme.value, themeOverrides: theme.overrides.value, locale: zhCN, dateLocale: dateZhCN }, + { + default: () => + h( + NMessageProvider, + {}, + { + default: () => + h( + ActionMessageProvider, + {}, + { + default: () => [ + h(NGlobalStyle), + h('main', { style: 'height:100dvh;overflow:auto;padding:24px' }, [ + h( + 'h1', + { style: 'font-size:22px;margin-bottom:12px' }, + '联合摄影与图片费用 · Mock隔离验收' + ), + h( + 'p', + { style: 'margin-bottom:20px' }, + '全部接口已拦截,测试材料仅保存在内存,不连接正式项目或真实模型。' + ), + h( + 'div', + { + style: 'display:flex;flex-wrap:wrap;gap:12px;margin-bottom:20px' + }, + [ + h( + NButton, + { onClick: () => (settings.value = true) }, + () => '项目图片授权与原请求' + ), + h( + NButton, + { onClick: () => (keyframe.value = true) }, + () => '原首帧生成入口' + ), + h( + NButton, + { onClick: () => (neighborConflict = true) }, + () => '模拟采用时邻镜变化' + ), + h( + NButton, + { onClick: () => (auditConflict = true) }, + () => '模拟一次费用复核冲突' + ), + h( + NButton, + { onClick: () => (environmentConflict = true) }, + () => '模拟采用时原文变化' + ) + ] + ), + h(ShotDerivedReview, { + projectId: 'mock-joint-project', + episodeNo: 1, + shot: joint.shot, + shots: joint.shots, + disabled: false + }), + h( + 'p', + { role: 'status', style: 'margin-top:20px' }, + `模拟同步操作 ${writes.value} 次 · 模拟图片请求 ${mockGenerations.value} 次 · 真实模型请求 0 次` + ) + ]), + h(ProjectSettingsDialog, { + projectId: 'billing-project', + disabled: false, + initialTab: 'image-authorization', + open: settings.value, + 'onUpdate:open': value => (settings.value = value) + }), + h(KeyframeDialog, { + projectId: 'billing-project', + shotId: 'audit-shot', + shotTitle: '仅供Mock的原镜头', + disabled: true, + additionalAllowed: true, + open: keyframe.value, + 'onUpdate:open': value => (keyframe.value = value), + reuseExisting: async () => hasImage, + submitGeneration: async input => { + const result = await fetch( + '/api/storyboard-shots/audit-shot/keyframe?projectId=billing-project', + { method: 'POST', body: JSON.stringify(input) } + ) + return { accepted: result.ok } + } + }) + ] + } + ) + } + ) + } + ) + } +}) +createApp(Preview).mount('#app') diff --git a/tests/features/image-authorization/additional.test.ts b/tests/features/image-authorization/additional.test.ts new file mode 100644 index 0000000..f9e3466 --- /dev/null +++ b/tests/features/image-authorization/additional.test.ts @@ -0,0 +1,302 @@ +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { NCheckbox, NInput, NInputNumber, NSelect } from 'naive-ui' +import { additionalImageFixture } from '../../fixtures/image-additional' +import { additionalImageEligibility, imageChargeEligibility } from '@/features/image-authorization/model' +import { billingErrorText } from '@/lib/billing-errors' +import { imageAuthorizationApi } from '@/features/image-authorization/api' +import ImageAuthorizationSettings from '@/features/image-authorization/ImageAuthorizationSettings.vue' +import KeyframeDialog from '@/features/production/components/KeyframeDialog.vue' +import { billingCatalog, billingProfile } from '../../fixtures/billing' +import { imageRequestNotice, runGuardedImageRequest } from '@/features/subject-images/image-request-guard' + +/** 释放弹层、查询和单次请求标记。 */ +const wrappers: VueWrapper[] = [] +afterEach(() => { + wrappers.splice(0).forEach(wrapper => wrapper.unmount()) + sessionStorage.clear() +}) +/** + * 创建正式包装结构的隔离响应。 + * @param data Mock原数据 + * @returns 独立响应 + */ +function response(data: unknown) { + return new Response(JSON.stringify({ data })) +} +/** + * 以原精确范围核对人工许可。 + * @param list 当前隔离费用投影 + * @returns 当前范围资格 + */ +function eligibility(list: ReturnType) { + return additionalImageEligibility( + list, + 'additional-permit', + 'billing-project', + 'audit-shot', + 'gpt-image-2.5-flare', + 'c'.repeat(64), + 'b'.repeat(64) + ) +} + +describe('人工追加不解除原unknown与费用', () => { + it('默认unknown阻断;许可仅放行本精确计划,并显示已用和剩余次数', () => { + const list = additionalImageFixture() + expect( + imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed + ).toBe(false) + expect(eligibility(list).allowed).toBe(true) + expect(eligibility(list).message).toContain('剩余 2 次') + expect(list.requests[0]!.status).toBe('unknown') + expect(list.requests[0]!.output?.actualBilledMicros).toBeNull() + expect(list.billingBlocked).toBe(true) + }) + it.each([ + 'revoked', + 'exhausted', + 'budget', + 'expired', + 'project', + 'shot', + 'model', + 'source', + 'plan', + 'inflight', + 'another-unknown' + ])('拒绝撤销/用尽/跨范围/未核清并发:%s', scenario => { + const list = additionalImageFixture(), + permit = list.additionalAuthorizations![0]!, + parent = list.requests[0]!, + grant = list.authorizations[0]! + if (scenario === 'revoked') permit.status = 'revoked' + if (scenario === 'exhausted') permit.remainingRequests = 0 + if (scenario === 'budget') grant.remainingMicros = 1 + if (scenario === 'expired') grant.expired = true + if (scenario === 'project') parent.input.projectId = 'other-project' + if (scenario === 'shot') parent.input.targetId = 'other-shot' + if (scenario === 'model') parent.input.model = 'other-model' + if (scenario === 'source') parent.input.sourceFingerprint = 'e'.repeat(64) + if (scenario === 'plan') parent.input.planFingerprint = 'f'.repeat(64) + if (scenario === 'inflight') parent.status = 'running' + if (scenario === 'another-unknown') { + list.requests.push({ ...structuredClone(parent), id: 'unapproved-request' }) + list.blockingRequestIds.push('unapproved-request') + } + expect(eligibility(list).allowed).toBe(false) + }) + it('完整同计划结果优先免费复用,许可撤销或剩余次数不能触发继续收费', () => { + const list = additionalImageFixture() + const completed = { + ...structuredClone(list.requests[0]!), + id: 'returned-request', + status: 'completed', + output: { usageCostMicros: 1, actualBilledMicros: null, result: { image: 'test-saved-result' } } + } + list.requests.push(completed) + list.additionalAuthorizations![0]!.status = 'revoked' + const result = imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64), { + id: 'additional-permit', + projectId: 'billing-project', + sourceFingerprint: 'c'.repeat(64) + }) + expect(result).toMatchObject({ allowed: true, reusable: true }) + expect(list.billingBlocked).toBe(true) + }) + it('费用核清但没有结果的原unknown精确计划仍不能普通重发', () => { + const list = additionalImageFixture() + list.billingBlocked = false + list.blockingRequestIds = [] + expect( + imageChargeEligibility(list, 'keyframe', 'audit-shot', 'gpt-image-2.5-flare', 'b'.repeat(64)).allowed + ).toBe(false) + }) + it('原网络连接与真实Provider额度错误分开,底层原因不伪装为额度不足', () => { + expect( + billingErrorText('OPENAI_IMAGE_REQUEST_UNKNOWN', { + failureType: 'timeout_unknown', + transportMode: 'proxy', + causeCode: 'UND_ERR_CONNECT_TIMEOUT' + }) + ).toContain('底层连接超时') + expect( + billingErrorText('OPENAI_IMAGE_PROVIDER_ERROR', { + failureType: 'billing_quota_exceeded', + transportMode: 'proxy', + causeCode: 'UND_ERR_CONNECT_TIMEOUT' + }) + ).toContain('计费配额不足') + expect( + billingErrorText('OPENAI_IMAGE_PROVIDER_ERROR', { + failureType: 'billing_quota_exceeded', + transportMode: 'proxy', + causeCode: 'UND_ERR_CONNECT_TIMEOUT' + }) + ).not.toContain('底层连接超时') + }) +}) + +describe('原授权设置与首帧入口追加交互', () => { + it('用户逐项接受风险才登记additional,不提交新金额/模型/目标;撤销仍用原接口', async () => { + const list = additionalImageFixture(), + fetcher = vi.fn(async (url, init) => { + if (String(url).endsWith('/generation-models')) return response(billingCatalog) + if (init?.method === 'POST') + return response({ authorizationId: 'additional-created', status: 'approved' }) + return response(list) + }) + vi.stubGlobal('fetch', fetcher) + const wrapper = mount(ImageAuthorizationSettings, { props: { projectId: 'billing-project', disabled: false } }) + wrappers.push(wrapper) + await flushPromises() + await wrapper + .findAll('.n-collapse-item__header-main') + .find(item => item.text() === '原生成请求与费用状态')! + .trigger('click') + await flushPromises() + await wrapper + .findAll('button') + .find(button => button.text() === '人工有限追加')! + .trigger('click') + await flushPromises() + expect(wrapper.text()).toContain('原精确计划人工有限追加') + expect( + wrapper + .findAllComponents(NInputNumber) + .find(input => input.attributes('aria-label') === '人工追加次数')! + .props('value') + ).toBeNull() + await wrapper.vm.save() + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(0) + wrapper + .findAllComponents(NInputNumber) + .find(input => input.attributes('aria-label') === '人工追加次数')! + .vm.$emit('update:value', 2) + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '追加批准人')! + .vm.$emit('update:value', '测试明确批准人') + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '追加批准说明')! + .vm.$emit('update:value', '接受原未知费用,仅追加此精确计划两次') + wrapper + .findAllComponents(NCheckbox) + .find(input => input.text().includes('我接受原请求'))! + .vm.$emit('update:checked', true) + await flushPromises() + await wrapper.vm.save() + const call = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')! + expect(JSON.parse(String(call[1]?.body))).toEqual({ + mode: 'additional', + idempotencyKey: expect.any(String), + parentRequestId: 'original-image-request', + maxRequests: 2, + acknowledgeUnknownPriorBilling: true, + approvedBy: '测试明确批准人', + approvalNote: '接受原未知费用,仅追加此精确计划两次' + }) + expect(list.requests[0]!.status).toBe('unknown') + await imageAuthorizationApi.revoke('billing-project', 'additional-created', { + revokedBy: '测试操作者', + reason: '关闭剩余次数' + }) + expect(fetcher.mock.calls.at(-1)?.[0]).toBe( + '/api/projects/billing-project/image-authorizations/additional-created/revoke' + ) + expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/primary|\/vision/.test(String(url)))).toBe( + false + ) + }) + it('首帧必须主动选许可并重新预览,仅提交一次;原本地unknown标记不清除', async () => { + const list = additionalImageFixture(), + submit = vi.fn<() => Promise<{ accepted: boolean }>>().mockResolvedValue({ accepted: true }) + const fetcher = vi.fn(async url => { + const path = String(url) + if (path.endsWith('/generation-models')) return response(billingCatalog) + if (path.endsWith('/creative-profile')) return response(billingProfile) + if (path.endsWith('/resolve')) + return response({ provider: 'openai-image', model: 'gpt-image-2.5-flare', options: {} }) + if (path.endsWith('/image-authorizations')) return response(list) + if (path.endsWith('/image-authorizations/preview')) + return response({ + provider: 'openai-image', + model: 'gpt-image-2.5-flare', + context: { + projectId: 'billing-project', + targetId: 'audit-shot', + scope: 'keyframe', + sourceFingerprint: 'c'.repeat(64) + }, + planFingerprint: 'b'.repeat(64), + authorization: list + }) + if (path.endsWith('/keyframe/preview')) { + return response({ + shotId: 'audit-shot', + provider: 'openai-image', + model: 'gpt-image-2.5-flare', + providerPrompt: 'Mock首帧输入', + previewFingerprint: 'a'.repeat(64), + referenceImages: [], + generationConfig: {} + }) + } + throw new Error('未模拟 ' + path) + }) + vi.stubGlobal('fetch', fetcher) + await expect( + runGuardedImageRequest('keyframe:audit-shot', async () => { + throw new Error('原连接结果未知') + }) + ).rejects.toThrow('原连接结果未知') + const wrapper = mount(KeyframeDialog, { + attachTo: document.body, + props: { + open: true, + projectId: 'billing-project', + shotId: 'audit-shot', + shotTitle: '隔离镜头', + disabled: true, + additionalAllowed: true, + submitGeneration: submit + } + }) + wrappers.push(wrapper) + await flushPromises() + const selection = wrapper + .findAllComponents(NSelect) + .find(select => select.attributes('aria-label') === '本次人工追加许可')! + expect(selection.props('value')).toBeNull() + selection.vm.$emit('update:value', 'additional-permit') + await flushPromises() + const preview = [...document.querySelectorAll('button')].find( + button => button.textContent?.trim() === '预览实际生成输入' + )! + preview.click() + await flushPromises() + const confirm = [...document.querySelectorAll('button')].find( + button => button.textContent?.trim() === '确认生成首帧' + )! + expect( + JSON.parse(String(fetcher.mock.calls.find(([url]) => String(url).endsWith('/keyframe/preview'))![1]?.body)) + ).not.toHaveProperty('additionalAuthorizationId') + expect(confirm.disabled).toBe(false) + confirm.click() + await flushPromises() + confirm.click() + await flushPromises() + expect(submit).toHaveBeenCalledTimes(1) + expect(submit).toHaveBeenCalledWith( + expect.objectContaining({ + provider: 'openai-image', + additionalAuthorizationId: 'additional-permit', + expectedPreviewFingerprint: 'a'.repeat(64), + setPrimary: false + }) + ) + expect(imageRequestNotice('keyframe:audit-shot')).toContain('待核对') + expect(list.requests[0]!.status).toBe('unknown') + }) +}) diff --git a/tests/features/image-authorization/billing-audit.test.ts b/tests/features/image-authorization/billing-audit.test.ts new file mode 100644 index 0000000..8383247 --- /dev/null +++ b/tests/features/image-authorization/billing-audit.test.ts @@ -0,0 +1,246 @@ +import { defineComponent, h } from 'vue' +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useImageBillingAudit } from '@/features/image-authorization/useImageBillingAudit' +import { imageBillingAuditApi } from '@/features/image-authorization/billing-audit-api' +import { + imageBillingAmountMicros, + imageBillingEvidenceIssues, + imageBillingReleaseIssues +} from '@/features/image-authorization/billing-audit' +import { imageAuditFixture, imageAuditFacts } from '../../fixtures/image-billing-audit' +import type { + ImageBillingEvidenceInput, + ImageBillingReviewInput +} from '@/features/image-authorization/billing-audit.types' + +/** 释放查询,避免迟到请求串到其它用例。 */ +const wrappers: VueWrapper[] = [] +afterEach(() => wrappers.splice(0).forEach(wrapper => wrapper.unmount())) +/** + * 返回正式包装结构的隔离响应。 + * @param data Mock业务值 + * @returns 独立响应 + */ +function response(data: unknown) { + return new Response(JSON.stringify({ data })) +} + +describe('图片原请求费用事实与正式API', () => { + it.each([ + { amount: null, micros: null }, + { amount: 0, micros: 0 }, + { amount: 0.000001, micros: 1 }, + { amount: 1.000001, micros: 1000001 }, + { amount: 0.0000001, micros: null }, + { amount: -1, micros: null }, + { amount: 10000000000, micros: null } + ])('微美元精确换算,不把unknown显示成0:$amount', ({ amount, micros }) => + expect(imageBillingAmountMicros(amount)).toBe(micros) + ) + it('本地和LangSmith编号、弱证据和原成功事实冲突不能用于核清', () => { + const view = imageAuditFixture(), + facts = imageAuditFacts() + facts.providerRequestId = view.requestId + expect(imageBillingEvidenceIssues(facts, view)).toContain( + '本地任务、请求或 LangSmith 编号不能作为供应方请求号。' + ) + facts.providerRequestId = 'test-trace' + facts.artifacts.push({ + id: 'trace', + kind: 'langsmith', + recordId: 'test-trace', + sha256: '3'.repeat(64), + reference: 'Mock观察' + }) + expect(imageBillingEvidenceIssues(facts, view)).toContain( + '本地任务、请求或 LangSmith 编号不能作为供应方请求号。' + ) + facts.providerRequestId = 'test-provider-request' + facts.execution.outcome = 'unknown' + expect(imageBillingReleaseIssues({ ...facts, identity: view.identity }, view).join(' ')).toContain('仍未确认') + facts.execution.outcome = 'failed' + view.hasOriginalReceipt = true + expect(imageBillingReleaseIssues({ ...facts, identity: view.identity }, view)).toContain( + '外部声明与原成功回执冲突。' + ) + }) + it('原项目、原应用请求和原完整身份通过正式图片路径提交,不混用视频或当前新镜头', async () => { + const view = imageAuditFixture('p/1', 'r/1'), + fetcher = vi.fn().mockImplementation(async () => response(view)) + vi.stubGlobal('fetch', fetcher) + await imageBillingAuditApi.get('p/1', 'r/1') + const body: ImageBillingEvidenceInput = { + expectedTaskFingerprint: view.taskFingerprint, + operator: '测试登记人', + evidence: { ...imageAuditFacts(), identity: view.identity } + } + await imageBillingAuditApi.evidence('p/1', 'r/1', body) + expect(fetcher.mock.calls.map(([url]) => url)).toEqual([ + '/api/projects/p%2F1/image-requests/r%2F1/audit', + '/api/projects/p%2F1/image-requests/r%2F1/audit/evidence' + ]) + expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual(body) + expect(body.evidence.identity).toBe(view.identity) + }) +}) + +/** + * 主动登记一组隔离材料,绝不自动选择复核或解除。 + * @param form 真实审计表单 + */ +async function register(form: ReturnType) { + form.operator.value = '测试登记人' + form.facts.value = imageAuditFacts() + form.confirmed.value = true + await form.submit() + await flushPromises() +} + +describe('图片证据登记与独立复核编排', () => { + /** + * 挂载真实Hook,所有写入只进入内存投影。 + * @param projectId 隔离项目 + * @returns 表单、Mock控制和只读状态 + */ + async function harness(projectId = 'image-audit-flow') { + const view = imageAuditFixture(projectId) + let conflictNext = false + const changed = vi.fn<() => void>() + const fetcher = vi.fn(async (url, init) => { + const path = String(url) + if (init?.method !== 'POST') + return response({ + ...view, + projectId: path.includes('/other-project/') ? 'other-project' : view.projectId, + identity: { + ...view.identity, + projectId: path.includes('/other-project/') ? 'other-project' : view.projectId + } + }) + const body = JSON.parse(String(init.body)) + if (path.endsWith('/evidence')) { + view.history.evidence.push({ + id: 'registered-evidence', + requestId: view.requestId, + taskFingerprint: view.taskFingerprint, + digest: '3'.repeat(64), + body: body as ImageBillingEvidenceInput + }) + view.evidenceSetFingerprint = '4'.repeat(64) + return response({ ...view, evidenceId: 'registered-evidence', reused: false }) + } + if (conflictNext) { + conflictNext = false + view.reviewFingerprint = '5'.repeat(64) + return new Response( + JSON.stringify({ code: 'IMAGE_BILLING_AUDIT_REVIEW_CONFLICT', message: '另一项复核已先完成' }), + { status: 409 } + ) + } + view.history.reviews.push({ + id: 'reviewed-evidence', + requestId: view.requestId, + taskFingerprint: view.taskFingerprint, + digest: '6'.repeat(64), + revision: view.history.reviews.length + 1, + body: body as ImageBillingReviewInput + }) + view.status = body.decision === 'release_future_charges' ? 'released' : 'blocked' + view.released = view.status === 'released' + view.billingBlocked = !view.released + view.reviewedAmountMicros = view.released ? 1 : null + return response({ ...view, reviewId: 'reviewed-evidence', reused: false }) + }) + vi.stubGlobal('fetch', fetcher) + let form!: ReturnType + const wrapper = mount( + defineComponent({ + props: { projectId: { type: String, required: true } }, + setup(props) { + form = useImageBillingAudit( + { + get projectId() { + return props.projectId + }, + requestId: 'unknown-image' + }, + changed + ) + return () => h('div') + } + }), + { props: { projectId } } + ) + wrappers.push(wrapper) + await flushPromises() + return { + form, + fetcher, + view, + changed, + wrapper, + conflict: () => { + conflictNext = true + } + } + } + it('登记不解锁;用户另行选择和复核才核清,原unknown/null/预留仍保留', async () => { + const { form, fetcher, view, changed } = await harness() + expect(fetcher).toHaveBeenCalledTimes(1) + expect(form.facts.value.billing.amount).toBeNull() + await register(form) + expect(view.billingBlocked).toBe(true) + expect(view.originalRequestStatus).toBe('unknown') + expect(form.action.value).toBe('evidence') + expect(form.confirmed.value).toBe(false) + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1) + form.action.value = 'review' + form.evidenceId.value = 'registered-evidence' + form.decision.value = 'release_future_charges' + form.reviewer.value = '测试独立复核人' + form.reason.value = 'Mock原件与唯一请求已经核对' + form.confirmationSha256.value = '7'.repeat(64) + form.confirmed.value = true + expect(form.canSubmit.value).toBe(true) + await form.submit() + await flushPromises() + expect(view.billingBlocked).toBe(false) + expect(view.originalRequestStatus).toBe('unknown') + expect(view.originalActualBilledMicros).toBeNull() + expect(view.reservedMicros).toBe(1000000) + expect(changed).toHaveBeenCalledTimes(2) + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2) + expect(fetcher.mock.calls.every(([url]) => String(url).includes('/image-requests/'))).toBe(true) + await form.refresh() + await form.submit() + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2) + }) + it('409刷新正式GET并保留表单、撤销确认,不自动重复提交', async () => { + const setup = await harness('image-conflict') + await register(setup.form) + const form = setup.form + form.action.value = 'review' + form.evidenceId.value = 'registered-evidence' + form.reviewer.value = '测试复核人' + form.reason.value = '保留此前已填理由' + form.confirmationSha256.value = '8'.repeat(64) + form.confirmed.value = true + setup.conflict() + await form.submit() + expect(form.reason.value).toBe('保留此前已填理由') + expect(form.confirmationSha256.value).toBe('8'.repeat(64)) + expect(form.confirmed.value).toBe(false) + expect(form.query.data.value?.reviewFingerprint).toBe('5'.repeat(64)) + expect(setup.view.history.reviews).toHaveLength(0) + await form.submit() + expect(setup.fetcher.mock.calls.filter(([url]) => String(url).endsWith('/reviews'))).toHaveLength(1) + await setup.wrapper.setProps({ projectId: 'other-project' }) + await flushPromises() + expect(form.operator.value).toBe('') + expect(form.reason.value).toBe('') + expect(form.confirmationSha256.value).toBe('') + expect(form.evidenceId.value).toBe('') + expect(form.facts.value.artifacts).toEqual([]) + }) +}) diff --git a/tests/features/storyboard/directory-position.test.ts b/tests/features/storyboard/directory-position.test.ts new file mode 100644 index 0000000..1974f70 --- /dev/null +++ b/tests/features/storyboard/directory-position.test.ts @@ -0,0 +1,40 @@ +import { defineComponent, h } from 'vue' +import { flushPromises, mount } from '@vue/test-utils' +import { expect, it, vi } from 'vitest' +import BeatShotDirectory from '@/features/storyboard/components/BeatShotDirectory.vue' +import { designedShot } from '@/features/storyboard/testing/fixtures' + +it('定位嵌套镜头时避让所属段落标题,首行镜号不被吸顶标题遮挡', async () => { + const wrapper = mount( + defineComponent({ + props: { activeId: { type: String, required: true } }, + setup: props => () => + h('div', { class: 'n-scrollbar-container' }, [ + h(BeatShotDirectory, { + shots: [designedShot('first'), { ...designedShot('next'), beatNo: 2 }], + activeId: props.activeId, + itemClass: 'shot-link' + }) + ]) + }), + { props: { activeId: 'first' } } + ) + try { + await flushPromises() + const viewport = wrapper.get('.n-scrollbar-container').element + const selected = wrapper.findAll('.directory-item')[1]!.element + const heading = selected.closest('[role="group"]')!.querySelector('h4')! + Object.defineProperty(heading, 'offsetHeight', { configurable: true, value: 38 }) + vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 100, 240, 400)) + vi.spyOn(selected, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 180, 240, 88)) + viewport.scrollTop = 80 + /** 记录目录自身滚动目标,断言标题避让距离。 */ + const scrollTo = vi.fn<(options: ScrollToOptions) => void>() + Object.defineProperty(viewport, 'scrollTo', { configurable: true, value: scrollTo }) + await wrapper.setProps({ activeId: 'next' }) + await flushPromises() + expect(scrollTo).toHaveBeenLastCalledWith({ top: 122, behavior: 'smooth' }) + } finally { + wrapper.unmount() + } +}) diff --git a/tests/features/storyboard/joint-review.test.ts b/tests/features/storyboard/joint-review.test.ts new file mode 100644 index 0000000..6efeb29 --- /dev/null +++ b/tests/features/storyboard/joint-review.test.ts @@ -0,0 +1,381 @@ +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { NCheckbox, NInput } from 'naive-ui' +import JointDraftReviewPanel from '@/features/storyboard/components/JointDraftReviewPanel.vue' +import { jointDraftDifferences } from '@/features/storyboard/joint-review' +import { visualStateTimeSections, visualStateTimeIssueLabel } from '@/features/storyboard/visual-state-time' +import { imagePreviewFixture } from '../../fixtures/image-preview' +import { createHash } from 'node:crypto' +import { jointReviewFixture } from '../../fixtures/joint-review' + +/** 每个镜头用例隔离项目锁。 */ +let serial = 0 +/** 释放查询和免费请求。 */ +const wrappers: VueWrapper[] = [] +afterEach(() => wrappers.splice(0).forEach(wrapper => wrapper.unmount())) +/** + * 正式包装的独立Mock响应。 + * @param data 原契约数据 + * @returns 独立响应 + */ +function response(data: unknown) { + return new Response(JSON.stringify({ data })) +} + +describe('联合采用完整差异与时间展示', () => { + it('完整列出摄影、主体及四项环境差异,身份与主体集合仍禁止修改', () => { + const fixture = jointReviewFixture(), + draft = structuredClone(fixture.saved.draft) + let differences = jointDraftDifferences(fixture.formal, draft) + expect(differences).toHaveLength(4) + expect(differences.every(item => item.allowed)).toBe(true) + expect(differences.map(item => item.change?.target)).toEqual([ + 'direction', + 'direction', + 'visualState', + 'subject' + ]) + draft.visualState.environment.weather = '' + draft.visualState.subjects[0]!.formId = '不能偷偷换形态' + differences = jointDraftDifferences(fixture.formal, draft) + expect(differences.find(item => item.label === '环境 · 天气')).toMatchObject({ + allowed: true, + change: { target: 'environment', field: 'weather', before: '小雨', after: '' } + }) + expect(differences.filter(item => !item.allowed).map(item => item.label)).toContain('@CH0001 · 形态身份') + draft.visualState.subjects.push({ ...draft.visualState.subjects[0]!, subjectRef: '@CH9999' }) + expect( + jointDraftDifferences(fixture.formal, draft).some(item => !item.allowed && item.label.includes('主体集合')) + ).toBe(true) + }) + it('只按正式四个时间标记排版,旧文字和原问题不被重写或判通过', () => { + const note = jointReviewFixture().saved.draft.visualState.continuityNote + expect(visualStateTimeSections(note).map(section => section.kind)).toEqual([ + 'input', + 'planned', + 'continuity', + 'video' + ]) + expect(visualStateTimeSections('角色已经持物,后续动作尚待拍摄。')).toEqual([ + { kind: 'legacy', title: '原衔接说明(未分段)', text: '角色已经持物,后续动作尚待拍摄。' } + ]) + expect(visualStateTimeIssueLabel({ code: 'VISUAL_STATE_START_CONFLICT', severity: 'error' })).toBe( + '开拍状态冲突' + ) + expect(visualStateTimeIssueLabel({ code: 'VISUAL_STATE_TIME_NEEDS_REVIEW', severity: 'needs_review' })).toBe( + '时间语义待人工核对' + ) + expect( + visualStateTimeIssueLabel({ code: 'VISUAL_STATE_VIDEO_END_UNSUPPORTED', severity: 'needs_review' }) + ).toBe('真实视频末态缺少证据') + expect(visualStateTimeIssueLabel({ code: 'other', severity: 'needs_review' })).toBe('需要人工核对') + }) +}) + +/** + * 点击真实组件当前显示的指定操作。 + * @param wrapper 实际表单 + * @param label 可见按钮名称 + */ +async function click(wrapper: VueWrapper, label: string) { + const button = wrapper.findAll('button').find(item => item.text() === label)! + expect(button.attributes('disabled')).toBeUndefined() + await button.trigger('click') + await flushPromises() +} +/** + * 明确填写实际审核人及剪辑依据。 + * @param wrapper 实际表单 + */ +async function author(wrapper: VueWrapper) { + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '联合修订依据')! + .vm.$emit('update:value', '本次仅调整当前开拍状态,保留原动作和相邻观察轴。') + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '联合审核人')! + .vm.$emit('update:value', '测试联合审核人') + await flushPromises() +} + +describe('原摄影抽屉内的联合流程', () => { + /** + * 挂载真实联合模式,成功/冲突均只写隔离投影。 + * @param conflict 是否模拟相邻版本冲突 + * @param reused 是否模拟幂等采用 + * @param environment 是否包含有据环境修订 + * @returns 组件、模拟请求及正式来源 + */ + async function editor(conflict = false, reused = false, environment = false) { + const projectId = `joint-flow-${++serial}`, + fixture = jointReviewFixture(projectId) + /** 正式项目详情中的本集身份与原始正文,摘要不能代替正文哈希。 */ + const episode = { + id: 'source-episode', + projectId, + episode: 1, + title: '当前源集', + content: '第一行\r\n午后,维修间透入日光。\n天气未指定。' + } + if (environment) { + fixture.saved.draft.visualState.environment.timeOfDay = '午后' + fixture.saved.draft.visualState.environment.weather = '' + fixture.saved.draft.visualState.environment.atmosphere = '自然日光' + fixture.saved.draft.visualState.environment.transientState = '' + } + const fetcher = vi.fn(async (url, init) => { + const path = String(url) + if (path === `/api/projects/${projectId}`) return response({ id: projectId, episodes: [episode] }) + if (path.includes('/keyframe-review-draft')) { + if (init?.method === 'PUT') { + const body = JSON.parse(String(init.body)) + fixture.saved.draft = body.draft + fixture.saved.revision++ + fixture.saved.providerInput = body.providerInput + fixture.saved.expectedCurrentFormalSourceFingerprint = body.expectedCurrentFormalSourceFingerprint + } + return response(fixture.saved) + } + if (path.endsWith('/storyboard-quality-confirmation')) + return response({ ...fixture.approval.approval, valid: true, confirmation: fixture.approval.record }) + if (path.includes('/storyboard-directions?')) return response(fixture.directions) + if (path.includes('/storyboard-visual-states?')) return response(fixture.visuals) + if (path.includes('/keyframe-spec')) return response(fixture.keyframe) + if (path.includes('/keyframe/preview')) { + const body = JSON.parse(String(init?.body)) + if (!body.draft) return response({ ...imagePreviewFixture(), shotId: fixture.shot.shotId }) + return response({ + ...imagePreviewFixture(), + shotId: fixture.shot.shotId, + draftFingerprint: 'a'.repeat(64), + currentDerivedFingerprint: 'c'.repeat(64), + adjacentDerivedVersions: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }], + productionReady: false, + productionGate: { ready: false, reason: '项目未完成' }, + sceneSources: [] + }) + } + if (path.endsWith('/storyboard-derived-reviews/confirm')) { + const body = JSON.parse(String(init?.body)) + if (conflict) { + if (environment) episode.content += '\n源正文已被其他人修改。' + return new Response( + JSON.stringify({ + message: environment + ? 'JOINT_REVISION_ENVIRONMENT_SOURCE_STALE: 本集原文已变化。' + : 'JOINT_REVISION_NEIGHBOR_STALE: 紧邻镜头已更新,请重读。' + }), + { status: 409 } + ) + } + if (!body.preview) fixture.saved.status = 'stale' + return response({ + projectId, + preview: body.preview, + changed: !body.preview && !reused, + reused: !body.preview && reused, + requestFingerprint: 'f'.repeat(64), + shots: [ + { shotId: fixture.shot.shotId, directionId: 'direction-formal', visualStateId: 'visual-formal' } + ] + }) + } + throw new Error(`未模拟 ${init?.method ?? 'GET'} ${path}`) + }) + vi.stubGlobal('fetch', fetcher) + const wrapper = mount(JointDraftReviewPanel, { + props: { projectId, episodeNo: 1, shot: fixture.shot, shots: fixture.shots, disabled: false } + }) + wrappers.push(wrapper) + await flushPromises() + return { wrapper, fixture, fetcher, episode } + } + it.each([false, true])('保存、画面预览、联合免费预检和采用分开,幂等回执=%s', async reused => { + const { wrapper, fetcher, fixture } = await editor(false, reused) + expect(wrapper.text()).toContain('完整字段差异(4 项)') + expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true) + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '联合摄影意图')! + .vm.$emit('update:value', '明确修改后保存的摄影意图') + await flushPromises() + await wrapper.vm.save() + await flushPromises() + expect(wrapper.emitted('changed')).toBeUndefined() + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1) + await click(wrapper, '免费核对草案画面输入') + expect(wrapper.text()).toContain('相邻镜头依据') + await author(wrapper) + await click(wrapper, '免费预检联合采用') + expect(wrapper.vm.canAdopt).toBe(false) + wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true) + await flushPromises() + expect(wrapper.vm.canAdopt).toBe(true) + await wrapper.vm.adopt() + await flushPromises() + const confirms = fetcher.mock.calls.filter(([url]) => + String(url).endsWith('/storyboard-derived-reviews/confirm') + ) + expect(confirms).toHaveLength(2) + const first = JSON.parse(String(confirms[0]![1]?.body)), + second = JSON.parse(String(confirms[1]![1]?.body)) + expect(second).toEqual({ ...first, preview: false }) + expect(first.shots[0].jointRevision).toMatchObject({ + expectedDraftRevision: 8, + expectedDerivedFingerprint: 'c'.repeat(64), + expectedNeighbors: [{ shotId: 'shot-db-1-2', derivedFingerprint: 'd'.repeat(64) }] + }) + expect(first.shots[0].jointRevision.changes).toHaveLength(4) + expect(first.shots[0].jointRevision).not.toHaveProperty('environmentSource') + expect(first.shots[0].expectedCurrentFormalSourceFingerprint).toBe(fixture.keyframe.formalSourceFingerprint) + expect(first.shots[0].draft).not.toHaveProperty('subjectStateRevision') + expect(wrapper.emitted('changed')).toHaveLength(1) + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1) + expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/vision|\/primary/.test(String(url)))).toBe( + false + ) + expect(wrapper.text()).toContain('原草案和历史保留') + }) + it('邻镜变化409保留原稿并重读,不自动采用或改为当前新版本', async () => { + const { wrapper, fetcher } = await editor(true) + await click(wrapper, '免费核对草案画面输入') + await author(wrapper) + await click(wrapper, '免费预检联合采用') + expect(wrapper.vm.canAdopt).toBe(false) + expect(wrapper.text()).toContain('当前输入已保留') + expect( + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '联合摄影意图')! + .props('value') + ).toBe('保留正式动作的开拍意图') + const confirms = fetcher.mock.calls.filter(([url]) => + String(url).endsWith('/storyboard-derived-reviews/confirm') + ) + expect(confirms).toHaveLength(1) + expect(JSON.parse(String(confirms[0]![1]?.body)).preview).toBe(true) + expect(wrapper.emitted('changed')).toBeUndefined() + }) + it('内容改变撤销原预检,不自动套用重新读取的草案', async () => { + const { wrapper, fetcher, fixture } = await editor() + await click(wrapper, '免费核对草案画面输入') + await author(wrapper) + await click(wrapper, '免费预检联合采用') + wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true) + await flushPromises() + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '摄影构图')! + .vm.$emit('update:value', '重新编辑,旧确认失效') + await flushPromises() + expect(wrapper.vm.canAdopt).toBe(false) + fixture.saved.draft.visualState.environment.weather = '不能暗改天气' + await click(wrapper, '重新读取正式来源与草案') + expect( + fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm')) + ).toHaveLength(1) + }) + + it('环境差异须逐字本集证据,冻结原字节全文SHA;保存和预检不自动采用', async () => { + const { wrapper, fetcher, episode } = await editor(false, false, true) + expect(wrapper.text()).toContain('本集原文依据') + await wrapper.vm.save() + await flushPromises() + await click(wrapper, '免费核对草案画面输入') + await author(wrapper) + const preflight = () => wrapper.findAll('button').find(item => item.text() === '免费预检联合采用')! + expect(preflight().attributes('disabled')).toBeDefined() + const quote = wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '环境原文片段')! + quote.vm.$emit('update:value', '另一集才有的晴天') + await flushPromises() + expect(preflight().attributes('disabled')).toBeDefined() + quote.vm.$emit('update:value', '午后,维修间透入日光。') + await flushPromises() + await click(wrapper, '免费预检联合采用') + const confirms = () => + fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm')) + expect(confirms()).toHaveLength(1) + const previewBody = JSON.parse(String(confirms()[0]![1]?.body)) + expect(previewBody.shots[0].jointRevision.environmentSource).toEqual({ + episodeId: 'source-episode', + expectedContentFingerprint: createHash('sha256').update(episode.content).digest('hex'), + quote: '午后,维修间透入日光。' + }) + expect( + previewBody.shots[0].jointRevision.changes.filter((row: { target: string }) => row.target === 'environment') + ).toHaveLength(4) + expect(wrapper.vm.canAdopt).toBe(false) + wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true) + await flushPromises() + quote.vm.$emit('update:value', '午后,维修间透入日光。\n天气未指定。') + await flushPromises() + expect(wrapper.vm.canAdopt).toBe(false) + await click(wrapper, '免费预检联合采用') + wrapper.getComponent(NCheckbox).vm.$emit('update:checked', true) + await flushPromises() + await Promise.all([wrapper.vm.adopt(), wrapper.vm.adopt()]) + expect(confirms()).toHaveLength(3) + const second = JSON.parse(String(confirms()[1]![1]?.body)), + adopted = JSON.parse(String(confirms()[2]![1]?.body)) + expect(adopted).toEqual({ ...second, preview: false }) + expect(fetcher.mock.calls.some(([url]) => /\/keyframe$|\/generate|\/vision|\/primary/.test(String(url)))).toBe( + false + ) + }) + it('环境来源409重读本集全文并保留片段和草案,不自动重试', async () => { + const { wrapper, fetcher, episode } = await editor(true, false, true) + await click(wrapper, '免费核对草案画面输入') + await author(wrapper) + const quote = wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '环境原文片段')! + quote.vm.$emit('update:value', '午后,维修间透入日光。') + await flushPromises() + await click(wrapper, '免费预检联合采用') + expect(quote.props('value')).toBe('午后,维修间透入日光。') + expect(wrapper.vm.canAdopt).toBe(false) + expect( + fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm')) + ).toHaveLength(1) + expect( + fetcher.mock.calls.filter(([url]) => String(url) === `/api/projects/${episode.projectId}`).length + ).toBeGreaterThanOrEqual(2) + await wrapper + .findAll('.n-collapse-item__header-main') + .find(item => item.text() === '环境修订(需本集原文)')! + .trigger('click') + await flushPromises() + expect( + wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '环境天气')! + .props('value') + ).toBe('') + }) + it('正式集身份或全文缺失时保留输入但不允许环境预检', async () => { + const { wrapper, episode, fetcher } = await editor(false, false, true) + await click(wrapper, '免费核对草案画面输入') + await author(wrapper) + const quote = wrapper + .findAllComponents(NInput) + .find(input => input.attributes('aria-label') === '环境原文片段')! + quote.vm.$emit('update:value', '午后,维修间透入日光。') + await flushPromises() + Reflect.deleteProperty(episode, 'content') + await click(wrapper, '刷新本集原文') + expect(wrapper.text()).toContain('缺少本集正式身份或全文') + expect(quote.props('value')).toBe('午后,维修间透入日光。') + expect( + wrapper + .findAll('button') + .find(item => item.text() === '免费预检联合采用')! + .attributes('disabled') + ).toBeDefined() + expect( + fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard-derived-reviews/confirm')) + ).toHaveLength(0) + }) +}) diff --git a/tests/features/storyboard/page-browsing.test.ts b/tests/features/storyboard/page-browsing.test.ts new file mode 100644 index 0000000..770bb58 --- /dev/null +++ b/tests/features/storyboard/page-browsing.test.ts @@ -0,0 +1,117 @@ +import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' +import { afterEach, describe, expect, it, vi } from 'vitest' +import StoryboardPage from '@/features/storyboard/StoryboardPage.vue' +import { projectContextKey } from '@/features/projects/context' +import { testProjectContext } from '@/testing/project-context' +import { directionsResult, visualStatesResult, storyboardCheckpoint } from '@/features/storyboard/testing/fixtures' +import { preparationFixture } from '../storyboard-preparation/fixtures' +import type { WorkflowExecution } from '@/features/workflows/execution.types' + +/** 释放真实页面及任务订阅,避免迟到响应跨用例。 */ +const wrappers: VueWrapper[] = [] +afterEach(() => { + wrappers.splice(0).forEach(wrapper => wrapper.unmount()) + localStorage.clear() +}) +/** + * 还原进入页面后发现已结束历史任务的场景,不连接真实服务。 + * @param projectId 当前隔离项目 + * @returns 实际页面和请求记录 + */ +async function page(projectId: string) { + const context = testProjectContext(projectId) + context.data.value!.checkpoints = [storyboardCheckpoint()] + const fixture = preparationFixture(projectId) + const history: WorkflowExecution = { + id: 'restored-direction-history', + projectId, + workflowName: 'storyboard-direction', + status: 'completed', + stage: 'completed', + current: 2, + total: 2, + currentResourceId: null, + metadata: { episodeNo: 1 }, + error: null, + startedAt: null, + completedAt: null, + createdAt: '2026-11-16T00:00:00Z', + updatedAt: '2026-11-16T00:00:00Z', + result: { + projectId, + episodeCount: 1, + completedEpisodes: 1, + skippedEpisodes: 0, + failedEpisodes: 0, + episodes: [{ episodeNo: 1, status: 'completed', directionCount: 2, shotCount: 2 }] + } + } + localStorage.setItem(`short-drama:workflow-execution:${projectId}:storyboard-direction`, history.id) + const fetcher = vi.fn(async (url, init) => { + const path = String(url) + if (init?.method && init.method !== 'GET') throw new Error('浏览页面不应产生写入') + let data: unknown + if (path.includes('/storyboard-directions?')) data = directionsResult(projectId) + else if (path.includes('/storyboard-visual-states?')) data = visualStatesResult(projectId, 1, true) + else if (path.endsWith('/storyboard-quality-confirmation')) + data = { ...fixture.approval, valid: true, confirmation: fixture.record } + else if (path.endsWith('/storyboard-quality-confirmation/preflight')) + data = { + current: { ...fixture.approval, valid: true, confirmation: fixture.record }, + quality: fixture.quality + } + else if (path.endsWith('/production/entry-readiness')) data = fixture.entry + else if (path.endsWith('/storyboard/duration-audit')) data = { projectId, issues: [] } + else if (path.endsWith('/duration-budget')) data = { projectId, episodes: [] } + else if (path.includes('/workflow-executions/latest')) + data = path.includes('workflowName=storyboard-direction') ? history : null + else if (path.includes('/workflow-executions/restored-direction-history')) data = history + else throw new Error(`未模拟只读请求 ${path}`) + return Response.json({ data }) + }) + vi.stubGlobal('fetch', fetcher) + const wrapper = mount(StoryboardPage, { + attachTo: document.body, + global: { provide: { [projectContextKey as symbol]: context } } + }) + wrappers.push(wrapper) + await flushPromises() + await flushPromises() + return { wrapper, fetcher } +} + +describe('分镜浏览与生成配置分离', () => { + it('恢复历史回执只提示入口,不自动打开生成配置', async () => { + const { wrapper, fetcher } = await page('browse-restored-history') + expect(wrapper.find('[data-workspace-tools]').attributes('aria-expanded')).toBe('false') + expect(wrapper.find('[data-workspace-tools]').text()).toContain('有回执') + expect(document.body.querySelector('.n-drawer')).toBeNull() + expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true) + }) + it('普通目录只浏览,用户打开生成范围后才能按镜头勾选,历史回执仍可查看', async () => { + const { wrapper, fetcher } = await page('browse-range-selection') + const directory = wrapper.get('nav[aria-label="本集镜头"]') + expect(directory.findAll('[role="checkbox"]')).toHaveLength(0) + await directory.findAll('button')[1]!.trigger('click') + expect(directory.findAll('.selected')).toHaveLength(1) + await wrapper.get('[data-workspace-tools]').trigger('click') + await flushPromises() + const history = [...document.querySelectorAll('.n-collapse-item__header-main')].find(item => + item.textContent?.includes('历史任务与回执') + )! + history.click() + await flushPromises() + expect(document.body.textContent).toContain('摄影设计任务') + const range = [...document.querySelectorAll('.n-collapse-item__header-main')].find(item => + item.textContent?.includes('选择镜头') + )! + range.click() + await flushPromises() + const checkbox = document.querySelector('.n-drawer [aria-label="选择镜头 1.1"]')! + checkbox.click() + await flushPromises() + expect(document.body.textContent).toContain('第 1 集所选 1 镜') + expect(directory.findAll('[role="checkbox"]')).toHaveLength(0) + expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true) + }) +}) diff --git a/tests/fixtures/image-additional.ts b/tests/fixtures/image-additional.ts new file mode 100644 index 0000000..8a3085b --- /dev/null +++ b/tests/fixtures/image-additional.ts @@ -0,0 +1,60 @@ +import { imageAuthorizationsFixture } from './billing' +import type { ImageChargeRequest, ImageAuthorizationList } from '../../src/features/image-authorization/types' +/** + * 仅供Mock的unknown请求及同一精确计划的有限许可。 + * @param projectId 隔离项目 + * @returns 原预留与unknown始终保留的费用投影 + */ +export function additionalImageFixture(projectId = 'billing-project'): ImageAuthorizationList { + const list = imageAuthorizationsFixture() + const grant = list.authorizations[0]! + const parent: ImageChargeRequest = { + id: 'original-image-request', + status: 'unknown', + input: { + projectId, + authorizationId: grant.id, + candidateId: 'original-image', + targetId: 'audit-shot', + scope: 'keyframe', + provider: 'openai-image', + model: 'gpt-image-2.5-flare', + planFingerprint: 'b'.repeat(64), + sourceFingerprint: 'c'.repeat(64), + reservedMicros: grant.input.perRequestMicros, + request: { prompt: '仅供Mock的原精确计划' } + }, + output: { + usageCostMicros: null, + actualBilledMicros: null, + error: { failureType: 'timeout_unknown', transportMode: 'proxy', causeCode: 'UND_ERR_CONNECT_TIMEOUT' } + } + } + grant.usedRequests++ + grant.remainingRequests-- + grant.accountedMicros += parent.input.reservedMicros + grant.remainingMicros -= parent.input.reservedMicros + list.requests.push(parent) + list.billingBlocked = true + list.originalBlockingRequestIds = [parent.id] + list.blockingRequestIds = [parent.id] + list.additionalAuthorizations = [ + { + id: 'additional-permit', + status: 'approved', + input: { + mode: 'additional', + idempotencyKey: 'test-additional', + parentRequestId: parent.id, + maxRequests: 2, + acknowledgeUnknownPriorBilling: true, + approvedBy: '测试人工批准人', + approvalNote: '仅供Mock的有限风险确认', + parentInputFingerprint: 'd'.repeat(64) + }, + usedRequests: 0, + remainingRequests: 2 + } + ] + return list +} diff --git a/tests/fixtures/image-billing-audit.ts b/tests/fixtures/image-billing-audit.ts new file mode 100644 index 0000000..3698975 --- /dev/null +++ b/tests/fixtures/image-billing-audit.ts @@ -0,0 +1,72 @@ +import type { BillingFacts } from '../../src/features/billing-audit/types' +import type { ImageBillingAuditView } from '../../src/features/image-authorization/billing-audit.types' +/** + * 仅供Mock的原图片请求视图,不代表真实Provider材料。 + * @param projectId 隔离项目 + * @param requestId 隔离原请求 + * @returns 带完整原版本和空历史的审计视图 + */ +export function imageAuditFixture(projectId = 'audit-project', requestId = 'unknown-image'): ImageBillingAuditView { + return { + projectId, + requestId, + identity: { + projectId, + requestId, + authorizationId: 'grant', + scope: 'keyframe', + targetId: 'audit-shot', + candidateId: 'unknown-candidate', + provider: 'openai-image', + model: 'gpt-image-2.5-flare', + sourceFingerprint: 'c'.repeat(64), + planFingerprint: 'b'.repeat(64), + requestFingerprint: 'd'.repeat(64) + }, + taskFingerprint: 'a'.repeat(64), + evidenceSetFingerprint: 'e'.repeat(64), + reviewFingerprint: 'f'.repeat(64), + originalRequestStatus: 'unknown', + reservedMicros: 1_000_000, + originalUsageCostMicros: null, + originalActualBilledMicros: null, + originalProviderRequestId: null, + hasOriginalReceipt: false, + originalBillingBlocked: true, + billingBlocked: true, + released: false, + status: 'unreviewed', + reviewId: null, + reviewedAmountMicros: null, + releaseIssues: ['缺少当前独立复核的证据'], + history: { evidence: [], reviews: [] } + } +} +/** + * 只用于隔离验收的合格材料,不能登记到正式项目。 + * @returns 明确标为测试的Provider原件声明 + */ +export function imageAuditFacts(): BillingFacts { + return { + correlation: 'unique', + providerRequestId: 'test-provider-request', + artifacts: [ + { + id: 'exec', + kind: 'provider-execution', + recordId: 'test-provider-execution', + sha256: '1'.repeat(64), + reference: '仅供Mock验收的执行原件' + }, + { + id: 'bill', + kind: 'provider-billing', + recordId: 'test-provider-bill', + sha256: '2'.repeat(64), + reference: '仅供Mock验收的账单原件' + } + ], + execution: { outcome: 'failed', evidenceIds: ['exec'] }, + billing: { finding: 'charged', amount: 0.000001, currency: 'USD', evidenceIds: ['bill'] } + } +} diff --git a/tests/fixtures/joint-review.ts b/tests/fixtures/joint-review.ts new file mode 100644 index 0000000..f8a96c3 --- /dev/null +++ b/tests/fixtures/joint-review.ts @@ -0,0 +1,53 @@ +import { directionsResult, visualStatesResult, designedShot } from '../../src/features/storyboard/testing/fixtures' +import { draftFromFormal } from '../../src/features/storyboard/derived-review' +import { preparationFixture } from '../features/storyboard-preparation/fixtures' +import type { KeyframeSpec } from '../../src/features/production/types' +import type { SavedKeyframeDraft } from '../../src/features/storyboard/derived-review.types' +/** + * 当前正式数据和已保存草案的隔离投影,不用于正式项目。 + * @param projectId 隔离项目 + * @returns 可用于Vitest/Chrome的完整原版本与有限差异 + */ +export function jointReviewFixture(projectId = 'joint-review-project') { + const shot = designedShot(), + approval = preparationFixture(projectId), + directions = directionsResult(projectId), + visuals = visualStatesResult(projectId, 1, true) + const keyframe: KeyframeSpec = { + projectId, + shotId: shot.shotId, + episodeNo: 1, + beatNo: 1, + shotNo: 1, + prompt: '隔离正式开拍输入', + formalSourceFingerprint: 'e'.repeat(64), + references: [] + } + const formal = draftFromFormal(shot, keyframe, approval.record.shotFingerprint) + const draft = structuredClone(formal) + draft.direction.composition = '仅用于Mock的构图调整' + draft.direction.visualIntent = '保留正式动作的开拍意图' + draft.visualState.subjects[0]!.pose = '仅用于Mock的0秒姿态' + draft.visualState.continuityNote = + '【输入事实】原主体保持开拍姿态。【规划末态】后续镜头规划,尚未执行。【连续要求】保持原观察轴。【视频末态】未知,尚无真实视频末态证据。' + const saved: SavedKeyframeDraft = { + shotId: shot.shotId, + revision: 7, + updatedAt: '2026-11-16T01:00:00Z', + status: 'current', + staleReason: null, + draft, + providerInput: { provider: 'openai-image', generationOptions: { quality: 'auto' } }, + expectedCurrentFormalSourceFingerprint: keyframe.formalSourceFingerprint! + } + return { + shot, + shots: [shot, { ...designedShot('shot-db-1-2'), beatNo: 2 }], + approval, + directions, + visuals, + keyframe, + formal, + saved + } +}