小壹首次开工按专用清单装配组件并复用资产
This commit is contained in:
parent
21da6a28da
commit
03f0ee9ed3
@ -176,6 +176,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
}
|
||||
store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true });
|
||||
store.projectExportRoot = config.projectExportRoot;
|
||||
store.xiaoyiCache = config.xiaoyiCache;
|
||||
signal?.throwIfAborted();
|
||||
broker.bind(bindingConfig);
|
||||
const info = await broker.info(productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
|
||||
|
||||
@ -2,6 +2,8 @@ import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import { EnterpriseKnowledge } from './enterprise-knowledge.mjs';
|
||||
import { openXiaoyiSkills } from './xiaoyi-release.mjs';
|
||||
import { normalizeTemplateMapping } from './template-mapping.mjs';
|
||||
import { digest } from './store.mjs';
|
||||
import { EnterpriseContext } from './enterprise-context.mjs';
|
||||
import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs';
|
||||
@ -332,8 +334,60 @@ export class EnterpriseTemplates {
|
||||
}
|
||||
}
|
||||
|
||||
export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
|
||||
const {templateId,projectDir,cache} = input;
|
||||
const skills = await openXiaoyiSkills({dir:projectDir,xiaoyiCache:cache,xiaoyiProgress:onProgress},templateId,signal,undefined,fetch);
|
||||
const {manifest,root} = skills.snapshot;
|
||||
if (!manifest.bindings || !Object.keys(manifest.bindings).length) throw Error('小壹清单缺少组件绑定');
|
||||
const files = new Map(manifest.files.map(file => [file.path,file]));
|
||||
const assets = new Map(manifest.assets.map(asset => [asset.path,asset]));
|
||||
const itemAt = (index, relative, type) => {
|
||||
const item = index.get(relative);
|
||||
if (item?.type !== type) throw Error('小壹组件绑定缺少' + type + ':' + relative);
|
||||
return item;
|
||||
};
|
||||
const jsonAt = async item => JSON.parse(await fs.readFile(path.join(root,item.path),'utf8'));
|
||||
const packs = {};
|
||||
for (const [component,binding] of Object.entries(manifest.bindings)) {
|
||||
const mappingFile = itemAt(files,binding.mapping,'mapping');
|
||||
const inventoryFile = itemAt(files,binding.inventory,'inventory');
|
||||
const raw = await jsonAt(mappingFile);
|
||||
const inventory = await jsonAt(inventoryFile);
|
||||
if (inventory.template_id !== templateId || (inventory.component ?? 'detail') !== component ||
|
||||
inventory.mapping_version !== raw.mapping_version) throw Error('小壹图层清单与组件映射不一致');
|
||||
const pages = Object.entries(binding.pages ?? {});
|
||||
const references = binding.original ? [{original:binding.original,assetId:raw.source?.assets?.[0]?.asset_id ?? 'original'}]
|
||||
: [...new Map(pages.map(([,page])=>[page.assetId,page])).values()];
|
||||
const originals = references.map(ref => {
|
||||
const file = itemAt(assets,ref.original,'original');
|
||||
if (file.component !== component) throw Error('小壹原稿不属于当前组件');
|
||||
return {id:ref.assetId,file};
|
||||
});
|
||||
const mapping = normalizeTemplateMapping(raw,originals,templateId,component);
|
||||
for (const [page,ref] of pages) {
|
||||
if (!mapping.screens.some(screen=>screen.screen_id===page && screen.asset_id===ref.assetId) ||
|
||||
!inventory.source?.assets?.some(asset=>asset.asset_id===ref.assetId)) throw Error('小壹页面原稿绑定不一致:' + page);
|
||||
}
|
||||
if (!binding.original && pages.length !== mapping.screens.length) throw Error('小壹页面原稿绑定不完整');
|
||||
const descriptor = {component,mappingVersion:mapping.mapping_version,mappingAssetId:binding.mapping,
|
||||
sourceInventoryAssetId:binding.inventory,originalAssetIds:originals.map(({id})=>id)};
|
||||
const pack = componentPack({version:manifest.version,template:{
|
||||
templateId,name:input.name || raw.template_name || templateId,brand:raw.brand,category:raw.category,
|
||||
components:[descriptor],assets:originals.map(({id,file})=>({...file,declaredId:id,assetId:id,revision:manifest.version})),
|
||||
}},manifest.bundle.sha256,{[component]:mapping},input);
|
||||
const original = pack.enterprise.components[component].originals[0];
|
||||
Object.assign(pack.enterprise,{component,sourceKind:'xiaoyi-release',snapshotVersion:manifest.version,
|
||||
originalSha256:original.sha256,canvas:original.canvas,
|
||||
mappingPath:path.join(root,binding.mapping),inventoryPath:path.join(root,binding.inventory)});
|
||||
pack.xiaoyi = skills.productionBinding;
|
||||
packs[component] = pack;
|
||||
}
|
||||
return {packs};
|
||||
}
|
||||
|
||||
const clients = new Map();
|
||||
export async function templateRequest(input,options) {
|
||||
if (input.action === 'xiaoyi-pack') return xiaoyiPacks(input,options);
|
||||
if (typeof input.root !== 'string' || !path.isAbsolute(input.root)) throw Error('模板缓存目录无效');
|
||||
let client=clients.get(input.root);
|
||||
if (!client) {client=new EnterpriseTemplates(input.root);clients.set(input.root,client);}
|
||||
|
||||
@ -2,7 +2,7 @@ import fs from 'node:fs/promises';
|
||||
import { createReadStream, createWriteStream } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Readable, Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { setTimeout as wait } from 'node:timers/promises';
|
||||
import { unzipSync } from 'fflate';
|
||||
@ -23,11 +23,15 @@ function fileAt(root, relative) {
|
||||
return path.join(root, ...relative.split('/'));
|
||||
}
|
||||
|
||||
async function matches(file, item) {
|
||||
async function hasSize(file, item) {
|
||||
const stat = await fs.stat(file).catch(error => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
if (!stat?.isFile() || stat.size !== item.size) return false;
|
||||
return stat?.isFile() && stat.size === item.size;
|
||||
}
|
||||
|
||||
async function matches(file, item) {
|
||||
if (!await hasSize(file, item)) return false;
|
||||
const digest = createHash('sha256');
|
||||
for await (const bytes of createReadStream(file)) digest.update(bytes);
|
||||
return digest.digest('hex') === item.sha256;
|
||||
@ -93,7 +97,7 @@ export async function acquireXiaoyiRelease(options) {
|
||||
}
|
||||
|
||||
async function download(route, file, item) {
|
||||
if (await matches(file, item)) return;
|
||||
if (await hasSize(file, item)) return;
|
||||
await fs.mkdir(path.dirname(file), {recursive:true});
|
||||
const partial = file + '.part';
|
||||
await retry(async () => {
|
||||
@ -118,7 +122,18 @@ export async function acquireXiaoyiRelease(options) {
|
||||
await fs.rm(partial, {force:true});
|
||||
throw Object.assign(Error('小壹知识包续传范围无效'), {retryable:true,retryMs:0});
|
||||
}
|
||||
await pipeline(Readable.fromWeb(response.body), createWriteStream(partial, {flags:append?'a':'w'}), {signal});
|
||||
let received = append ? offset : 0;
|
||||
let reported = performance.now();
|
||||
const progress = new Transform({transform(chunk, _encoding, done) {
|
||||
received += chunk.length;
|
||||
const now = performance.now();
|
||||
if (now - reported >= 2000) {
|
||||
options.onProgress?.({phase:'download',bytes:received,totalBytes:item.size});
|
||||
reported = now;
|
||||
}
|
||||
done(null,chunk);
|
||||
}});
|
||||
await pipeline(Readable.fromWeb(response.body), progress, createWriteStream(partial, {flags:append?'a':'w'}), {signal});
|
||||
if (!await matches(partial, item)) {
|
||||
const length = (await fs.stat(partial)).size;
|
||||
if (length < item.size) throw Object.assign(Error('小壹知识包下载中断'), {network:true});
|
||||
@ -155,7 +170,7 @@ export async function acquireXiaoyiRelease(options) {
|
||||
const release = template + '/releases/' + encodeURIComponent(manifest.version);
|
||||
const missing = [];
|
||||
for (const item of manifest.files) {
|
||||
if (!await matches(fileAt(root, item.path), item)) missing.push(item);
|
||||
if (!await (saved ? hasSize : matches)(fileAt(root, item.path), item)) missing.push(item);
|
||||
}
|
||||
if (missing.length) {
|
||||
if (!/^[a-f0-9]{64}$/.test(manifest.bundle.sha256)) throw Error('小壹知识包摘要无效');
|
||||
@ -175,13 +190,13 @@ export async function acquireXiaoyiRelease(options) {
|
||||
let confirmedAssetRelease = false;
|
||||
for (const item of manifest.assets) {
|
||||
const file = fileAt(root, item.path);
|
||||
if (await matches(file, item)) continue;
|
||||
if (await hasSize(file, item)) continue;
|
||||
if (!/^[a-f0-9]{64}$/.test(item.sha256)) throw Error('小壹资产摘要无效');
|
||||
const cached = path.join(cache, item.sha256);
|
||||
await fs.mkdir(cache, {recursive:true});
|
||||
const unlock = await lockfile.lock(cached, {realpath:false, retries:30});
|
||||
try {
|
||||
if (!await matches(cached, item)) {
|
||||
if (!await hasSize(cached, item)) {
|
||||
if (saved && !confirmedAssetRelease) {
|
||||
// A blob can be referenced by multiple releases. Check the pinned release
|
||||
// before repairing files so a retired release cannot borrow another one's access.
|
||||
@ -192,7 +207,8 @@ export async function acquireXiaoyiRelease(options) {
|
||||
}
|
||||
} finally { await unlock(); }
|
||||
await fs.mkdir(path.dirname(file), {recursive:true});
|
||||
await fs.copyFile(cached, file);
|
||||
await fs.rm(file, {force:true});
|
||||
await fs.link(cached, file);
|
||||
}
|
||||
const packaged = new Set(manifest.files.map(item => item.path));
|
||||
if (![manifest.entrypoint,manifest.supplement,manifest.productionConfig].every(entry => packaged.has(entry))) {
|
||||
@ -234,7 +250,7 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
});
|
||||
}
|
||||
const {manifest, root, productionProfiles} = await acquireXiaoyiRelease({
|
||||
templateId, directory, cache:path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion,
|
||||
templateId, directory, cache:store.xiaoyiCache ?? path.join(path.dirname(store.dir), 'xiaoyi-blobs'), signal, pinnedKnowledgeVersion, onProgress:store.xiaoyiProgress,
|
||||
fetch:(route, init) => fetch(new URL(route, origin), init),
|
||||
});
|
||||
const entry = fileAt(root, manifest.entrypoint);
|
||||
@ -252,7 +268,7 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
|
||||
};
|
||||
const sources = [...documents.values()];
|
||||
return {
|
||||
knowledgeVersion:manifest.knowledgeVersion, execution, productionProfiles,
|
||||
knowledgeVersion:manifest.knowledgeVersion, execution, productionProfiles, snapshot:{manifest,root},
|
||||
productionBinding:{templateId, knowledgeVersion:manifest.knowledgeVersion, productionProfiles,
|
||||
assets:manifest.assets.map(item => ({...item,localPath:fileAt(root,item.path)}))},
|
||||
filesRoot:root, resource, documents, sources,
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import {xiaoyiPacks} from '../src/enterprise-templates.mjs';
|
||||
import {createServer} from 'node:http';
|
||||
import {once} from 'node:events';
|
||||
import {xiaoyiFixture} from './xiaoyi-fixture.mjs';
|
||||
@ -13,20 +14,31 @@ import {acquireXiaoyiRelease,openXiaoyiSkills} from '../src/xiaoyi-release.mjs';
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const describe = bytes => ({size:bytes.length,sha256:sha(bytes)});
|
||||
|
||||
async function fixture(t, {badHash = false,templateId = 'CHAIR'} = {}) {
|
||||
async function fixture(t, {badHash = false,templateId = 'CHAIR',withBindings = false} = {}) {
|
||||
const dir = await fs.mkdtemp(path.join(os.tmpdir(),'xiaoyi-release-'));
|
||||
t.after(() => fs.rm(dir,{recursive:true,force:true}));
|
||||
const config = Buffer.from('{"productionProfiles":{"detail":{"pages":{"D01":{}}}}}');
|
||||
const guide = Buffer.from('guide');
|
||||
const bundle = Buffer.from(zipSync({'规则/SKILL.md':guide,'小壹/production.json':config}));
|
||||
const guide = Buffer.from(withBindings?'---\nname: chair\ndescription: Fixture template.\n---\n指南':'guide');
|
||||
const blob = Buffer.from('original');
|
||||
const mapping = Buffer.from(JSON.stringify({
|
||||
template_id:templateId,component:'detail',mapping_version:'1',
|
||||
canvas:[40,40],source:{sha256:sha(blob)},
|
||||
fields:[{field_id:'D01-I01',type:'图片',name:'商品',screen_id:'D01',
|
||||
ps_location:{path:'商品',name:'商品'},ps_style:{coverage_rect:[0,0,40,40]}}],
|
||||
screens:[{screen_id:'D01',title:'商品页',bounds:[0,0,40,40]}],
|
||||
}));
|
||||
const inventory = Buffer.from(JSON.stringify({template_id:templateId,component:'detail',mapping_version:'1'}));
|
||||
const extra = withBindings ? {'模板/mapping.json':mapping,'模板/inventory.json':inventory} : {};
|
||||
const bundle = Buffer.from(zipSync({'规则/SKILL.md':guide,'小壹/production.json':config,...extra}));
|
||||
const manifest = {
|
||||
schemaVersion:1,templateId,version:'v1',knowledgeVersion:templateId+'@v1',
|
||||
entrypoint:'规则/SKILL.md',supplement:'规则/SKILL.md',
|
||||
productionConfig:'小壹/production.json',
|
||||
bundle:describe(bundle),assets:[{path:'模板/original.psd',...describe(blob)}],
|
||||
...(withBindings?{bindings:{detail:{mapping:'模板/mapping.json',inventory:'模板/inventory.json',original:'模板/original.psd'}}}:null),
|
||||
bundle:describe(bundle),assets:[{path:'模板/original.psd',type:'original',component:'detail',...describe(blob)}],
|
||||
files:[{path:'规则/SKILL.md',...describe(guide),...(badHash?{sha256:sha('wrong')}:null)},
|
||||
{path:'小壹/production.json',...describe(config)}],
|
||||
{path:'小壹/production.json',...describe(config)},
|
||||
...Object.entries(extra).map(([path,bytes])=>({path,type:path.endsWith('mapping.json')?'mapping':'inventory',...describe(bytes)}))],
|
||||
};
|
||||
const raw = Buffer.from(JSON.stringify(manifest));
|
||||
const requests = [];
|
||||
@ -179,6 +191,10 @@ test('a second template reuses an already verified blob by digest', async t => {
|
||||
const second = await acquireXiaoyiRelease({...next.options,cache:first.options.cache});
|
||||
assert.equal(second.manifest.templateId,'TABLE');
|
||||
assert.equal(next.requests.some(([route])=>route.includes('/blobs/')),false);
|
||||
const asset = await fs.stat(path.join(second.root,'模板','original.psd'),{bigint:true});
|
||||
const cached = await fs.stat(path.join(first.options.cache,sha(next.blob)),{bigint:true});
|
||||
assert.equal(asset.ino,cached.ino);
|
||||
assert.equal(cached.nlink,3n);
|
||||
});
|
||||
|
||||
test('a resumed project with a missing manifest uses its recorded version', async t => {
|
||||
@ -190,3 +206,17 @@ test('a resumed project with a missing manifest uses its recorded version', asyn
|
||||
assert.equal(recovered.manifest.version,'v1');
|
||||
assert.deepEqual(requests.map(([route])=>route),['/api/xiaoyi/v1/templates/CHAIR/releases/v1/manifest']);
|
||||
});
|
||||
|
||||
test('first production prepares the component from only manifest bindings and release files', async t => {
|
||||
const {options,requests} = await fixture(t,{withBindings:true});
|
||||
const result = await xiaoyiPacks({
|
||||
templateId:options.templateId,projectDir:options.directory,cache:options.cache,
|
||||
brandId:'fixture-brand',categoryId:'fixture-category',name:'Fixture chair',
|
||||
},{fetch:(url,init)=>options.fetch(url.pathname,init)});
|
||||
const pack = result.packs.detail;
|
||||
assert.equal(pack.enterprise.sourceKind,'xiaoyi-release');
|
||||
assert.equal(pack.outputs[0].originalAssetId,'original');
|
||||
assert.equal(pack.outputs[0].slots[0].fieldId,'D01-I01');
|
||||
assert.deepEqual(pack.xiaoyi.productionProfiles.detail.pages,{D01:{}});
|
||||
assert.ok(requests.every(([route])=>route.startsWith('/api/xiaoyi/v1/')));
|
||||
});
|
||||
|
||||
@ -256,7 +256,7 @@ pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path)
|
||||
command.env_remove("EKB_XIAOYI_READ_KEY");
|
||||
command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH");
|
||||
command.env("PHOTOCRAFT_KNOWLEDGE_HOST", binary);
|
||||
if let Some(path) = super::knowledge_http::config_path() {
|
||||
if let Some(path) = super::knowledge_http::config_path().filter(|_| std::env::var_os("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE").is_none()) {
|
||||
command.env("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE", path);
|
||||
}
|
||||
for (name, _) in std::env::vars_os() {
|
||||
|
||||
@ -3661,6 +3661,9 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
// Older projects stored the mapping's combined requirements. Use the original
|
||||
// typed fields from the cached mapping for that same fixed template version.
|
||||
fn cached_prompt_mapping(dir: &Path, pack: &Value) -> Option<Value> {
|
||||
if let Some(file) = pack["enterprise"]["mappingPath"].as_str() {
|
||||
return read_json(Path::new(file)).ok();
|
||||
}
|
||||
let component = pack["enterprise"]["component"].as_str()?;
|
||||
let mapping_id = pack["enterprise"]["components"][component]["mappingAssetId"].as_str()?;
|
||||
let mapping = pack["resourceFiles"].as_array()?.iter()
|
||||
@ -3853,58 +3856,6 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
fn product_templates(&self, brief: &Value, selected_pack: &Value) -> R<(Value, Value)> {
|
||||
let selected_set = &selected_pack["enterprise"]["resourceSetId"];
|
||||
let resource_input = json!({"resourceSetId":selected_set,
|
||||
"brandId":brief["brandId"],"categoryId":brief["categoryId"],
|
||||
"brandName":brief["brandName"],"categoryName":brief["categoryName"]});
|
||||
let catalog = if selected_set.is_string() {
|
||||
let mut request = resource_input.clone();
|
||||
request["action"] = json!("resource-set");
|
||||
self.enterprise_template_request(request).map(|response| response["items"].clone())
|
||||
} else { Ok(Value::Null) };
|
||||
let mut packs = serde_json::Map::new();
|
||||
let mut blocked = serde_json::Map::new();
|
||||
for component in SUPPORTED_PRODUCTION_OUTPUTS {
|
||||
let pack = (|| -> R<Value> {
|
||||
let mut pack = if selected_pack["outputs"].as_array().is_some_and(|outputs|
|
||||
outputs.iter().any(|output| output["component"] == component))
|
||||
{
|
||||
selected_pack.clone()
|
||||
} else if selected_set.is_string() {
|
||||
let parts = catalog.as_ref().map_err(Clone::clone)?;
|
||||
let matching: Vec<_> = parts.as_array().into_iter().flatten()
|
||||
.filter(|part| part["kind"] == component).collect();
|
||||
let [part] = matching.as_slice() else {
|
||||
return Err(if matching.is_empty() { "所选企业模板未发布该组件" }
|
||||
else { "模板有多份组件,请明确要使用的原稿" }.into());
|
||||
};
|
||||
let mut request = resource_input.clone();
|
||||
request["action"] = json!("resource-component");
|
||||
request["componentId"] = part["id"].clone();
|
||||
let response = self.enterprise_template_request(request)?;
|
||||
let item = &response["items"][0];
|
||||
let mut pack = item["pack"].as_object().ok_or_else(|| {
|
||||
let issues = item["issues"].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).collect::<Vec<_>>().join("。");
|
||||
if issues.is_empty() { "未取得组件的原稿和字段映射".into() } else { issues }
|
||||
}).map(|pack| Value::Object(pack.clone()))?;
|
||||
pack["contentHash"] = json!(template_slots::pack_hash(&pack)?);
|
||||
template_slots::validate_pack(&pack)?;
|
||||
if pack["enterprise"]["component"] != component { return Err("模板组件与输出类型不符".into()); }
|
||||
pack
|
||||
} else { return Err("所选模板未包含该组件".into()); };
|
||||
production_profile::add_image_fields(&mut pack, component)?;
|
||||
Ok(pack)
|
||||
})();
|
||||
match pack {
|
||||
Ok(pack) => { packs.insert(component.into(), pack); }
|
||||
Err(reason) => { blocked.insert(component.into(), json!(reason)); }
|
||||
}
|
||||
}
|
||||
Ok((Value::Object(packs), Value::Object(blocked)))
|
||||
}
|
||||
|
||||
pub(super) fn canvas_workspace_result(&self, doc: u64, dir: &Path) -> R<Value> {
|
||||
let workflow = snapshot(dir)?;
|
||||
Ok(
|
||||
@ -4286,8 +4237,29 @@ impl Backend {
|
||||
let production = input["generateProduct"] == true;
|
||||
let brand = common["brandId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品牌")?;
|
||||
let category = common["categoryId"].as_str().filter(|value| !value.is_empty()).ok_or("请先选择品类")?;
|
||||
let pack = canvas_template(previous.as_ref(), &input["template"], brand, category,
|
||||
|| self.selected_template_pack(&input["template"], brand, category))?;
|
||||
let new_release = production && previous.is_none() && input["template"]["enterprise"].is_object();
|
||||
let release_packs = if new_release {
|
||||
let project = self.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
let session = dir.join("agent").join(self.scope()).join(project).join("conversation-v1");
|
||||
let template_id = input["template"]["id"].as_str().ok_or("企业模板编号缺失")?;
|
||||
let result = self.enterprise_template_request(json!({"action":"xiaoyi-pack","templateId":template_id,
|
||||
"name":input["template"]["name"],"brandId":brand,"categoryId":category,
|
||||
"projectDir":session,"cache":self.dir().join("xiaoyi-blobs")}))?;
|
||||
let mut packs = result["packs"].as_object().cloned().ok_or("小壹清单没有可用组件")?;
|
||||
for (component, pack) in &mut packs {
|
||||
production_profile::add_image_fields(pack, component)?;
|
||||
pack["contentHash"] = json!(template_slots::pack_hash(pack)?);
|
||||
template_slots::validate_pack(pack)?;
|
||||
}
|
||||
Some(packs)
|
||||
} else { None };
|
||||
let pack = if let Some(packs) = &release_packs {
|
||||
let component = input["template"]["enterprise"]["component"].as_str().unwrap_or("detail");
|
||||
packs.get(component).cloned().ok_or("所选组件未在小壹知识包发布")?
|
||||
} else {
|
||||
canvas_template(previous.as_ref(), &input["template"], brand, category,
|
||||
|| self.selected_template_pack(&input["template"], brand, category))?
|
||||
};
|
||||
let width = pack["enterprise"]["canvas"][0].as_u64().or_else(|| {
|
||||
let outputs = pack["outputs"].as_array()?;
|
||||
outputs.iter().find(|output| output["component"] == input["outputId"])
|
||||
@ -4310,7 +4282,8 @@ impl Backend {
|
||||
if let Some(path) = input.get("deliveryDir") {
|
||||
changes["deliveryDir"] = path.clone();
|
||||
}
|
||||
self.creation_action("creation-save", &changes, None, events, ctx)?;
|
||||
let release_pack = pack.get("xiaoyi").map(|_| &pack);
|
||||
self.save_creation_brief(doc, &dir, &changes, release_pack)?;
|
||||
let c = creation::load(&dir)?;
|
||||
let mut next = previous.unwrap_or_else(
|
||||
|| json!({"version":1,"canvasFirst":true,"id":Uuid::new_v4().to_string(),"revision":0,
|
||||
@ -4321,9 +4294,21 @@ impl Backend {
|
||||
next["variants"] = json!(variants);
|
||||
next["activeVariantId"] = json!(active);
|
||||
if production {
|
||||
let (packs, blocked) = self.product_templates(&common, &pack)?;
|
||||
next["productTemplates"] = packs;
|
||||
next["productTemplateIssues"] = blocked;
|
||||
if let Some(packs) = release_packs {
|
||||
next["productTemplates"] = Value::Object(packs);
|
||||
next["productTemplateIssues"] = json!({});
|
||||
} else if !next["productTemplates"].is_object() {
|
||||
let mut packs = serde_json::Map::new();
|
||||
for component in SUPPORTED_PRODUCTION_OUTPUTS {
|
||||
if pack["outputs"].as_array().into_iter().flatten().any(|output| output["component"] == component) {
|
||||
let mut component_pack = pack.clone();
|
||||
production_profile::add_image_fields(&mut component_pack, component)?;
|
||||
packs.insert(component.into(), component_pack);
|
||||
}
|
||||
}
|
||||
next["productTemplates"] = Value::Object(packs);
|
||||
next["productTemplateIssues"] = json!({});
|
||||
}
|
||||
for stage in runnable_stages(&next, production_stages(&next)) {
|
||||
generation_references(&dir, &next, stage["variantId"].as_str().ok_or("制作款式缺失")?)?;
|
||||
}
|
||||
|
||||
@ -475,6 +475,60 @@ impl Backend {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn save_creation_brief(&mut self, doc: u64, dir: &Path, input: &Value, release_pack: Option<&Value>) -> R<Value> {
|
||||
let mut c = load(dir)?;
|
||||
revision(&c, input)?;
|
||||
let delivery_dir = input.get("deliveryDir")
|
||||
.map(|value| super::project_file::delivery_directory(dir, value)).transpose()?;
|
||||
let before = c.clone();
|
||||
c["brief"] = model::brief(&input["brief"])?;
|
||||
if let Some(width) = input["width"].as_u64().filter(|&width| width > 0) {
|
||||
c["width"] = json!(width);
|
||||
}
|
||||
for image in c["brief"]["images"]
|
||||
.as_array()
|
||||
.ok_or("产品图格式无效")?
|
||||
.iter()
|
||||
.chain(c["brief"]["variants"].as_array().into_iter().flatten().flat_map(|variant| variant["images"].as_array().into_iter().flatten()))
|
||||
{
|
||||
if !assets_file(dir, image["source"].as_str().ok_or("图片来源无效")?)?.is_file() {
|
||||
return Err("产品原图尚未保存,本次未修改资料".into());
|
||||
}
|
||||
}
|
||||
if c["brief"]["brandId"].as_str() == Some("") {
|
||||
c["designSnapshot"] = Value::Null;
|
||||
} else if c["brief"]["brandId"] != before["brief"]["brandId"] || c["designSnapshot"].is_null() {
|
||||
let selected=c["brief"]["brandId"].as_str().ok_or("品牌编号无效")?;
|
||||
let brand = if let Some(pack) = release_pack {
|
||||
json!({"id":selected,"name":pack["brandName"],"profile":{"name":pack["brandName"],
|
||||
"tone":"","visualRules":{}}})
|
||||
} else {
|
||||
self.validate()?;
|
||||
if selected.starts_with("ekb:brand:") {
|
||||
self.enterprise_template_request(json!({"action":"brand","brandId":selected}))?["brand"].clone()
|
||||
} else {
|
||||
let id=identifier(selected)?;
|
||||
self.json(&format!("catalog/brands/{id}"))?
|
||||
}
|
||||
};
|
||||
if brand.to_string().len() > 256_000 {
|
||||
return Err("品牌快照超出限制".into());
|
||||
}
|
||||
c["brief"]["brandName"] = brand["name"].clone();
|
||||
c["designSnapshot"] = json!({"brand":brand,"models":current_models(self)});
|
||||
}
|
||||
model::invalidate(&mut c, &before);
|
||||
let preferences_only = c == before && delivery_dir.is_some();
|
||||
if let Some(path) = delivery_dir {
|
||||
c["deliveryDir"] = json!(path);
|
||||
}
|
||||
save_with_revision(dir, &mut c, !preferences_only)?;
|
||||
if !preferences_only {
|
||||
super::canvas_workspace::apply_saved_variant_edits(dir)?;
|
||||
}
|
||||
self.creation_result(doc, &dir)
|
||||
}
|
||||
|
||||
pub(super) fn creation_action(
|
||||
&mut self,
|
||||
method: &str,
|
||||
@ -630,54 +684,7 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
"creation-product" => self.creation_product(input, tx, ctx),
|
||||
"creation-save" => {
|
||||
let mut c = load(&dir)?;
|
||||
revision(&c, input)?;
|
||||
let delivery_dir = input.get("deliveryDir")
|
||||
.map(|value| super::project_file::delivery_directory(&dir, value)).transpose()?;
|
||||
let before = c.clone();
|
||||
c["brief"] = model::brief(&input["brief"])?;
|
||||
if let Some(width) = input["width"].as_u64().filter(|&width| width > 0) {
|
||||
c["width"] = json!(width);
|
||||
}
|
||||
for image in c["brief"]["images"]
|
||||
.as_array()
|
||||
.ok_or("产品图格式无效")?
|
||||
.iter()
|
||||
.chain(c["brief"]["variants"].as_array().into_iter().flatten().flat_map(|variant| variant["images"].as_array().into_iter().flatten()))
|
||||
{
|
||||
if !assets_file(&dir, image["source"].as_str().ok_or("图片来源无效")?)?.is_file() {
|
||||
return Err("产品原图尚未保存,本次未修改资料".into());
|
||||
}
|
||||
}
|
||||
if c["brief"]["brandId"].as_str() == Some("") {
|
||||
c["designSnapshot"] = Value::Null;
|
||||
} else if c["brief"]["brandId"] != before["brief"]["brandId"] || c["designSnapshot"].is_null() {
|
||||
self.validate()?;
|
||||
let selected=c["brief"]["brandId"].as_str().ok_or("品牌编号无效")?;
|
||||
let brand = if selected.starts_with("ekb:brand:") {
|
||||
self.enterprise_template_request(json!({"action":"brand","brandId":selected}))?["brand"].clone()
|
||||
} else {
|
||||
let id=identifier(selected)?;
|
||||
self.json(&format!("catalog/brands/{id}"))?
|
||||
};
|
||||
if brand.to_string().len() > 256_000 {
|
||||
return Err("品牌快照超出限制".into());
|
||||
}
|
||||
c["brief"]["brandName"] = brand["name"].clone();
|
||||
c["designSnapshot"] = json!({"brand":brand,"models":current_models(self)});
|
||||
}
|
||||
model::invalidate(&mut c, &before);
|
||||
let preferences_only = c == before && delivery_dir.is_some();
|
||||
if let Some(path) = delivery_dir {
|
||||
c["deliveryDir"] = json!(path);
|
||||
}
|
||||
save_with_revision(&dir, &mut c, !preferences_only)?;
|
||||
if !preferences_only {
|
||||
super::canvas_workspace::apply_saved_variant_edits(&dir)?;
|
||||
}
|
||||
self.creation_result(doc, &dir)
|
||||
}
|
||||
"creation-save" => self.save_creation_brief(doc, &dir, input, None),
|
||||
"creation-select" => {
|
||||
self.creation_guard(doc, &dir)?;
|
||||
let mut c = load(&dir)?;
|
||||
|
||||
@ -604,10 +604,25 @@ mod tests {
|
||||
assert!(creation::load(&project).unwrap()["deliveryDir"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the verified local Xiaoyi pilot pack fixture"]
|
||||
fn jiansun_xiaoyi_loopback_delivery_records_the_locked_version() {
|
||||
let packs = std::env::var_os("Z31_PILOT_PACKS").expect("pilot pack fixture");
|
||||
let packs = read_json(&PathBuf::from(packs)).unwrap();
|
||||
let version = packs["detail"]["xiaoyi"]["knowledgeVersion"].as_str().unwrap();
|
||||
let (_root, project, local, mut input) = fixture();
|
||||
input["knowledgeVersion"] = json!(version);
|
||||
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
|
||||
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
|
||||
let manifest = PathBuf::from(delivered["path"].as_str().unwrap()).join("交付清单.json");
|
||||
assert_eq!(read_json(&manifest).unwrap()["knowledgeVersion"], version);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locally_published_outputs_form_a_reopenable_verified_bundle_and_keep_older_deliveries() {
|
||||
let (root, project, local, mut input) = fixture();
|
||||
input["knownIssues"] = json!([{"outputId":"detail","page":2,"status":"已知问题","reason":"尺寸线待校准"}]);
|
||||
input["knowledgeVersion"] = json!("SFY-CHAIR-001@2026-11-29.2");
|
||||
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
|
||||
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
|
||||
assert_eq!(delivered["allOutputsCompleted"], true);
|
||||
@ -619,6 +634,7 @@ mod tests {
|
||||
let manifest_path = final_dir.join("交付清单.json");
|
||||
let manifest = read_json(&manifest_path).unwrap();
|
||||
assert_eq!(manifest["knownIssues"], input["knownIssues"]);
|
||||
assert_eq!(manifest["knowledgeVersion"], input["knowledgeVersion"]);
|
||||
assert_eq!(manifest["outputEvidence"][0]["unverifiedFacts"], json!([{
|
||||
"fieldId":"S01-T01","pageId":"S01","label":"材质","productValues":[],"basis":"资料未注明"
|
||||
}]));
|
||||
|
||||
@ -23,7 +23,9 @@ fn default_origins() -> R<[String; 2]> {
|
||||
|
||||
pub(super) fn origins() -> R<[String; 2]> {
|
||||
let mut origins = default_origins()?;
|
||||
if let Some(path) = config_path().filter(|path| path.exists()) {
|
||||
let configured = std::env::var_os("PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE")
|
||||
.map(std::path::PathBuf::from).or_else(config_path);
|
||||
if let Some(path) = configured.filter(|path| path.exists()) {
|
||||
origins[0] = super::read_json(&path)?.as_str().ok_or(INVALID)?.to_owned();
|
||||
}
|
||||
Ok(origins)
|
||||
|
||||
@ -127,13 +127,14 @@ fn knowledge_catalog(pack:&Value, creation:&Value) -> R<Value> {
|
||||
"template":{"id":pack["id"],"sourceVersion":pack["version"],"sourceCanvas":pack["enterprise"]["canvas"],"screens":screens}}]}))
|
||||
}
|
||||
|
||||
fn knowledge_rule(b:&Backend,doc:u64) -> R<Option<(Option<Value>,Value)>> {
|
||||
fn knowledge_rule(b:&Backend,doc:u64,production:bool) -> R<Option<(Option<Value>,Value)>> {
|
||||
let dir=b.project_dir(doc)?;
|
||||
let creation=super::creation::load(&dir)?;
|
||||
let brand=creation["brief"]["brandId"].as_str().unwrap_or("");
|
||||
if !brand.starts_with("ekb:brand:") {return Ok(None);}
|
||||
let category=creation["brief"]["categoryId"].as_str().unwrap_or("");
|
||||
let selected=&creation["brief"]["templateSelection"];
|
||||
let workspace = production.then(|| super::canvas_workspace::load(&dir)).transpose()?;
|
||||
let selected = workspace.as_ref().map_or(&creation["brief"]["templateSelection"], |state| &state["template"]);
|
||||
if category.is_empty() || !selected["enterprise"].is_object() {
|
||||
return Ok(Some((None,json!({"state":"needs-template","reason":"请先选择知识库品类与模板"}))));
|
||||
}
|
||||
@ -147,7 +148,7 @@ fn knowledge_rule(b:&Backend,doc:u64) -> R<Option<(Option<Value>,Value)>> {
|
||||
return Ok(Some((Some(saved.clone()),json!({"state":"ready","updateAvailable":false,"templateId":selected["id"],"contentHash":saved["contentHash"]}))));
|
||||
}
|
||||
can_change_rule(&dir)?;
|
||||
let pack=b.selected_template_pack(selected,brand,category)?;
|
||||
let pack = if production { selected.clone() } else { b.selected_template_pack(selected,brand,category)? };
|
||||
let catalog=knowledge_catalog(&pack,&creation)?;
|
||||
let saved=rule_cache::package(pack["id"].as_str().ok_or("模板编号缺失")?,&json!({"catalog":catalog,"revision":pack["contentHash"]}),None)?;
|
||||
can_change_rule(&dir)?;
|
||||
@ -231,7 +232,7 @@ pub(super) fn rules(b: &mut Backend, input: &Value) -> R<Value> {
|
||||
b.ensure_owner(doc)?;
|
||||
b.validate()?;
|
||||
let dir = b.project_dir(doc)?;
|
||||
if let Some((rule,state))=knowledge_rule(b,doc)? {
|
||||
if let Some((rule,state))=knowledge_rule(b,doc,false)? {
|
||||
return Ok(json!({"items":[],"categories":[],"rule":rule,"ruleState":state,"creation":super::creation::load(&dir)?,"doc":doc,"accountId":b.auth["account"]["id"],"origin":b.origin}));
|
||||
}
|
||||
let wanted = original_rule(&dir)?.and_then(|s| s["id"].as_str().map(str::to_owned));
|
||||
@ -615,7 +616,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
let begin = std::time::Instant::now();
|
||||
// Pi RPC validates the same account alongside model authorization before production starts.
|
||||
if !product_prompt { b.validate()?; }
|
||||
let saved = if let Some((saved,_))=knowledge_rule(b,doc)? {
|
||||
let saved = if let Some((saved,_))=knowledge_rule(b,doc,product_prompt)? {
|
||||
saved
|
||||
} else {
|
||||
let wanted = original_rule(&dir)?.and_then(|s| s["id"].as_str().map(str::to_owned));
|
||||
@ -629,7 +630,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
let profile = b.root.parent().ok_or("配置位置无效")?;
|
||||
let scope = &input["context"]["requestScope"];
|
||||
let config = json!({"binary":binary,"profile":profile,"root":dir.join("agent"),"projectExportRoot":dir.join("product-exports"),
|
||||
"project":project,"scope":b.scope(),"documentId":doc,
|
||||
"project":project,"scope":b.scope(),"documentId":doc,"xiaoyiCache":b.dir().join("xiaoyi-blobs"),
|
||||
"dispatchLease":b.access.dispatch_path(),
|
||||
"ruleCatalog":saved.as_ref().map(|rule|rule["catalog"].clone()),"ruleId":saved.as_ref().map(|rule|rule["id"].clone()),
|
||||
"projectEvidence":project_evidence(&super::creation::load(&dir)?,&b.scope(),&project,doc,&input["context"]["requestScope"]["variantId"]),
|
||||
@ -1168,6 +1169,46 @@ mod tests {
|
||||
backend.locations.insert(doc, local.clone());
|
||||
(backend, doc, local)
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires the local Xiaoyi pilot release and temporary pack fixture"]
|
||||
fn jiansun_xiaoyi_loopback_release_imports_a_bound_original() {
|
||||
let path = std::env::var_os("Z31_PILOT_PACKS").expect("pilot pack fixture");
|
||||
let mut packs = read_json(Path::new(&path)).unwrap();
|
||||
let expected = packs["detail"]["xiaoyi"]["knowledgeVersion"].as_str().unwrap();
|
||||
let mut frames = Vec::new();
|
||||
super::super::knowledge_http::exchange(&json!({
|
||||
"origin":"http://127.0.0.1:18980","path":"/api/xiaoyi/v1/templates/SFY-CHAIR-001/current",
|
||||
"httpMethod":"GET","headers":{}
|
||||
}), |frame| { frames.push(frame); Ok(()) }).unwrap();
|
||||
assert_eq!(frames[0]["status"], 200);
|
||||
let raw: Vec<u8> = frames.iter().filter_map(|frame| frame["data"].as_str())
|
||||
.flat_map(|chunk| base64::Engine::decode(&base64::engine::general_purpose::STANDARD, chunk).unwrap()).collect();
|
||||
let current: Value = serde_json::from_slice(&raw).unwrap();
|
||||
assert_eq!(expected, format!("SFY-CHAIR-001@{}", current["version"].as_str().unwrap()));
|
||||
let detail = super::super::production_profile::select(&packs["detail"], "detail").unwrap().unwrap();
|
||||
assert_eq!(super::super::production_profile::agent_rules(detail)["referenceMode"], "template-base");
|
||||
for pack in packs.as_object_mut().unwrap().values_mut() {
|
||||
pack["contentHash"] = json!(super::super::template_slots::pack_hash(pack).unwrap());
|
||||
super::super::template_slots::validate_pack(pack).unwrap();
|
||||
}
|
||||
let component = "sku_images";
|
||||
let pack = &mut packs[component];
|
||||
assert!(pack["xiaoyi"]["productionProfiles"][component]["pages"].is_object());
|
||||
let (backend, _, _) = local_backend();
|
||||
let mut original = backend.enterprise_template_canvas(pack, component, Some("K01"),
|
||||
&Uuid::new_v4().to_string(), |_| {}).unwrap();
|
||||
assert_eq!(original.size.width, 1440);
|
||||
assert_eq!(original.size.height, 1440);
|
||||
assert!(!original.layers.is_empty());
|
||||
let mut mapping: Value = serde_json::from_str(&original.metadata.text.iter()
|
||||
.find(|(key, _)| key == "jiansun.slot-mapping.v1").unwrap().1).unwrap();
|
||||
let profile = super::super::production_profile::select(pack, component).unwrap().unwrap();
|
||||
super::super::production_profile::apply(&mut original, &mut mapping, profile).unwrap();
|
||||
let (_, _, layer) = original.walk().into_iter().find(|(_, _, layer)| layer.psd_id == Some(33)).unwrap();
|
||||
assert!(!layer.visible, "K01 profile hides its scoped original layer");
|
||||
println!("{} K01 原稿与按页配置通过", packs["sku_images"]["xiaoyi"]["knowledgeVersion"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_export_observations_extend_the_same_agent_event_stream() {
|
||||
let (mut backend, doc, project) = local_backend();
|
||||
|
||||
@ -25,6 +25,9 @@ fn hex(value: &Value) -> bool {
|
||||
}
|
||||
|
||||
pub(super) fn enterprise_version(enterprise: &Value, version: &Value) -> bool {
|
||||
if enterprise["sourceKind"] == "xiaoyi-release" {
|
||||
return enterprise["snapshotVersion"] == *version;
|
||||
}
|
||||
enterprise["adapterVersion"] == 4
|
||||
&& enterprise["sourceKind"] == "resource-map"
|
||||
&& enterprise["snapshotVersion"] == *version
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user