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

238 lines
13 KiB
JavaScript

import { BridgeError } from '../src/bridge-error.mjs';
import { productionExportReceipt, stubProductionOperations } from './production-store-fixture.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import { randomUUID } from 'node:crypto';
import { ProjectStore } from '../src/store.mjs';
import { openAgent } from './fake-canvas.mjs';
import { cleanup } from './cleanup.mjs';
const setup = async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
const scope = 'd'.repeat(64), project = randomUUID();
const store = await ProjectStore.open(root, { scope, project }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', source: 'qa', version: '1', rules: [] });
return { root, scope, store };
};
test('project lease rejects another process/session before opening transcript or posting', async () => {
const { root, scope, store } = await setup();
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' } } };
const a = await openAgent({ store, transport });
await assert.rejects(openAgent({ store, transport }), /已有本地Agent/);
await a.dispose();
const b = await openAgent({ store, transport });
await b.dispose(); await cleanup(root);
});
test('a waiting detail original does not hold independent main image and SKU goals',async t=>{
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const variantId=randomUUID(),originalId=randomUUID();
const model={id:'qa',protocol:'openai-chat',supportsImageInput:true};
const original={id:originalId,modelRole:'detail',phase:'unknown',detailSlot:'product/goal/'+variantId+'/detail'};
const offered=[];
const workspaceId=randomUUID();
const requestedOutputs=['detail','main_images','sku_images'].map(outputId=>({outputId,variantId}));
for(const {outputId} of requestedOutputs.slice(1)){
const goal={outputId,variantId,workspaceId,requestedOutputs};
const broker={
info:async()=>({accountScope:scope,model,pending:[original]}),
status:async()=>({pending:[original]}),
forDetailSlot:requestScope=>{
assert.equal(requestScope,'product/goal/'+variantId+'/'+outputId);
return {close:async()=>{},round:()=>{
const id=randomUUID();
return {id,fetch:async()=>{
offered.push({id,requestScope});
const call={index:0,id:'finish-'+id,type:'function',function:{name:'finish_production',arguments:'{"revision":4}'}};
const packet='data: '+JSON.stringify({id,model:model.id,choices:[{index:0,delta:{tool_calls:[call]},finish_reason:'tool_calls'}]})+
'\n\ndata: [DONE]\n\n';
return new Response(packet,{headers:{'content-type':'text/event-stream'}});
},finish:async()=>({phase:'complete'})};
}};
},
recover:()=>assert.fail('an independent goal must not query or dispatch the held detail request'),
};
const canvas={run:outputId,documentId:13,detailImages(){},finishProduction:async input=>productionExportReceipt(input),begin:async()=>({run:outputId,conversationActive:true}),
read:async()=>({conversationActive:true}),delta:async()=>{},end:async()=>{},activity:async()=>{}};
const host=await openAgent({store,broker,canvas,productionGoal:goal});
stubProductionOperations(host,goal,{
async finish_production(){return {text:'本输出已复核',production:{...goal,complete:true,canvasRevision:4}};},
});
try {
const {production:receipt} = await host.prompt('继续整套制作',{goalContinuation:true});
assert.deepEqual(receipt,productionExportReceipt({...goal,complete:true,canvasRevision:4}));
assert.ok(host.manager.getEntries().some(row=>row.customType==='production-goal'&&row.data.goal.status==='complete'));
}finally{await host.dispose();}
}
assert.equal(offered.length,2);
assert.ok(offered.every(row=>row.id!==originalId));
});
test('DeepSeek Flash 1017 can receive an optional strategy tool and product image with thinking disabled', async t => {
const { root, scope, store } = await setup();
t.after(() => cleanup(root));
const model = { id: 'deepseek-v4.1-flash-1017', protocol: 'openai-chat', supportsImageInput: true };
const responses = [];
const toolName = 'save_product_strategy';
const broker = {
info: async () => ({ accountScope: scope, model, pending: [] }),
forDetailSlot: () => ({
close: async () => {},
round: () => ({
id: randomUUID(),
fetch: async (_url, init) => {
responses.push(JSON.parse(init.body));
const call = { index: 0, id: 'strategy-tool', type: 'function',
function: { name: toolName, arguments: '{"evidence":"P01"}' } };
const reply = { id: 'strategy', model: model.id,
choices: [{ index: 0, delta: { tool_calls: [call] }, finish_reason: 'tool_calls' }] };
return new Response('data: ' + JSON.stringify(reply) + '\n\ndata: [DONE]\n\n',
{ headers: { 'content-type': 'text/event-stream' } });
},
finish: async () => ({ phase: 'complete' }),
}),
}),
};
const canvas = { run:'strategy-run', read: async () => ({ conversationActive: true, revision: 1 }) };
const host = await openAgent({ store, broker, canvas });
try {
host.activityScope = {run:canvas.run};
await host.runDetailAgent('production-strategy', '核对同款原图', '商品', [{
name: toolName, label: '保存策划', description: '保存证据编号',
parameters: { type: 'object', properties: { evidence: { type: 'string' } }, required: ['evidence'] },
execute: async (_id, args) => {
assert.equal(args.evidence, 'P01');
return { content: [{ type: 'text', text: '已保存' }], details: {}, terminate: true };
},
}], [{ type: 'image', mimeType: 'image/png', data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==' }], 'product/strategy/' + randomUUID());
assert.equal(responses.length, 1);
const [body] = responses;
assert.equal(body.thinking,undefined);
assert.equal(body.tool_choice??'auto','auto');
assert.ok(body.messages.some(message => Array.isArray(message.content) &&
message.content.some(part => part.image_url?.url === 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==')));
} finally {
await host.dispose();
}
});
test('the main Anthropic session serializes short cache markers through the native broker', async t => {
const {root,scope,store}=await setup();
t.after(()=>cleanup(root));
const model={id:'claude-opus-5-5',protocol:'anthropic-messages',contextWindow:1000000,maxTokens:128000};
const events=[
{type:'message_start',message:{id:'msg_qa',type:'message',role:'assistant',model:model.id,content:[],
stop_reason:null,stop_sequence:null,usage:{input_tokens:9,output_tokens:1}}},
{type:'content_block_start',index:0,content_block:{type:'text',text:''}},
{type:'content_block_delta',index:0,delta:{type:'text_delta',text:'本地缓存验证完成。'}},
{type:'content_block_stop',index:0},
{type:'message_delta',delta:{stop_reason:'end_turn',stop_sequence:null},usage:{output_tokens:8}},
{type:'message_stop'},
];
const sent=[];
const broker={
info:async()=>({accountScope:scope,model,pending:[]}),
round:()=>({id:randomUUID(),
fetch:async(url,{body})=>{
sent.push({url:String(url),body:JSON.parse(body)});
return new Response(events.map(event=>'event: '+event.type+'\ndata: '+JSON.stringify(event)+'\n\n').join(''),
{headers:{'content-type':'text/event-stream'}});
},
finish:async()=>({phase:'complete'}),
}),
};
const host=await openAgent({store,broker});
try {
await host.prompt('查看当前项目。');
assert.equal(sent.length,1);
assert.equal(new URL(sent[0].url).pathname, '/v1/messages');
const {system,tools,messages}=sent[0].body;
assert.ok(system.some(block=>block.cache_control?.type==='ephemeral'));
assert.ok(tools.some(block=>block.cache_control?.type==='ephemeral'));
assert.ok(messages.some(row=>Array.isArray(row.content)&&row.content.some(block=>block.cache_control?.type==='ephemeral')));
} finally {await host.dispose();}
});
test('Opus 5.5 planning and review use automatic tools while preserving their image evidence', async t => {
const { root, scope, store } = await setup();
t.after(() => cleanup(root));
const model = {id:'claude-opus-5-5',protocol:'anthropic-messages',supportsImageInput:true,
contextWindow:1000000,contextWindowSource:'pi-model-catalog:anthropic/claude-opus-5-5',maxTokens:128000};
const sent = [];
const events = toolName => [
{type:'message_start',message:{id:'msg_qa',type:'message',role:'assistant',model:model.id,content:[],
stop_reason:null,stop_sequence:null,usage:{input_tokens:9,output_tokens:1}}},
{type:'content_block_start',index:0,content_block:{type:'tool_use',id:'toolu_qa',name:toolName,input:{}}},
{type:'content_block_delta',index:0,delta:{type:'input_json_delta',partial_json:'{"evidence":"P01"}'}},
{type:'content_block_stop',index:0},
{type:'message_delta',delta:{stop_reason:'tool_use',stop_sequence:null},usage:{output_tokens:8}},
{type:'message_stop'},
];
const broker = {
info:async()=>({accountScope:scope,model,pending:[]}),
forDetailSlot:()=>({close:async()=>{},round:()=>({id:randomUUID(),
fetch:async(_url,init)=>{
const body=JSON.parse(init.body);
sent.push(body);
if(body.tool_choice&&body.tool_choice.type!=='auto')return new Response('{"type":"error","error":{"type":"invalid_request_error","message":"forced tool use is unsupported"}}',
{status:400,headers:{'content-type':'application/json'}});
return new Response(events(body.tools[0].name).map(event=>'event: '+event.type+'\ndata: '+JSON.stringify(event)+'\n\n').join(''),
{headers:{'content-type':'text/event-stream'}});
},
finish:async()=>({phase:'complete'}),
})}),
};
const host=await openAgent({store,broker,canvas:{read:async()=>({conversationActive:true,revision:1})}});
try {
let executed=0;
const id=randomUUID();
const cases=[
['supervisor','plan_page_copy',`product/copy/${id}/detail`],
['production-strategy-audit','review_product_strategy',`product/strategy-audit/${id}`],
['supervisor','write_copy_fields',`product/copy-audit/${id}/detail`],
['supervisor','review_page_copy',`product/copy-audit/${id}/detail`],
['review','review_candidate',`product/review/${id}`],
];
for(const [slotId,toolName,requestScope] of cases){
await host.runDetailAgent(slotId,'按同款原图提交结果','商品和屏序',[{
name:toolName,label:'提交结果',description:'保存原图证据',
parameters:{type:'object',properties:{evidence:{type:'string'}},required:['evidence']},
execute:async(_id,{evidence})=>{
assert.equal(evidence,'P01');
executed++;
return {content:[{type:'text',text:'已保存'}],terminate:true};
},
}],[{type:'image',mimeType:'image/png',data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='}],requestScope);
}
assert.equal(executed,cases.length);
assert.equal(sent.length,cases.length);
assert.deepEqual(sent[0].thinking,{type:'disabled'});
assert.equal(sent[0].output_config,undefined);
for(const body of sent){
assert.equal(body.max_tokens,128000);
assert.equal(body.tool_choice?.type??'auto','auto');
assert.ok(body.messages.some(message=>message.content.some(block=>block.type==='image'&&block.source.data==='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==')));
}
} finally {
await host.dispose();
}
});
test('handover returns the host refusal to the agent, which replies without editing', async () => {
const { root, scope, store } = await setup(); let posts = 0, ended;
const broker = { info: async () => ({ accountScope: scope, model: { id: 'qa', protocol: 'openai-chat' }, pending: [] }), round() {
posts++;
const call={index:0,id:'proposed',type:'function',function:{name:'canvas_edit',arguments:JSON.stringify({revision:1,command:'type.edit',params:{layer:1,text:'不能应用'},label:'测试写入'})}};
const [delta,finish]=posts===1?[{tool_calls:[call]},'tool_calls']:[{content:'用户已接手,本次修改没有应用。'},'stop'];
const raw=`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:finish}]})}\n\ndata: [DONE]\n\n`;
return {id:randomUUID(),fetch:async()=>new Response(raw,{headers:{'content-type':'text/event-stream'}}),finish:async()=>({phase:'complete'})};
} };
const canvas = { async begin() {}, async read() { return { conversationActive:true,allowed:false,writeBlocked:true,revision:1 }; },async activity(){},async requestWrite(){throw new BridgeError('用户已接手,写入未获许可','write_revoked');},async edit(){throw Error('must never edit');}, async end(text) { ended = text; } };
const host = await openAgent({ store, broker, canvas });
const result = await host.prompt('开始后立即接手');
assert.match(result.text, /用户已接手/); assert.equal(ended,result.text); assert.equal(posts, 2);
await host.dispose(); await cleanup(root);
});