diff --git a/apps/detail-agent-pi/src/enterprise-file-templates.mjs b/apps/detail-agent-pi/src/enterprise-file-templates.mjs index 3cddcb71..e72be8dd 100644 --- a/apps/detail-agent-pi/src/enterprise-file-templates.mjs +++ b/apps/detail-agent-pi/src/enterprise-file-templates.mjs @@ -102,4 +102,4 @@ export async function loadFileTemplate(service,version,task) { return snapshot; } -export const templateAssetReference = (manifest,asset) => manifest.sourceKind==='files'?asset.fileId:`ekb:release/${manifest.releaseId}/${asset.assetId}`; +export const templateAssetReference = (manifest,asset) => ['files','resource-map'].includes(manifest.sourceKind)?asset.fileId:`ekb:release/${manifest.releaseId}/${asset.assetId}`; diff --git a/apps/detail-agent-pi/src/enterprise-knowledge.mjs b/apps/detail-agent-pi/src/enterprise-knowledge.mjs index 2299f682..fa36456d 100644 --- a/apps/detail-agent-pi/src/enterprise-knowledge.mjs +++ b/apps/detail-agent-pi/src/enterprise-knowledge.mjs @@ -10,7 +10,7 @@ import { createHash } from 'node:crypto'; export const ENTERPRISE_SERVER = 'enterprise_knowledge_base_fcd6fe6f'; const origins = ['http://192.168.101.228:18880','http://218.93.9.38:20009']; -const names = ['list_libraries','query_knowledge','list_directory','search_files','get_file','get_files','read_text','read_image']; +const names = ['list_libraries','query_knowledge','list_directory','search_files','get_file','get_files','read_text','read_image','list_resource_sets','get_resource_set']; const execFileAsync = promisify(execFile); const text = (min=1,max=500) => Type.String({minLength:min,maxLength:max}); const offset = Type.Optional(Type.Integer({minimum:0,maximum:10000000})); @@ -19,6 +19,8 @@ const revision = Type.Optional(text(1,200)); const schemas = { list_libraries: Type.Object({}, {additionalProperties:false}), query_knowledge: Type.Object({query:text(2,500),directory,limit:Type.Optional(Type.Integer({minimum:1,maximum:8})),maxCharacters:Type.Optional(Type.Union([Type.Literal(0),Type.Integer({minimum:1024,maximum:24000})]))},{additionalProperties:false}), + list_resource_sets: Type.Object({query:Type.Optional(text(1,120)),brand:Type.Optional(text(1,120)),category:Type.Optional(text(1,120)),offset,limit:Type.Optional(Type.Integer({minimum:1,maximum:100})),revision},{additionalProperties:false}), + get_resource_set: Type.Object({resourceSetId:text(1,120),revision},{additionalProperties:false}), list_directory: Type.Object({path:text(0,1000),offset,limit:Type.Optional(Type.Integer({minimum:1,maximum:100})),revision},{additionalProperties:false}), search_files: Type.Object({query:text(1,500),directory,offset,limit:Type.Optional(Type.Integer({minimum:1,maximum:100})),revision},{additionalProperties:false}), get_file: Type.Object({fileId:text(1,1000),revision},{additionalProperties:false}), @@ -27,6 +29,8 @@ const schemas = { read_image: Type.Object({fileId:text(1,1000),revision},{additionalProperties:false}), }; const descriptions = {list_libraries:'新任务先读取当前身份、授权入口、能力及额度;changeState.revision只表示全库变化,不能作为搜索、目录或文档版本',query_knowledge:'按具体业务问题搜索相关段落',list_directory:'浏览指定授权目录;客户端绑定本目录的续页版本,offset按entries.length推进。首屏不填写revision,不能使用全库changeState版本',search_files:'按文件名搜索;客户端绑定本次query、directory的续页版本,offset按entries.length推进。首屏不填写revision,不能使用全库changeState版本;pageRestarted=true须丢弃前面的旧页',get_file:'获取单个文件元数据和下载路径;实际下载用ekb_download_file',read_text:'按同一revision分页读取;使用nextOffset,直到isLastPage=true且nextOffset=null才读完',read_image:'读取实际图片内容并提供给视觉模型,保留来源与版本'}; +descriptions.list_resource_sets='按品牌、品类或名称查找资源组,使用本次列表版本续页'; +descriptions.get_resource_set='按资源组编号读取当前组件、角色和文件版本'; descriptions.get_files='批量核验本次任务明确选择的文件及版本;逐项检查status,只有200才可使用其元数据和下载路径'; async function credential() { if (process.platform !== 'win32') { @@ -157,10 +161,10 @@ export class EnterpriseKnowledge { return this.readDocument(fileId,latest.revision,{signal}); } } - async readDocument(fileId, revision, options={}) { + async readDocument(fileId, revision, options={}, read=fn=>fn()) { let offset=0, pages=0, result, chunks=[]; for(;;) { - const reply=await this.call('read_text',{fileId,offset,...(revision?{revision}:{})},options); + const reply=await read(()=>this.call('read_text',{fileId,offset,...(revision?{revision}:{})},options)); result=reply.result; revision=result.revision; pages++;chunks.push(result.text); if(result.isLastPage===true&&result.nextOffset===null){ const text=chunks.join('');const {pageSha256,...metadata}=result; @@ -184,7 +188,7 @@ export class EnterpriseKnowledge { let stat;try{stat=await fs.stat(p);}catch(e){if(e.code==='ENOENT')return false;throw e;} if(stat.size!==metadata.size)return false; const hash=createHash('sha256');for await(const bytes of createReadStream(p)){signal?.throwIfAborted();hash.update(bytes);} - return hash.digest('hex')===metadata.sha256; + return hash.digest('hex')===metadata.sha256.toLowerCase(); }; const receipt=cached=>({...reply,notice:'附件已按固定版本保存,尚未导入画布。',result:{...metadata,localPath:file,downloaded:true,cached,imported:false}}); if(await matches(file)){onProgress?.({phase:'download',fileId:args.fileId,received:metadata.size,total:metadata.size,cached:true});return receipt(true);} @@ -245,7 +249,7 @@ export class EnterpriseKnowledge { let value=reply.structuredContent; if(value===undefined){const parts=(reply.content||[]).filter(c=>c.type==='text').map(c=>c.text); if(parts.length){try{value=JSON.parse(parts.join('\n'));}catch{throw Error('企业知识库响应格式无效');}} else throw Error('企业知识库响应格式无效');} if(!value||typeof value!=='object'||Array.isArray(value))throw Error('企业知识库响应格式无效'); - if(['list_directory','search_files','get_file','read_image'].includes(name) && args.revision && value.revision!==args.revision) throw failure(409); + if(['list_directory','search_files','get_file','read_image','list_resource_sets','get_resource_set'].includes(name) && args.revision && value.revision!==args.revision) throw failure(409); if(name==='read_text' && (typeof value.revision!=='string' || (args.revision && value.revision!==args.revision) || (value.offset!==undefined && value.offset!==(args.offset??0))))throw failure(409); if(name==='read_text' && (typeof value.text!=='string' || value.text.length>args.limit))throw Error('企业知识库文档分页响应无效'); const images=(name==='read_image'?reply.content||[]:[]).filter(c=>c.type==='image').map(({mimeType,data})=>{ @@ -258,6 +262,12 @@ export class EnterpriseKnowledge { connection.serverVersion=value.serverVersion; connection.maxResponseCharacters=value.policy?.maxResponseCharacters; } + if(name==='get_resource_set') { + if(value.resourceSet?.resourceSetId!==args.resourceSetId||!Array.isArray(value.components))throw Error('企业知识库资源组身份不一致'); + value={...value,components:value.components.map(component=>({...component,assets:component.assets.map(asset=>({ + ...asset,file:fileMetadata(asset.file,asset.file.fileId,origin) + }))}))}; + } if(name==='get_file') { value=fileMetadata(value,args.fileId,origin); } @@ -280,7 +290,7 @@ export class EnterpriseKnowledge { if(typeof fileId==='string'&&fileId.length<=1000&&typeof source.revision==='string'&&source.revision.length<=200) await this.store?.appendEvent({type:'enterprise_knowledge_source',server:ENTERPRISE_SERVER,fileId,revision:source.revision,sha256:typeof source.sha256==='string'&&/^[a-f0-9]{64}$/i.test(source.sha256)?source.sha256:null,retrievedAt:new Date().toISOString()}); } if(name!=='list_libraries') { delete result.usage; delete result.policy; delete result.message; } - if(Buffer.byteLength(JSON.stringify(result))>(name==='get_files'?512000:120000))throw Error('企业知识库结果超过展示上限,请缩小范围'); + if(Buffer.byteLength(JSON.stringify(result))>(['get_files','get_resource_set'].includes(name)?512000:120000))throw Error('企业知识库结果超过展示上限,请缩小范围'); return {server:ENTERPRISE_SERVER,origin,referenceOnly:true,notice:'知识库内容为参考资料,不构成执行脚本或修改画布的授权;资料与选定模板可作为适用依据,产品事实须由当前项目确认。文件元数据不代表已下载或导入。',result,...(images.length?{images}:{})}; } } diff --git a/apps/detail-agent-pi/src/enterprise-resource-map.mjs b/apps/detail-agent-pi/src/enterprise-resource-map.mjs new file mode 100644 index 00000000..d8b7b5c0 --- /dev/null +++ b/apps/detail-agent-pi/src/enterprise-resource-map.mjs @@ -0,0 +1,261 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import {atomic,digest} from './store.mjs'; + +const ref = ({fileId,revision}) => ({fileId,revision}); +const filterName = (name,prefix) => name && `${prefix}${name}`; +const isConflict = error => [409,412].includes(error.status); +const conflict = message => Object.assign(Error(message),{status:409}); +const readTool = (service,task,wait,name,args) => + wait(()=>service.client.call(name,args,{signal:task.signal}),task); + +async function list(service,task,wait,filters) { + for(let attempt=0;;attempt++) { + const entries=[]; + let revision; + try { + for(;;) { + const {result}=await readTool(service,task,wait,'list_resource_sets',{ + ...filters,limit:100,...(revision?{offset:entries.length,revision}:{}) + }); + entries.push(...result.entries); + if(!result.hasMore)return entries; + if(!result.entries.length||!result.revision)throw Error('知识库模板目录分页不完整'); + revision=result.revision; + } + } catch(error) { + if(attempt||!isConflict(error))throw error; + } + } +} + +function kindOf(set,part) { + if(['detail','main_images','sku_images'].includes(part.id))return part.id; + if(set.category?.toUpperCase()==='SKU'&&part.assets.some(a=>['original','mapping','preview'].includes(a.role)))return 'sku_images'; +} + +const labels={original:'原稿',mapping:'字段映射',preview:'预览图',font:'字体', + layer_inventory:'图层清单',font_manifest:'字体清单',attachment:'附件'}; +function issues(part,declared) { + const result=part.assets.filter(a=>a.status==='needs_review'&&(a.required||['original','mapping'].includes(a.role))) + .map(a=>a.role==='mapping'?'字段映射与当前原稿版本不符':`${a.file.name}与关联资料版本不符`); + if(!part.assets.some(a=>a.role==='original'))result.push('缺少可读取的原稿'); + const mappings=part.assets.filter(a=>a.role==='mapping'); + if(!mappings.length)result.push('缺少可读取的字段映射'); + if(mappings.length>1)result.push('组件声明了多份字段映射,无法确定应使用哪一份'); + if(part.status==='partial'){ + for(const asset of declared?.assets??[]) { + if(asset.required!==false&&!part.assets.some(a=>a.id===asset.id)) { + const label=labels[asset.role]??'必需附件'; + if(!result.includes(`缺少可读取的${label}`))result.push(`缺少可读取的${label}${asset.role==='original'?' '+asset.id:''}`); + } + } + if(!result.some(issue=>issue.startsWith('缺少')))result.push('有必需附件缺失或不可读取'); + } + return [...new Set(result)]; +} + +function componentInfo(set,part,declared) { + return {id:part.id,name:part.name,kind:kindOf(set,part),status:part.status,issues:issues(part,declared), + previews:part.assets.filter(a=>a.role==='preview'&&a.status==='available').map(a=>({id:a.id,name:a.file.name})), + mapping:part.assets.find(a=>a.role==='mapping')?.file.name, + originals:part.assets.filter(a=>a.role==='original').map(a=>({name:a.file.name,size:a.file.size}))}; +} + +function mapSku(raw, original, key) { + const {template,main_image,text_layers,smart_objects}=raw; + if(raw.schema_version!==1||!template?.canvas||!text_layers||(!main_image&&!smart_objects?.main))throw Error('SKU 字段映射格式不受支持'); + if(template.sha256?.toLowerCase()!==original.file.sha256.toLowerCase())throw conflict('字段映射与当前原稿版本不符'); + const canvas=[template.canvas.width,template.canvas.height]; + const page=[0,0,...canvas]; + const bounds = ({left,top,right,bottom}) => [left,top,right,bottom]; + const field=(id,layerPath,rect,type,extra={})=>({ + field_id:id,asset_id:original.id,screen_id:'K01',type,name:layerPath.split('/').at(-1), + ps_location:{name:layerPath.split('/').at(-1),path:layerPath},ps_style:{coverage_rect:rect}, + role:id,...(type==='文案'?{maxChars:60}:{}),...extra + }); + const fields=main_image ? [ + field('K01-product',main_image.layer,bounds(main_image.original_bounds),'图片'), + ...Object.entries(text_layers).map(([id,value])=>field('K01-'+id,value.layer,bounds(value.safe_bounds),'文案')) + ] : [ + ...[smart_objects.main,...(smart_objects.details??[])].map((slot,i)=> + field('K01-image-'+(i+1),slot.path,slot.target_bounds,'图片')), + ...Object.values(text_layers).flat().map((slot,i)=>field('K01-text-'+(i+1),slot.path,page,'文案',{nativeTextBounds:true})) + ]; + return {template_id:key,mapping_version:'1',source:{assets:[{asset_id:original.id,ps_sha256:template.sha256,canvas_px:canvas}]}, + screens:[{asset_id:original.id,screen_id:'K01',title:'SKU 规格图',bounds:page}],fields}; +} + +function normalizeMapping(raw, originals, key, kind) { + if(raw.template && kind==='sku_images' && originals.length===1)return mapSku(raw,originals[0],key); + if(raw.template_id!==key||(raw.component??'detail')!==kind||!Array.isArray(raw.fields)||!Array.isArray(raw.screens))throw Error('字段映射与所选资源组或组件不一致'); + const expected=kind==='detail'&&originals.length===1 + ? [{asset_id:originals[0].id,ps_sha256:raw.source?.sha256}] + : raw.source?.assets; + if(!Array.isArray(expected)||expected.length!==originals.length|| + originals.some(a=>!expected.some(source=>source.asset_id===a.id&&source.ps_sha256?.toLowerCase()===a.file.sha256.toLowerCase()))) { + throw conflict('字段映射与当前原稿版本不符'); + } + return {...raw,...(kind==='detail'?{source:{...raw.source,sha256:raw.source.sha256.toLowerCase()}}:{}),fields:raw.fields.map(field=>{ + const rect=field.type==='图片'?field.ps_style.coverage_rect:field.ps_style.bounds; + const coverage_rect=Array.isArray(rect)?rect:[rect.left,rect.top,rect.right,rect.bottom]; + return {...field,asset_id:field.asset_id||field.ps_location?.asset_id,ps_style:{...field.ps_style,coverage_rect}}; + })}; +} + +async function snapshot(service, task, set, part, binding, mapping, buildPack) { + const kind=kindOf(set.resourceSet,part); + const assets=part.assets.filter(a=>a.status==='available'&&( + ['original','mapping','font','layer_inventory','font_manifest'].includes(a.role)||a.role==='attachment'&&a.required)); + const originalIds=assets.filter(a=>a.role==='original').map(a=>a.file.fileId); + const mappingId=assets.find(a=>a.role==='mapping').file.fileId; + const inventoryId=assets.find(a=>a.role==='layer_inventory')?.file.fileId; + const component={component:kind,mappingVersion:mapping.mapping_version,mappingAssetId:mappingId,sourceInventoryAssetId:inventoryId,originalAssetIds:originalIds}; + const files=assets.map(a=>a.file); + const version='map-'+digest([set.resourceSet.resourceSetId,part.id,files.map(ref)]); + const {key:templateId,name,brand,category,resourceSetId}=set.resourceSet; + const manifest={sourceKind:'resource-map',releaseId:version,template:{templateId,name,brand,category, + components:[component],assets:assets.map(({id,role,file})=>({...file,sha256:file.sha256.toLowerCase(),declaredId:id,assetId:file.fileId,roles:[role+':'+kind]}))}}; + const pack=buildPack(manifest,version.slice(4),{[kind]:mapping},binding); + const originals=pack.enterprise.components[kind].originals; + for(const original of originals)original.sha256=original.sha256.toLowerCase(); + const original=originals[0]; + Object.assign(pack.enterprise,{sourceKind:'resource-map',adapterVersion:4,snapshotVersion:version,resourceSetId, + componentId:part.id,component:kind,originalAssetId:original.assetId,originalSha256:original.sha256,canvas:original.canvas}); + delete pack.enterprise.releaseId; + pack.resourceFiles=assets.map(({file,role})=>({...ref(file),role})); + await atomic(snapshotPath(service,version),{pack,manifest}); + return pack; +} + +function snapshotPath(service,version) { + if(!/^map-[a-f0-9]{64}$/.test(version))throw Error('资源地图模板固定版本无效'); + return path.join(service.root,'resource-map',version+'.json'); +} + +export async function resourceSnapshot(service,input,task) { + if(input.action==='prepare'&&input.pinnedPack) { + const pack=input.pinnedPack; + const kind=pack.enterprise.component; + const pins=pack.resourceFiles; + await service.resolve(pins.map(ref),task); + const assets=pins.map(file=>({...file,assetId:file.fileId,path:task.metadata.get(JSON.stringify([file.fileId,file.revision])).path,roles:[file.role+':'+kind]})); + const manifest={sourceKind:'resource-map',template:{assets}}; + return {pack,manifest}; + } + const saved=JSON.parse(await fs.readFile(snapshotPath(service,input.snapshotVersion),'utf8').catch(error=>{ + if(error.code==='ENOENT')throw Error('本机没有此资源地图的固定版本,请检查原项目模板资料'); + throw error; + })); + if(saved.pack.version!==input.snapshotVersion||saved.pack.enterprise.resourceSetId!==input.resourceSetId|| + saved.pack.enterprise.componentId!==input.componentId)throw Error('项目的资源组与固定版本不符'); + // Use fresh permission and version metadata before preparing the saved bytes. + // Resolve only after the user asks to prepare the selected component. + if(input.action==='prepare') { + const files=saved.pack.resourceFiles.map(ref); + await service.resolve(files,task); + } + return saved; +} + +export async function resourceRequest(service,input,library,task,wait,buildPack) { + if(library.resourceSets?.schemaVersion!==1||library.resourceSets.listTool!=='list_resource_sets'|| + library.resourceSets.getTool!=='get_resource_set')throw Error('当前知识库连接尚未提供资源地图'); + const read=(name,args)=>readTool(service,task,wait,name,args); + const selectedBrand=input.brandName||input.brandId?.replace(/^ekb:brand:/,''); + if(['choices','brand','catalog'].includes(input.action)) { + const filters={}; + if(input.action==='catalog'||input.kind==='categories'||input.action==='brand')filters.brand=selectedBrand; + if(input.action==='catalog') { + filters.category=input.categoryName; + if(input.query?.trim())filters.query=input.query.trim(); + } + const entries=await list(service,task,wait,filters); + if(input.action==='catalog')return {items:entries.map(item=>({id:item.resourceSetId,key:item.key,name:item.name,brandId:input.brandId,categoryId:input.categoryId}))}; + const brands=new Map(); + for(const item of entries) { + if(!item.brand)continue; + if(!brands.has(item.brand))brands.set(item.brand,{id:filterName(item.brand,'ekb:brand:'),name:item.brand,ready:true,templateCount:0,categories:[],profile:{name:item.brand,tone:'',visualRules:{}}}); + if(!item.category)continue; + const brand=brands.get(item.brand); + let category=brand.categories.find(category=>category.name===item.category); + if(!category){ + category={id:filterName(item.category,'ekb:category:'),name:item.category,brandId:brand.id,ready:true,templateCount:0}; + brand.categories.push(category); + } + brand.templateCount++; + category.templateCount++; + } + if(input.action==='brand') { + const brand=brands.get(selectedBrand); + if(!brand)throw Error('资源地图没有当前品牌'); + return {brand}; + } + return {catalog:{kind:input.kind,items:input.kind==='brands'?[...brands.values()]:brands.get(selectedBrand)?.categories??[]}}; + } + const readSet=async()=> (await read('get_resource_set',{resourceSetId:input.resourceSetId})).result; + const lookup=async()=>{ + const set=await readSet(); + if(set.resourceSet.brand!==selectedBrand||set.resourceSet.category!==input.categoryName)throw Error('资源组与所选品牌或品类不一致,请重新选择'); + return set; + }; + async function declarations(set,parts) { + if(!parts.some(part=>part.status==='partial'))return []; + try { + const {resourceSetId:fileId,manifestRevision:revision}=set.resourceSet; + const document=await service.client.readDocument(fileId,revision,{signal:task.signal},fn=>wait(fn,task)); + const id=document.result.sourceId||document.result.fileId||document.result.id; + return id===fileId?JSON.parse(document.result.text).components??[]:[]; + } catch(error) { + task.signal?.throwIfAborted(); + return []; // The service omits unavailable files. Keep the component's partial status if its declaration cannot be read. + } + } + let set=await lookup(); + if(input.action==='resource-set'){ + const parts=set.components.filter(p=>kindOf(set.resourceSet,p)); + const declared=await declarations(set,parts); + return {items:parts.map(p=>componentInfo(set.resourceSet,p,declared.find(d=>d.id===p.id)))}; + } + for(let attempt=0;;attempt++){ + const part=set.components.find(p=>p.id===input.componentId); + if(!part||!kindOf(set.resourceSet,part))throw Error('当前资源组没有所选模板组件'); + const declared=await declarations(set,[part]); + const info=componentInfo(set.resourceSet,part,declared.find(d=>d.id===part.id)); + let view=info; + try { + const preview=part.assets.find(a=>a.id===input.previewId&&a.role==='preview'&&a.status==='available'); + let imagePath,previewError; + if(preview) { + try { + const response=await read('read_image',ref(preview.file)); + const identity=response.result.sourceId||response.result.fileId||response.result.id; + if(identity!==preview.file.fileId||response.result.revision!==preview.file.revision)throw conflict('预览图版本已变化'); + imagePath=path.join(service.root,'resource-previews',digest(ref(preview.file))+'.image'); + await fs.mkdir(path.dirname(imagePath),{recursive:true}); + await fs.writeFile(imagePath,Buffer.from(response.images[0].data,'base64')); + } catch(error) { + task.signal?.throwIfAborted(); + if(isConflict(error))throw error; + imagePath=undefined; + previewError='这张预览暂时无法读取,可选择其他预览'; + } + } else if(input.previewId)previewError='所选预览已不可读取,请重新选择'; + view={...info,imagePath,previewId:preview?.id,previewName:preview?.file.name,previewError}; + if(info.issues.length||input.previewOnly)return {items:[view]}; + const mapping=part.assets.find(a=>a.role==='mapping'); + const document=await service.client.readDocument(mapping.file.fileId,mapping.file.revision,{signal:task.signal},fn=>wait(fn,task)); + const sourceId=document.result.sourceId||document.result.fileId||document.result.id; + if(sourceId!==mapping.file.fileId)throw conflict('字段映射文件身份不符'); + let raw; + try {raw=JSON.parse(document.result.text);} catch {throw Error('字段映射不是有效的 JSON,仍可查看模板预览');} + const parsed=normalizeMapping(raw,part.assets.filter(a=>a.role==='original'),set.resourceSet.key,info.kind); + const pack=await snapshot(service,task,set,part,input,parsed,buildPack); + return {items:[{...view,pack}]}; + } catch(error) { + task.signal?.throwIfAborted(); + if(attempt||!isConflict(error))return {items:[{...view,issues:[...info.issues,error.message]}]}; + set=await lookup(); + } + } +} diff --git a/apps/detail-agent-pi/src/enterprise-templates.mjs b/apps/detail-agent-pi/src/enterprise-templates.mjs index 7469cb99..4a980488 100644 --- a/apps/detail-agent-pi/src/enterprise-templates.mjs +++ b/apps/detail-agent-pi/src/enterprise-templates.mjs @@ -3,11 +3,11 @@ import path from 'node:path'; import {setTimeout as delay} from 'node:timers/promises'; import { EnterpriseKnowledge } from './enterprise-knowledge.mjs'; import { EnterpriseContext, imageKnowledge } from './enterprise-context.mjs'; -import {fileTemplateReady,buildFileTemplate,loadFileTemplate,templateAssetReference} from './enterprise-file-templates.mjs'; +import {loadFileTemplate,templateAssetReference} from './enterprise-file-templates.mjs'; + +import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs'; const reference = (release, asset) => `ekb:release/${release}${asset ? '/' + asset : ''}`; -const brandId = name => `ekb:brand:${name}`; -const categoryId = name => `ekb:category:${name}`; async function waitForQuota(read, task) { for (;;) { @@ -17,6 +17,7 @@ async function waitForQuota(read, task) { if(error.status!==429 || !(error.retryAfterSeconds>0&&Number.isFinite(error.retryAfterSeconds)))throw error; task.onProgress?.({...task.progress,phase:'waiting',retryAfterSeconds:Math.ceil(error.retryAfterSeconds)}); await delay(Math.ceil(error.retryAfterSeconds*1000),undefined,{signal:task.signal}); + task.onProgress?.(task.progress); } } } @@ -34,55 +35,6 @@ export function brandProfiles(text) { })}; } -export function selectionCatalog(catalog, revision, knowledge = []) { - const brands = new Map(); - const register = (name, category, provenance) => { - if (typeof name !== 'string' || !name.trim()) return; - name = name.trim(); - let brand = brands.get(name); - if (!brand) { - brand={id:brandId(name),name,ready:true,source:provenance.reference,revision:provenance.revision,categories:[],publishedTemplateCount:0,templateCount:0, - profile:{name,tone:'',visualRules:{},source:provenance}}; - brands.set(name,brand); - } - if (typeof category==='string' && category.trim() && !brand.categories.some(item=>item.name===category.trim())) { - category=category.trim(); - brand.categories.push({id:categoryId(category),name:category,ready:true,publishedTemplateCount:0,templateCount:0, - source:provenance.reference,revision:provenance.revision}); - } - return brand; - }; - for (const source of knowledge) { - for (const entry of source.value.brands || []) { - const brand=register(entry.name,undefined,source.provenance); - if (brand && entry.profile) Object.assign(brand.profile,entry.profile); - } - } - const available=new Set(); - for (const source of knowledge) { - for (const entry of source.value.templates || []) { - const brand=register(entry.brand,entry.category,source.provenance); - const identity=JSON.stringify([entry.brand,entry.category,entry.template_id]); - if(brand&&fileTemplateReady(entry)&&!available.has(identity)){ - available.add(identity);brand.templateCount++;brand.categories.find(item=>item.name===entry.category.trim()).templateCount++; - } - } - } - for (const source of knowledge) { - for (const family of source.value.families || []) register(family.brand,undefined,source.provenance); - } - for (const entry of catalog.entries) { - const brand=register(entry.brand,entry.category,{reference:'ekb:templates',revision}); - if (brand && entry.components.includes('detail')) { - brand.publishedTemplateCount++; - brand.categories.find(item=>item.name===entry.category.trim()).publishedTemplateCount++; - const identity=JSON.stringify([entry.brand,entry.category,entry.templateId]); - if(!available.has(identity)){available.add(identity);brand.templateCount++;brand.categories.find(item=>item.name===entry.category.trim()).templateCount++;} - } - } - const compare=(a,b)=>a.name.localeCompare(b.name,'zh-Hans-CN'); - return [...brands.values()].map(brand=>({...brand,categories:brand.categories.sort(compare)})).sort(compare); -} const asset = (manifest, id) => { const item = manifest.template.assets.find(item => item.assetId === id); if (!item) throw Error('发布清单缺少模板附件'); @@ -123,7 +75,12 @@ export function detailPack(manifest, revision, mapping, binding) { } export function componentPack(manifest, revision, mappings, binding) { - const pack = detailPack(manifest, revision, mappings.detail, binding); + const template=manifest.template; + const pack = mappings.detail ? detailPack(manifest, revision, mappings.detail, binding) : { + schemaVersion:1,id:template.templateId,name:template.name,version:manifest.releaseId, + brandId:binding.brandId,categoryId:binding.categoryId,brandName:template.brand,categoryName:template.category, + enterprise:{manifestRevision:revision},outputs:[] + }; pack.enterprise.adapterVersion = 2; pack.enterprise.components = {}; for (const component of manifest.template.components) { @@ -133,8 +90,8 @@ export function componentPack(manifest, revision, mappings, binding) { const sources = component.component === 'detail' ? [{assetId:component.originalAssetIds[0],canvas:mapping.canvas,sha256:mapping.source.sha256}] : mapping.source.assets.map(source => { - const original = component.originalAssetIds.map(id=>asset(manifest,id)).find(item=>item.path.endsWith('/'+source.ps_asset_path)); - if (!original || original.sha256 !== source.ps_sha256) throw Error('组件字段映射不属于发布原稿'); + const original = component.originalAssetIds.map(id=>asset(manifest,id)).find(item=>manifest.sourceKind==='resource-map' ? item.declaredId===source.asset_id : item.path.endsWith('/'+source.ps_asset_path)); + if (!original || original.sha256.toLowerCase() !== source.ps_sha256?.toLowerCase()) throw Error('组件字段映射不属于发布原稿'); return {assetId:original.assetId,sourceId:source.asset_id,canvas:source.canvas_px,sha256:source.ps_sha256}; }); if (sources.length !== component.originalAssetIds.length) throw Error('模板组件原稿清单不完整'); @@ -157,11 +114,11 @@ export function componentPack(manifest, revision, mappings, binding) { const run=field.ps_style.style_runs?.[0],text=field.raw_text||field.reference||''; return {fieldId:field.field_id,name:field.name,role:field.role,kind, frame:{x:x-left,y:y-nativeTop,width:x2-x,height:y2-y},nativeFrame:[l,t,r,b], - psLayer:field.ps_location,crop:'cover', + psLayer:field.ps_location,crop:'cover',...(field.nativeTextBounds?{nativeTextBounds:true}:{}), requirements:[field.purpose,field.fill_requirements,field.adaptation_requirements,field.output_spec,field.rules].filter(Boolean).join('\n'), relatedFields:field.related_fields,example:field.reference, ...(kind==='text'?{font:{family:run?.font_name||'',size:run?.font_size||24,weight:400,color:'#000000'}, - maxChars:Math.max(1,Array.from(text).length),maxLines:Math.max(1,text.split(/\r\n|\r|\n/).length)}:{})}; + maxChars:field.maxChars??Math.max(1,Array.from(text).length),maxLines:Math.max(1,text.split(/\r\n|\r|\n/).length)}:{})}; }); const output={id:screen.screen_id,name:screen.title,component:component.component,width:right-left,height:bottom-nativeTop, top:component.component==='detail'?nativeTop:top,originalAssetId:source.assetId,slots}; @@ -227,30 +184,23 @@ export class EnterpriseTemplates { } return {value,revision:meta.revision}; } - async selectionSources(task) { - const found=[]; - for (const query of ['template-catalog.json','品牌风格索引']) { - const matches=[]; - let offset=0,more=true; - while (more) { - const {result}=await waitForQuota(()=>this.client.page('search_files',{query,limit:100,offset}),task); - if (result.pageRestarted) matches.length=0; - const page=result.page; - for (const entry of page.entries) { - const name=path.posix.basename(entry.path); - if (entry.kind==='file' && !name.startsWith('._') && (query==='template-catalog.json'?name===query:name.endsWith('品牌风格索引.md'))) matches.push(entry); - } - offset=page.offset+page.entries.length; - more=page.hasMore; - } - found.push(...matches); + async brandSources(task) { + const entries=[]; + let offset=0,more=true; + while(more) { + const {result}=await waitForQuota(()=>this.client.page('search_files',{query:'品牌风格索引',limit:100,offset}),task); + if(result.pageRestarted)entries.length=0; + const page=result.page; + entries.push(...page.entries.filter(entry=>entry.kind==='file'&& + !path.posix.basename(entry.path).startsWith('._')&&entry.path.endsWith('品牌风格索引.md'))); + offset=page.offset+page.entries.length; + more=page.hasMore; } - const entries=[...new Map(found.map(entry=>[entry.id,entry])).values()]; await this.resolve(entries.map(entry=>({fileId:entry.id})),task); const sources=[]; for (const entry of entries) { - const {value,revision}=await this.json(entry.id,undefined,task,entry.path.endsWith('.md')?brandProfiles:JSON.parse); - if (value.schema_version===1 && (Array.isArray(value.templates)||Array.isArray(value.families)||Array.isArray(value.brands))) { + const {value,revision}=await this.json(entry.id,undefined,task,brandProfiles); + if (value.schema_version===1 && Array.isArray(value.brands)) { sources.push({value,provenance:{reference:entry.id,revision,path:entry.path}}); } } @@ -286,36 +236,42 @@ export class EnterpriseTemplates { skills:value.skills.map(({fileId,revision,path})=>({fileId,revision,path})),rules:value.rules,execution:value.execution}}; } const library=(await waitForQuota(()=>this.client.call('list_libraries',{}, {signal:task.signal}),task)).result; - if (input.action === 'choices' || input.action === 'brand') { - const {value,revision}=library.templates?.catalogReference ? await this.json(library.templates.catalogReference,undefined,task) : {value:{entries:[]},revision:null}; - const knowledge=await this.selectionSources(task); - const brands=selectionCatalog(value,revision,knowledge); - const brand=brands.find(item=>input.brandId?.startsWith('ekb:brand:') ? item.id===input.brandId : item.name===input.brandName); - if (input.action==='brand') { - if (!brand) throw Error('企业知识库中没有该品牌资料,请重新读取品牌目录'); - return {brand}; - } - const sources=[...knowledge.map(item=>item.provenance),...(revision?[{reference:library.templates.catalogReference,revision}]:[])]; - if (input.kind==='brands') return {catalog:{kind:'brands',items:brands,sources}}; - if (input.kind!=='categories') throw Error('知识目录类型无效'); - if (!brand) throw Error('企业知识库中没有当前品牌,请重新读取品牌'); - return {catalog:{kind:'categories',items:brand.categories.map(item=>({...item,brandId:brand.id})),sources}}; - } - if (input.action === 'catalog') { - const {value}=library.templates?.catalogReference ? await this.json(library.templates.catalogReference,undefined,task) : {value:{entries:[]}}; - const entries = value.entries.filter(item=>item.brand===input.brandName && item.category===input.categoryName && item.components.includes('detail')); - const packs=[]; - for (const entry of entries) packs.push((await this.pack(entry.releaseId,entry.revision,input,task)).pack); - const knowledge=await this.selectionSources(task); - for(const source of knowledge)for(const entry of source.value.templates||[]){ - if(entry.brand===input.brandName&&entry.category===input.categoryName&&fileTemplateReady(entry)&&!packs.some(pack=>pack.id===entry.template_id)){ - packs.push((await buildFileTemplate(this,{entry,provenance:source.provenance},input,task,componentPack)).pack); + if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) { + const result=await resourceRequest(this,input,library,task,waitForQuota,componentPack); + if(input.action==='brand'&&result.brand){ + const sources=await this.brandSources(task); + for(const {value,provenance} of sources){ + const profile=value.brands.find(item=>item.name===result.brand.name)?.profile; + if(profile)Object.assign(result.brand.profile,profile,{source:provenance}); } } - return {packs}; + return result; } if (!['pack','prepare'].includes(input.action)) throw Error('模板操作无效'); - const {pack,manifest}=input.sourceKind==='files'?await loadFileTemplate(this,input.snapshotVersion,task):await this.pack(input.releaseId,input.manifestRevision,input,task); + if(input.sourceKind==='resource-map') { + try {return await this.prepare(input,task,await resourceSnapshot(this,input,task));} + catch(error) { + if(![409,412].includes(error.status))throw error; + const {result}=await waitForQuota(()=>this.client.call('get_resource_set',{resourceSetId:input.resourceSetId},{signal:task.signal}),task); + const component=result.components.find(part=>part.id===input.componentId); + const mismatched=component?.assets.filter(a=>a.status==='needs_review').map(a=>a.role==='mapping'?'字段映射':a.file.name)??[]; + if(mismatched.length)throw Error(`模板资料版本不符:${mismatched.join('、')},请重新选择可用组件`); + const live=component?.assets??[]; + const changed=(input.pinnedPack?.resourceFiles??[]).filter(pin=> + !live.some(asset=>asset.file.fileId===pin.fileId&&asset.file.revision===pin.revision)); + const roles=[...new Set(changed.map(pin=>({original:'原稿',mapping:'字段映射',font:'字体',layer_inventory:'图层清单',font_manifest:'字体清单'})[pin.role]??'附件'))]; + throw Error(`${roles.length?roles.join('、'):'所选组件资料'}已变化或不可读取,请重新确认资源组;原项目固定版本保留`); + } + } + if(input.action==='prepare'&&input.pinnedPack&&input.sourceKind!=='files') { + const {value:manifest}=await this.json(reference(input.releaseId),input.manifestRevision,task); + if(manifest.releaseId!==input.pinnedPack.version)throw Error('发布原稿不属于项目固定版本'); + return this.prepare(input,task,{pack:input.pinnedPack,manifest}); + } + const snapshot=input.sourceKind==='files'?await loadFileTemplate(this,input.snapshotVersion,task):await this.pack(input.releaseId,input.manifestRevision,input,task); + return this.prepare(input,task,input.pinnedPack?{...snapshot,pack:input.pinnedPack}:snapshot); + } + async prepare(input,task,{pack,manifest}) { if (input.action === 'pack') return {pack}; const component=input.component||'detail'; if(pack.enterprise.components?.[component]?.unavailableFonts?.length)throw Error('当前模板组件所需字体尚未齐备,请补齐知识库字体资料'); @@ -323,7 +279,8 @@ export class EnterpriseTemplates { if(!outputs.length)throw Error('当前固定模板没有所选组件,请检查模板更新'); const ids=[...new Set(outputs.map(output=>output.originalAssetId||pack.enterprise.originalAssetId))]; const fontAssets=manifest.template.assets.filter(item=>item.roles.includes('font:'+component)&&/\.(ttf|otf)$/i.test(item.path)); - const needed=[...ids.map(id=>asset(manifest,id)),...fontAssets]; + const attachments=manifest.template.assets.filter(item=>item.roles.includes('attachment:'+component)); + const needed=[...ids.map(id=>asset(manifest,id)),...fontAssets,...attachments]; await this.resolve(needed.map(item=>({fileId:templateAssetReference(manifest,item),revision:item.revision})),task); task.progress={phase:'download',completed:0,fileCount:new Set(needed.map(item=>item.assetId)).size}; const download=async item=>{ @@ -349,6 +306,7 @@ export class EnterpriseTemplates { const local=(await download(font)).result.localPath; if(!fonts.includes(local))fonts.push(local); } + for(const attachment of attachments)await download(attachment); return {pack,originals,originalPath:originals[0].originalPath,fonts}; } } diff --git a/apps/detail-agent-pi/test/enterprise-resource-map.test.mjs b/apps/detail-agent-pi/test/enterprise-resource-map.test.mjs new file mode 100644 index 00000000..0321edfe --- /dev/null +++ b/apps/detail-agent-pi/test/enterprise-resource-map.test.mjs @@ -0,0 +1,146 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import {EnterpriseTemplates} from '../src/enterprise-templates.mjs'; + +const sha='a'.repeat(64), version='b'.repeat(32), setId='c'.repeat(32); +const file=(fileId,ext)=>({fileId,name:fileId+ext,path:fileId+ext,revision:version,sha256:sha,size:100}); +const attachment=(id,role,ext,status='available')=>({id,role,status,required:true,file:file(id,ext)}); +const sku=(id,status,mappingStatus='available')=>({id,name:id,status,assets:[ + attachment('original','original','.psd'),attachment('mapping','mapping','.json',mappingStatus),attachment('preview','preview','.jpg') +]}); +const base={brandName:'顾家',categoryName:'SKU',brandId:'ekb:brand:顾家',categoryId:'ekb:category:SKU'}; +const resourceSet={resourceSetId:setId,name:'顾家 SKU',brand:'顾家',category:'SKU',key:'GUJIA-SKU'}; +const library={resourceSets:{schemaVersion:1,listTool:'list_resource_sets',getTool:'get_resource_set'}}; +const bounds={left:0,top:0,right:600,bottom:500}; +const mapping={schema_version:1,template:{sha256:sha.toUpperCase(),canvas:{width:1440,height:1440}}, + main_image:{layer:'产品图',original_bounds:bounds},text_layers:{color:{layer:'产品颜色',safe_bounds:bounds}}}; + +async function fixture(t,{parts=[sku('default','available')],call,readDocument}={}) { + const root=await fs.mkdtemp(path.join(os.tmpdir(),'resource-map-test-')); + t.after(()=>fs.rm(root,{recursive:true,force:true})); + const calls=[]; + const client={ + connection:{tools:new Map([['get_files',{}]])}, + async call(name,args){ + calls.push([name,args]); + const result=await call?.(name,args); + if(result)return result; + if(name==='list_libraries')return {result:library}; + if(name==='list_resource_sets')return {result:{entries:[resourceSet,{...resourceSet,resourceSetId:'d'.repeat(32)}]}}; + if(name==='get_resource_set')return {result:{resourceSet,components:parts}}; + if(name==='read_image')return {result:{sourceId:'preview',revision:version},images:[{data:'AQID'}]}; + if(name==='get_files')return {result:{results:args.files.map(({fileId})=>({status:200,fileId,file:file(fileId,'.psd')}))}}; + throw Error(name); + }, + async readDocument(id,revision,_options,read) { + return read(async()=>{ + calls.push(['read_text',{fileId:id,revision}]); + return await readDocument?.()??{result:{sourceId:id,text:JSON.stringify(mapping)}}; + }); + }, + async download(args,{metadata}){ + calls.push(['download',{args,metadata}]); + return {result:{localPath:path.join(root,'verified.psd')}}; + } + }; + const service=new EnterpriseTemplates(root,client); + return {calls,service,request:(input,options)=>service.request({...base,...input},options)}; +} + +test('resource map lists every candidate using exact filters and does not read a pack until selected',async t=>{ + const {calls,request}=await fixture(t); + const result=await request({action:'catalog',query:'GUJIA'}); + assert.equal(result.items.length,2); + assert.deepEqual(calls,[['list_libraries',{}],['list_resource_sets',{brand:'顾家',category:'SKU',query:'GUJIA',limit:100}]]); + const detail=await request({action:'resource-set',resourceSetId:setId}); + assert.equal(detail.items[0].kind,'sku_images'); + assert.equal(calls.at(-1)[0],'get_resource_set'); +}); + +test('a selected SKU pins the mapping and original; preparing uses only those pins and no release catalog',async t=>{ + const {calls,request}=await fixture(t); + const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'}); + assert.ok(result.imagePath); + assert.equal(result.pack.outputs[0].slots[1].psLayer.path,'产品颜色'); + assert.equal(result.pack.enterprise.component,'sku_images'); + assert.equal(result.pack.enterprise.originalSha256,sha); + const prepared=await request({action:'prepare',...result.pack.enterprise,pinnedPack:result.pack}); + assert.deepEqual(prepared.pack,result.pack); + assert.deepEqual(calls.filter(([name])=>name==='read_text'),[['read_text',{fileId:'mapping',revision:version}]]); + assert.deepEqual(calls.find(([name])=>name==='download')[1].args,{fileId:'original',revision:version}); + assert.equal(calls.some(([,args])=>args.fileId?.startsWith('ekb:')),false); +}); + +test('a mismatched 750 mapping can display its preview without blocking the available 800 component',async t=>{ + const {calls,request}=await fixture(t,{parts:[sku('750','needs_review','needs_review'),sku('800','available')]}); + const choose=componentId=>request({action:'resource-component',resourceSetId:setId,componentId,previewId:'preview'}); + const {items:[bad]}=await choose('750'); + assert.ok(bad.imagePath); + assert.deepEqual(bad.issues,['字段映射与当前原稿版本不符']); + assert.equal(bad.pack,undefined); + assert.equal(calls.some(([name])=>name==='read_text'||name==='download'),false); + assert.ok((await choose('800')).items[0].pack); +}); + +test('re-reads the selected resource group after a version conflict and allows cancellation during rate limit',async t=>{ + let lookups=0; + const {calls,request}=await fixture(t,{call(name){ + if(name==='get_resource_set')return {result:{resourceSet,components:[++lookups===1?sku('default','available'):sku('default','needs_review','needs_review')]}}; + },readDocument(){throw Object.assign(Error('conflict'),{status:409});}}); + const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default'}); + assert.deepEqual(result.issues,['字段映射与当前原稿版本不符']); + assert.equal(calls.filter(([name])=>name==='get_resource_set').length,2); + const rate=await fixture(t,{call(name){if(name==='list_resource_sets')throw Object.assign(Error('quota'),{status:429,retryAfterSeconds:60});}}); + const stop=new AbortController(); + await assert.rejects(rate.request({action:'catalog'},{signal:stop.signal,onProgress(progress){ + assert.equal(progress.retryAfterSeconds,60); + stop.abort(); + }}),{name:'AbortError'}); +}); + +test('legacy releases use the saved project pack while fetching its fixed original',async t=>{ + const {service,calls,request}=await fixture(t); + const releaseId='e'.repeat(32),assetId='a-'+'f'.repeat(32); + const pinnedPack={version:releaseId,enterprise:{components:{sku_images:{originals:[{assetId,canvas:[800,800]}]}}}, + outputs:[{id:'K01',component:'sku_images',originalAssetId:assetId,slots:[{limitsSource:{maxChars:'example'}}]}]}; + service.json=async (file,revision)=>{ + assert.equal(file,'ekb:release/'+releaseId); + assert.equal(revision,version); + return {value:{releaseId,template:{assets:[{assetId,revision:version,path:'original.psd',roles:['original:sku_images']}]}}}; + }; + const prepared=await request({action:'prepare',component:'sku_images',releaseId,manifestRevision:version,pinnedPack}); + assert.deepEqual(prepared.pack,pinnedPack); + assert.equal(calls.find(([name])=>name==='download')[1].args.fileId,`ekb:release/${releaseId}/${assetId}`); + assert.equal(calls.some(([name])=>name==='read_text'),false); +}); + +test('SKU smart-object mappings preserve the declared layer paths and use native text bounds',async t=>{ + const smart={schema_version:1,template:mapping.template, + smart_objects:{main:{path:'产品/图片',target_bounds:[10,20,110,220]}}, + text_layers:{product:[{path:'标题/产品名称'}]}}; + const {request}=await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(smart)}})}); + const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default'}); + const [image,text]=result.pack.outputs[0].slots; + assert.deepEqual(image.frame,{x:10,y:20,width:100,height:200}); + assert.equal(image.psLayer.path,'产品/图片'); + assert.equal(text.psLayer.path,'标题/产品名称'); + assert.equal(text.nativeTextBounds,true); +}); + +test('a quota wait resumes the unfinished read without reloading the chosen resource set',async t=>{ + let previews=0; + const {calls,request}=await fixture(t,{call(name){ + if(name==='read_image'&&++previews===1)throw Object.assign(Error('quota'),{status:429,retryAfterSeconds:0.01}); + }}); + const progress=[]; + const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'}, + {onProgress:event=>progress.push(event.phase)}); + assert.ok(result.imagePath&&result.pack); + assert.deepEqual(progress,['waiting','metadata']); + assert.equal(calls.filter(([name])=>name==='get_resource_set').length,1); + assert.equal(calls.filter(([name])=>name==='read_image').length,2); + assert.equal(calls.filter(([name])=>name==='read_text').length,1); +}); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs index 9c82b083..40569d91 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_agent_daemon.rs @@ -119,6 +119,7 @@ impl Daemon { if let Err(error) = self.send(&json!({"type":"run","runId":run,"config":config})) { self.fail(); return Err(error); } Ok(receiver) } + #[cfg(test)] pub(super) fn knowledge(&self, input: Value) -> R { self.knowledge_with_progress(input, |_| {}) } @@ -132,10 +133,15 @@ impl Daemon { } let result = self.send(&json!({"type":"knowledge","id":id,"input":input})).and_then(|_| { progress(json!({"jobId":id,"phase":"metadata"})); - let deadline = Instant::now() + Duration::from_secs(300); + let mut deadline = Instant::now() + Duration::from_secs(300); loop { match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) { - Ok(KnowledgeEvent::Progress(mut value)) => { value["jobId"] = json!(id); progress(value); } + Ok(KnowledgeEvent::Progress(mut value)) => { + let retry = value["retryAfterSeconds"].as_u64().unwrap_or(0).min(86_400); + deadline = Instant::now() + Duration::from_secs(retry + 300); + value["jobId"] = json!(id); + progress(value); + } Ok(KnowledgeEvent::Result(result)) => break result, Err(_) => { let _ = self.cancel_knowledge(&id); break Err("模板读取超时,请重试;已下载内容保留".into()); } } 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 898a5ae0..fc2ca3fc 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -651,7 +651,7 @@ impl Backend { let category = common["categoryId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品类")?.to_owned(); self.validate()?; let pack = canvas_template(previous.as_ref(), &input["template"], &brand, &category, || self.selected_template_pack(&input["template"], &brand, &category))?; - if pack["outputs"].as_array().ok_or("模板输出缺失")?.iter().any(|output| output["width"] != width) { + if pack["enterprise"]["adapterVersion"] != 4 && pack["outputs"].as_array().ok_or("模板输出缺失")?.iter().any(|output| output["width"] != width) { return Err("所选画布宽度与模板原生宽度不一致,请选择对应模板".into()); } let variants = variants(&dir, &common, previous.as_ref())?; @@ -691,6 +691,10 @@ impl Backend { let mut operation_error = None; if method == "slot-skeleton" { let component = input["outputId"].as_str().unwrap_or("detail"); + let component = if input["brief"].is_object() && state["template"]["enterprise"]["adapterVersion"] == 4 { + state["template"]["enterprise"]["component"].as_str().ok_or("固定模板组件缺失")? + } else { component }.to_owned(); + let component = component.as_str(); let variant_id = output_variant(&state, component, input["variantId"].as_str())?.to_owned(); let document = input["documentId"].as_str(); let key = mapping_key(&variant_id, component, document); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs index 065b6cf3..8ae8f403 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_creation.rs @@ -470,22 +470,53 @@ impl Backend { "creation-attachment-import" | "creation-attachment-import-data" => self.composer_import(method, input, doc, &dir), "creation-catalog" => { // The authenticated catalogue GET rechecks the live account and ACL. - let kind = input["kind"].as_str().filter(|s| matches!(*s, "brands" | "categories" | "materials" | "products" | "templates")).ok_or("资料目录类型无效")?; - if matches!(kind,"brands"|"categories") { + let kind = input["kind"].as_str().filter(|s| matches!(*s, "brands" | "categories" | "materials" | "products" | "templates" | "resource-set" | "resource-component")).ok_or("资料目录类型无效")?; + if matches!(kind,"brands"|"categories"|"templates"|"resource-set"|"resource-component") { self.validate()?; let mut request=input.clone(); - request["action"]=json!("choices"); - let result=self.enterprise_template_request(request)?; - return Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"kind":kind,"brandId":input["brandId"],"categoryId":input["categoryId"],"catalog":result["catalog"]})); - } - if kind == "templates" { - self.validate()?; - let brand = input["brandId"].as_str().ok_or("请先选择品牌")?; - let category = input["categoryId"].as_str().ok_or("请先选择品类")?; - let items = self.enterprise_template_catalog(input)?; - return Ok( - json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"kind":kind,"brandId":brand,"categoryId":category,"catalog":{"kind":kind,"items":items}}), - ); + request["action"]=json!(match kind {"brands"|"categories"=>"choices","templates"=>"catalog",other=>other}); + if kind == "resource-set" { + request["resourceSetId"] = input["query"].clone(); + } + if kind == "resource-component" { + let selection: Value = serde_json::from_str(input["query"].as_str().ok_or("请选择模板组件")?) + .map_err(|_| "所选组件无效")?; + for key in ["resourceSetId","componentId","previewId","previewOnly"] { + request[key] = selection[key].clone(); + } + } + let mut result=self.enterprise_template_read(&mut request, |mut value| { + value["readId"]=input["readId"].clone(); + value["doc"]=json!(doc); + value["accountId"]=self.auth["account"]["id"].clone(); + value["origin"]=json!(self.origin); + let _=tx.send(Event::Json("resource-progress".into(), Ok(value))); + ctx.request_repaint(); + })?; + let catalog = if matches!(kind, "brands" | "categories") { result["catalog"].take() } else { + if kind == "resource-component" && let Some(row) = result["items"].get_mut(0) { + if row["pack"].is_object() { + let mut pack=row["pack"].take(); + row["choice"]=self.resource_template_choice(&mut pack,input)?; + } + if let Some(file)=row["imagePath"].take().as_str() { + let file = Path::new(file); + let root=self.dir().join("enterprise-templates").join("resource-previews"); + if file.parent() != Some(root.as_path()) { return Err("模板预览位置无效".into()); } + let mut bytes=Vec::new(); + if fs::File::open(file).and_then(|file| file.take(8*1024*1024+1).read_to_end(&mut bytes)).is_ok() + && bytes.len() <= 8*1024*1024 && let Ok(preview) = reference_thumbnail(&bytes) + { + let pixels: Vec<_> = preview.pixels.iter().flat_map(|color| color.to_array()).collect(); + row["image"]=json!({"size":preview.size,"rgba":STANDARD.encode(pixels)}); + } else { + row["previewError"]=json!("这张预览暂时无法显示,可选择其他预览"); + } + } + } + json!({"kind":kind,"items":result["items"]}) + }; + return Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"kind":kind,"brandId":input["brandId"],"categoryId":input["categoryId"],"catalog":catalog})); } let mut query = url::form_urlencoded::Serializer::new(String::new()); for key in ["query", "page", "identifierType", "identifier"] { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs index 5b9989f1..c28bfef6 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_pi_runtime.rs @@ -116,6 +116,8 @@ fn knowledge_catalog(pack:&Value, creation:&Value) -> R { let brand_key=format!("enterprise:{}",brand.as_str().ok_or("项目品牌缺失")?); let source=if pack["enterprise"]["sourceKind"]=="files" { pack["enterprise"]["fileManifest"]["fileId"].as_str().ok_or("模板文件来源缺失")?.to_owned() + } else if pack["enterprise"]["sourceKind"] == "resource-map" { + pack["enterprise"]["resourceSetId"].as_str().ok_or("模板资源组缺失")?.to_owned() } else { format!("ekb:release/{}",pack["version"].as_str().ok_or("模板版本缺失")?) }; let revision=&pack["contentHash"]; let screens=pack["outputs"].as_array().ok_or("模板页面缺失")?.iter() diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs index 1d5a44be..e687fb25 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_canvas.rs @@ -442,24 +442,39 @@ fn enterprise_source(pack: &Value, source: &Value, outputs: &[&Value], variant: doc.name = pack["name"].as_str().ok_or("模板名称缺失")?.to_owned(); if json!([doc.size.width,doc.size.height]) != source["canvas"] { return Err("原稿尺寸与字段映射不一致".into()); } let mut locations = HashMap::new(); - fn locate(layers: &[Layer], parent: &str, locations: &mut HashMap) -> R<()> { + let mut paths = HashMap::>::new(); + fn locate(layers: &[Layer], parent: &str, locations: &mut HashMap, + paths: &mut HashMap>) -> R<()> { for layer in layers { let path = if parent.is_empty() { layer.name.clone() } else { format!("{parent}/{}", layer.name) }; if let Some(id) = layer.psd_id && locations.insert(id, (layer.id, path.clone())).is_some() { return Err("原稿图层编号重复".into()); } - if let LayerContent::Group(group) = &layer.content { locate(&group.children, &path, locations)?; } + paths.entry(path.clone()).or_default().push(layer.id); + if let LayerContent::Group(group) = &layer.content { locate(&group.children, &path, locations, paths)?; } } Ok(()) } - locate(&doc.layers, "", &mut locations)?; + locate(&doc.layers, "", &mut locations, &mut paths)?; let mut mapped_outputs = Vec::new(); for output in outputs { let mut fields = Vec::new(); for field in output["slots"].as_array().ok_or("模板字段缺失")? { - let psd_id = field["psLayer"]["layer_id"].as_u64().and_then(|id| u32::try_from(id).ok()).ok_or("字段原稿图层编号缺失")?; - let (id, path) = locations.get(&psd_id).ok_or_else(|| format!("字段 {} 的原稿图层不存在", field["fieldId"]))?; - let original_layer = doc.layer(*id).ok_or("原稿图层不存在")?; + let psd_id = field["psLayer"]["layer_id"].as_u64().and_then(|id| u32::try_from(id).ok()); + let expected_path = field["psLayer"]["path"].as_str().ok_or("原稿图层路径缺失")?; + let (id, path) = if let Some(psd_id) = psd_id { + let (id, path) = locations.get(&psd_id).ok_or_else(|| format!("字段 {} 的原稿图层不存在", field["fieldId"]))?; + (*id, path.as_str()) + } else if pack["enterprise"]["adapterVersion"] == 4 { + let ids = paths.get(expected_path).filter(|ids| ids.len() == 1) + .ok_or_else(|| format!("原稿没有唯一图层「{expected_path}」"))?; + (*ids.first().ok_or("原稿图层不存在")?, expected_path) + } else { + return Err("字段原稿图层编号缺失".into()); + }; + let original_layer = doc.layer(id).ok_or("原稿图层不存在")?; + let original_psd_id = original_layer.psd_id; + let original_bounds = (field["nativeTextBounds"] == true).then(|| photocraft_doc::comps::position_bounds(original_layer)); let original_text = if let LayerContent::Text(text) = &original_layer.content { Some(text.text.clone()) } else { None }; - if original_layer.name != field["psLayer"]["name"].as_str().ok_or("原图层名称缺失")? || Some(path.as_str()) != field["psLayer"]["path"].as_str() { + if original_layer.name != field["psLayer"]["name"].as_str().ok_or("原图层名称缺失")? || path != expected_path { return Err(format!("字段 {} 的图层名称或层级与发布映射不一致", field["fieldId"])); } if field["kind"] == "image" { @@ -472,9 +487,9 @@ fn enterprise_source(pack: &Value, source: &Value, outputs: &[&Value], variant: source.layers.push(Layer::new("图片", LayerContent::Raster(surface.translated(-bounds.x0, -bounds.y0, bounds)))); let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).map_err(|error| error.to_string())?; let object = SmartObject::new(SmartSource::Embedded { file_name:source.name, bytes:Arc::new(bytes) }, Affine::translate(bounds.x0 as f64,bounds.y0 as f64), Some(surface.clone())); - doc.layer_mut(*id).ok_or("图片字段不存在")?.content = LayerContent::Smart(object); + doc.layer_mut(id).ok_or("图片字段不存在")?.content = LayerContent::Smart(object); } - let layer = doc.layer_mut(*id).ok_or("图片字段不存在")?; + let layer = doc.layer_mut(id).ok_or("图片字段不存在")?; if !matches!(layer.content, LayerContent::Smart(_)) { return Err("图片字段不是可替换图层".into()); } // Retain the original clipping stack; its frame also guides fitted replacement. if layer.vector_mask.is_none() && layer.mask.is_none() { @@ -487,13 +502,18 @@ fn enterprise_source(pack: &Value, source: &Value, outputs: &[&Value], variant: return Err(format!("文字字段 {} 无法作为原生文字编辑", field["fieldId"])); } let mut mapped = field.clone(); + if let Some(bounds) = original_bounds { + if bounds.is_empty() { return Err(format!("文字字段「{expected_path}」缺少可核对的原稿范围")); } + mapped["nativeFrame"] = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]); + mapped["frame"] = json!({"x":bounds.x0,"y":bounds.y0,"width":bounds.width(),"height":bounds.height()}); + } if let Some(text) = original_text { mapped["originalText"] = json!(text); } mapped["slotId"] = json!(sha(json!([pack["contentHash"],variant,field["fieldId"]]).to_string().as_bytes())); mapped["nativeLayerId"] = json!(id.0); - mapped["psdLayerId"] = json!(psd_id); + mapped["psdLayerId"] = json!(psd_id.or(original_psd_id)); mapped["layerName"] = field["psLayer"]["name"].clone(); mapped["label"] = field["name"].clone(); - mapped["frame"]["y"] = json!(field["frame"]["y"].as_f64().ok_or("字段纵坐标无效")? + output["top"].as_f64().ok_or("页面纵坐标无效")?); + mapped["frame"]["y"] = json!(mapped["frame"]["y"].as_f64().ok_or("字段纵坐标无效")? + output["top"].as_f64().ok_or("页面纵坐标无效")?); fields.push(mapped); } mapped_outputs.push(json!({"documentId":output["id"],"outputId":output["id"],"top":output["top"],"width":output["width"],"height":output["height"],"mapping":{"fields":fields}})); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_cache.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_cache.rs index 88efacf4..081cba16 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_cache.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_cache.rs @@ -149,24 +149,19 @@ fn background_refresh(backend: &Backend, root: PathBuf, owner: Value, brand: Str impl Backend { pub(super) fn enterprise_template_request(&self, mut input: Value) -> R { + self.enterprise_template_read(&mut input, |_| {}) + } + pub(super) fn enterprise_template_read(&self, input: &mut Value, progress: impl FnMut(Value)) -> R { let (node, script) = super::pi_runtime::runtime()?; let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?; let profile = self.root.parent().ok_or("配置位置无效")?; input["root"] = json!(self.dir().join("enterprise-templates")); - super::agent_daemon::service(&node, &script, &binary, profile)?.knowledge(input) + super::agent_daemon::service(&node, &script, &binary, profile)?.knowledge_with_progress(input.clone(), progress) } - pub(super) fn enterprise_template_catalog(&self, input: &Value) -> R { - let mut request = input.clone(); - request["action"] = json!("catalog"); - let response = self.enterprise_template_request(request)?; - let mut items = Vec::new(); - for value in response["packs"].as_array().ok_or("企业模板目录格式无效")? { - let mut pack = value.clone(); - pack["contentHash"] = json!(template_slots::pack_hash(&pack)?); - matching_pack(&pack, input["brandId"].as_str().ok_or("品牌缺失")?, input["categoryId"].as_str().ok_or("品类缺失")?)?; - items.push(json!({"id":pack["id"],"name":pack["name"],"version":pack["version"],"contentHash":pack["contentHash"],"brandId":pack["brandId"],"categoryId":pack["categoryId"],"enterprise":pack["enterprise"]})); - } - Ok(json!(items)) + pub(super) fn resource_template_choice(&self, pack: &mut Value, input: &Value) -> R { + pack["contentHash"] = json!(template_slots::pack_hash(pack)?); + matching_pack(pack, input["brandId"].as_str().ok_or("品牌缺失")?, input["categoryId"].as_str().ok_or("品类缺失")?)?; + Ok(json!({"id":pack["id"],"name":pack["name"],"version":pack["version"],"contentHash":pack["contentHash"],"brandId":pack["brandId"],"categoryId":pack["categoryId"],"enterprise":pack["enterprise"],"width":pack["outputs"][0]["width"]})) } pub(super) fn selected_template_pack(&self, selected: &Value, brand: &str, category: &str) -> R { if !selected["enterprise"].is_object() { return self.template_pack(brand, category, false); } @@ -186,6 +181,7 @@ impl Backend { request["categoryId"] = pack["categoryId"].clone(); request["component"] = json!(component); request["documentId"] = json!(document); + request["pinnedPack"] = pack.clone(); let (node, script) = super::pi_runtime::runtime()?; let binary = std::env::current_exe().map_err(|_| "客户端位置不可用")?; let profile = self.root.parent().ok_or("配置位置无效")?; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs index 45219c6e..04bb8c8b 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_template_slots.rs @@ -28,6 +28,10 @@ pub(super) fn enterprise_version(enterprise: &Value, version: &Value) -> bool { && version.as_str().is_some_and(|s| s.len() == 70 && s.starts_with("files-") && s.bytes().skip(6).all(|b| b.is_ascii_hexdigit())) && enterprise["fileManifest"]["fileId"].as_str().is_some_and(|s| !s.is_empty()) && enterprise["fileManifest"]["revision"].as_str().is_some_and(|s| !s.is_empty()), + Some(4) => enterprise["sourceKind"] == "resource-map" && enterprise["snapshotVersion"] == *version + && version.as_str().is_some_and(|s| s.len() == 68 && s.starts_with("map-") && s.bytes().skip(4).all(|b| b.is_ascii_hexdigit())) + && enterprise["resourceSetId"].as_str().is_some_and(|s| s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit())) + && enterprise["componentId"].as_str().is_some_and(|s| !s.is_empty()), _ => false, } } @@ -60,7 +64,7 @@ pub(super) fn validate_pack(pack: &Value) -> R<()> { if !matches!(output["component"].as_str(), Some("detail" | "main_images" | "sku_images")) { return Err("产出类型无效".into()); } - let width = output["width"].as_u64().filter(|n| matches!(*n, 750 | 1440)).ok_or("模板宽度须为750或1440")?; + let width = output["width"].as_u64().filter(|n| matches!(*n, 750 | 1440) || pack["enterprise"]["adapterVersion"] == 4 && (1..=8192).contains(n)).ok_or("模板画布宽度不受支持")?; let height = output["height"].as_u64().filter(|n| (1..=30_000).contains(n)).ok_or("模板高度无效")?; if width * height > 43_200_000 { return Err("模板画布超出限制".into()); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 57d93a88..ba6c3360 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1594,7 +1594,11 @@ impl Workspace { state["creationView"] = json!({"open":self.creation_open,"step":self.creation_step,"dirty":self.creation_dirty,"progress":self.creation_progress,"pendingCanvas":self.creation_pending.is_some(),"brief":self.creation_brief,"screenCount":self.creation_count,"selected":self.creation_selected}); state["templateProgress"] = self.template_progress.clone(); state["creationView"]["geometry"] = self.creation_view_geometry.clone(); - state["creationView"]["catalogs"] = json!(self.creation_catalog); + let mut catalogs = json!(self.creation_catalog); + if let Some(rows) = catalogs["resource-component"].as_array_mut() { + for row in rows { row["image"].as_object_mut().map(|image| image.remove("rgba")); } + } + state["creationView"]["catalogs"] = catalogs; state["creationView"]["reads"] = self.creation_reads_state(); state["creationView"]["thumbnailReady"] = json!(self.creation_thumbs.keys().collect::>()); state["navigation"] = json!({"view":if self.material {"materials"}else if self.library {"projects"}else{"creation"},"step":self.creation_step,"geometry":self.navigation_geometry}); @@ -2281,6 +2285,7 @@ impl Workspace { if method == "project-operation" { self.project_operation_received(app, result); return; } match method.as_str() { "template-progress" => { self.receive_template_progress(app, result); return; } + "resource-progress" => { self.resource_progress_received(app, result); return; } "knowledge-cancel" => return, "slot-skeleton" => self.template_progress = Value::Null, _ => {} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index b870835c..4ae32509 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -1476,7 +1476,10 @@ impl Workspace { super::stitch_ui::vertical_divider(ui); let outputs = [("detail", "详情"), ("main_images", "主图"), ("sku_images", "SKU")]; let selected = outputs.iter().position(|(id, _)| *id == self.canvas_workspace.output).unwrap_or(0); - let segmented = super::stitch_ui::segmented_control(ui, egui::Id::unique("canvas-output"), &[("详情", true), ("主图", true), ("SKU", true)], selected, self.reduce_motion); + let map_template = self.template_workflow["templateVersion"].as_str().is_some_and(|version| version.starts_with("map-")); + let choices = outputs.map(|(id, label)| (label, !map_template + || self.template_workflow["outputs"].as_array().into_iter().flatten().any(|output| output["outputId"] == id))); + let segmented = super::stitch_ui::segmented_control(ui, egui::Id::unique("canvas-output"), &choices, selected, self.reduce_motion); if let Some(index) = segmented.selected { let id = outputs[index].0; if self.canvas_workspace.output != id || self.canvas_workspace.scope_blocked || !current_color_visible { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs index d1960a95..6edff736 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation.rs @@ -1631,10 +1631,198 @@ impl Workspace { } } + fn resource_template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, selected: &Value, brand: &str, category: &str) { + let bound = |row: &Value| row["brandId"] == brand && row["categoryId"] == category; + if !bound(&self.creation_reads.resource_set) { + self.creation_reads.resource_set = Value::Null; + self.creation_reads.resource_component.clear(); + self.creation_catalog.remove("resource-set"); + self.creation_catalog.remove("resource-component"); + } + let rows = self.creation_catalog.get("templates").into_iter().flatten().filter(|row| bound(row)).cloned().collect::>(); + if !brand.is_empty() && !category.is_empty() + && !self.creation_catalog.contains_key("templates") && !self.creation_catalog_loading("templates") && self.creation_catalog_error("templates").is_none() + { + self.catalog(app, "templates", String::new()); + } + let label = self.creation_reads.resource_set["name"].as_str().or(selected["name"].as_str()).unwrap_or("选择模板").to_owned(); + let mut geometry = Vec::new(); + let response = picker_height(ui, "creation-template", width, PICKER_HEIGHT, + &label, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| { + if brand.is_empty() || category.is_empty() { + ui.weak("先选择品牌与品类"); + return; + } + ui.horizontal(|ui| { + let query = ui.add_sized([(ui.available_width() - 68.0).max(80.0), 28.0], + egui::TextEdit::singleline(&mut self.creation_reads.resource_query).hint_text("模板名称或编号").char_limit(120)); + if stitch_ui::button(ui, "搜索", false).clicked() || query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + self.creation_catalog.remove("templates"); + self.catalog(app, "templates", self.creation_reads.resource_query.clone()); + } + }); + let error = self.creation_catalog_error("templates").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("templates"), error.as_deref(), rows.is_empty(), "当前筛选没有模板") { + self.catalog(app, "templates", self.creation_reads.resource_query.clone()); + } + for row in &rows { + let active = self.creation_reads.resource_set["id"] == row["id"]; + let text = format!("{} · {}", row["name"].as_str().unwrap_or("模板"), row["key"].as_str().unwrap_or("")); + let ready = !self.creation_catalog_loading("templates"); + let item = template_picker_row(ui, active, &text, ready, None); + geometry.push(json!({"id":row["id"],"key":row["key"],"ready":ready,"rect":rect_value(item.rect)})); + if item.clicked() { + self.creation_reads.resource_set = row.clone(); + self.creation_reads.resource_component.clear(); + self.creation_reads.resource_image = None; + self.creation_brief["templateSelection"] = Value::Null; + self.creation_dirty = true; + self.creation_catalog.remove("resource-set"); + self.creation_catalog.remove("resource-component"); + self.catalog(app, "resource-set", row["id"].as_str().unwrap_or("").into()); + ui.close(); + } + } + }).response; + self.picker_geometry(ui, "template", &response, self.creation_catalog_loading("templates"), !rows.is_empty(), geometry); + if let Some(error) = self.creation_catalog_error("templates") { + stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); + } + if let Some(progress) = self.resource_progress() { + let wait = progress["retryAfterSeconds"].as_u64(); + ui.horizontal_wrapped(|ui| { + if let Some(seconds) = wait { ui.label(format!("知识库访问受限,约 {seconds} 秒后继续")); } + let cancel = stitch_ui::button(ui, "取消读取", false); + if cancel.clicked() { + let _ = self.tx.send(Request::Action("knowledge-cancel".into(), json!({"jobId":progress["jobId"]}))); + } + }); + } + let Some(set) = self.creation_reads.resource_set["id"].as_str().map(str::to_owned) else { return; }; + let parts = self.creation_catalog.get("resource-set").cloned().unwrap_or_default(); + let error = self.creation_catalog_error("resource-set").map(str::to_owned); + if picker_notice(ui, self.creation_catalog_loading("resource-set"), error.as_deref(), parts.is_empty(), "该资源组没有可用的模板组件") { + self.catalog(app, "resource-set", set.clone()); + } + for part in &parts { + let Some(id) = part["id"].as_str() else { continue; }; + let name = part["name"].as_str().unwrap_or("模板组件"); + let issues = part["issues"].as_array().cloned().unwrap_or_default(); + let preview = part["previews"].as_array().and_then(|images| images.first()).map(|image| &image["id"]); + let action = stitch_ui::action_button(ui, name, stitch_ui::ButtonRole::Secondary, !self.creation_catalog_loading("resource-component")); + self.control_geometry(&format!("resource-component-{id}"), action.rect); + if action.clicked() { + self.creation_reads.resource_component = id.to_owned(); + self.creation_reads.resource_image = None; + self.creation_catalog.remove("resource-component"); + self.creation_brief["templateSelection"] = Value::Null; + self.creation_dirty = true; + self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":id,"previewId":preview}).to_string()); + } + if self.creation_reads.resource_component != id || self.creation_catalog_loading("resource-component") { + for issue in issues.iter().filter_map(Value::as_str) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); + } + } + } + if self.creation_catalog_loading("resource-component") { ui.weak("正在核对模板资料…"); } + if let Some(error) = self.creation_catalog_error("resource-component") { + stitch_ui::status_label(ui, error, stitch_ui::StatusTone::Error); + } + let result = self.creation_catalog.get_mut("resource-component").and_then(|rows| rows.first_mut()) + .filter(|row| row["id"] == self.creation_reads.resource_component).map(|row| { + let result = row.clone(); + if let Some(image) = row["image"].as_object_mut() { image.remove("rgba"); } + result + }); + if let Some(result) = result { + self.resource_component_result(app, ui, width, &set, &result); + } + self.creation_view_geometry["resourceSet"] = self.creation_reads.resource_set.clone(); + self.creation_view_geometry["templateSelection"] = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + } + + fn resource_component_result(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32, set: &str, result: &Value) { + use base64::Engine as _; + let component = result["id"].as_str().unwrap_or(""); + if let Some(mapping) = result["mapping"].as_str() { + let label = if template_identity(&result["choice"]) { "字段映射已核对" } else { "字段映射" }; + ui.weak(format!("{label} · {mapping}")); + } + for issue in result["issues"].as_array().into_iter().flatten().filter_map(Value::as_str) { + stitch_ui::status_label(ui, issue, stitch_ui::StatusTone::Error); + } + if let Some(error) = result["previewError"].as_str() { ui.weak(error); } + let preview_key = format!("{set}:{component}:{}", result["previewId"]); + if self.creation_reads.resource_image.as_ref().is_none_or(|(key, _)| key != &preview_key) + && let (Some(w), Some(h), Some(rgba)) = (result["image"]["size"][0].as_u64(), result["image"]["size"][1].as_u64(), result["image"]["rgba"].as_str()) + && (1..=320).contains(&w) && (1..=320).contains(&h) + && let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(rgba) + && bytes.len() as u64 == w * h * 4 + { + let image = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &bytes); + self.creation_reads.resource_image = Some((preview_key, ui.ctx().load_texture("resource-template-preview", image, egui::TextureOptions::LINEAR))); + } + if let Some((_, image)) = &self.creation_reads.resource_image { + let size = preview_size(image.size_vec2(), vec2(width.min(320.0), 220.0)); + let preview = ui.image((image.id(), size)).on_hover_text("知识库原稿预览"); + self.control_geometry("resource-preview", preview.rect); + } + if let Some(previews) = result["previews"].as_array().filter(|images| images.len() > 1) { + let label = result["previewName"].as_str().unwrap_or("选择预览"); + picker(ui, "resource-preview-select", width, label, |ui| { + for preview in previews { + let Some(id) = preview["id"].as_str() else { continue; }; + if stitch_ui::select_option(ui, preview["name"].as_str().unwrap_or("预览"), result["previewId"] == id, true).clicked() { + self.creation_reads.resource_image = None; + self.catalog(app, "resource-component", json!({"resourceSetId":set,"componentId":component,"previewId":id}).to_string()); + ui.close(); + } + } + }); + } + if template_identity(&result["choice"]) { + if let Some(width) = result["choice"]["width"].as_u64() { + ui.weak(format!("原稿宽度 {width} px")); + } + let applied = self.creation_brief["templateSelection"]["contentHash"] == result["choice"]["contentHash"]; + let use_template = stitch_ui::action_button(ui, if applied {"已选择此组件"} else {"使用此组件"}, stitch_ui::ButtonRole::Primary, + !applied && !self.creation_catalog_loading("resource-component")); + self.control_geometry("resource-use", use_template.rect); + if use_template.clicked() { + let mut choice = result["choice"].clone(); + if let Some(width) = choice["width"].as_u64().filter(|width| matches!(width, 750 | 1440)) { + self.creation_width = width as u32; + } + choice.as_object_mut().map(|value| value.remove("width")); + self.creation_brief["templateSelection"] = choice; + self.creation_dirty = true; + } + } + } + fn template_select(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) { let brand = self.creation_brief["brandId"].as_str().unwrap_or("").to_owned(); let category = self.creation_brief["categoryId"].as_str().unwrap_or("").to_owned(); let selected = selected_template(&self.creation_brief, &self.template_workflow, &self.creation["brief"]); + if self.template_workflow["canvasFirst"] == true && template_identity(&selected) && selected["enterprise"]["sourceKind"] == "resource-map" { + let name = selected["name"].as_str().unwrap_or("项目模板"); + let view = ui.label(format!("{name} · 已固定")); + self.control_geometry("template", view.rect); + self.creation_view_geometry["templateSelection"] = selected; + return; + } + if brand.starts_with("ekb:brand:") || brand.is_empty() { + if self.template_workflow["canvasFirst"] == true && template_identity(&selected) { + let name = selected["name"].as_str().unwrap_or("项目模板"); + let view = ui.label(format!("{name} · 已固定")); + self.control_geometry("template", view.rect); + self.creation_view_geometry["templateSelection"] = selected; + } else { + self.resource_template_select(app, ui, width, &selected, &brand, &category); + } + return; + } let rows = self .creation_catalog .get("templates") diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs index 7486d57b..39e8ecc5 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/creation_reads.rs @@ -24,7 +24,8 @@ struct Queued { } struct Pending { request: Queued, - started: Instant, + deadline: Instant, + progress: Value, } #[derive(Default)] pub(super) struct UiState { @@ -36,6 +37,10 @@ pub(super) struct UiState { catalog_errors: HashMap, thumbnail_errors: HashMap, cache_order: VecDeque, + pub(super) resource_set: Value, + pub(super) resource_component: String, + pub(super) resource_query: String, + pub(super) resource_image: Option<(String, egui::TextureHandle)>, } fn same(input: &Value, value: &Value) -> bool { @@ -82,6 +87,10 @@ impl Workspace { self.creation_reads.catalog_errors.clear(); self.creation_reads.thumbnail_errors.clear(); self.creation_catalog.clear(); + self.creation_reads.resource_set = Value::Null; + self.creation_reads.resource_component.clear(); + self.creation_reads.resource_query.clear(); + self.creation_reads.resource_image = None; if identity_changed { self.creation_thumbs.clear(); self.creation_reads.cache_order.clear(); @@ -98,7 +107,7 @@ impl Workspace { } pub(super) fn request_creation_catalog(&mut self, app: &PhotocraftApp, kind: &str, query: String, refresh: bool) { self.creation_read_scope(app); - if !["brands", "categories", "materials", "products", "templates"].contains(&kind) || query.chars().count() > 200 { + if !["brands", "categories", "materials", "products", "templates", "resource-set", "resource-component"].contains(&kind) || query.chars().count() > if kind == "resource-component" { 512 } else { 120 } { self.creation_reads.catalog_errors.insert(kind.into(), "目录查询参数无效".into()); return; } @@ -116,7 +125,7 @@ impl Workspace { input[field]=json!(value); } } - if kind == "templates" { + if matches!(kind, "templates" | "resource-set" | "resource-component") { input["refresh"] = json!(refresh); for field in ["brandId", "categoryId", "brandName", "categoryName"] { let Some(value) = self.creation_brief[field].as_str().filter(|value| !value.is_empty() && value.chars().count() <= 150) else { @@ -241,7 +250,7 @@ impl Workspace { request.attempts += 1; let method = request.method; let input = request.input.clone(); - self.creation_reads.pending.insert(serial, Pending { request, started: Instant::now() }); + self.creation_reads.pending.insert(serial, Pending { request, deadline: Instant::now() + READ_WAIT, progress: Value::Null }); if self.tx.send(Request::Action(method.into(), input)).is_err() && let Some(pending) = self.creation_reads.pending.remove(&serial) { @@ -251,7 +260,7 @@ impl Workspace { } pub(super) fn creation_reads_tick(&mut self, app: &PhotocraftApp) { self.creation_read_scope(app); - let expired: Vec = self.creation_reads.pending.iter().filter_map(|(id, p)| (p.started.elapsed() >= READ_WAIT).then_some(*id)).collect(); + let expired: Vec = self.creation_reads.pending.iter().filter_map(|(id, p)| (Instant::now() >= p.deadline).then_some(*id)).collect(); for serial in expired { if let Some(pending) = self.creation_reads.pending.remove(&serial) { self.creation_read_failed(pending.request, "只读加载超时,请重读;未影响模型原请求", false); @@ -260,6 +269,21 @@ impl Workspace { // Continues after closing the popup; no render loop must keep it open. self.pump_creation_reads(); } + pub(super) fn resource_progress_received(&mut self, app: &PhotocraftApp, result: Result) { + self.creation_read_scope(app); + let Ok(value) = result else { return; }; + let Some(read_id) = value["readId"].as_u64() else { return; }; + let Some(pending) = self.creation_reads.pending.get_mut(&read_id) else { return; }; + if ["doc", "accountId", "origin"].iter().any(|key| value[*key] != pending.request.input[*key]) { return; } + let wait = value["retryAfterSeconds"].as_u64().unwrap_or(0).min(86_400); + pending.deadline = Instant::now() + Duration::from_secs(wait) + READ_WAIT; + pending.progress = value; + } + pub(super) fn resource_progress(&self) -> Option { + self.creation_reads.pending.values().find_map(|pending| { + pending.progress["jobId"].as_str().map(|_| pending.progress.clone()) + }) + } pub(super) fn creation_read_received(&mut self, app: &PhotocraftApp, method: &str, value: &Value) -> bool { if !matches!(method, "creation-catalog" | "creation-thumbnail") { return false;