gongxiangp2/apps/detail-agent-pi/test/whitelabel.test.mjs

196 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { productionObjective, productionTools } from '../src/production-goal.mjs';
import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from '../src/native-tools.mjs';
import { sessionSystemPrompt } from '../src/agent.mjs';
import { presentReply, presentProductReply } from '../src/stream-presentation.mjs';
const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8');
const technicalBrand = /(?<![A-Za-z0-9_])(?:Pi(?: Agent)?|PhotoCraft)(?![A-Za-z0-9_])|\bpcraft:/u;
test('conversation status, errors and tool guidance use product terminology', () => {
for (const file of [
'agent.mjs', 'desktop-host.mjs', 'xiaoyi-release.mjs', 'native-tools.mjs',
'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs',
'production-operations.mjs', 'production-tools.mjs', 'production-tool-schema.mjs',
'production-image-worker.mjs', 'production-screen-tools.mjs', 'runtime-policy.mjs',
'screen-review.mjs',
]) {
for (const [index, line] of source(file).split('\n').entries()) {
const copy = line.trim();
if (/^(?:\/\/|\/\*|\*)/.test(copy) || copy === "aliases: ['PhotoCraft', 'native'],") continue;
assert.doesNotMatch(copy, technicalBrand, `${file}:${index + 1}`);
}
}
});
test('production guidance batches determined operations and scopes screenshot review', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
assert.match(prompt, /codemode[^。]*依次 await[^。]*真实回执/);
assert.match(prompt, /native_catalog[^。]*复用[^。]*parameterDocs/);
assert.doesNotMatch(prompt, /NATIVE_CANVAS_QUICK_REFERENCE|2–4 屏/);
const description = productionTools.find(([name]) => name === 'read_output_screen')?.[1];
assert.match(description, /从 1 开始[^]*多屏[^]*只保留最新一次查看图片/);
});
test('both conversation prompts and delegated production share the product voice rule', () => {
const agent = source('agent.mjs');
for (const name of ['SYSTEM', 'PRODUCTION_SYSTEM']) {
const prompt = agent.match(new RegExp('const ' + name + ' = `([\\s\\S]+?)`;'))?.[1];
assert.ok(prompt?.includes('${PRODUCT_VOICE}'), name);
}
assert.match(agent, /systemPrompt:systemPrompt\+'\\n'\+PRODUCT_VOICE/);
assert.match(agent, /对用户回复、状态汇报和错误说明始终使用「小壹」「画布」「工作台」「制作助手」/);
assert.match(agent, /不得向用户暴露底层技术或开源底座名称/);
});
test('both conversation modes guide a designer-like voice and protect internal tool details',()=>{
for(const production of [false,true]){
const prompt=sessionSystemPrompt(production);
assert.match(prompt,/靠谱、温和、眼里有活的电商视觉设计搭档/);
assert.match(prompt,/先说结论和对方最关心的结果/);
assert.match(prompt,/严禁输出 Markdown 表格.*项目符号/);
assert.match(prompt,/严禁复述内部字段名、状态枚举、技术布尔值、内部缓存路径、带 \\\\\?\\\\ 的磁盘路径、UUID、候选哈希/);
}
});
test('chat renders table rows as bullets and translates receipt fragments before display',()=>{
const raw='| 成品 | 交付状态 |\n|---|---|\n| `main_images` | `exported` |\n| `sku_images` | `completed` |\n'+
'allOutputsCompleted=true,pendingOutputs=[],writeBlocked=false。'+
'dd6f9c0b-a03b-4d42-8aac-f5ce110a681c,candidateId=5b05b95。';
const visible=presentProductReply(raw);
assert.match(visible,/- 主图,已导出\n- SKU 图,已完成/);
assert.match(visible,/成品已全部完成,没有待交付成品,画布可以编辑/);
assert.doesNotMatch(visible,/\||main_images|sku_images|exported|completed|allOutputsCompleted|pendingOutputs|writeBlocked|dd6f9c0b|5b05b95/);
assert.equal(presentProductReply('正在核对。\n| 主图 | 已导',true),'正在核对。\n');
assert.equal(presentProductReply('成品 | 进度\n--- | ---\n详情页 | 已导出'),'- 成品,进度\n\n- 详情页,已导出');
assert.equal(presentProductReply('成品 | 进度',true),'- 成品,进度');
assert.equal(presentReply('`writeBlocked`,deliveryStatus: partial_delivered。'),'画布编辑状态,交付进度:部分成品已交付。');
const english='Show product detail, true color, completed look';
assert.equal(presentReply(english),english);
const digest='1234567890'.repeat(6)+'1234';
const ordinary='建议保留「原木 | 藤编」的品类名。\n- 颜色 | 材质';
assert.equal(presentReply(ordinary),ordinary);
assert.equal(presentReply(ordinary,true),ordinary);
assert.equal(presentReply('标记「'+digest+'」'), '标记「制作记录」');
assert.equal(presentReply('| 核对 | '+digest+' |',true),'- 核对,制作记录');
});
test('production prompts refer to the published skill and keep screen semantics with the tool', () => {
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
const tool = name => productionTools.find(([tool]) => tool === name)?.[1];
assert.match(prompt, /锁定的企业 Skill、模板和补充规则/);
const standard=source('agent.mjs').match(/const SYSTEM = `([\s\S]+?)`;/)?.[1];
assert.match(standard,/只确认经回执验证的结果/);
assert.doesNotMatch(standard,/申请写入许可后执行实际修改/);
assert.doesNotMatch(prompt, /overlayLayers|NATIVE_CANVAS_QUICK_REFERENCE|每批/);
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'), /全页字段[^。]*指定页面或字段/);
assert.match(tool('plan_production'), /固定版本的规则路径,可用 read 读取/);
assert.match(tool('open_production_output'), /切换前保存原工程/);
assert.match(tool('finish_production'), /scope=all.*逐一导出待交付成品/);
assert.match(tool('check_image_slots'), /复核输入包含当前图位关联文案/);
assert.doesNotMatch([prompt,tool('read_output_screen'),source('copy-image-alignment.mjs')].join('\n'), /桌腿|木种|SFY-CHAIR-001/);
});
test('built-in image skill documents request and canvas receipt fields', () => {
const skill = source('skills/product-image-sources/SKILL.md');
for (const field of ['useTemplateBase','productReferences','requestId','candidateId','cropSourcePixels','targetFrame',
'resolutionRatio','resolutionSufficient','canvasFacts','annotationLayout','nearestLine','crossings']) {
assert.ok(skill.includes(field), field);
}
const example = JSON.parse(skill.match(/```json\r?\n([\s\S]+?)\r?\n```/)?.[1]);
assert.equal(example.method, 'engine.execute');
assert.equal(example.params.command, 'paint.remove');
});
test('native tooling and production share the documented canvas commands', () => {
const engine = file => readFileSync(new URL(`../../detail-photocraft/crates/engine/src/${file}`, import.meta.url), 'utf8');
const docs = [
['cmd.rs', 'layer.setProps', ['layer','visible','opacity','fill','blend'], ['0..1','Multiply']],
['cmd.rs', 'layer.delete', ['layer'], []],
['cmd.rs', 'layer.moveTo', ['layer','target','position'], ['above|below|into']],
['cmd.rs', 'layer.select', ['layer','mode'], ['replace|toggle|range|add|remove']],
['cmd/transform_cmds.rs', 'edit.transform', ['layer','dx','dy','scaleX','scaleY','rotate','matrix'], []],
['cmd/type_cmds.rs', 'type.info', ['layer'], []],
['cmd/type_cmds.rs', 'type.edit', ['layer','text'], []],
['cmd/type_cmds.rs', 'type.setStyle', ['layer','font','size','color','align'], ['left|center|right']],
['layer_style.rs', 'layer.layerStyle.dropShadow', ['layer','color','opacity','angle','distance','size'], ['0..100']],
['layer_style.rs', 'layer.layerStyle.stroke', ['size','position','color','opacity'], ['inside|outside|center','0..100']],
['layer_style.rs', 'layer.layerStyle.colorOverlay', ['color','opacity'], ['0..100']],
];
for (const [file,id,keys,values] of docs) {
const rust = engine(file);
const specId = file==='layer_style.rs' ? id.split('.').at(-1) : id;
const start = rust.indexOf(`"${specId}"`, file==='layer_style.rs' ? rust.indexOf('pub fn specs()') :
file==='cmd/type_cmds.rs' ? rust.indexOf('id: "type.edit"') : 0);
assert.ok(start>=0,id);
const docsStart = rust.indexOf('r##"',start)+4;
const native = rust.slice(docsStart,rust.indexOf('"##',docsStart)) +
(id==='type.setStyle'?rust.match(/const CHAR_PARAMS[^\n]+/)[0]:'');
const quick = NATIVE_CANVAS_QUICK_REFERENCE.split('\n').find(line=>line.includes(id));
assert.ok(quick,id);
for (const key of keys) {
assert.ok(native.includes(`"${key}"`),`${id} native ${key}`);
assert.ok(quick.includes(key),`${id} quick reference ${key}`);
}
for (const value of values)assert.ok(native.includes(value),`${id} ${value}`);
}
const [catalog,call] = nativeTools({canvas:{nativeCatalog(){},nativeCall(){}}},
(name,description)=>({name,description}));
assert.ok(call.description.includes(NATIVE_CANVAS_QUICK_REFERENCE));
assert.match(call.description,/native_catalog/);
assert.match(catalog.description,/parameterDocs/);
assert.doesNotMatch(call.description,technicalBrand);
});
test('the unattended objective records the intended delivery', () => {
const objective = productionObjective([{ outputId: 'detail', label: '详情图' }]);
const prompt = source('agent.mjs').match(/const PRODUCTION_SYSTEM = `([\s\S]+?)`;/)?.[1];
assert.match(prompt, /小壹的制作助手,当前为无人值守制作/);
assert.doesNotMatch(source('skills/product-image-sources/SKILL.md'),technicalBrand);
assert.match(objective, /按适用制作指引和模板制作并交付[^。]*详情图/);
assert.doesNotMatch(objective, /useTemplateReference|read_output_screen/);
assert.doesNotMatch(objective, /无人值守/);
assert.doesNotMatch(objective, technicalBrand);
});
test('the retired goal extension is not loaded',()=>{
assert.doesNotMatch(source('photocraft-extension.mjs'),/vendor\/pi-goal|update_goal/u);
});
test('Rust UI user-visible copy in jiansun stays white-label and avoids raw error leakage', () => {
const jiansunDir = fileURLToPath(new URL('../../detail-photocraft/crates/ui-egui/src/jiansun', import.meta.url));
const collectRs = dir => {
const files = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) files.push(...collectRs(full));
else if (entry.isFile() && entry.name.endsWith('.rs')) files.push(full);
}
return files;
};
const uiCallPattern = /(?:ui\.label|ui\.button|RichText::new|status_label|status_chip|action_button|on_hover_text)\s*\(/;
const rawErrorInUiPattern = /format!\s*\(\s*"[^"]*\{(?:e|err|error)\}/;
for (const file of collectRs(jiansunDir)) {
const content = readFileSync(file, 'utf8');
const production = content.split('#[cfg(test)]')[0].split('mod tests {')[0];
for (const [index, line] of production.split('\n').entries()) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('//')) continue;
if (uiCallPattern.test(trimmed)) {
for (const match of trimmed.matchAll(/"([^"\\]*(?:\\.[^"\\]*)*)"/g)) {
assert.doesNotMatch(match[1], technicalBrand, `${file}:${index + 1}`);
}
assert.doesNotMatch(trimmed, rawErrorInUiPattern, `${file}:${index + 1} raw error format`);
}
}
}
});