合入报错回执补改正信息、交付清单补页号(R5-Z52)

This commit is contained in:
WuYongJie 2026-11-30 05:34:25 +08:00
commit bfcb7656d9
9 changed files with 167 additions and 28 deletions

View File

@ -100,7 +100,7 @@ export function nativeTools(host, make) {
return [
{...make('native_catalog', '查询画布命令和工作台界面能力。filter支持空格分隔的并列关键词,按相关度返回紧凑摘要(默认10项);id精确取某个命令完整parameterDocs,ids可在一次调用中批量精确查询多个命令的完整parameterDocs。批量精确查询合并 id 和 ids,未找到的命令见 missingIds。parameterDocs是原生说明而非完整JSON Schema。原生说明中的 document:index 指目录回执的 documentIndex,省略时使用当前文档。复用会话内已取得的说明,避免重复单查或反复打印未筛选整页。实时enabled/reason保留,不需要逐业务工具迁移。', nativeCatalogParameters,
catalog), ...nativeToolMetadata('native_catalog')},
{...make('native_call', '执行原生命令或界面操作。engine.execute 的 params 为 {command,params},其余方法沿用目录契约。参数要求 document:index 时用目录的 documentIndex,当前文档可省略。revision 来自实时读取。制作期间,明确指定 layer 的文字修改、文字样式、图层显示属性和像素变换可由宿主核对关联图层后使用当前修订。发生冲突时查看 currentRevision 和 changedLayers。返回真实原生结果,后台任务等待原 job 终态。resultRef 用 result.read {resultId,pointer?,offset?} 读取,pointer 采用 JSON Pointer(如 /layers),按 nextOffset 翻页。依次 await 各步真实回执。其余命令与完整参数见 native_catalog。\n'+NATIVE_CANVAS_QUICK_REFERENCE, nativeCallParameters,
{...make('native_call', '执行原生命令或界面操作。engine.execute 的 params 为 {command,params},其余方法沿用目录契约。参数要求 document:index 时用目录的 documentIndex,当前文档可省略。revision 来自实时读取。制作期间,明确指定 layer 的文字修改、文字样式、图层显示属性和像素变换可由宿主核对关联图层后使用当前修订。发生冲突时查看 currentRevision 和 changedLayers。返回真实原生结果,后台任务等待原 job 终态。resultRef 用 result.read {resultId,pointer?,offset?} 读取,pointer 采用 JSON Pointer(如 /layers),按 nextOffset 翻页。依次 await 各步真实回执。无效的 command 回执包含收到的编号和目录中前缀相近的命令 ID。其余命令与完整参数见 native_catalog。\n'+NATIVE_CANVAS_QUICK_REFERENCE, nativeCallParameters,
async (args, signal) => {
available();
const scope=canvasOperations(host);

View File

@ -41,7 +41,7 @@ const productImageArgs={
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
};
const reuseTarget=obj({outputId:optional(text),slotId:slotRef});
const transformDescription='在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选。返回新候选、cropSourcePixels、targetFrame、resolutionRatio 和 resolutionSufficient。';
const transformDescription='在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选。sourceCandidateId 接收候选编号,referenceIndex 接收从 0 开始的实拍序号。来源编号无效时返回匹配图位或目标图位的已完成候选。返回新候选、cropSourcePixels、targetFrame、resolutionRatio 和 resolutionSufficient。';
const transformImageArgs={
reference:optional(productReference),
sourceCandidateId:optional(Type.String({description:'本项目当前花色的已完成候选号,可来自其他图位。'})),

View File

@ -74,18 +74,50 @@ export async function projectTools(host) {
},
}});
return {...tool,async execute(id,params,signal,onUpdate){
const skills = host.productionSkills;
if (!worker && skills && !path.isAbsolute(params.path)) {
const file = path.resolve(skills.filesRoot, params.path);
if (skills.documents.has(file)) params = {...params,path:file};
const missingKnowledgePath=async (skills,file,requested)=>{
const documents=[...skills.documents];
const basename=path.basename(file);
const names=documents.filter(([registered])=>path.basename(registered)===basename);
const suggestions=(names.length?names:documents.filter(([registered])=>path.dirname(registered)===path.dirname(file)))
.map(([,resource])=>resource.path);
let message='当前小壹知识版本没有此路径:'+requested;
if (exports && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu.test(requested)) {
const state=await fs.readFile(path.join(path.dirname(exports),'canvas-workspace.json'),'utf8').then(JSON.parse,error=>{
if(error.code!=='ENOENT')throw error;
return {};
});
if(state.candidates?.includes(requested.toLowerCase())) {
message+='。这是本项目的候选编号。list_project_images、read_slot_images、review_image_slots 和 adopt_production_image 接收 candidateId,transform_slot_image 接收 sourceCandidateId。';
}
}
try {return await tool.execute(id,params,signal,onUpdate);}
catch(error){
if(!(error instanceof UnlockedEnterpriseFile))throw error;
throw Error(workerSkills.missingFileMessage(error.file,params.path));
}
}};
if(suggestions.length) message+='\n登记路径:\n'+suggestions.join('\n');
return Error(message);
};
return {...tool,
description:tool.description+' 锁定知识路径支持文件读取和目录清单,空路径或 . 返回登记文件清单。',
async execute(id,params,signal,onUpdate){
const skills=workerSkills??host.productionSkills;
const requested=params.path;
const file=skills&&path.resolve(skills.filesRoot,requested);
if (skills?.documents.has(file)) {
params={...params,path:file};
} else if (skills&&within(skills.filesRoot,file)) {
const entries=[...skills.documents].filter(([registered])=>within(file,registered))
.map(([,resource])=>resource.path).sort();
if(entries.length || file===skills.filesRoot) {
return {content:[{type:'text',text:entries.join('\n')}],details:{files:entries}};
}
}
try {return await tool.execute(id,params,signal,onUpdate);}
catch(error){
if(error instanceof UnlockedEnterpriseFile)throw await missingKnowledgePath(skills,error.file,requested);
if(!worker&&skills&&error.code==='ENOENT'&&within(skills.filesRoot,file)) {
throw await missingKnowledgePath(skills,file,requested);
}
throw error;
}
}};
};
const writeFile=async (file,content)=>fs.writeFile(await checked(file),content);
const stat=async file=>fs.stat(await checked(file));

View File

@ -279,7 +279,6 @@ export async function openXiaoyiSkills(store, templateId, signal, finishedGoal,
const file = fileAt(root,item.path);
return {file,source:documents.get(file)};
}),
missingFileMessage:(_file, requested) => '当前小壹知识版本没有此路径:' + requested,
};
} finally { await unlock(); }
}

View File

@ -98,7 +98,7 @@ test('Pi production and its worker read the same locked Skill and its relative r
let main=0,worker=0,serial=0;
const reads=new Map();
const skillLists=new Map();
const missing='当前小壹知识版本没有此路径:Skills/lighting/finish.md';
const missing='当前小壹知识版本没有此路径:Skills/lighting/finish.md\n登记路径:\n'+reference.path;
const transport={info:info(id.scope),stream(_model,context){
const system=getCurrentSystemPrompt(context.messages);
assert.match(system,/<name>lighting<\/name>/);
@ -195,6 +195,7 @@ test('a missing snapshot path stays missing until the next published round', asy
const initial = xiaoyiFixture('light','v1',entry,documents);
const next = xiaoyiFixture('light','v2',entry,{...documents,[target]:'The exact published reference.'});
const host={store,productionSkills:await openXiaoyiSkills(store,'light',undefined,undefined,initial)};
store.projectExportRoot=path.join(dir,'product-exports');
const {read}=await projectTools(host);
await fs.writeFile(path.join(store.dir,'workspace','outside.md'),'Project note');
assert.equal((await read('main').execute('workspace',{path:'outside.md'})).content[0].text,'Project note');
@ -205,6 +206,18 @@ test('a missing snapshot path stays missing until the next published round', asy
host.productionSkills=await openXiaoyiSkills(store,'light',undefined,'finished',next);
for (const agent of ['main','worker']) {
assert.equal((await read(agent).execute('present',{path:target})).content[0].text,'The exact published reference.');
for (const directory of ['', '.', 'Skills/lights']) {
const expected=directory==='Skills/lights'?[entry,target]:[entry,target,'小壹/production.json'];
assert.deepEqual((await read(agent).execute('directory',{path:directory})).details.files,expected.sort());
}
await assert.rejects(read(agent).execute('same-name',{path:'Skills/other/finish.md'}),
error=>error.message.endsWith(target));
await assert.rejects(read(agent).execute('same-parent',{path:'Skills/lights/references/missing.md'}),
error=>error.message.endsWith(target));
const candidate=randomUUID();
await fs.writeFile(path.join(dir,'canvas-workspace.json'),JSON.stringify({candidates:[candidate]}));
await assert.rejects(read(agent).execute('candidate',{path:candidate}),
/这是本项目的候选编号.*list_project_images.*sourceCandidateId/);
}
});

View File

@ -6649,6 +6649,15 @@ mod tests {
"request":{"slotId":slot,"sourceCandidateId":source_id,"transform":{"crop":[250,200,750,800]}}});
let (events, _receiver) = mpsc::channel();
let ctx = egui::Context::default();
for wrong in [source["binding"]["fieldId"].as_str().unwrap(), source["binding"]["slotId"].as_str().unwrap()] {
action["request"]["sourceCandidateId"] = json!(wrong);
let error = backend.production_image_request(doc, &action, &events, &ctx, None).unwrap_err().to_string();
assert!(error.contains(&source_id) && error.contains("complete") && error.contains(wrong), "{error}");
}
action["request"]["sourceCandidateId"] = json!(Uuid::new_v4().to_string());
let error = backend.production_image_request(doc, &action, &events, &ctx, None).unwrap_err().to_string();
assert!(error.contains("已完成候选:[]") && error.contains("list_project_images"), "{error}");
action["request"]["sourceCandidateId"] = json!(source_id);
let derived = backend.production_image_request(doc, &action, &events, &ctx, None).unwrap();
let id = derived["id"].as_str().unwrap();
let durable = read_candidate(dir, id).unwrap();

View File

@ -150,6 +150,16 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
files.push(copy_artifact(root, generation, &data["sourceDocument"], "工程文件", folder, label)?);
files.push(copy_artifact(root, generation, &data["layeredDocument"], "PSD", folder, label)?);
let images = data["files"].as_array().filter(|rows| !rows.is_empty()).ok_or("成品 JPG 缺失")?;
let copy_page = |source: &Value, category: &str, name: &str| -> R<Value> {
let mut file = copy_artifact(root, generation, source, category, folder, name)?;
if let Some(page_id) = source.get("pageId") {
file["pageId"] = page_id.clone();
}
file["outputId"] = json!(component);
file["variantId"] = json!(variant);
file["variantName"] = json!(color);
Ok(file)
};
if component == "detail" {
let mut screens = data["screenFiles"].as_array().filter(|rows| !rows.is_empty()).ok_or("详情页切片缺失")?.iter().collect::<Vec<_>>();
screens.sort_by_key(|screen| screen["top"].as_u64());
@ -158,7 +168,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
}
files.push(copy_artifact(root, generation, &images[0], "详情页长图", folder, "详情页长图")?);
for (index, screen) in screens.into_iter().enumerate() {
files.push(copy_artifact(root, generation, screen, "详情页切片", folder, &format!("详情页-{:02}", index + 1))?);
files.push(copy_page(screen, "详情页切片", &format!("详情页-{:02}", index + 1))?);
}
} else {
let sku_name = color.filter(|_| component == "sku_images").map(|name| format!("SKU-{name}"));
@ -168,7 +178,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
Some(name) => format!("{name}-{:02}", index + 1),
None => format!("{label}-{:02}", index + 1),
};
files.push(copy_artifact(root, generation, image, label, folder, &name)?);
files.push(copy_page(image, label, &name)?);
}
}
let mut adopted = Vec::new();
@ -473,6 +483,11 @@ mod tests {
("main_images", vec![(0, 8, 4), (4, 8, 6)], vec![]),
("sku_images", vec![(0, 8, 10)], vec![]),
] {
let pages = if component == "detail" { &screens } else { &regions };
let outputs = pages.iter().enumerate().map(|(index, (top, width, height))|
json!({"documentId":format!("{component}-{}",index+1),"top":top,"width":width,"height":height}))
.collect::<Vec<_>>();
canvas.metadata.text = vec![("jiansun.slot-mapping.v1".into(), json!({"canvasFirst":true,"outputs":outputs}).to_string())];
let receipt = canvas_workspace::receipt_path(&project, &variant, component);
let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component});
if component == "detail" {
@ -661,6 +676,17 @@ mod tests {
assert_eq!(entry["sha256"], canvas_workspace::file_digest(&path).unwrap());
assert_eq!(entry["verified"], true);
}
for (category, output, page_count) in [("详情页切片", "detail", 2), ("主图", "main_images", 2), ("SKU", "sku_images", 1)] {
let pages = manifest["files"].as_array().unwrap().iter().filter(|entry| entry["category"] == category)
.collect::<Vec<_>>();
assert_eq!(pages.len(), page_count);
for (index, page) in pages.into_iter().enumerate() {
assert_eq!(page["pageId"], format!("{output}-{}", index+1));
assert_eq!(page["outputId"], output);
assert_eq!(page["variantId"], detail["variantId"]);
assert_eq!(page["variantName"], "浅橡木");
}
}
for (path, width, height) in [
("详情页长图/详情页长图.jpg", 8, 10),
("详情页切片/详情页-01.jpg", 8, 4),

View File

@ -3,12 +3,51 @@
use super::{
Digest, Path, R, Sha256, Uuid, Value, candidate_available, candidate_pixels, candidate_uses_current_inputs, crop_product_image, definition,
generation_references, hash, image_output_component, input_hash, json, local_product_photo, mapped_slot, material_task_id, new_binding, now, output_uses_variant,
product_slot_binding, read_candidate, reserve_candidate, slot_frame, template_slots, uuid, write_json,
product_slot_binding, read_candidate, reserve_candidate, slot_frame, slot_id, template_slots, uuid, write_json,
};
use image::{Rgba, Rgba32FImage, imageops};
use photocraft_codecs::{ChannelLayout, Image, SampleType};
use serde::{Deserialize, Serialize};
fn invalid_source(dir: &Path, state: &Value, candidate: &str, target: &str, variant: &str) -> String {
let mut source_slots = std::collections::HashSet::new();
let packs = state["productTemplates"].as_object().into_iter().flat_map(|packs| packs.values())
.chain(std::iter::once(&state["template"]));
for pack in packs {
for field in pack["outputs"].as_array().into_iter().flatten()
.flat_map(|output| output["slots"].as_array().into_iter().flatten())
.filter(|field| field["kind"] == "image")
{
let Some(field_id) = field["fieldId"].as_str() else { continue; };
let label = field.get("name").or(field.get("label")).and_then(Value::as_str);
for color in state["variants"].as_array().into_iter().flatten().filter_map(|row| row["id"].as_str()) {
let id = slot_id(&pack["contentHash"], color, field_id);
if candidate == id || candidate == field_id || label == Some(candidate) {
source_slots.insert(id);
}
}
}
}
let matched_slot = !source_slots.is_empty();
let sources = state["candidates"].as_array().into_iter().flatten().rev().filter_map(Value::as_str)
.filter_map(|id| read_candidate(dir, id).ok())
.filter(|row| {
let binding = &row["binding"];
candidate_available(row) && if matched_slot {
binding["slotId"].as_str().is_some_and(|id| source_slots.contains(id))
} else {
binding["slotId"] == target && binding["variantId"] == variant
}
})
.take(8)
.map(|row| json!({"candidateId":row["id"],"slotId":row["binding"]["slotId"],
"fieldId":row["binding"]["fieldId"],"variantId":row["binding"]["variantId"],"phase":row["phase"]}))
.collect::<Vec<_>>();
let scope = if matched_slot { "匹配图位的已完成候选" } else { "目标图位同花色的已完成候选" };
let received = candidate.chars().take(200).collect::<String>();
format!("来源候选编号无效:收到「{received}」;sourceCandidateId 应填候选编号。{scope}:{}。跨图位候选可用 list_project_images 查询。", json!(sources))
}
pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R<Value> {
let slot = input["slotId"].as_str().ok_or("缺少目标图位")?;
let variant = uuid(&input["variantId"], "花色")?;
@ -29,12 +68,9 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R<Valu
.filter(|id| prefix.len() >= 8 && id.starts_with(prefix.as_str())).collect();
(rows.len() == 1).then(|| rows[0].to_owned())
};
let id = uuid(&json!(candidate), "来源候选").ok().or_else(by_prefix).ok_or_else(|| format!(
"来源候选编号无效:收到「{}」;sourceCandidateId 应填 list_project_images 或 read_slot_images 回执中的完整 candidateId",
candidate.chars().take(60).collect::<String>()))?;
if !state["candidates"].as_array().is_some_and(|rows| rows.contains(&json!(id))) {
return Err("来源候选不属于本项目".into());
}
let id = uuid(&json!(candidate), "来源候选").ok().or_else(by_prefix)
.filter(|id| state["candidates"].as_array().is_some_and(|rows| rows.contains(&json!(id))))
.ok_or_else(|| invalid_source(dir, &state, candidate, slot, &variant))?;
let record = read_candidate(dir, &id)?;
let original_binding = &record["binding"];
if !candidate_available(&record) || original_binding["variantId"] != variant {

View File

@ -523,6 +523,22 @@ fn catalog_relevance(row: &Value, terms: &[String]) -> Option<((u8, usize, u32),
/// A paged union of implemented native engine and shell commands. Summaries
/// stay bounded; exact-ID lookup returns the original parameter documentation.
fn catalog_menu_items(app: &PhotocraftApp) -> impl Iterator<Item = crate::menus::MenuItem> {
crate::menus::menu_items(app).into_iter().filter(|item| crate::menus::is_live(&item.id)
&& !item.id.starts_with(crate::menus::DOCUMENT_ITEM) && !item.id.starts_with("file.openRecent."))
}
fn nearby_command_ids<'a>(received: &str, ids: impl Iterator<Item = &'a str>) -> Vec<&'a str> {
let received = received.trim().to_ascii_lowercase();
let mut matches = ids.filter_map(|id| {
let prefix = received.bytes().zip(id.bytes()).take_while(|(a, b)| a.eq_ignore_ascii_case(b)).count();
(prefix >= 2 || (prefix == 1 && received.len() == 1)).then_some((std::cmp::Reverse(prefix), id))
}).collect::<Vec<_>>();
matches.sort_unstable();
matches.dedup();
matches.into_iter().take(8).map(|(_, id)| id).collect()
}
pub(super) fn catalog(w: &Workspace, app: &mut PhotocraftApp, input: &Value) -> Result<Value, String> {
arguments(input, &["run", "documentId", "filter", "id", "offset", "limit"])?;
let catalog_started = std::time::Instant::now();
@ -546,9 +562,7 @@ pub(super) fn catalog(w: &Workspace, app: &mut PhotocraftApp, input: &Value) ->
"parameterDocs":spec.params,"source":"engine"}));
}
if rows.is_empty() || requested.is_none() {
for item in crate::menus::menu_items(app).into_iter().filter(|item| crate::menus::is_live(&item.id)
&& !item.id.starts_with(crate::menus::DOCUMENT_ITEM) && !item.id.starts_with("file.openRecent.")
&& requested.is_none_or(|id| id == item.id)) {
for item in catalog_menu_items(app).filter(|item| requested.is_none_or(|id| id == item.id)) {
rows.entry(item.id.clone()).or_insert_with(|| json!({"id":item.id,"label":item.label,"menu":item.path,"shortcut":item.shortcut,
"parameterDocs":Value::Null,"nativeEnabled":item.enabled,"nativeReason":if item.enabled {Value::Null} else {json!("当前原生菜单不可用")},"source":"shell"}));
}
@ -633,7 +647,15 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
let mut native_params = Value::Object(params.clone());
let command = if method == "engine.execute" {
arguments(&native_params, &["command", "params"])?;
let id = native_params["command"].as_str().filter(|id| !id.is_empty() && id.len() <= 200 && crate::menus::is_live(id)).ok_or("原生命令未实现或编号无效")?.to_owned();
let received = &native_params["command"];
let id = received.as_str().filter(|id| !id.is_empty() && id.len() <= 200 && crate::menus::is_live(id))
.ok_or_else(|| {
let menu = catalog_menu_items(app).collect::<Vec<_>>();
let ids = photocraft_engine::command_specs().iter().map(|spec| spec.id)
.chain(menu.iter().map(|item| item.id.as_str()));
let nearby = nearby_command_ids(received.as_str().unwrap_or_default(), ids);
format!("原生命令未实现或编号无效:收到 command={received};native_catalog 中前缀相近的命令 ID:{}", json!(nearby))
})?.to_owned();
if !native_params["params"].is_object() { return Err("原生命令params须为对象".into()); }
// The bridge returns the real job rather than installing an unrelated
// transport waiter. Completion is polled by the owning run only.
@ -1212,6 +1234,8 @@ mod tests {
assert!(blocked["items"][0]["authorityReason"].is_null());
input["id"] = json!("layer.setProps");
assert!(catalog(&w, &mut app, &input).unwrap()["items"][0]["parameterDocs"].as_str().unwrap().contains("opacity"));
let error = invoke(&mut w, &mut app, "engine.execute", json!({"command":"view.zoomInn","params":{}})).unwrap_err();
assert!(error.contains("view.zoomInn") && error.contains("\"view.zoomIn\"") && error.contains("native_catalog"), "{error}");
assert!(w.agent_native.last_receipt().is_none());
assert!(requests.try_recv().is_err(), "discovery never dispatches a backend/model request");
}