gongxiangp2/apps/detail-agent-pi/test/convergence-and-refs.test.mjs

301 lines
13 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { randomUUID } from 'node:crypto';
import { canonicalProductBrief } from '../src/product-brief.mjs';
import { openProductionOperations } from '../src/production-operations.mjs';
import { callProductionTool } from '../src/production-goal.mjs';
import { scopedProductionBrief } from '../src/production-repository.mjs';
import { selectBestCandidate } from '../src/production-slots.mjs';
import { productionStore } from './production-store-fixture.mjs';
const TINY_PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
const PIXELS = { type: 'image', data: TINY_PNG, mimeType: 'image/png' };
const cleanup = dir => fs.rm(dir, { recursive: true, force: true });
test('selectBestCandidate and candidate-limit auto-adopt pick best candidate and record knownIssues without leaving empty slot', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-142-slot-limit-'));
t.after(() => cleanup(dir));
let selectedCandidateId = null;
const reviewCalls = [];
const candidates = [
{ id: 'cand-1', status: 'complete', sequence: 1 },
{ id: 'cand-2', status: 'complete', sequence: 2 },
];
const slotRecord = {
id: 'slot-1',
fieldId: 'P05',
label: '场景图',
candidates,
generationRequestIds: ['cand-1', 'cand-2'],
get selectedCandidateId() { return selectedCandidateId; },
};
let revision = 1;
const preparedOps = new Map();
const host = {
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak', refinement: false },
canvas: {
workflowRead: async () => ({
available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: 'oak',
template: { contentHash: 'tpl-limit', production: { referenceMode: 'none', autoAdopt: true } },
totalSlots: 1, slots: [slotRecord],
}),
detailCopyFields: async () => ({
revision, pages: ['p1'], fields: [], screenFingerprint: 'fp-1',
progressSummary: { totalScreens: 1, unreviewedScreens: [], screensWithOpenIssues: [], screensReadyForReview: [] },
}),
read: async () => ({ revision }),
detailImages: async (_slotId, candidateId) => ({
candidateId, referenceCount: 1, images: [PIXELS, PIXELS],
}),
detailCandidateScreen: async ({ slotId, candidateId }) => ({
slotId, candidateId, page: 0, screenFingerprint: 'fp-1', imageSlots: [slotId],
overlayLayers: [], copyFields: [], images: [PIXELS],
}),
detailRender: async () => ({ revision, overlayLayers: [] }),
requestWrite: async rev => ({ allowed: true, revision: rev }),
workflowPrepare: async input => ({ operationId: randomUUID(), candidateId: input.candidateId }),
workflowExecute: async input => {
selectedCandidateId = input.candidateId;
revision++;
return { operationId: input.operationId, phase: 'complete', candidateId: input.candidateId, revision };
},
imageRequest: async () => [],
delta: async () => {},
},
runDetailAgent: async (_id, _sys, prompt, [tool]) => {
const {candidateId}=JSON.parse(prompt);
reviewCalls.push(candidateId);
const imageIssues=[{slotId:'slot-1',issue:'阴影偏重',suggestion:'柔化阴影'}];
if(candidateId==='cand-2')imageIssues.push({slotId:'slot-1',issue:'画面误用汽车内饰',suggestion:'使用本款家具实拍'});
await tool.execute('', {
verdict: 'revise',
reason: candidateId==='cand-2'?'画面主体错误':'边缘阴影略重',
imageIssues,
overlayFixes: [],
copyFixes: [],
});
},
};
assert.equal(selectBestCandidate({ candidates }, {
reviewHistory: [
{ candidateId: 'cand-1', verdict: 'revise', mustRedo: [{ problem: 'A' }, { problem: 'B' }] },
{ candidateId: 'cand-2', verdict: 'revise', mustRedo: [{ problem: 'A' }] },
],
}), 'cand-2');
assert.equal(selectBestCandidate({candidates},{}),null);
const actions = await openProductionOperations(host);
host.productionWork=new Map([[JSON.stringify(['detail','oak']),Promise.resolve(actions)]]);
const unreviewed=await callProductionTool(host,'adopt_production_image',{slotId:'slot-1',candidateId:'cand-2'});
assert.equal(unreviewed.verdict,'revise',JSON.stringify(unreviewed));
assert.equal(unreviewed.adopted,false);
assert.equal(selectedCandidateId,null);
await actions.await_image_slots({slotIds:['slot-1'],autoAdopt:true});
assert.deepEqual(reviewCalls,['cand-2','cand-1']);
assert.equal(selectedCandidateId,'cand-1');
const reviewSummary = await actions.review_image_slots({ slotIds: ['slot-1'] });
assert.equal(reviewSummary.pictures[0].selectedCandidateId, 'cand-1');
const finished = await actions.finish_production({});
assert.equal(finished.production.complete, true);
assert.equal(finished.production.slotCoverage.adopted, 1);
assert.equal(finished.production.slotCoverage.empty, 0);
assert.ok(finished.production.issues.some(issue => issue.page === 1 && issue.reason.includes('cand-1')));
await actions.close();
});
test('review_image_slots surfaces bestCandidateId when drawLimitReached and slot is still unadopted', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-142-best-id-'));
t.after(() => cleanup(dir));
const slot = {
id: 'slot-1',
fieldId: 'P05',
label: '场景图',
candidates: [
{ id: 'c1', status: 'complete', sequence: 1, reviewDecision: 'revise' },
{ id: 'c2', status: 'complete', sequence: 2, reviewDecision: 'pass' },
],
generationRequestIds: ['c1', 'c2'],
};
const host = {
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak', refinement: false },
canvas: {
workflowRead: async () => ({
available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: 'oak',
template: { contentHash: 'tpl-best', production: { referenceMode: 'none' } },
totalSlots: 1, slots: [slot],
}),
detailCopyFields: async () => ({ revision: 1, pages: ['p1'], fields: [] }),
imageRequest: async () => [],
delta: async () => {},
},
};
const actions = await openProductionOperations(host);
const res = await actions.review_image_slots({});
assert.equal(res.pictures[0].bestCandidateId, 'c2');
const detail = await actions.review_image_slots({ slotIds: ['slot-1'] });
assert.equal(detail.pictures[0].bestCandidateId, 'c2');
await actions.close();
});
test('screen review converges after max rework rounds (reviewConverged: true) and records residual issues in finish_production', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-142-screen-conv-'));
t.after(() => cleanup(dir));
let round = 0;
let agentCalls = 0;
const host = {
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak' },
canvas: {
workflowRead: async () => ({
available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: 'oak',
template: { contentHash: 'tpl-conv', production: { referenceMode: 'none' } },
totalSlots: 1, slots: [{ id: 'slot-1', fieldId: 'P05', label: '主图', selectedCandidateId: 'c1', candidates: [{ id: 'c1', status: 'complete' }] }],
productEvidence: { brief: { name: '测试品', barcodeEntries: [{ barcode: 'B1', colorName: '原木色' }], detailBarcode: 'B1', images: [{ id: 'img1', source: 'local:' + 'a'.repeat(64) }] } },
}),
detailCopyFields: async () => ({
revision: 10 + round, pages: ['p1'], fields: [], screenFingerprint: `fp-${round}`,
progressSummary: { totalScreens: 1, unreviewedScreens: [], screensWithOpenIssues: [], screensReadyForReview: [] },
}),
read: async () => ({ revision: 10 + round }),
detailImages: async () => ({ referenceCount: 1, images: [PIXELS] }),
detailRender: async () => ({
revision: 10 + round, screenFingerprint: `fp-${round}`, images: [PIXELS, PIXELS], fields: ['P05'], overlayLayers: [],
}),
imageRequest: async () => [],
delta: async () => {},
},
runDetailAgent: async (_id, _sys, _input, [tool]) => {
agentCalls++;
await tool.execute('', {
verdict: 'needs_fix',
summary: '仍有轻微瑕疵',
imageIssues: [{ slotId: 'slot-1', issue: '边缘光影仍略硬', suggestion: '柔化边缘阴影' }],
overlayFixes: [],
copyFixes: [],
});
},
};
const actions = await openProductionOperations(host);
round = 1;
const r1 = (await actions.check_output_screens({ pages: [1], wait: true }))[0];
assert.equal(r1.error, undefined, JSON.stringify(r1));
assert.equal(r1.reviewRound, 1);
assert.equal(r1.reviewConverged, undefined);
round = 2;
const r2 = (await actions.check_output_screens({ pages: [1], wait: true }))[0];
assert.equal(r2.reviewRound, 2);
assert.equal(r2.reviewConverged, undefined);
round = 3;
const r3 = (await actions.check_output_screens({ pages: [1], wait: true }))[0];
assert.equal(r3.reviewRound, 3);
assert.equal(r3.reviewConverged, true);
assert.ok(Array.isArray(r3.residualIssues) && r3.residualIssues.length === 1);
// Round 4 should short-circuit without calling runDetailAgent again
round = 4;
const r4 = (await actions.check_output_screens({ pages: [1], wait: true }))[0];
assert.equal(r4.reviewConverged, true);
assert.equal(r4.reused, true);
assert.equal(agentCalls, 3);
const finished = await actions.finish_production({});
assert.equal(finished.production.complete, true);
assert.ok(finished.production.issues.some(issue => issue.page === 1 && issue.reason.includes('返工上限')));
await actions.close();
});
test('prepare_image_request and dispatch_image_request allow referenceMode="none" to override template-base', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-142-refmode-'));
t.after(() => cleanup(dir));
const prepared = [];
const dispatched = [];
const host = {
store: productionStore(dir),
productionGoal: { outputId: 'detail', variantId: 'oak' },
canvas: {
workflowRead: async () => ({
available: true, canvasFirst: true, version: 1, outputId: 'detail', productVariantId: 'oak',
template: { contentHash: 'tpl-ref', production: { referenceMode: 'template-base' } },
totalSlots: 1, slots: [{ id: 'slot-1', fieldId: 'P05', label: '场景图' }],
}),
detailCopyFields: async () => ({ revision: 1, pages: ['p1'], fields: [] }),
detailImages: async () => ({ referenceCount: 1, images: [PIXELS] }),
imageRequest: async (action, args) => {
if (action === 'prepare') {
prepared.push(args);
return { requestId: 'req-1', revision: 1, requestSpecHash: 'hash-1', outputId: 'detail', variantId: 'oak', slotId: 'slot-1', spec: { prompt: args.instructions } };
}
if (action === 'read') {
return { requestId: 'req-1', phase: 'prepared', revision: 1, requestSpecHash: 'hash-1', outputId: 'detail', variantId: 'oak', slotId: 'slot-1' };
}
if (action === 'dispatch') {
dispatched.push(args);
return { id: 'cand-1', status: 'complete' };
}
if (action === 'pending') {
return [];
}
throw Error('unexpected action ' + action);
},
delta: async () => {},
},
};
const actions = await openProductionOperations(host);
await actions.prepare_image_request({
slotId: 'slot-1',
prompt: '直腿电脑桌放在明亮书房中',
productReferences: ['P01'],
referenceMode: 'none',
});
assert.equal(prepared.at(-1).useTemplateBase, false);
assert.equal(prepared.at(-1).referenceMode, 'none');
await actions.dispatch_image_request({ requestId: 'req-1', referenceMode: 'none' });
assert.equal(dispatched.at(-1).useTemplateBase, false);
assert.equal(dispatched.at(-1).referenceMode, 'none');
await actions.close();
});
test('briefImages falls back to product-level or sibling variant/barcode images when current scope has none', () => {
const hash1 = 'a'.repeat(64);
const brief = {
name: '电脑桌',
variants: [
{ id: 'v1', colorName: '原木色', images: [{ id: 'img-v1', source: `local:${hash1}`, kind: 'whiteBackground', name: '白底图.jpg' }] },
{ id: 'v2', colorName: '胡桃色', images: [] },
],
barcodeEntries: [
{ barcode: 'B1', variantId: 'v1', colorName: '原木色' },
{ barcode: 'B2', variantId: 'v2', colorName: '胡桃色' },
],
};
const scopedV2 = scopedProductionBrief(brief, 'v2', 'sku_images');
assert.equal(scopedV2.brief.images.length, 1);
assert.equal(scopedV2.brief.images[0].id, 'img-v1');
assert.equal(scopedV2.brief.images[0].inherited, true);
assert.equal(scopedV2.brief.images[0].fallbackSource, 'variant:v1');
const canonicalV2 = canonicalProductBrief(brief, { variantId: 'v2', barcodes: ['B2'] });
assert.equal(canonicalV2.images.length, 1);
assert.equal(canonicalV2.images[0].inherited, true);
});