fix(xiaoyi): isolate duplicate-barcode SKU files in subdirs and slim P2 tool schema

This commit is contained in:
WuYongJie 2026-12-04 23:27:09 +08:00
parent 9b842d24e1
commit 398c4e6e7e
10 changed files with 134 additions and 21 deletions

View File

@ -762,11 +762,27 @@ async function downloadAsZip(
}
return { asset, fileUrl, fileName, resolution };
});
for (const { asset, fileUrl, fileName, resolution } of files) {
const groupedFiles = files.map(({ asset, fileUrl, fileName, resolution }) => {
const repeatedSkuName = asset.assetType === 'sku' && (skuNames.get(fileName.toLowerCase()) ?? 0) > 1;
const group = repeatedSkuName || (resolution && skuResolutions.size > 1)
? `sku/${resolution ?? asset.sortOrder}` : asset.assetType;
const entryName = `${group}/${fileName}`;
return { asset, fileUrl, fileName, group };
});
const skuGroupNameCounts = new Map<string, number>();
for (const item of groupedFiles) {
if (item.asset.assetType !== 'sku') continue;
const key = `${item.group}\u0000${item.fileName.toLowerCase()}`;
skuGroupNameCounts.set(key, (skuGroupNameCounts.get(key) ?? 0) + 1);
}
const skuGroupNameOffsets = new Map<string, number>();
for (const { asset, fileUrl, fileName, group } of groupedFiles) {
const key = `${group}\u0000${fileName.toLowerCase()}`;
let entryName = `${group}/${fileName}`;
if (asset.assetType === 'sku' && (skuGroupNameCounts.get(key) ?? 0) > 1) {
const offset = (skuGroupNameOffsets.get(key) ?? 0) + 1;
skuGroupNameOffsets.set(key, offset);
entryName = `${group}/${String(offset).padStart(2, '0')}/${fileName}`;
}
try {
const localPath = resolveAssetLocalPath(fileUrl);

View File

@ -159,7 +159,7 @@ export async function verifyDeliveryBundle(directory, expected = []) {
if (row.format !== 'jpg' || row.category !== category) return false;
const dir = path.posix.dirname(row.relativePath);
if (dir === expectedDir) return true;
return category === 'SKU' && dir.startsWith(expectedDir + '/') && /^\d+x\d+$/.test(dir.slice(expectedDir.length + 1));
return category === 'SKU' && dir.startsWith(expectedDir + '/') && /^(?:\d+x\d+\/)?[^/]+$/.test(dir.slice(expectedDir.length + 1));
}), `缺少 ${category}${folder}`);
}
}

View File

