为小壹原生子代理补全复核退回回执和轮数预算
This commit is contained in:
parent
6504b620ab
commit
67ff51b37d
@ -17,6 +17,7 @@ import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, Model
|
||||
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat';
|
||||
import { atomic } from './store.mjs';
|
||||
import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs';
|
||||
import { workerTurnBudget } from './worker-receipts.mjs';
|
||||
import { createImageContextPruningExtension } from './image-context-pruning.mjs';
|
||||
import { productContext } from './project-context.mjs';
|
||||
import { workflowContext, workflowResult } from './workflow-context.mjs';
|
||||
@ -578,9 +579,19 @@ export class DetailPiAgent {
|
||||
const worker = {slotId,requestScope,broker:scoped,signal:activeSignal,systemPrompt:systemPrompt+'\n'+PRODUCT_VOICE,
|
||||
cacheKey:host.manager.getSessionId()+':'+(kind==='product'?step:tools[0]?.name??'detail')};
|
||||
const abort = () => { void workerSession.abort(); };
|
||||
const budget = workerTurnBudget(slotId);
|
||||
const finishTurn = workerSession.agent.finishTurn;
|
||||
workerSession.agent.finishTurn = async (turn, turnSignal) => {
|
||||
const decision = await finishTurn(turn,turnSignal);
|
||||
const limit = budget.finishTurn();
|
||||
// Native Pi may retry a failed model turn after the agent loop ends.
|
||||
if(limit && turn.message.stopReason==='error')abort();
|
||||
return limit ?? decision;
|
||||
};
|
||||
workers.set(sessionId,worker);
|
||||
activeSignal?.addEventListener('abort',abort,{once:true});
|
||||
const unsubscribe = workerSession.subscribe(event=>{
|
||||
budget.observe(event);
|
||||
if(event.type==='tool_execution_start'||event.type==='tool_execution_end'){
|
||||
const activity=toolActivity(event,host.activityScope||activityScope(store.identity));
|
||||
void recordToolEvent(event,activity,{slotId,requestScope})
|
||||
@ -593,6 +604,7 @@ export class DetailPiAgent {
|
||||
captions?[{type:'text',text:captions[index]},image]:[image])] : prompt;
|
||||
await workerSession.sendCustomMessage({customType:'photocraft-worker-task',content,display:false},{triggerTurn:true});
|
||||
activeSignal?.throwIfAborted();
|
||||
if(budget.failure)throw budget.failure;
|
||||
const result = workerSession.messages.findLast(message=>message.role==='assistant');
|
||||
if (result?.stopReason==='length') throw Error('模型回复达到单次输出长度,当前制作步骤未完成');
|
||||
if (result?.stopReason==='error'||result?.stopReason==='aborted') {
|
||||
|
||||
@ -2,6 +2,7 @@ import { Type } from '@sinclair/typebox';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { InvalidToolReply } from './response-audit.mjs';
|
||||
import { mergeReviewCopy } from './copy-image-alignment.mjs';
|
||||
import { validateWorkerArguments } from './worker-receipts.mjs';
|
||||
|
||||
const params = properties => Type.Object(properties,{additionalProperties:false});
|
||||
const tool = (name, description, parameters, execute) => ({
|
||||
@ -67,10 +68,21 @@ export async function reviewProductionCandidate({
|
||||
...(guides.length?{structureGuides:Type.Optional(params(Object.fromEntries(guides.map(([id,spec])=>
|
||||
[id,Type.Array(guidePoint,{description:typeof spec==='string'?spec:spec.target})]))))}:null),
|
||||
});
|
||||
const fields=screenCopy.filter(row=>row.field!==undefined).map(row=>row.field);
|
||||
const facts=()=>[
|
||||
`本次可用 candidateId ${JSON.stringify(candidateId)}`,
|
||||
`本次图位 slotId ${JSON.stringify(slot.id)}`,
|
||||
`本次可用 field ${JSON.stringify(fields)}`,
|
||||
...(guides.length?[`本次结构标注编号 ${JSON.stringify(guides.map(([id])=>id))}`]:[]),
|
||||
].join('\n');
|
||||
let receipt;
|
||||
const review=tool('review_candidate','提交对候选图的独立结论、理由和画面依据。',assessment,value=>{
|
||||
if(value.candidateId!==candidateId)throw Error('验图候选编号不一致');
|
||||
if(!['pass','revise','missing'].includes(value.verdict))throw new InvalidToolReply('请明确填写候选的验图结论');
|
||||
const errors=[];
|
||||
if(value.candidateId!==candidateId)errors.push(`candidateId ${JSON.stringify(value.candidateId)} 与本次受审候选不一致`);
|
||||
value.shownFields?.forEach(({field},index)=>{
|
||||
if(!fields.includes(field))errors.push(`shownFields[${index}].field ${JSON.stringify(field)} 不在本次文案清单中`);
|
||||
});
|
||||
if(errors.length)throw new InvalidToolReply([...errors,facts()].join('\n'));
|
||||
receipt={candidateId,verdict:value.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform,
|
||||
checks:value.checks,reason:value.reason,shownSubject:value.shownSubject,observation:{
|
||||
source,shownSubject:value.shownSubject,reviewedCopy,visualEvidence:value.shownFields??[],
|
||||
@ -81,6 +93,7 @@ export async function reviewProductionCandidate({
|
||||
const details={verdict:receipt.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform};
|
||||
return {content:[{type:'text',text:JSON.stringify(details)}],details,terminate:true};
|
||||
});
|
||||
review.prepareArguments=value=>validateWorkerArguments(review.name,assessment,value,facts);
|
||||
const requirements=rule?.focus??input.prompt??input.requirements;
|
||||
const prompt=JSON.stringify({candidateId,fieldId:slot.fieldId,slot:slot.label,rule,requirements,
|
||||
templateContext:requirements===input.requirements?undefined:input.requirements,
|
||||
|
||||
@ -15,6 +15,7 @@ import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
|
||||
import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs';
|
||||
import { reviewOutputScreen } from './screen-review.mjs';
|
||||
import { createTailWatcher } from './tail-watcher.mjs';
|
||||
import { validateWorkerArguments } from './worker-receipts.mjs';
|
||||
|
||||
const {frontmatter: {maxGenerationAttempts: defaultGenerationLimit}} = parseFrontmatter(
|
||||
readFileSync(new URL('./skills/product-image-sources/SKILL.md', import.meta.url), 'utf8'),
|
||||
@ -698,9 +699,10 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const preparedRequest=async(requestId,slot)=>{
|
||||
const receipt=await canvas.imageRequest('read',{requestId});
|
||||
if(receipt.requestId!==requestId||receipt.templateHash!==plan.template.contentHash||
|
||||
receipt.outputId!==outputId||receipt.variantId!==variantId||slot&&receipt.slotId!==slot.id){
|
||||
throw Error('生图请求不属于本轮工作画布或委托图位');
|
||||
receipt.outputId!==outputId||receipt.variantId!==variantId){
|
||||
throw Error(`requestId ${JSON.stringify(requestId)} 不属于当前模板、成品或花色,请使用当前画布生图准备回执中的 requestId`);
|
||||
}
|
||||
if(slot&&receipt.slotId!==slot.id)throw Error(`requestId ${JSON.stringify(requestId)} 属于图位 ${receipt.slotId},本次委托图位 slotId 为 ${slot.id}`);
|
||||
return receipt;
|
||||
};
|
||||
const dispatchImageRequest=async(slot,approval,request,workerNumber,onEnqueued)=>{
|
||||
@ -1053,20 +1055,24 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const row={number:nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'排队中',active:true};
|
||||
let rework, produced=false;
|
||||
const dispatched=new Set();
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>({
|
||||
name,label:description,description,parameters:obj(properties),executionMode:'sequential',
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
const activeSignal=workerSignal?AbortSignal.any([workerSignal,delegateSignal]):delegateSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const result=await execute(args,activeSignal);
|
||||
const done=typeof terminate==='function'?terminate(result):terminate;
|
||||
if(terminate||name==='transform_slot_image'){
|
||||
produced=true;
|
||||
if(name==='use_product_image'||name==='transform_slot_image')generation.set(workerId,{slotId:slot.id,...result});
|
||||
}
|
||||
return {...imageResult(result),...(done?{terminate:true}:null)};
|
||||
},
|
||||
});
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>{
|
||||
const parameters=obj(properties);
|
||||
return {
|
||||
name,label:description,description,parameters,executionMode:'sequential',
|
||||
...(terminate?{prepareArguments:args=>validateWorkerArguments(name,parameters,args,()=>`本次委托图位 slotId ${JSON.stringify(slot.id)}`)}:null),
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
const activeSignal=workerSignal?AbortSignal.any([workerSignal,delegateSignal]):delegateSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const result=await execute(args,activeSignal);
|
||||
const done=typeof terminate==='function'?terminate(result):terminate;
|
||||
if(terminate||name==='transform_slot_image'){
|
||||
produced=true;
|
||||
if(name==='use_product_image'||name==='transform_slot_image')generation.set(workerId,{slotId:slot.id,...result});
|
||||
}
|
||||
return {...imageResult(result),...(done?{terminate:true}:null)};
|
||||
},
|
||||
};
|
||||
};
|
||||
const makeTools=()=>[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>useProductImage(slot,args,activeSignal)),true),
|
||||
@ -1076,7 +1082,17 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal))),
|
||||
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
|
||||
(approval,activeSignal)=>onCanvas(activeSignal,async()=>{
|
||||
const request=await preparedRequest(approval.requestId,slot);
|
||||
const request=await preparedRequest(approval.requestId,slot).catch(error=>{
|
||||
throw Error(`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}。请核对当前图位的生图准备回执。原因:${error.message}`,{cause:error});
|
||||
});
|
||||
const errors=[];
|
||||
if(approval.expectedRevision!==undefined&&approval.expectedRevision!==request.revision){
|
||||
errors.push(`expectedRevision ${approval.expectedRevision} 与准备回执不一致,可用值为 ${request.revision}`);
|
||||
}
|
||||
if(approval.expectedHash!==undefined&&approval.expectedHash!==request.requestSpecHash){
|
||||
errors.push(`expectedHash ${JSON.stringify(approval.expectedHash)} 与准备回执不一致,可用值为 ${JSON.stringify(request.requestSpecHash)}`);
|
||||
}
|
||||
if(errors.length)throw Error([`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}`,...errors].join('\n'));
|
||||
row.step='正在生图';
|
||||
notice('子代理正在生图');
|
||||
const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number);
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { InvalidToolReply } from './response-audit.mjs';
|
||||
import { digest } from './store.mjs';
|
||||
import { validateWorkerArguments } from './worker-receipts.mjs';
|
||||
|
||||
export function screenReviewScope(variantId, outputId, page) {
|
||||
// The broker accepts a UUID for a review scope. Keeping it stable lets the broker
|
||||
@ -21,8 +21,8 @@ const assessment = object({
|
||||
verdict:Type.Union([Type.Literal('pass'),Type.Literal('needs_fix')]),
|
||||
summary:text(280),
|
||||
imageIssues:finding({slotId:Type.Optional(text(200)),location:text(160)}),
|
||||
overlayFixes:finding({nativeLayerId:Type.Integer({minimum:1})}),
|
||||
copyFixes:finding({field:text(200)}),
|
||||
overlayFixes:finding({nativeLayerId:Type.Optional(Type.Integer({minimum:1})),location:Type.Optional(text(160))}),
|
||||
copyFixes:finding({field:Type.Optional(text(200)),location:Type.Optional(text(160))}),
|
||||
});
|
||||
|
||||
export async function reviewOutputScreen({runAgent, page, screen, references, slots, outputId, variantId, signal}) {
|
||||
@ -36,22 +36,42 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
|
||||
const layerIds = new Set(overlayLayers.map(layer => layer.nativeLayerId));
|
||||
const fields = new Set(screenCopy.map(row => row.field));
|
||||
const slotIds = new Set(slots.map(slot => slot.id));
|
||||
const facts=()=>[
|
||||
`本屏可用 nativeLayerId ${JSON.stringify(overlayLayers.map(({nativeLayerId,name,text})=>({nativeLayerId,name,text})))}`,
|
||||
`本屏可用 slotId ${JSON.stringify(slots.map(({id,label,fieldId})=>({slotId:id,label,fieldId})))}`,
|
||||
`本屏可用 field ${JSON.stringify(screenCopy.map(({field,label})=>({field,label})))}`,
|
||||
'找不到对应条目时,省略编号并填写 location。',
|
||||
].join('\n');
|
||||
let receipt;
|
||||
const tool = {
|
||||
name:'review_output_screen',
|
||||
label:'提交本屏复核',
|
||||
description:'提交整屏实际画面的复核结论、问题位置与修改建议。',
|
||||
parameters:assessment,
|
||||
prepareArguments:value=>validateWorkerArguments('review_output_screen',assessment,value,facts),
|
||||
execute:(_id, value) => {
|
||||
if (!Value.Check(assessment, value)) throw new InvalidToolReply('请按字段提交简短的复核结论和修改建议');
|
||||
const {verdict,summary,imageIssues,overlayFixes,copyFixes} = value;
|
||||
const hasIssues = imageIssues.length + overlayFixes.length + copyFixes.length > 0;
|
||||
if (hasIssues !== (verdict === 'needs_fix') ||
|
||||
imageIssues.some(issue => issue.slotId !== undefined && !slotIds.has(issue.slotId)) ||
|
||||
overlayFixes.some(fix => !layerIds.has(fix.nativeLayerId)) ||
|
||||
copyFixes.some(fix => !fields.has(fix.field))) {
|
||||
throw new InvalidToolReply('请提交与本屏图位、叠层和文案相符的复核结论');
|
||||
const errors=[];
|
||||
if (hasIssues !== (verdict === 'needs_fix')) {
|
||||
errors.push(hasIssues?'verdict 为 pass,但问题列表有内容':'verdict 为 needs_fix,但三组问题列表均为空');
|
||||
}
|
||||
for (const [group,findings,key,allowed,inventory] of [
|
||||
['imageIssues',imageIssues,'slotId',slotIds,'图位'],
|
||||
['overlayFixes',overlayFixes,'nativeLayerId',layerIds,'叠层'],
|
||||
['copyFixes',copyFixes,'field',fields,'文案'],
|
||||
]) {
|
||||
findings.forEach((finding,index)=>{
|
||||
const id=finding[key];
|
||||
if (id===undefined && !finding.location?.trim()) {
|
||||
errors.push(`${group}[${index}].location 缺少画面位置,未填写 ${key} 时必填`);
|
||||
}
|
||||
if (id!==undefined && !allowed.has(id)) {
|
||||
errors.push(`${group}[${index}].${key} ${JSON.stringify(id)} 不在本屏${inventory}清单中`);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (errors.length) throw new InvalidToolReply([...errors,facts()].join('\n'));
|
||||
receipt = {page,revision,verdict,summary,imageIssues,overlayFixes,copyFixes};
|
||||
return {content:[{type:'text',text:'已收到本屏复核结论'}],details:{verdict},terminate:true};
|
||||
},
|
||||
@ -60,6 +80,7 @@ export async function reviewOutputScreen({runAgent, page, screen, references, sl
|
||||
const instructions = [
|
||||
'复核整屏成片。第一张是整屏实际画面,后续是本款实拍。',
|
||||
'用 review_output_screen 提交结论、画面依据和修改建议。图片问题填写 location 和已知 slotId,叠层问题填写 overlayLayers 中的 nativeLayerId,正文问题填写 screenCopy 中的 field。',
|
||||
'找不到对应叠层或文案字段时,省略编号并用 location 描述在画面中的具体位置。',
|
||||
'有问题时填写 needs_fix 和至少一项问题。通过时三组问题均为空。',
|
||||
].join('\n');
|
||||
const prompt = JSON.stringify({page,revision,product,slots,screenCopy,overlayLayers,productReferenceCount:photos.length});
|
||||
|
||||
36
apps/detail-agent-pi/src/worker-receipts.mjs
Normal file
36
apps/detail-agent-pi/src/worker-receipts.mjs
Normal file
@ -0,0 +1,36 @@
|
||||
import { validateToolArguments } from '@earendil-works/pi-ai';
|
||||
import { InvalidToolReply } from './response-audit.mjs';
|
||||
|
||||
export function validateWorkerArguments(name, parameters, args, facts) {
|
||||
try {
|
||||
return validateToolArguments({name,parameters},{name,arguments:args});
|
||||
} catch (error) {
|
||||
throw new InvalidToolReply(`${error.message}\n${facts()}`);
|
||||
}
|
||||
}
|
||||
|
||||
// R4 实机正常复核用 2–6 轮,再留 4 轮用于根据回执纠正。
|
||||
export const WORKER_TURN_LIMIT = 10;
|
||||
|
||||
export function workerTurnBudget(slotId) {
|
||||
let turns=0, submitted=false, lastRejection, failure;
|
||||
return {
|
||||
observe(event) {
|
||||
if (event.type!=='tool_execution_end') return;
|
||||
if (event.isError) {
|
||||
lastRejection=event.result.content.filter(item=>item.type==='text').map(item=>item.text).join('\n');
|
||||
} else if (event.result.terminate) {
|
||||
submitted=true;
|
||||
}
|
||||
},
|
||||
finishTurn() {
|
||||
if (++turns<WORKER_TURN_LIMIT) return;
|
||||
if (!submitted) {
|
||||
const reason=lastRejection ? `\n最后一次退回原因\n${lastRejection}` : '';
|
||||
failure=Error(`子代理 ${slotId} 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论。${reason}`);
|
||||
}
|
||||
return {action:'end'};
|
||||
},
|
||||
get failure() { return failure; },
|
||||
};
|
||||
}
|
||||
@ -10,6 +10,7 @@ import { EventEmitter } from 'node:events';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
import { WORKER_TURN_LIMIT } from '../src/worker-receipts.mjs';
|
||||
import { auditResponse, InvalidToolReply } from '../src/response-audit.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
import { decodeToolReply } from '../src/json-tool-codec.mjs';
|
||||
@ -816,7 +817,6 @@ test('a worker can change course after many identical calls without terminating'
|
||||
const x=await setup((payload,round)=>{
|
||||
imageCounts.push(payload.messages.reduce((count,{content})=>count+
|
||||
(Array.isArray(content)?content.filter(part=>part.type==='image_url').length:0),0));
|
||||
if(round===12)return sse({content:'核对完成。'},'stop');
|
||||
return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'read_slot_images',
|
||||
arguments:JSON.stringify({item:round===10?'other':'same'})}}]},'tool_calls');
|
||||
},undefined,undefined,{canvas:{}});
|
||||
@ -824,12 +824,27 @@ test('a worker can change course after many identical calls without terminating'
|
||||
const tool={name:'read_slot_images',label:'Inspect item',description:'Inspect item',parameters:{type:'object',properties:{item:{type:'string'}},required:['item']},
|
||||
async execute(_id,{item}){
|
||||
calls.push(item);
|
||||
return {content:[{type:'text',text:item},image],details:{item}};
|
||||
return {content:[{type:'text',text:item},image],details:{item},terminate:item==='other'};
|
||||
}};
|
||||
await x.host.runDetailAgent('slot-a','Inspect the item.','Read the fixture.',[tool],[],'product/slot/slot-a');
|
||||
assert.deepEqual(calls,[...Array(9).fill('same'),'other','same']);
|
||||
assert.deepEqual(imageCounts,[0,...Array(11).fill(1)]);
|
||||
assert.equal(x.requests.length,12);
|
||||
assert.deepEqual(calls,[...Array(9).fill('same'),'other']);
|
||||
assert.deepEqual(imageCounts,[0,...Array(9).fill(1)]);
|
||||
assert.equal(x.requests.length,10);
|
||||
});
|
||||
|
||||
test('a retryable response at the worker limit does not trigger another Pi request',async t=>{
|
||||
const x=await setup((_payload,round)=>{
|
||||
if(round>=WORKER_TURN_LIMIT)return new Response('overloaded',{status:503});
|
||||
return sse({tool_calls:[{index:0,id:`worker-${round}`,type:'function',function:{name:'submit',
|
||||
arguments:'{}'}}]},'tool_calls');
|
||||
},undefined,undefined,{canvas:{}});
|
||||
t.after(x.close);
|
||||
const tool={name:'submit',label:'Submit',description:'Submit',parameters:{type:'object',properties:{}},
|
||||
execute(){throw Error('未找到受审编号,可用编号是 13');}};
|
||||
await assert.rejects(x.host.runDetailAgent('screen-13','Inspect.','Review.',[tool],[]),
|
||||
error=>error.message.includes(`screen-13 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`)&&
|
||||
error.message.includes('未找到受审编号,可用编号是 13'));
|
||||
assert.equal(x.requests.length,WORKER_TURN_LIMIT);
|
||||
});
|
||||
|
||||
test('Pi project tools share the same file boundary',async()=>{
|
||||
|
||||
@ -3,11 +3,16 @@ import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
|
||||
import { activityToolLabel, toolActivity } from '../src/activity-event.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
import { openProductionOperations, productionOperationTools } from '../src/production-operations.mjs';
|
||||
import { callProductionTool } from '../src/production-goal.mjs';
|
||||
import { screenReviewScope } from '../src/screen-review.mjs';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { WORKER_TURN_LIMIT } from '../src/worker-receipts.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
import { productionStore } from './production-store-fixture.mjs';
|
||||
|
||||
@ -22,6 +27,44 @@ const needsFix={
|
||||
copyFixes:[{field:'title-2',issue:'文案把涂装当成木种',suggestion:'改成橡胶木深木色涂装'}],
|
||||
};
|
||||
|
||||
async function usePiWorker(t,host,name,reply) {
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-worker-receipt-'));
|
||||
const scope='a'.repeat(64);
|
||||
const store=await ProjectStore.open(dir,{scope,project:randomUUID()},{brandId:'qa',shopId:'qa',categoryId:'qa',
|
||||
platform:'qa',version:'1',source:'worker-receipt-test',rules:['仅使用离线夹具']});
|
||||
const writes=[];
|
||||
const appendEvent=store.appendEvent.bind(store);
|
||||
store.appendEvent=event=>{
|
||||
const write=appendEvent(event);
|
||||
writes.push(write);
|
||||
return write;
|
||||
};
|
||||
let calls=0;
|
||||
const sdk=await DetailPiAgent.open({store,transport:{info:{accountScope:scope,model:{id:'qa-model',protocol:'openai-chat'}},
|
||||
stream(model,context){
|
||||
assert.ok(++calls<=WORKER_TURN_LIMIT,'Pi attempted another request after exhausting the worker budget');
|
||||
const args=reply(calls,context.messages.findLast(message=>message.role==='toolResult'));
|
||||
const content=[{type:'toolCall',name,id:`submit-${calls}`,arguments:args}];
|
||||
const output=createAssistantMessageEventStream();
|
||||
const message={role:'assistant',api:model.api,provider:model.provider,model:model.id,content,stopReason:'toolUse',
|
||||
timestamp:Date.now(),usage:{input:1,output:1,cacheRead:0,cacheWrite:0,totalTokens:2,
|
||||
cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}};
|
||||
queueMicrotask(()=>{
|
||||
output.push({type:'start',partial:message});
|
||||
output.push({type:'done',reason:'toolUse',message});
|
||||
output.end(message);
|
||||
});
|
||||
return output;
|
||||
},
|
||||
}});
|
||||
t.after(async()=>{await sdk.dispose();await cleanup(dir);});
|
||||
host.runDetailAgent=sdk.runDetailAgent;
|
||||
return {calls:()=>calls,async events(){
|
||||
await Promise.all(writes);
|
||||
return (await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
|
||||
}};
|
||||
}
|
||||
|
||||
async function fixture(t) {
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-screen-review-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
@ -40,7 +83,7 @@ async function fixture(t) {
|
||||
state.reads.push(page);
|
||||
if(page>=pages.length)throw Error('此屏不属于当前工作画布');
|
||||
return {page,revision:state.revision,images:[pixels],fields:[slots[page].fieldId],
|
||||
...(state.overlay?{overlayLayers:[{nativeLayerId:201+page,text:'旧尺寸',overlapsSlots:[slots[page].fieldId]}]}:null)};
|
||||
...(state.overlay?{overlayLayers:[{nativeLayerId:201+page,name:'尺寸标注',text:'旧尺寸',overlapsSlots:[slots[page].fieldId]}]}:null)};
|
||||
},
|
||||
detailImages:async(_slot,_candidate,options)=>{
|
||||
assert.equal(options.includeTemplateReference,false);
|
||||
@ -63,7 +106,7 @@ test('screen reviews keep images in the worker and record only the verified scre
|
||||
assert.match(scope,/^product\/review\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/);
|
||||
assert.equal(revision,7);
|
||||
assert.equal(product.variant.colorName,'深木色');
|
||||
assert.deepEqual(overlayLayers[0],{nativeLayerId:200+page,text:'旧尺寸',overlapsSlots:[slots[0].fieldId]});
|
||||
assert.deepEqual(overlayLayers[0],{nativeLayerId:200+page,name:'尺寸标注',text:'旧尺寸',overlapsSlots:[slots[0].fieldId]});
|
||||
assert.equal(screenCopy[0].field,`title-${page}`);
|
||||
assert.equal(slots[0].id,`slot-${page}`);
|
||||
assert.deepEqual(images,[pixels,pixels]);
|
||||
@ -86,6 +129,92 @@ test('screen reviews keep images in the worker and record only the verified scre
|
||||
[[0,7,[],{100:'橡胶木桌面'}]]);
|
||||
});
|
||||
|
||||
test('Pi returns all invalid screen targets and accepts the corrected and location-only findings', {timeout:10_000}, async t=>{
|
||||
const {host,actions}=await fixture(t);
|
||||
const locationOnly={...needsFix,
|
||||
overlayFixes:[{location:'右上方角标',issue:'角标压住标题',suggestion:'挪到标题上方'}],
|
||||
copyFixes:[{location:'图片下沿',issue:'合成图残留旧规格',suggestion:'改为实际规格'}],
|
||||
};
|
||||
const worker=await usePiWorker(t,host,'review_output_screen',(round,previous)=>{
|
||||
if(round===1)return {...needsFix,verdict:'pass',
|
||||
imageIssues:[{...needsFix.imageIssues[0],slotId:'wrong-slot'}],
|
||||
overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:999}],
|
||||
copyFixes:[{...needsFix.copyFixes[0],field:'wrong-field'},{issue:'规格错误',suggestion:'改成实际规格'}],
|
||||
};
|
||||
assert.equal(round,2);
|
||||
assert.equal(previous.isError,true);
|
||||
const reason=previous.content[0].text;
|
||||
for(const fact of ['verdict 为 pass','imageIssues[0].slotId "wrong-slot"','overlayFixes[0].nativeLayerId 999',
|
||||
'copyFixes[0].field "wrong-field"','copyFixes[1].location','"nativeLayerId":202','"name":"尺寸标注"',
|
||||
'"text":"旧尺寸"','"slotId":"slot-2"','"field":"title-2"'])assert.ok(reason.includes(fact),reason);
|
||||
return locationOnly;
|
||||
});
|
||||
assert.deepEqual(await actions.check_output_screens({pages:[2],wait:true}),[{page:2,revision:7,...locationOnly}]);
|
||||
assert.equal(worker.calls(),2);
|
||||
});
|
||||
|
||||
test('waiting screen review returns its last rejection when Pi reaches the turn limit', {timeout:10_000}, async t=>{
|
||||
const {host,actions}=await fixture(t);
|
||||
const worker=await usePiWorker(t,host,'review_output_screen',round=>({
|
||||
...needsFix,overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:900+round}],
|
||||
}));
|
||||
const [receipt]=await actions.check_output_screens({pages:[2],wait:true});
|
||||
assert.equal(worker.calls(),WORKER_TURN_LIMIT);
|
||||
assert.equal(receipt.page,2);
|
||||
assert.ok(receipt.error.includes(`screen-2 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`));
|
||||
assert.ok(receipt.error.includes(`最后一次退回原因\noverlayFixes[0].nativeLayerId ${900+WORKER_TURN_LIMIT}`));
|
||||
assert.deepEqual((await actions.await_image_slots({})).screenChecks,[receipt]);
|
||||
const scope=screenReviewScope(variantId,outputId,2);
|
||||
const events=(await worker.events()).filter(event=>event.slotId==='screen-2'&&event.requestScope===scope);
|
||||
const starts=events.filter(event=>event.type==='tool_execution_start');
|
||||
const ends=events.filter(event=>event.type==='tool_execution_end');
|
||||
assert.equal(starts.length,WORKER_TURN_LIMIT);
|
||||
assert.equal(ends.length,WORKER_TURN_LIMIT);
|
||||
assert.ok(ends.every(event=>event.isError&&event.toolName==='review_output_screen'));
|
||||
assert.deepEqual(ends.map(event=>event.toolCallId).sort(),starts.map(event=>event.toolCallId).sort());
|
||||
});
|
||||
|
||||
test('await_image_slots releases a candidate review that never submits a valid conclusion', {timeout:10_000}, async t=>{
|
||||
const {host,actions}=await fixture(t);
|
||||
const candidateId=randomUUID();
|
||||
host.canvas.detailImages=async()=>({candidateId,referenceCount:1,images:[pixels,pixels],
|
||||
relatedCopy:[{field:'wood',text:'橡胶木'}]});
|
||||
const worker=await usePiWorker(t,host,'review_candidate',(round,previous)=>{
|
||||
if(round>1){
|
||||
const reason=previous.content[0].text;
|
||||
for(const fact of [`candidateId "wrong-${round-1}"`,`本次可用 candidateId "${candidateId}"`,
|
||||
'shownFields[0].field "unknown"','本次可用 field ["wood","title-2"]'])assert.ok(reason.includes(fact),reason);
|
||||
}
|
||||
return {candidateId:`wrong-${round}`,verdict:'pass',reason:'与原图相符',
|
||||
checks:{structure:true,color:true,composition:true,evidence:true},shownFields:[{field:'unknown',location:'画面中央'}]};
|
||||
});
|
||||
await actions.check_image_slots({candidates:[{slotId:'slot-2',candidateId}]});
|
||||
const result=await actions.await_image_slots({slotIds:['slot-2']});
|
||||
assert.equal(worker.calls(),WORKER_TURN_LIMIT,JSON.stringify(result.checks));
|
||||
assert.equal(result.checking,0);
|
||||
assert.equal(result.checks[0].candidateId,candidateId);
|
||||
assert.ok(result.checks[0].error.includes(`slot-2 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`));
|
||||
assert.ok(result.checks[0].error.includes(`candidateId "wrong-${WORKER_TURN_LIMIT}"`));
|
||||
});
|
||||
|
||||
test('a candidate can correct a schema rejection and submit on the last allowed turn', {timeout:10_000}, async t=>{
|
||||
const {host,actions}=await fixture(t);
|
||||
const candidateId=randomUUID();
|
||||
host.canvas.detailImages=async()=>({candidateId,referenceCount:1,images:[pixels,pixels]});
|
||||
const worker=await usePiWorker(t,host,'review_candidate',(round,previous)=>{
|
||||
if(round>1){
|
||||
assert.equal(previous.isError,true);
|
||||
assert.match(previous.content[0].text,/checks\.structure/);
|
||||
assert.ok(previous.content[0].text.includes(`本次可用 candidateId "${candidateId}"`));
|
||||
}
|
||||
return {candidateId,verdict:'pass',reason:'与原图相符',
|
||||
checks:{color:true,composition:true,evidence:true,...(round===WORKER_TURN_LIMIT?{structure:true}:null)}};
|
||||
});
|
||||
const [receipt]=await actions.check_image_slots({candidates:[{slotId:'slot-2',candidateId}],wait:true});
|
||||
assert.equal(worker.calls(),WORKER_TURN_LIMIT,receipt.error);
|
||||
assert.equal(receipt.verdict,'pass');
|
||||
});
|
||||
|
||||
test('finish and progress forward review revisions for the real canvas summary',async t=>{
|
||||
const {host,state}=await fixture(t);
|
||||
const {canvas}=host;
|
||||
@ -173,7 +302,7 @@ test('screen review refuses unsupported evidence, invalid targets and stale pass
|
||||
const fix={...needsFix,imageIssues:[],copyFixes:[],overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:999}]};
|
||||
tool.execute('',fix);
|
||||
};
|
||||
assert.match((await actions.check_output_screens({pages:[2]}))[0].error,/相符的复核结论/);
|
||||
assert.match((await actions.check_output_screens({pages:[2]}))[0].error,/overlayFixes\[0\]\.nativeLayerId 999 不在本屏叠层清单中/);
|
||||
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>{
|
||||
tool.execute('',pass);
|
||||
state.revision++;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user