gongxiangp2/apps/detail-agent-pi/test/liberate-agent-js.test.mjs

230 lines
9.6 KiB
JavaScript

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { Type } from '@sinclair/typebox';
import { callProductionTool, closeProductionTurn, productionTools } from '../src/production-goal.mjs';
import { candidateUsage } from '../src/production-slots.mjs';
import { normalizeToolArgs, toolSchema } from '../src/tool-schema.mjs';
import { acquireXiaoyiRelease } from '../src/xiaoyi-release.mjs';
import { cleanup } from './cleanup.mjs';
import { productionStore } from './production-store-fixture.mjs';
const sha256 = data => createHash('sha256').update(data).digest('hex');
test('toolSchema strips additionalProperties:false and normalizeToolArgs handles aliases, nulls, singletons, and numeric strings', () => {
const rawSchema = Type.Object({
outputId: Type.Optional(Type.String()),
variantId: Type.Optional(Type.String()),
slotIds: Type.Optional(Type.Array(Type.String())),
pages: Type.Optional(Type.Array(Type.Integer({ minimum: 1 }))),
references: Type.Optional(Type.Array(Type.String())),
pageId: Type.Optional(Type.String()),
reason: Type.Optional(Type.String()),
mustRedo: Type.Optional(Type.Array(Type.Object({
location: Type.String(),
problem: Type.String(),
suggestion: Type.String(),
}, { additionalProperties: false }))),
}, { additionalProperties: false });
const schema = toolSchema('test_tool', rawSchema);
assert.equal(schema.additionalProperties, undefined);
assert.equal(schema.properties.mustRedo.items.additionalProperties, undefined);
const normalized = normalizeToolArgs({
outputId: 'detail',
productVariantId: 'oak',
slotId: 'S01',
pages: '2',
reference: 'P01',
pageId: '1',
reasonDetail: '画面构图偏右',
notes: null,
extraHint: 'harmless',
mustRedo: [{ location: '顶部', issue: '裁切过紧', suggestion: '留白', extra: null }],
}, schema);
const validated = validateToolArguments({ name: 'test_tool', parameters: schema }, { name: 'test_tool', arguments: normalized });
assert.equal(validated.variantId, 'oak');
assert.deepEqual(validated.slotIds, ['S01']);
assert.deepEqual(validated.pages, [2]);
assert.deepEqual(validated.references, ['P01']);
assert.equal(validated.pageId, '1');
assert.equal(validated.reason, '画面构图偏右');
assert.equal(validated.notes, undefined);
assert.deepEqual(validated.mustRedo[0], { location: '顶部', issue: '裁切过紧', problem: '裁切过紧', suggestion: '留白' });
});
test('all 9 previously missing productionTools accept optional outputId and variantId', () => {
const expectedNames = [
'set_production_settings', 'read_copy_fields', 'write_copy_fields',
'read_archived_images', 'adopt_production_image', 'retire_production_image',
'read_output_screen', 'check_output_screens', 'defer_production_output',
];
const byName = new Map(productionTools.map(([name, , schema]) => [name, toolSchema(name, schema)]));
for (const name of expectedNames) {
const schema = byName.get(name);
assert.ok(schema, name);
assert.ok(schema.properties.outputId, `${name} missing outputId`);
assert.ok(schema.properties.variantId, `${name} missing variantId`);
assert.equal(schema.additionalProperties, undefined, `${name} should not have additionalProperties:false`);
}
});
test('candidateUsage decouples local crops/reuses from paid maxCandidatesPerSlot', () => {
const slot = {
generationRequestIds: ['gen-1'],
candidates: [
{ id: 'gen-1', status: 'complete' },
{ id: 'crop-1', status: 'complete', sourceType: 'transform' },
{ id: 'crop-2', status: 'complete', sourceType: 'transform' },
{ id: 'photo-1', status: 'complete', sourceType: 'product-reference' },
{ id: 'reuse-1', status: 'complete', reusedFrom: { candidateId: 'other' } },
],
};
assert.deepEqual(candidateUsage(slot, 2), { candidateCount: 1, candidatesRemaining: 1 });
});
test('callProductionTool allows non-working read/review/retire, finish_production returns unadoptedPassed without blocking, and maps detail to 详情页', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-liberate-'));
t.after(() => cleanup(dir));
const store = productionStore(dir);
const slot = {
id: 'slot-1',
fieldId: 'D01-I01',
label: '首屏主图',
aspectRatio: '1:1',
candidates: [{ id: 'cand-pass', status: 'complete', reviewDecision: 'pass' }],
};
const host = {
store,
productionGoal: {
outputId: 'detail',
variantId: 'oak',
requestedOutputs: [
{ outputId: 'detail', variantId: 'oak' },
{ outputId: 'main_images', variantId: 'oak' },
],
},
canvas: {
imageRequest: async () => [],
workflowRead: async ({ outputId = 'detail' }) => ({
available: true,
canvasFirst: true,
outputId,
productVariantId: 'oak',
template: { contentHash: 'tpl-hash' },
totalSlots: 1,
slots: [slot],
}),
detailCopyFields: async () => ({ pages: ['p1'], fields: [] }),
detailHistory: async ({targetOutput}) => ({ outputId:targetOutput.outputId, productVariantId:targetOutput.variantId,
template:{contentHash:'tpl-hash'}, slots:[slot] }),
read: async () => ({ revision: 3 }),
finishProduction: async input => ({
...input,
finalized: false,
deliveryStatus: 'partial_delivered',
files: ['detail.jpg'],
pendingOutputs: [{ outputId: 'main_images', variantId: 'oak' }],
}),
},
};
t.after(() => closeProductionTurn(host));
// Non-working output read_copy_fields is NOT blocked by canvas_inactive
const copyRes = await callProductionTool(host, 'read_copy_fields', { outputId: 'main_images', variantId: 'oak' });
assert.notEqual(copyRes.reason, 'canvas_inactive');
// check_output_screens with matching outputId & variantId passes seamlessly
const screenCopy = await callProductionTool(host, 'read_copy_fields', { outputId: 'detail', variantId: 'oak' });
assert.ok(screenCopy);
// finish_production does not soft-block on unadopted_passed_candidates and maps detail -> 详情页
const finished = await callProductionTool(host, 'finish_production', { outputId: 'detail', variantId: 'oak' });
assert.notEqual(finished.reason, 'unadopted_passed_candidates');
assert.equal(finished.unadoptedPassed[0].slotId, 'slot-1');
assert.match(host.productionDelivery.text, /已导出详情页。/u);
assert.match(host.productionDelivery.text, /主图还待交付。/u);
assert.doesNotMatch(host.productionDelivery.text, /\bdetail\b/u);
assert.doesNotMatch(host.productionDelivery.text, /\bmain_images\b/u);
});
test('acquireXiaoyiRelease downloads missing blobs with 4-way bounded concurrency', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-release-conc-'));
t.after(() => cleanup(dir));
const { zipSync, strToU8 } = await import('fflate');
const entryBytes = strToU8('# entry');
const suppBytes = strToU8('# supp');
const cfgBytes = strToU8(JSON.stringify({ productionProfiles: { fast: {} } }));
const zipBytes = zipSync({ 'SKILL.md': entryBytes, 'supp.md': suppBytes, 'prod.json': cfgBytes });
const assets = Array.from({ length: 8 }, (_, i) => {
const data = Buffer.from(`asset-${i}-${'x'.repeat(64)}`);
return { path: `assets/a${i}.bin`, size: data.length, sha256: sha256(data), data };
});
const manifest = {
schemaVersion: 1,
templateId: 'tpl-1',
version: '1.0.0',
knowledgeVersion: 'tpl-1@1.0.0',
entrypoint: 'SKILL.md',
supplement: 'supp.md',
productionConfig: 'prod.json',
bundle: { size: zipBytes.byteLength, sha256: sha256(zipBytes) },
files: [
{ path: 'SKILL.md', size: entryBytes.byteLength, sha256: sha256(entryBytes) },
{ path: 'supp.md', size: suppBytes.byteLength, sha256: sha256(suppBytes) },
{ path: 'prod.json', size: cfgBytes.byteLength, sha256: sha256(cfgBytes) },
],
assets: assets.map(({ path: p, size, sha256: s }) => ({ path: p, size, sha256: s })),
};
const manifestRaw = Buffer.from(JSON.stringify(manifest));
let inFlightBlobs = 0;
let maxInFlightBlobs = 0;
const fakeFetch = async (url) => {
const u = String(url);
if (u.endsWith('/current')) {
return new Response(JSON.stringify({ version: '1.0.0', manifestSha256: sha256(manifestRaw) }), { status: 200 });
}
if (u.endsWith('/manifest')) {
return new Response(manifestRaw, { status: 200 });
}
if (u.endsWith('/bundle')) {
return new Response(zipBytes, { status: 200 });
}
const blobMatch = u.match(/\/api\/xiaoyi\/v1\/blobs\/([a-f0-9]{64})$/u);
if (blobMatch) {
inFlightBlobs++;
maxInFlightBlobs = Math.max(maxInFlightBlobs, inFlightBlobs);
await new Promise(resolve => setTimeout(resolve, 40));
inFlightBlobs--;
const asset = assets.find(a => a.sha256 === blobMatch[1]);
return new Response(asset.data, { status: 200 });
}
return new Response('not found', { status: 404 });
};
const result = await acquireXiaoyiRelease({
templateId: 'tpl-1',
directory: dir,
cache: path.join(dir, 'cache'),
fetch: fakeFetch,
origin: 'https://example.invalid',
});
assert.equal(result.manifest.version, '1.0.0');
assert.ok(maxInFlightBlobs > 1 && maxInFlightBlobs <= 4, `expected 2..4 concurrent blobs, got ${maxInFlightBlobs}`);
for (const asset of assets) {
const content = await fs.readFile(path.join(result.cache, asset.sha256));
assert.equal(sha256(content), asset.sha256);
}
});