@ -560,7 +560,7 @@ export class DetailPiAgent {
if (signals.length) options = {...options, signal:AbortSignal.any(signals)};
(async () => {
let round;
const purpose = worker ? 'whole-detail-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
const purpose = worker ? 'slot-worker' : host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation';
try {
options.signal?.throwIfAborted();
if (host.compromised) throw Error('本地会话锁失效,已停止模型调用');

View File

@ -1,6 +1,5 @@
import { StringEnum } from '@earendil-works/pi-ai';
import { Type } from '@sinclair/typebox';
import { OVERLAY_SCREEN_FIELDS } from './copy-image-alignment.mjs';
import {
dispatchArgs, fit, ids, imageRequestDescription, obj, optional, page, preparationArgs, productImageArgs,
reuseTarget, rev, slotRef, text, transformDescription, transformImageArgs,
@ -47,7 +46,7 @@ export const productionOperationTools = [
['adopt_production_image','采用选定候选,返回画布修订、模板叠层。单图位屏与已有验图画面一致时附复核结论。可用 reason 记录采用理由。screensReadyForReview 列出待验多图位屏,可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})],
['retire_production_image','清理已判失败的图位候选,保留原因、提示词及原请求记录。若已上画布,返回应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按保存的原操作或候选号核查。未绑定画布时查询本轮项目输出,可用完整图位 id 限定。unknown 按原号继续核查、取回留存结果,避免重复付费。expired 表示原请求收口,可另备新请求。原因包括网关 HTTP 410、下载 404/410,或 180 秒恢复预算用完仍 unresolved 或 404 request_not_found。404 request_not_found 收口按未发起处理,其余已派发请求仍计入次数。',obj({...outputScope,slotIds:optional(ids)})],
['read_output_screen',`读取整屏合成画面、模板差异、overlayLayers、slotGeometry、annotationLayout 和 textClipping。page 或 pages 从 0 开始,可查看 2–4 屏;局部用单屏、region(画布 [x,y,w,h])和 1–4 倍 zoom,网格为原坐标。includeTemplateImage 附原屏,templateLayerId 查完整原值和现值,以 nextChangeOffset 翻模板差异。slotImageFacts 给出来源、当前与原屏近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空)及本成品最多三个最近图位的 64 位 dHash 汉明距离(越小越相似)。subjectBounds 按像素与边缘背景色差估测并裁到可见图框,失败见 subjectBoundsReason。textLayers 给出样式、字形对比度 P10/P50 和底色亮度标准差。annotationLayout 给出文字、线端点、穿线长度、与主体的重叠及最近距离;dimensionGroups 给出标签、线和相对主体边界的像素偏移,guides 给出当前和原屏同层的对比度、线宽和端点直径。textClipping 给出墨迹边界及越屏部分。reviewRound 是已完成的整屏复核次数,issueHistory 是历轮问题数。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({
['read_output_screen','读取整屏合成画面、模板差异、图位与标注布局。page 或 pages 从 0 开始,可查看 2–4 屏;局部用单屏、region(画布 [x,y,w,h])和 1–4 倍 zoom。includeTemplateImage 附原屏,templateLayerId 查完整原值和现值,templateChangeOffset 翻模板差异。只保留最新一次查看图片。详细像素、文字与布局核查字段见随包 Skill。',obj({
page:optional(page),pages:optional(Type.Array(page)),
region:optional(Type.Array(Type.Integer(),{minItems:4,maxItems:4,description:'画布坐标 [x,y,w,h],宽高至少 1 像素。'})),
zoom:optional(Type.Number({minimum:1,maximum:4})),

View File

@ -172,3 +172,37 @@ test('allows multi-resolution SKU subdirectories under SKU output folder', async
const report = await verifyDeliveryBundle(root, ['main_images', 'sku_images']);
assert.equal(report.ok, true, JSON.stringify(report.errors));
});
test('allows numbered subdirectories for same-resolution duplicate SKU barcodes', async t => {
const root = await fixture(t);
const manifestPath = path.join(root, '交付清单.json');
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const jpeg = Buffer.from('ffd8ffc0000b080001000101011100ffd9', 'hex');
const sha256 = createHash('sha256').update(jpeg).digest('hex');
const pcraftBytes = await fs.readFile(path.join(root, '工程文件/主图.pcraft'));
await fs.writeFile(path.join(root, '工程文件/SKU.pcraft'), pcraftBytes);
await fs.writeFile(path.join(root, 'PSD/SKU.psb'), await fs.readFile(path.join(root, 'PSD/主图.psb')));
const pcraftHash = createHash('sha256').update(pcraftBytes).digest('hex');
const psdBytes = await fs.readFile(path.join(root, 'PSD/SKU.psb'));
const psdHash = createHash('sha256').update(psdBytes).digest('hex');
manifest.files.push(
{ relativePath: '工程文件/SKU.pcraft', category: '工程文件', format: 'pcraft', width: 1, height: 1, sizeBytes: pcraftBytes.length, sha256: pcraftHash, verified: true },
{ relativePath: 'PSD/SKU.psb', category: 'PSD', format: 'psb', width: 1, height: 1, sizeBytes: psdBytes.length, sha256: psdHash, verified: true },
);
manifest.counts['工程文件'] += 1;
manifest.counts['PSD'] += 1;
manifest.completedOutputs = 2;
manifest.totalOutputs = 2;
for (const relativePath of ['SKU/800x800/01/BARCODE01.jpg', 'SKU/800x800/02/BARCODE01.jpg', 'SKU/01/BARCODE02.jpg']) {
await fs.mkdir(path.dirname(path.join(root, relativePath)), { recursive: true });
await fs.writeFile(path.join(root, relativePath), jpeg);
manifest.files.push({
relativePath, category: 'SKU', format: 'jpg', width: 1, height: 1,
sizeBytes: jpeg.length, sha256, verified: true,
});
}
manifest.counts['SKU'] = 3;
await fs.writeFile(manifestPath, JSON.stringify(manifest));
const report = await verifyDeliveryBundle(root, ['main_images', 'sku_images']);
assert.equal(report.ok, true, JSON.stringify(report.errors));
});

View File

@ -48,8 +48,8 @@ test('production prompts refer to the published skill and keep screen semantics
const tool = name => productionTools.find(([tool]) => tool === name)?.[1];
assert.match(prompt, /锁定的企业 Skill、模板和补充规则/);
assert.doesNotMatch(prompt, /overlayLayers|NATIVE_CANVAS_QUICK_REFERENCE|每批/);
assert.match(tool('read_output_screen'), /整屏合成画面[^]*annotationLayout/);
assert.match(tool('read_output_screen'), /overlapsSlots.*fieldId.*bounds.*text.*mapped/);
assert.match(tool('read_output_screen'), /整屏合成画面[^]*随包 Skill/);
assert.doesNotMatch(tool('read_output_screen'), /overlapsSlots|nearWhiteFlatRatio/);
assert.match(tool('adopt_production_image'), /read_output_screen 查看整屏合成画面/);
assert.match(tool('check_output_screens'), /按企业 Skill[^]*整屏合成画面/);
assert.match(tool('read_copy_fields'), /全页字段[^。]*指定页面或字段/);

View File

@ -320,22 +320,39 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
photocraft_ui_egui::jiansun::production_facts::product_brief::resolve_sku_spec_target(&c["brief"], variant)
.and_then(|target| target.spec_id)
});
for (index, image) in images.iter().enumerate() {
if let Some(creation) = &creation {
let mut sku_entries = Vec::new();
let mut sku_counts: BTreeMap<(String, String), usize> = BTreeMap::new();
if let Some(creation) = &creation {
for (index, image) in images.iter().enumerate() {
let (names, missing) = sku_export_names(&creation["brief"], variant, index);
sku_barcode_warning |= missing;
let (width, height) = image["width"].as_u64().zip(image["height"].as_u64())
.ok_or("SKU 图缺少尺寸")?;
let size = format!("{width}x{height}");
let target = if images.len() > 1 { folder.join(size) } else { folder.to_path_buf() };
for name in names {
let mut file = copy_page(image, label, &target, &name)?;
if let Some(spec) = &spec_id {
file["specId"] = json!(spec);
}
files.push(file);
*sku_counts.entry((size.clone(), name.clone())).or_insert(0) += 1;
sku_entries.push((image, size.clone(), name));
}
} else {
}
let mut sku_offsets: BTreeMap<(String, String), usize> = BTreeMap::new();
for (image, size, name) in sku_entries {
let base_target = if images.len() > 1 { folder.join(&size) } else { folder.to_path_buf() };
let key = (size, name);
let target = if sku_counts.get(&key).copied().unwrap_or(0) > 1 {
let offset = sku_offsets.entry(key.clone()).or_insert(0);
*offset += 1;
base_target.join(format!("{:02}", *offset))
} else {
base_target
};
let mut file = copy_page(image, label, &target, &key.1)?;
if let Some(spec) = &spec_id {
file["specId"] = json!(spec);
}
files.push(file);
}
} else {
for (index, image) in images.iter().enumerate() {
files.push(copy_page(image, label, folder, &format!("{label}-{:02}", index + 1))?);
}
}
@ -1461,4 +1478,38 @@ mod tests {
assert!(unit_hints.iter().any(|h| h.contains("Alibaba-PuHuiTi-M")));
assert!(unit_hints.iter().any(|h| h == SKU_BARCODE_WARNING));
}
#[test]
fn same_resolution_duplicate_sku_barcodes_are_isolated_in_numbered_subdirs() {
let (_root, project, local, mut input) = fixture();
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
let variant = input["published"][0]["variantId"].as_str().unwrap().to_owned();
let doc = Document::new("浅橡木", Size::new(8, 12), ColorMode::Rgb, SampleType::U8);
let receipt = canvas_workspace::receipt_path(&project, &variant, "sku_images");
let mut sku = json!({"workspaceId":input["workspaceId"],"variantId":variant,"outputId":"sku_images"});
canvas_workspace::publish_product_generation(
&receipt,
&doc,
&json!(8),
&mut sku,
&[(0, 8, 4), (4, 8, 4), (8, 8, 6)],
&[],
).unwrap();
for item in input["published"].as_array_mut().unwrap() {
if item["outputId"] == "sku_images" {
item["generationId"] = sku["generationId"].clone();
}
}
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
assert_eq!(delivered["state"], "bundle_saved");
let bundle = Path::new(delivered["path"].as_str().unwrap());
for relative in [
"SKU/01 浅橡木/8x4/01/001-Blue.jpg",
"SKU/01 浅橡木/8x4/02/001-Blue.jpg",
"SKU/01 浅橡木/8x6/001-Blue.jpg",
] {
assert!(bundle.join(relative).is_file(), "missing {relative}");
}
assert!(!bundle.join("SKU/01 浅橡木/8x4/001-Blue.jpg").exists());
}
}

View File

@ -141,6 +141,15 @@ test('同条码的两种尺寸入库时保留纯条码文件名并分别存放',
request.assets.sku[1].width = request.assets.sku[1].height = 800
await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('同一分组中有重复文件')
request.assets.sku[1].sha256 = createHash('sha256').update('y').digest('hex')
const streamMock = jest.mocked(require('node:fs').createReadStream)
streamMock
.mockReturnValueOnce([Buffer.from('x')])
.mockReturnValueOnce([Buffer.from('x')])
.mockReturnValueOnce([Buffer.from('y')])
.mockReturnValueOnce([Buffer.from('x')])
await expect(createDesktopDelivery(account.id, request, authorize)).resolves.toMatchObject({ state: 'completed' })
request.assets.sku[1].sha256 = digest
request.assets.sku[1].fileName = 'SKU-001-A.jpg'
await expect(createDesktopDelivery(account.id, request, authorize)).rejects.toThrow('SKU 图的条码文件名或尺寸无效')
})

View File

@ -130,13 +130,17 @@ describe('external single-file S3 download range forwarding', () => {
['800x800/001-A.jpg', '1440x1920/001-A.jpg', '1440x1920/001-B.jpg'],
['sku/800x800/001-A.jpg', 'sku/1440x1920/001-A.jpg', 'sku/1440x1920/001-B.jpg'],
],
[
['800x800/001-A.jpg', '800x800/001-A.jpg', '1440x1920/001-A.jpg', '800x800/001-B.jpg'],
['sku/800x800/01/001-A.jpg', 'sku/800x800/02/001-A.jpg', 'sku/1440x1920/001-A.jpg', 'sku/800x800/001-B.jpg'],
],
])('小壹 ZIP 按分辨率组织 SKU 并保留单分辨率的历史目录(%j)', async (paths, expected) => {
jest.mocked(verifyDownloadToken).mockReturnValue({ materialId: 'material-1', downloadType: 'all' })
const assets = await Promise.all(paths.map(async (relative, sortOrder) => {
const [resolution, fileName] = relative.split('/')
const fileUrl = join(localTempDir, 'xiaoyi-deliveries', 'owner', 'project', 'request', 'sku', resolution, 'hash', fileName)
const fileUrl = join(localTempDir, 'xiaoyi-deliveries', 'owner', 'project', 'request', 'sku', resolution, `hash-${sortOrder}`, fileName)
await mkdir(dirname(fileUrl), { recursive: true })
await writeFile(fileUrl, relative)
await writeFile(fileUrl, `${relative}#${sortOrder}`)
return { assetType: 'sku', fileUrl, fileName, sortOrder }
}))
jest.mocked(prisma.material.findUnique).mockResolvedValue({
@ -147,7 +151,7 @@ describe('external single-file S3 download range forwarding', () => {
expect(response.status).toBe(200)
const zip = new AdmZip(Buffer.from(await response.arrayBuffer()))
expect(zip.getEntries().map(entry => entry.entryName).sort()).toEqual([...expected].sort())
expected.forEach((entry, index) => expect(zip.readAsText(entry)).toBe(paths[index]))
expected.forEach((entry, index) => expect(zip.readAsText(entry)).toBe(`${paths[index]}#${index}`))
})
test.each([{ accessScope: 'operations_g' }, { taskDetailPrivate: true }])(

View File

@ -112,7 +112,7 @@ function normalized(input: Input) {
'同一分组中有重复文件')
skuNames.set(nameKey, Boolean(resolution))
}
const fileKey = resolution ? nameKey + '\u0000' + resolution : legacy ? nameKey + '\u0000' + file.sha256 : nameKey
const fileKey = resolution ? nameKey + '\u0000' + resolution + '\u0000' + file.sha256 : legacy ? nameKey + '\u0000' + file.sha256 : nameKey
desktopAssert(!filenames.has(fileKey), '同一分组中有重复文件')
filenames.add(fileKey)
const metadata = { group: assetGroup, fileName: name.fileName!, fileSize: file.fileSize, sha256: file.sha256 }