diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 1ba4c060..1ef2e0bd 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -929,7 +929,7 @@ export class DetailPiAgent { if (this.productionGoal && template?.enterprise) { const {brandName,categoryName}=this.productEvidence.product; const selection={brandName,categoryName,templateId:template.id,releaseId:template.version, - resourceSetId:template.resourceSetId,...(production.outputId?{outputId:production.outputId}:null), + resourceSetId:template.resourceSetId,...(template.skillSources?{skillSources:template.skillSources}:null),...(production.outputId?{outputId:production.outputId}:null), runDeadline:production.deadline}; this.enterpriseContext??=new EnterpriseContext(this.store); this.productionSkills=await openEnterpriseSkills(this.store,selection, @@ -1024,7 +1024,7 @@ export class DetailPiAgent { return lock; } return this.loadWholeDetailKnowledge({task:production?'production':'image',outputId,brandName:brief?.brandName,categoryName:brief?.categoryName, - templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId},signal,!!drive); + templateId:plan.template.id,releaseId:plan.template.version,resourceSetId:plan.template.resourceSetId,skillSources:plan.template.skillSources},signal,!!drive); },{outputId,production,signal,drive, readModelOriginal:drive&&this.broker?async (id,recheck=false)=>{ if(!await this.store.ownsRequest(id))return null; diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index d31db278..b14a0738 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -46,11 +46,11 @@ export async function reviewProductionCandidate({ const assessment=params({ candidateId:Type.String(),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))), checks:params({structure:Type.Boolean(),color:Type.Boolean(), - templateStyle:Type.Optional(Type.Boolean({description:'图位素材类型、调色与光线是否符合模板'})), + templateStyle:Type.Optional(Type.Boolean({description:'按本项目发布的规则判断模板风格'})), composition:Type.Boolean(),evidence:Type.Boolean()}), mustRedo:Type.Optional(Type.Array(params({...issue, - kind:Type.Union([Type.Literal('product'),Type.Literal('templateStyle')]), - }),{description:'必须重做。仅列同款商品或模板调性的实质差异。'})), + kind:Type.String({description:'发布的审稿规则中对应的问题类别'}), + }),{description:'按本项目审稿规则必须重新制作的问题。'})), canvasFixes:Type.Optional(Type.Array(params(issue),{description:'可用画布处理。列位置、问题及具体操作建议。'})), reason:Type.String({minLength:1}), shownFields:Type.Optional(Type.Array(params({field:Type.String(),claim:Type.Optional(Type.Integer({minimum:0})), @@ -79,18 +79,14 @@ export async function reviewProductionCandidate({ candidateFile:input.candidateFile,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue, fit,artDirection,textRegions:input.textRegions,pixelFindings}); const instructions=[ - '独立验收最后一张候选图。图片按同款实拍、模板构图参考、附加局部、完整候选排列。实拍决定商品结构,模板只决定画面要求。', - ...(adopted?['最后一张取自当前画布的实际图框,包含模板排版。']:[]), - ...(containedOriginal?['候选是保留完整原片内容的等比放置。检查主体的外轮廓与接合位置。']:[]), - '附件是供视觉判断的 JPEG 预览,可能缩小并失去透明通道。候选原文件的像素尺寸和透明情况以 candidateFile 为准,图框与交付要求看 frame 和 outputSpec。', - '以这张图能否作为当前图位素材来验收。第一位是同款商品,先核对同款结构,对照实拍核对可见部件数量、形状、接合方式、比例和花色。发现错款或可见结构变形,退回并指出问题位置。', - '第二位是图位的画面类型和调性。核对模板需要生活场景、白底单品、多视角拼贴或其它类型,以及色调和光线。类型、色调或光线实质不符就退回。同为生活场景时,机位、景别、主体位置或留白有差异归画布处理。', - '机位、取景比例、裁切风险、文字区、像素尺寸、透明通道等交付规格、文案与画面不符,都列入 canvasFixes「可用画布处理」,不单凭这些退图。文案与画面不符时保留图片,建议根据画面中可见的事实改对应文字。', - 'mustRedo「必须重做」仅列同款商品或图位调性的实质错误。两类均写 location、problem、suggestion,类别没问题时返回空数组。同款商品的结构与颜色、图位的画面类型与调性都相符就提交 pass,即使有画布处理建议。有必须重做的错误提交 revise;证据不足以判断同款或图位类型时提交 missing 并说明还需查看什么。建议返工时以本款实拍和已确认资料为依据,只从模板取画面类型和调性。缺少本款的可信局部素材时,写明所缺证据,不以模板旧商品部件充当本款。', - '以实际像素作判断。检测结果和旧模板文字是定位线索。用 shownFields 记录图片能证明的事实,用 generationFixes 写出必须重做时的具体改法。', - ...(guides.length?['若有结构标注,请按模板说明给出图框左上 [0,0] 到右下 [1000,1000] 的实物落点。']:[]), + '读取本项目发布的验图 Skill 和适用引用,按其标准提交候选结论。附图依次为产品实拍、模板参考、附加局部和候选。', + ...(adopted?['最后一张取自当前画布的实际图框。']:[]), + ...(containedOriginal||cropFrameOnly?['最后一张是按实际图框和放置方式渲染的预览。']:[]), + '附件是供视觉查看的预览。原件的尺寸和透明通道见 candidateFile,实际图框见 frame。pixelFindings 是像素检查记录。', + '按发布规则分别记录 mustRedo 和 canvasFixes,填写问题位置、说明及建议。用 shownFields 记录画面可见依据。', + ...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]), ...(reviewKnowledge.files.length?[knowledgeReadInstruction]:[]), - '调用 review_candidate 提交你的结论。', + '调用 review_candidate 提交结论。', ].join('\n'); const scope=productRequestScope('review',candidateId); const model=host.info?.model?.id??null; diff --git a/apps/detail-agent-pi/src/enterprise-context.mjs b/apps/detail-agent-pi/src/enterprise-context.mjs index 8036f2f5..d18d8591 100644 --- a/apps/detail-agent-pi/src/enterprise-context.mjs +++ b/apps/detail-agent-pi/src/enterprise-context.mjs @@ -5,8 +5,6 @@ import path from 'node:path'; const tasks = {chat:'详情页项目创作流程、模板字段应用与品牌规范',copy:'卖点文案生成、修改与字段约束',image:'图片提示词、候选修改与视觉品牌规范',plan:'成熟模板内容策划与字段适配',canvas:'成熟模板字段回填、保留排版与局部修改'}; const skillRoot = file => file?.match(/^(.*\/Skills\/[^/]+)\//)?.[1]; -const productionSkills = ['家具详情页设计', '通用详情页制作与PS模板验证']; - export function links(document) { return [...document.text.matchAll(/\[([^\]]+)\]\(([^)\n]+\.md)(?:#[^)]*)?\)/g)] .filter(([, , target]) => !target.startsWith('/') && !/[:\\]/u.test(target)) @@ -16,49 +14,21 @@ export function links(document) { /** Resolve production resources through the authorized knowledge service. */ export class EnterpriseContext { constructor(store, client = new EnterpriseKnowledge({store})) { this.store=store; this.client=client; } - async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,turn,outputId}, {signal, read = execute => execute(), deferVisual = false, pins} = {}) { + async load({task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId}, {signal, read = execute => execute(), deferVisual = false, pins} = {}) { if (!tasks[task] && task!=='production') return null; - const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,turn,outputId,deferVisual]); + const key=JSON.stringify([task,brandName,categoryName,templateId,releaseId,resourceSetId,skillSources,turn,outputId,deferVisual]); if (this.key===key) return this.value; const navigation=(await read(()=>this.client.call('list_libraries',{},{signal}))).result; const directory=navigation.navigation?.find(item=>item.name==='Skills')?.path; - if (task==='production') { + if (task==='production' || task==='image') { const identity={task,brandName,categoryName,templateId,releaseId,resourceSetId}; const options={signal,read,deferVisual,pins}; - if (resourceSetId) { - const published=await this.declaredGuides(identity,options); - if (published) { - await this.addNativeSkill(directory,published,options); - return this.commit(key,{...published,skillDirectory:directory}); - } - } - const value=await this.imageContext(directory,identity,options); - const marketing=await this.specificDocument(directory,directory+'/产品营销文案/SKILL.md','skill',options); - value.skills.push(marketing); - const insight=links(marketing).find(document=>document.target.endsWith('/insight-and-selling-point.md')); - if(!insight)throw Error('营销技能缺少卖点挖掘规则'); - const general=directory+'/通用详情页制作与PS模板验证/references/'; - const rules=[ - [insight.target,'selling-points'], - [general+'01-内容策划/01-详情页分析与内容策划.md','content-planning'], - ]; - if(outputId==='main_images') rules.push([general+'02-视觉与审稿/04-电商主图制作.md','output']); - if(outputId==='sku_images') rules.push([general+'02-视觉与审稿/05-SKU内容与图片.md','output']); - for(const [target,kind] of rules) value.rules.push(await this.specificDocument(directory,target,kind,options)); - await this.addNativeSkill(directory,value,options); - return this.commit(key,{...value,skillDirectory:directory}); - } - if (task === 'image') { - const identity={task,brandName,categoryName,templateId,releaseId,resourceSetId}; - let value; - if(resourceSetId) { - for(let attempt=0;attempt<2;attempt++){ - try {value=await this.declaredGuides(identity,{signal,read});break;} - catch(error){if(attempt||![409,412].includes(error.status))throw error;} - } - } - value??=await this.imageContext(directory,identity,{signal,read}); - return this.commit(key,value); + const published = Array.isArray(skillSources) + ? await this.loadGuides(identity,skillSources,releaseId,options) + : resourceSetId ? await this.declaredGuides(identity,options) : null; + if (!published) throw Error('所选模板尚未发布制作 Skill,请核对模板资源组'); + if (task==='production') await this.addNativeSkill(directory,published,options); + return this.commit(key,{...published,skillDirectory:directory}); } const query=`通用详情页 ${tasks[task]}`.slice(0,500); const taskResult=(await this.client.call('query_knowledge',{query,...(directory?{directory}:{}),limit:3,maxCharacters:8000})).result; @@ -122,32 +92,39 @@ export class EnterpriseContext { } } - async declaredGuides(identity,{signal,read,pins}) { + async declaredGuides(identity,options) { + const {signal,read}=options; const set=(await read(()=>this.client.call('get_resource_set',{resourceSetId:identity.resourceSetId},{signal}))).result; if(set.resourceSet.brand!==identity.brandName||set.resourceSet.category!==identity.categoryName) throw Error('创作规则不属于所选品牌或品类'); const component=set.components.find(c=>c.id==='visual_guides'); if(!component)return null; - if(component.status!=='available')throw Error('所选模板的生图及验图规则尚有缺项'); + if(component.status!=='available')throw Error('所选模板发布的制作规则尚有缺项'); + const sources=component.assets.filter(asset=>asset.role==='guide'&&asset.required).map(asset=>{ + if(asset.status!=='available')throw Error('无法读取已发布的规则:'+asset.file?.name); + const {fileId,revision,path}=asset.file; + return {fileId,revision,path,kind:asset.file.name==='SKILL.md'?'skill':asset.id}; + }); + const result=await this.loadGuides(identity,sources,set.revision,options); + result.referenceSources=component.assets.filter(({file})=>file?.path?.endsWith('.md')&&file.fileId&&file.revision) + .map(({file:{fileId,revision,path}})=>({fileId,revision,path})); + return result; + } + + async loadGuides(identity,sources,resourceRevision,{signal,read,pins}) { const skills=[],rules=[]; - for (const asset of component.assets.filter(a=>a.role==='guide'&&a.required)) { - const {fileId,revision,path:source}=asset.file; - const kind=asset.file.name==='SKILL.md'?'skill':asset.id; + for (const {fileId,revision,path:source,kind} of sources) { + if(!fileId||!revision||!source||!kind)throw Error('模板制作规则缺少文件身份、版本或用途'); const target=kind==='skill'?skills:rules; const pinned=pins?.get(source); if (pinned) { target.push({...pinned,kind}); - continue; + } else { + const {result}=await this.client.readDocument(fileId,revision,{signal},read); + target.push({fileId,revision,path:source,kind,pages:result.pages,text:result.text}); } - if(asset.status!=='available')throw Error('无法读取必需规则:'+asset.file.name); - const {result}=await this.client.readDocument(fileId,revision,{signal},read); - target.push({fileId,revision,path:source,kind,pages:result.pages,text:result.text}); } - if(!skills.length||!rules.length)throw Error('该模板的图片制作规则没有完整声明'); - const referenceSources=identity.task==='production' ? component.assets - .filter(({file})=>file?.path?.endsWith('.md')&&file.fileId&&file.revision) - .map(({file:{fileId,revision,path}})=>({fileId,revision,path})) : undefined; - return {...identity,skills,rules,resourceRevision:set.revision,referenceSources, - execution:'按所选 Skill 的 PhotoCraft 路径执行,商品事实以本款资料为准。'}; + if(!skills.length)throw Error('所选模板未声明制作 Skill 正文'); + return {...identity,skills,rules,resourceRevision,execution:'按项目发布的 Skill 和引用执行。'}; } async loadReference(target, {directory, source, signal, read}) { @@ -184,44 +161,6 @@ export class EnterpriseContext { return {...document,revision:result.revision,text:result.text}; } - async imageContext(directory, identity, options) { - if (!directory) throw Error('企业知识库没有公开本任务的技能目录'); - const specific=(target,kind)=>this.specificDocument(directory,target,kind,options); - const skills=[]; - for (const folder of productionSkills) skills.push(await specific(directory+'/'+folder+'/SKILL.md','skill')); - const declared=links(skills[0]); - const required = [ - [/^模块二$/, 'image-production'], - [/^品牌(?:规范|索引)$/, 'brand-index'], - [/^统一审稿$/, 'review'], - [/^字段对接与依据$/, 'evidence'], - ]; - const rules=[]; - for (const [label,kind] of required) { - const entry=declared.find(link=>label.test(link.label)); - if (!entry) throw Error('所选 Skill 缺少任务引用:'+kind); - rules.push(await specific(entry.target,kind)); - } - const brandIndex=rules.find(rule=>rule.kind==='brand-index'); - const visualDirectory=path.posix.dirname(brandIndex.path); - const references=new Set(rules.map(rule=>rule.path)); - for (const {target} of declared) { - if (references.has(target) || path.posix.dirname(target)!==visualDirectory) continue; - references.add(target); - rules.push(await specific(target,'product-visual')); - } - const imageModule=rules.find(rule=>rule.kind==='image-production'); - for(const [label,kind] of [[/^五段框架$/,'image-prompt'],[/^视觉表达手法库$/,'composition'],[/^(?:原\s*PS\s*图片参考选择|原参考图反推要求)$/iu,'template-reference']]) { - const entry=links(imageModule).find(link=>label.test(link.label)); - if(!entry)throw Error('视觉制作模块缺少任务引用:'+kind); - rules.push(await specific(entry.target,kind)); - } - const brand=links(brandIndex).find(link=>link.label.includes(identity.brandName) && identity.brandName); - if (brand) rules.push(await specific(brand.target,'brand')); - return {...identity,skills,rules, - execution:'按所选 Skill 的 PhotoCraft 路径执行,商品事实以本款资料为准。'}; - } - async commit(key,value) { const {task,templateId,releaseId,skills,rules}=value; await atomic(path.join(this.store.root,'enterprise-context.json'),value); diff --git a/apps/detail-agent-pi/src/enterprise-templates.mjs b/apps/detail-agent-pi/src/enterprise-templates.mjs index 45d5f17e..c5228b24 100644 --- a/apps/detail-agent-pi/src/enterprise-templates.mjs +++ b/apps/detail-agent-pi/src/enterprise-templates.mjs @@ -54,6 +54,7 @@ function componentPack(manifest, revision, mappings, binding) { if (!['detail', 'main_images', 'sku_images'].includes(component.component)) continue; const mapping = mappings[component.component]; if (!mapping || mapping.template_id !== manifest.template.templateId || mapping.mapping_version !== component.mappingVersion) throw Error('模板组件或映射版本不一致'); + if (mapping.skill_sources !== undefined) pack.skillSources = mapping.skill_sources; if (mapping.production_profile !== undefined) { if (mapping.production_profile?.schemaVersion !== 1) throw Error('模板制作配置版本不支持'); pack.productionProfiles ??= {}; @@ -220,7 +221,7 @@ export class EnterpriseTemplates { const value=await new EnterpriseContext(store,this.client).load(input,{signal:task.signal,read:fn=>waitForQuota(fn,task)}); if (input.task==='image') { return {context:{...value,skills:value.skills.map(({fileId,revision,path})=>({fileId,revision,path})), - rules:value.rules.filter(rule=>['brand','product-visual','furniture-visual-rules'].includes(rule.kind)||rule.kind.endsWith('-visual-rules'))}}; + rules:value.rules.filter(rule=>['brand','product-visual'].includes(rule.kind)||rule.kind.endsWith('-visual-rules'))}}; } return {context:{task:value.task,brandName:value.brandName,categoryName:value.categoryName,templateId:value.templateId,releaseId:value.releaseId, skills:value.skills.map(({fileId,revision,path})=>({fileId,revision,path})),rules:value.rules,execution:value.execution}}; diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 74bf5787..c185257b 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -609,8 +609,7 @@ export async function openProductionOperations(host) { } } const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、回读核对、冻结,再按冻结 ID 派发。'+ - (rework?'\n先看随消息附上的退回图,结合验图原话、建议和上一次实发提示词。提交新要求时用 reworkChange 写清这次具体改什么。缺少的证据如实说明。'+ - '同一原因第二次退回就换办法:模板提示或构图参考带偏时用 useTemplateReference=false;也可改用实拍裁切或合成、建议主代理用画布处理,或在符合验图标准时建议主代理直接采用。':'')+ + (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+ knowledgeReadInstruction; await host.runDetailAgent(slot.id,instructions, JSON.stringify({rework,goal,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements, diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 8592d764..40631012 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -1,25 +1,13 @@ --- name: product-image-sources -description: Choose and review reference images for product-detail, main and SKU artwork. +description: Use product image sources and Image Request tools in PhotoCraft. --- -# 商品配图的素材依据 +# 商品配图工具 -按企业 Skill 和模板写明的图位要求选素材。需要表现连接、安装、受力、尺寸、纹理或其他实物细节时,优先核对本款原片和规格。实拍能看清所需内容时,可直接采用对应角度或裁切。用生成图表现使用场景时,商品原片决定结构和款式,模板参考决定构图、光色与景别。实拍或资料无法证明的内容,调整画面与文案的角度,不补造。 +从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。 -图位已发布素材来源时,沿用其定义。不同图位可选用不同的实拍或组合。 - - -当图位需要原片中没有的布景、人物动作或光线时,使用场景生成,把实拍作为同款参考。直接使用或裁切原片适合原片已经能证明的画面,原片路径会保留背景,场景要求在生成路径生效。验图指出缺少场景时,按实际底图和退回原因调整产出方式,再核对候选。 - -## 退回后换办法 - -委托返工时用被退回的候选号,先看图、验图原话与建议、上一次实发提示词和尝试次数,再说明本次具体改什么。返工要用的旧图先留给子代理读取。再因同一问题退回时,换素材或制作方法。模板提示词或构图参考带入旧商品时,生图传 useTemplateReference=false,按本款原片和这次的要求制作。实拍能证明的内容可改用裁切或合成。同款和调性都符合验图标准时,可直接采用,再用原生命令调整画布。 - -## 先采用,再修版式 - -候选素材先验同款结构和模板图位的画面类型、光色。某个图位只差机位、取景比例、叠字空间、裁切适配或交付像素时,先采用素材,再处理实际图框。同款结构、花色和图位调性都成立时,版式、规格或图文对应的问题在画布上修,不重新生图。文案与画面不一致时,按可见内容改对应文案。 - -通过 native_catalog 查找适用的 PhotoCraft 命令,用 native_call 对准该图层等比缩放、切换适配方式、平移、裁切、翻转或放大。文字区不清楚时可移动文字框、增加衬底或遮罩。在模板发布的变更范围内,可移开或隐藏已失效的旧图层。改后用 read_output_screen 查看实际画布,核对主体结构是否完整、文字可读以及标注落点。验图列为「必须重做」的候选先处理具体退回原因,确认通过后再采用。若按模板许可改用本款能证明的主题,先更新图文要求,按新主题重新验图,再把通过的候选放入画布。技术截面等局部仍以本款实拍或确认资料为准。 - -模板里的旧商品尺寸、材种和性能只作版式线索。替换为实拍或本款资料能支持的文字,无数据的项目不要代填数值。处理当前能完成的图位和文案,画布交接由客户端负责。 +- `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。 +- `prepare_image_request` 保存完整生图请求。`read_image_request` 回读正式文本、参考顺序与模型参数。用回读的版本和内容 hash 调 `freeze_image_request`。`dispatch_image_request` 接收冻结 ID。 +- `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。 +- 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。 diff --git a/apps/detail-agent-pi/test/enterprise-context.test.mjs b/apps/detail-agent-pi/test/enterprise-context.test.mjs index 939e2088..88f767f1 100644 --- a/apps/detail-agent-pi/test/enterprise-context.test.mjs +++ b/apps/detail-agent-pi/test/enterprise-context.test.mjs @@ -38,47 +38,34 @@ test('selected resource guides are read completely with their own versions',asyn assert.deepEqual(calls.slice(2).map(([name])=>name),['list_libraries','get_resource_set']); }); -test('visual guidance follows the declared PS reference selection across directories',async()=>{ - const directory='Skills'; - const furniture=directory+'/家具详情页设计'; - const general=directory+'/通用详情页制作与PS模板验证'; - const references=general+'/references'; - const visual=references+'/02-视觉与审稿'; - const choice=references+'/04-模板与工作簿/03-模板输入与制作衔接.md'; - const files=new Map([ - [furniture+'/SKILL.md',[ - '[模块二](../通用详情页制作与PS模板验证/references/02-视觉与审稿/01-视觉设计与图片制作.md)', - '[商品取景依据](category.md)','[品牌索引](brand-index.md)', - '[统一审稿](review.md)','[字段对接与依据](evidence.md)', - ].join('\n')], - [general+'/SKILL.md','通用技能'], - [visual+'/01-视觉设计与图片制作.md',[ - '[五段框架](02-视觉提示词框架.md)','[视觉表达手法库](03-视觉表达手法库.md)', - '[原 PS 图片参考选择](../04-模板与工作簿/03-模板输入与制作衔接.md#新品图片是否参考原-ps-构图)', - ].join('\n')], - [visual+'/02-视觉提示词框架.md','提示词框架'], - [visual+'/03-视觉表达手法库.md','视觉手法'], - [choice,'只参考原 PS 图片的构图。新品外观以本款资料为准。'], - ...['category','brand-index','review','evidence'].map(kind=>[furniture+'/'+kind+'.md',kind]), - ]); - const read=[]; +test('explicit template skill sources are read by their published file identity and version', async t => { + const root=await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-template-guides-')); + t.after(()=>fs.rm(root,{recursive:true})); + const calls=[]; + const docs=[]; + const skillSources=[ + {fileId:'workflow',path:'Skills/Lighting/SKILL.md',revision:'7',kind:'skill'}, + {fileId:'rules',path:'Skills/Lighting/review.md',revision:'11',kind:'review'}, + ]; const client={ - async call(name,{directory,query}){ - assert.equal(name,'search_files'); - const file=directory+'/'+query; - return {result:{entries:files.has(file)?[{id:file,path:file,revision:'pinned'}]:[]}}; + async call(name){ + calls.push(name); + return {result:{navigation:[{name:'Skills',path:'Skills'}]}}; }, - async readDocument(id,revision){ - read.push([id,revision]); - return {result:{text:files.get(id),revision}}; + async readDocument(id,revision) { + docs.push([id,revision]); + return {result:{text:id+' rules',revision}}; }, }; - const ctx=new EnterpriseContext({},client); - const result=await ctx.imageContext(directory,{brandName:'顾家'},{read:fn=>fn()}); - assert.deepEqual(result.rules.find(rule=>rule.kind==='template-reference'), - {fileId:choice,path:choice,revision:'pinned',kind:'template-reference',text:files.get(choice)}); - assert.equal(result.rules.find(rule=>rule.kind==='brand-index')?.path,furniture+'/brand-index.md'); - assert.deepEqual(read.filter(([id])=>id===choice),[[choice,'pinned']]); + const ctx=new EnterpriseContext({root,appendEvent:async()=>{}},client); + const input={task:'production',brandName:'Lighting Lab',categoryName:'灯具',releaseId:'release-3'}; + const result=await ctx.load({...input,skillSources}); + assert.deepEqual(calls,['list_libraries']); + assert.deepEqual(docs,[['workflow','7'],['rules','11']]); + assert.equal(result.resourceRevision,'release-3'); + assert.equal(result.rules[0].text,'rules rules'); + assert.equal(result.skills[0].path,'Skills/Lighting/SKILL.md'); + await assert.rejects(ctx.load(input),/尚未发布制作 Skill/u); }); test('knowledge responses accept separate JSON blocks without replacing the requested revision', async () => { diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index dfc861e5..16009221 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -122,8 +122,7 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie async runDetailAgent(slotId,system,prompt,tools,images){ assert.equal(slotId,'photo'); assert.match(system,/先看随消息附上的退回图/u); - assert.match(system,/同一原因第二次退回就换办法/u); - assert.match(system,/直接采用/u); + assert.match(system,/按发布规则处理/u); const context=JSON.parse(prompt); assert.equal(Object.keys(context)[0],'rework'); if(context.rework.candidateId==='missing'){ diff --git a/apps/detail-agent-pi/test/whole-detail.test.mjs b/apps/detail-agent-pi/test/whole-detail.test.mjs index 502042f1..d1ce5619 100644 --- a/apps/detail-agent-pi/test/whole-detail.test.mjs +++ b/apps/detail-agent-pi/test/whole-detail.test.mjs @@ -763,7 +763,7 @@ test('a declared structural guide is recorded from the accepted candidate frame' assert.deepEqual(input.structureGuides,structureGuides); return invoke(tools,'review_candidate',{candidateId:input.candidateId,visibleCounts:[],structureGuidesAligned:true}); } - assert.match(system,/实物落点/); + assert.match(system,/图框内 \[0,0\] 到 \[1000,1000\]/u); return invoke(tools,'review_candidate',{candidateId:input.candidateId,checks,subjects:1,people:0, detail:'clear',shownFields:[],reason:'当前候选的前框上沿清楚',structureGuides}); },async()=>({skills:[],rules:[]}),{production:true,prepareStrategy:async()=>({sourceIds:['P01']})}); @@ -789,12 +789,11 @@ test('the image reviewer owns each verdict and receives frame diagnostics separa const outcome=await runWholeDetail({canvas:f.canvas,store:f.store,turnEpoch:1},async(_id,system,prompt,tools,images,scope)=>{ const {candidateId,pixelFindings,candidateFile:original}=JSON.parse(prompt); assert.deepEqual(original,candidateFile); - assert.match(system,/JPEG 预览/u); - assert.match(system,/第一位是同款商品/u); - assert.match(system,/第二位是图位的画面类型和调性/u); - assert.match(system,/文案与画面不符时保留图片/u); - assert.match(system,/同款商品的结构与颜色、图位的画面类型与调性都相符就提交 pass/u); - assert.match(system,/缺少本款的可信局部素材时,写明所缺证据/u); + assert.match(system,/本项目发布的验图 Skill/u); + assert.match(system,/原件的尺寸和透明通道见 candidateFile/u); + assert.doesNotMatch(system,/第一位|第二位|都相符就提交 pass/u); + const rules=await tools.find(entry=>entry.name==='read_production_knowledge').execute('rules',{fileId:'brand-review'}); + assert.equal(rules.details.text,'按本品牌的暖调室内参考判断背景。'); assert.equal(scope,'product/review/'+candidateId); assert.equal(images.at(-2),reference); assert.deepEqual(pixelFindings.whiteSideBands,['left']); @@ -806,7 +805,9 @@ test('the image reviewer owns each verdict and receives frame diagnostics separa mustRedo:first?[{kind:'templateStyle',location:'图像背景',problem:'纯白底',suggestion:'改为有暖色自然光的室内场景'}]:[], canvasFixes:first?[]:[{location:'左侧文字区',problem:'留白不足',suggestion:'微调图层位置'}], }); - },async()=>({skills:[],rules:[]}),{production:true,outputId:'main_images',prepareStrategy:async()=>({sourceIds:['P01']})}); + },async()=>({skills:[],rules:[{kind:'review',fileId:'brand-review',revision:'2', + path:'Skills/Lamp/review.md',text:'按本品牌的暖调室内参考判断背景。'}]}), + {production:true,outputId:'main_images',prepareStrategy:async()=>({sourceIds:['P01']})}); assert.equal(outcome.production.complete,true,outcome.text); assert.deepEqual(calls,['slot-0-candidate-1','slot-0-candidate-2']); assert.deepEqual(f.calls.map(op=>op.intent),['generate_candidate','generate_candidate','adopt_candidate']); @@ -2435,7 +2436,7 @@ test('production rechecks an adopted close-up and keeps its rejection without re let reviewed=0; const result=await runWholeDetail({canvas:f.canvas,store:f.store,turnEpoch:1},async(_id,system,raw,tools,_images,scope)=>{ assert.match(scope,/^product\/review\//); - assert.match(system,/先核对同款结构/u); + assert.match(system,/当前画布|实际图框/u); const {candidateId}=JSON.parse(raw); assert.equal(candidateId,adopted); reviewed++; @@ -2726,7 +2727,7 @@ test('a complete original is reviewed alone with its actual contain placement',a assert.deepEqual(images,[photos.at(-1)]); assert.equal(input.fit,'contain'); assert.equal(input.originalReference,'P01'); - assert.match(system,/等比放置/u); + assert.match(system,/实际图框和放置方式/u); return invoke(tools,'review_candidate',{candidateId:input.candidateId,checks,subjects:1,people:0, detail:'clear',shownFields:[],reason:'能沿完整上缘和全部底端看到连续背景'}); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 4cf04d80..03d67ade 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -3142,7 +3142,7 @@ fn snapshot_for_view(dir: &Path, view: Option) -> R { let screen_count = active_mapping["outputs"].as_array().map_or_else(|| outputs.iter().filter(|output| output["outputId"] == state["activeOutput"]).count(),Vec::len); let template = json!({"id":state["template"]["id"],"name":state["template"]["name"],"version":state["template"]["version"],"contentHash":state["template"]["contentHash"],"resourceSetId":state["template"]["enterprise"]["resourceSetId"],"enterprise":state["template"]["enterprise"].is_object(), "width":original_canvas[0],"height":original_canvas[1],"screenCount":screen_count, - "productionRoute":pack["productionRoute"],"production":profile.map(production_profile::agent_rules)}); + "productionRoute":pack["productionRoute"],"skillSources":pack["skillSources"],"production":profile.map(production_profile::agent_rules)}); let mut workflow = json!({"canvasFirst":true,"revision":state["revision"],"workspaceId":state["id"],"structureHash":state["structureHash"],"templateId":state["template"]["id"],"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],"templateName":state["template"]["name"],"template":template,"confirmed":true,"confirmationKind":"template-selection","pending":pending,"recoveryCandidateId":recovery_candidates.first(),"recoveryCandidateIds":recovery_candidates,"activeVariantId":active,"variantId":active,"variants":state["variants"],"outputVariantIds":state["brief"]["outputVariantIds"],"outputId":state["activeOutput"],"outputs":outputs,"slots":slots,"capabilities":{"imageDispatchAllowed":ready&&!pending&&active_color_enabled,"copyDispatchAllowed":ready&&!pending&&active_color_enabled,"localApplyAllowed":ready}}); if state["productTemplates"].is_object() { workflow["productionStages"] = json!(runnable_stages(&state, remaining_stages(dir, &state, ¤t["revision"], false))); @@ -3501,6 +3501,9 @@ impl Backend { return Err("原生骨架与项目花色或模板不一致,未打开".into()); } meta["workspaceId"] = state["id"].clone(); + if !has_edit { + meta["originalLayerIds"] = json!(native.walk().iter().map(|(_,_,layer)| layer.id.0).collect::>()); + } let original_preview_path = original_preview_path(&dir, &key); let mut original_preview = (product_copy && state["template"]["enterprise"].is_object()) .then(|| photocraft_ui_egui::jiansun::template_preview::OriginalPreview::capture(&native, &meta)) @@ -3650,11 +3653,12 @@ impl Backend { } return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); } + let preparing = input["prepareRequest"] == true; let attachment_refs = input.get("attachments").cloned().unwrap_or_else(|| json!([])); if !attachment_refs.as_array().is_none_or(Vec::is_empty) && input["projectId"].as_str() != self.locations.get(&doc).map(String::as_str) { return Err("附件所属项目已变化,请重新选择".into()); } - if images.as_array().map_or(0, Vec::len) + attachments.len() > 8 { + if !preparing && images.as_array().map_or(0, Vec::len) + attachments.len() > 8 { return Err("产品参考图与临时附件合计最多8张".into()); } let production_rule = if batch && state["productTemplates"].is_object() { @@ -3679,10 +3683,10 @@ impl Backend { } else { None }; let fixed_layout = use_template_reference && batch && state["productTemplates"].is_object() && field["previewReference"].is_object(); let reference_count = images.as_array().map_or(0, Vec::len) + attachments.len(); - if scene.is_none() && fixed_layout && reference_count == 8 { + if !preparing && scene.is_none() && fixed_layout && reference_count == 8 { return Err("本图位需要同款原片和模板构图参考,请精简参考图后再制作".into()); } - let layout_position = if use_template_reference && scene.is_none() && batch && reference_count < 8 && let Some(bytes) = self.detail_layout_bytes(&field)? { + let layout_position = if use_template_reference && scene.is_none() && batch && (preparing || reference_count < 8) && let Some(bytes) = self.detail_layout_bytes(&field)? { let position = reference_count + 1; let reference = &field["previewReference"]; let file_id = reference["fileId"].as_str().ok_or("图位原参考身份无效")?; @@ -3694,7 +3698,6 @@ impl Backend { let (references, layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?; let settings = self.settings()?; let model = settings["imageModel"].as_str().filter(|model| !model.is_empty()).ok_or("请先选择生图模型")?; - let preparing = input["prepareRequest"] == true; let candidate = if input["workflowOperationId"].is_null() || preparing { Uuid::new_v4().to_string() } else { @@ -3716,7 +3719,8 @@ impl Backend { prompt.push_str(&refinement_prompt(base_index)); } let knowledge = if state["template"]["enterprise"].is_object() && input["detailBatch"] != true { - self.enterprise_template_request(json!({"action":"context","projectRoot":dir,"task":"image","brandName":state["brief"]["brandName"],"categoryName":state["brief"]["categoryName"],"templateId":state["template"]["id"],"releaseId":state["template"]["version"]}))?["context"].clone() + self.enterprise_template_request(json!({"action":"context","projectRoot":dir,"task":"image","brandName":state["brief"]["brandName"],"categoryName":state["brief"]["categoryName"],"templateId":state["template"]["id"],"releaseId":state["template"]["version"],"resourceSetId":state["template"]["enterprise"]["resourceSetId"], + "skillSources":state["template"]["skillSources"]}))?["context"].clone() } else { Value::Null }; if scene.is_none() { let profile = &creation["designSnapshot"]["brand"]["profile"]; diff --git a/apps/detail-photocraft/crates/engine/src/command_scope.rs b/apps/detail-photocraft/crates/engine/src/command_scope.rs index 483fcf5a..aab3372b 100644 --- a/apps/detail-photocraft/crates/engine/src/command_scope.rs +++ b/apps/detail-photocraft/crates/engine/src/command_scope.rs @@ -3,7 +3,8 @@ //! Other DocStates are moved out for the entire dispatch/apply, not filtered by //! guessed parameter names. Native History stays on the same owned DocState. use crate::{EngineError, Result, Session}; -use photocraft_doc::DocId; +use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; +use std::collections::HashSet; use serde_json::{Value, json}; use std::sync::{ Arc, Mutex, PoisonError, @@ -364,6 +365,7 @@ pub struct CommandScope { pub index: usize, cancelled: Arc, local: Arc>, + fixed_layers: Option>>, } impl std::fmt::Debug for CommandScope { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -402,12 +404,42 @@ fn global_library_operation(id: &str, params: &Value) -> bool { impl CommandScope { pub fn new(document: DocId, index: usize) -> Self { - Self { document, index, cancelled: Arc::new(AtomicBool::new(false)), local: Arc::new(Mutex::new(LocalState::default())) } + Self { document, index, cancelled: Arc::new(AtomicBool::new(false)), + local: Arc::new(Mutex::new(LocalState::default())), fixed_layers: None } } pub fn with_cancellation(mut self, token: Arc) -> Self { self.cancelled = token; self } + pub fn with_fixed_layers(mut self, layers: HashSet) -> Self { + self.fixed_layers = Some(Arc::new(layers)); + self + } + + fn template_violation(&self, before: &Arc, after: &Arc) -> Option { + let fixed = self.fixed_layers.as_ref()?; + if Arc::ptr_eq(before, after) { return None; } + let mapping = |document: &Document| document.metadata.text.iter() + .find(|(key,_)| key == "jiansun.slot-mapping.v1").map(|(_,value)| value.clone()); + if before.size != after.size || mapping(before) != mapping(after) { + return Some("当前模板未发布修改画布尺寸或模板映射的许可".into()); + } + let placed = |document: &Document| document.walk().into_iter() + .filter(|(_,_,layer)| fixed.contains(&layer.id)) + .map(|(path,_,layer)| (layer.id, (1..path.len()).filter_map(|depth| document.layer_at(&path[..depth]).map(|parent| parent.id)).collect::>())) + .collect::>(); + let placements = placed(before); + if placements != placed(after) { + return Some("当前模板未发布移动、重排或删除固定图层的许可".into()); + } + for (id,_) in placements { + if let (Some(left),Some(right)) = (before.layer(id),after.layer(id)) && !same_fixed_layer(left,right) { + return Some(format!("固定图层「{}」未发布变更许可(图层 {})",left.name,id.0)); + } + } + None + } + pub fn is_cancelled(&self) -> bool { self.cancelled.load(Ordering::SeqCst) } @@ -550,6 +582,20 @@ impl CommandScope { } } +fn same_fixed_layer(left: &Layer, right: &Layer) -> bool { + if left == right { return true; } + if !matches!((&left.content,&right.content),(LayerContent::Group(_),LayerContent::Group(_))) { return false; } + let mut left = left.clone(); + let mut right = right.clone(); + for layer in [&mut left,&mut right] { + if let LayerContent::Group(group) = &mut layer.content { + // Child slots and new layers can change without editing the fixed group's own design. + group.children.clear(); + } + } + left == right +} + impl Session { /// Unwind-safe isolation around the complete command, including native /// preconditions, direct `docs` iteration, bookkeeping and job snapshots. @@ -589,14 +635,19 @@ impl Session { .unwrap_or_else(|_| Err(denied("the command failed internally; other documents were preserved"))); let intact = self.docs.len() == 1 && self.active == Some(0) && self.docs.first().is_some_and(|state| state.doc.id == scope.document); let cancelled = scope.is_cancelled(); + let template_violation = self.docs.first().filter(|_| intact) + .and_then(|state| scope.template_violation(&backup.doc,&state.doc)); + let keep = intact && !cancelled && template_violation.is_none(); let result = if cancelled { Err(EngineError::Cancelled) + } else if let Some(reason) = template_violation { + Err(EngineError::Other(reason)) } else if intact { result } else { Err(denied("the command attempted to change the document set")) }; - let restored = if intact && !cancelled { + let restored = if keep { self.docs.pop().unwrap_or(backup.clone()) } else { let touched: Vec<_> = self.docs.iter().map(|state| state.doc.id).collect(); @@ -614,7 +665,7 @@ impl Session { self.active_doc_for_generation = active_doc_for_generation; self.command_scope_depth = 0; let mut global_journal = journal; - if intact && !cancelled { + if keep { global_journal.extend(self.journal.iter().skip(scoped_from).cloned()); } else { self.journal.truncate(scoped_from); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs index dd50b445..b47fc7f3 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_native.rs @@ -3,6 +3,7 @@ //! second implementation of editor features or invented JSON schemas. use super::{json, Value, VecDeque, Workspace, PhotocraftApp}; use crate::control::{ControlRequest, Outcome}; +use photocraft_doc::LayerId; use photocraft_engine::{CommandScope, jobs::JobId}; use std::{collections::BTreeMap, sync::{Arc, atomic::{AtomicBool, Ordering}}}; @@ -304,7 +305,11 @@ pub(super) fn authority(_w: &Workspace, app: &PhotocraftApp, scope: &CommandScop fn template_permission(doc: &photocraft_doc::Document, command: &str, params: &Value) -> Result<&'static str, String> { let Some((_, value)) = doc.metadata.text.iter().find(|(key, _)| key == "jiansun.allowed-changes.v1") else { - return Ok("default-allowed"); + return Ok(if super::canvas_workspace::document_mapping(doc).is_some_and(|mapping| mapping["canvasFirst"] == true) { + "mapped-fields" + } else { + "ordinary-canvas" + }); }; let policy: Value = serde_json::from_str(value).map_err(|_| "模板发布的允许变更格式无效")?; let rules = policy.as_array().ok_or("模板发布的允许变更须为操作列表")?; @@ -547,7 +552,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte if !read && w.agent_native.pending(input["run"].as_str().unwrap_or("")) { return Err("原生任务仍在处理中,请核查原任务,不重复派发".into()); } safe_services(app)?; if !read { w.agent_native.make_room()?; } - let (scope, token) = w.agent_native.scope(input["run"].as_str().unwrap_or(""), document, index)?; + let (mut scope, token) = w.agent_native.scope(input["run"].as_str().unwrap_or(""), document, index)?; if method == "engine.execute" { if let Some(error) = authority(w, app, &scope, &command, &native_params["params"]) { return Err(error); } if photocraft_engine::commands::find(&command).is_none() && !crate::menus::is_enabled(app, &command) { @@ -558,7 +563,19 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte && w.pi_request_scope["productProduction"] == true { let state = app.session.active().ok_or("当前画布未打开")?; match template_permission(&state.doc, &command, &native_params["params"]) { - Ok(policy) => Some(policy), + Ok(policy) => { + if policy == "mapped-fields" { + let mapping = super::canvas_workspace::document_mapping(&state.doc).ok_or("模板字段映射缺失")?; + let fields: std::collections::HashSet<_> = mapping["outputs"].as_array().into_iter().flatten() + .flat_map(|output| output["mapping"]["fields"].as_array().into_iter().flatten()) + .filter_map(|field| field["nativeLayerId"].as_u64().map(LayerId)).collect(); + let originals = mapping["originalLayerIds"].as_array().map_or_else( + || w.pi_canvas_basis.as_deref().unwrap_or(&state.doc).walk().into_iter().map(|(_,_,layer)|layer.id).collect::>(), + |ids| ids.iter().filter_map(|id|id.as_u64().map(LayerId)).collect()); + scope = scope.with_fixed_layers(originals.into_iter().filter(|id|!fields.contains(id)).collect()); + } + Some(policy) + } Err(error) => return Ok(json!({"executed":false,"completed":true,"pending":false,"revision":before,"error":error})), } } else { None }; @@ -1079,7 +1096,7 @@ mod tests { assert_eq!(applied["executed"], true); assert_eq!(applied["revision"], w.expected_revision); assert_eq!(applied["receipt"]["sequence"], 1); - assert_eq!(applied["receipt"]["templatePolicy"], "default-allowed"); + assert_eq!(applied["receipt"]["templatePolicy"], "ordinary-canvas"); let current = app.session.active().unwrap().doc.layer(LayerId(layer)).unwrap(); assert!(matches!(¤t.content, photocraft_doc::LayerContent::Text(text) if text.text == "New")); let hidden = invoke(&mut w, &mut app, "engine.execute", @@ -1106,7 +1123,7 @@ mod tests { let receipt = invoke(&mut w, &mut app, "engine.execute", command).unwrap(); assert_eq!(receipt["executed"], true); assert_eq!(receipt["revision"], before + 1); - assert_eq!(receipt["receipt"]["templatePolicy"], "default-allowed"); + assert_eq!(receipt["receipt"]["templatePolicy"], "ordinary-canvas"); let state = app.session.active().unwrap(); assert!(state.active_layer.is_none()); let bytes = photocraft_io::export(&state.doc, "pcraft", &Default::default()).unwrap().bytes; @@ -1138,6 +1155,46 @@ mod tests { assert!(!app.session.active().unwrap().doc.layer(layer).unwrap().visible); } + #[test] + fn a_template_without_a_published_policy_protects_only_original_unmapped_layers() { + let (mut w, mut app, _) = fixture(); + let fixed = app.session.active().unwrap().active_layer.unwrap(); + let mapped = app.session.execute("type.create", json!({"text":"Sample","size":18})).unwrap()["layer"].as_u64().unwrap(); + app.session.edit("Template fields", |doc, _| { + doc.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({ + "canvasFirst":true, "originalLayerIds":[fixed.0,mapped], + "outputs":[{"mapping":{"fields":[{"nativeLayerId":mapped}]}}] + }).to_string())); + Ok(()) + }).unwrap(); + w.pi_request_scope["productProduction"] = json!(true); + w.expected_revision = app.session.active().unwrap().revision; + + let updated = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"type.edit","params":{"layer":mapped,"text":"Desk lamp"}})).unwrap(); + assert_eq!(updated["executed"], true); + assert_eq!(updated["receipt"]["templatePolicy"], "mapped-fields"); + + let revision = w.expected_revision; + let rejected = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.setProps","params":{"layers":[fixed.0,mapped],"visible":false}})).unwrap(); + assert_eq!(rejected["executed"], false); + assert_eq!(w.expected_revision, revision); + assert!(rejected["error"].as_str().unwrap().contains("固定图层")); + let doc = &app.session.active().unwrap().doc; + assert!(doc.layer(fixed).unwrap().visible); + assert!(doc.layer(LayerId(mapped)).unwrap().visible); + + let added = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.new.layer","params":{"name":"Underlay"}})).unwrap(); + assert_eq!(added["executed"], true); + let new_layer = app.session.active().unwrap().active_layer.unwrap(); + let edited = invoke(&mut w, &mut app, "engine.execute", + json!({"command":"layer.setProps","params":{"layer":new_layer.0,"visible":false}})).unwrap(); + assert_eq!(edited["executed"], true); + assert!(!app.session.active().unwrap().doc.layer(new_layer).unwrap().visible); + } + #[test] fn a_published_policy_limits_the_actual_native_write() { let (mut w, mut app, _) = fixture();