gongxiangp2/apps/detail-agent-pi/test/native-wire.test.mjs

1345 lines
77 KiB
JavaScript

import { productionExportReceipt } from './production-store-fixture.mjs';
import { BridgeError } from '../src/bridge-error.mjs';
import test from 'node:test';
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 { 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';
import { normalizeContext } from '@earendil-works/pi-ai/compat';
import { createAssistantMessageEventStream, openAICompletionsApi, openAIResponsesApi } from '@earendil-works/pi-ai/compat';
import { SessionManager } from '@earendil-works/pi-coding-agent';
import { atomic } from '../src/store.mjs';
import { Native98kBroker } from '../src/native-bridge.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { projectTools } from '../src/project-tools.mjs';
import { parseReceipt } from '../src/receipt.mjs';
import { createPhotoCraftExtensions } from '../src/photocraft-extension.mjs';
import { callProductionTool } from '../src/production-goal.mjs';
import { productionStore, stubProductionOperations } from './production-store-fixture.mjs';
import { Value } from '@sinclair/typebox/value';
import { canvasReadParameters, canvasReadQuery } from '../src/canvas-contract.mjs';
import { nativeCatalogParameters, nativeTools } from '../src/native-tools.mjs';
test('native_catalog batches exact host lookups, reports misses and retains command leases', async () => {
const queries = [], events = [], writes = [];
const metadata = {documentId: 27, documentIndex: 2, revision: 8, parameterFormat: 'native documentation'};
const items = [
{id: 'layer.list', parameterDocs: '宿主读取说明', requiresRevisionLease: false, enabled: true},
{id: 'type.edit', parameterDocs: '宿主编辑说明', requiresRevisionLease: true, enabled: false, reason: '等待写入权限'},
];
const host = {
store: {appendEvent: async event => events.push(event)},
canvas: {
nativeCatalog: async query => {
queries.push(query);
return {...metadata, matchMode: query.id ? 'exact-id' : 'any-keyword',
items: items.filter(item => item.id === query.id), nativeTiming: {totalMs: 1}};
},
nativeCall: async () => ({completed: true, executed: true, revision: 8}),
requestWrite: async revision => {
writes.push(revision);
return {allowed: true, revision};
},
},
};
const [catalog, call] = nativeTools(host, (_name, _description, _parameters, execute) => ({execute}));
const args = {id: ' layer.list ', ids: ['layer.list', 'type.edit', ' type.edit ', 'unknown.command', ' '],
filter: 'ignored', offset: 2, limit: 1};
assert.equal(Value.Check(nativeCatalogParameters, args), true);
for (const invalid of [{ids: []}, {ids: ['']}, {ids: ['type.edit', 'type.edit']},
{ids: Array.from({length: 13}, (_, i) => String(i))}, {ids: ['x'.repeat(161)]}, {ids: ['a'], extra: true}]) {
assert.equal(Value.Check(nativeCatalogParameters, invalid), false);
}
assert.deepEqual(await catalog.execute(args), {
...metadata, matchMode: 'exact-ids', total: 2, items, missingIds: ['unknown.command'],
});
const expectedQueries = [{id: 'layer.list'}, {id: 'type.edit'}, {id: 'unknown.command'}];
assert.deepEqual(queries, expectedQueries);
assert.equal(events.filter(event => event.type === 'native_catalog_timing' && event.totalMs === 1).length, 3);
await call.execute({revision: 8, method: 'engine.execute', params: {command: 'layer.list'}});
assert.deepEqual(writes, []);
await call.execute({revision: 8, method: 'engine.execute', params: {command: 'type.edit'}});
assert.deepEqual(writes, [8]);
assert.deepEqual(queries, expectedQueries);
assert.deepEqual(await catalog.execute({id: ' layer.list '}), {...metadata, matchMode: 'exact-id', items: [items[0]]});
await catalog.execute({filter: 'layer', offset: 1, limit: 3});
assert.deepEqual(queries.slice(-2), [{id: 'layer.list'}, {filter: 'layer', offset: 1, limit: 3}]);
});
test('native request validation can prove that no model was dispatched', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
for (const rejectedBeforeDispatch of [true, false]) {
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close',0);
});
child.stdin.on('data', buffer => {
assert.equal(JSON.parse(buffer.toString()).method,'request');
const response = {type:'error',error:'本机拒绝该操作',
...(rejectedBeforeDispatch ? {dispatched:false} : {})};
child.stdout.write(JSON.stringify(response)+'\n');
});
const broker = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => child});
broker.scope='fixture';
try {
const round=broker.round();
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/本机拒绝该操作/);
} finally { await broker.close(); }
}
});
test('the native bridge reports a retryable preflight to Pi without replaying it', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.stdin.once('finish', () => {
child.stdout.end();
child.stderr.end();
child.emit('close', 0);
});
const requests=[];
child.stdin.on('data', buffer => {
requests.push(JSON.parse(buffer.toString()));
child.stdout.write(JSON.stringify({type:'error',error:'客户端准备模型请求失败,本次未发送',
dispatched:false,retryPreparation:true})+'\n');
});
const broker=new Native98kBroker({project:randomUUID(),profile,spawnProcess:()=>child});
broker.scope='fixture';
try {
const round=broker.round();
await assert.rejects(round.fetch('https://api.vip98k.com/v1/chat/completions',{method:'POST',body:'{}'}),/network error/);
assert.equal(requests.length,1);
assert.equal(requests[0].id,round.id);
} finally {await broker.close();}
});
test('the native bridge posts only to the endpoint bound to the selected route', async () => {
const route = randomUUID();
const broker = new Native98kBroker({project:randomUUID(),invocationHeaders:{'X-Relay-Route-Option':route}});
const requests = [];
broker.start = async (method, input, event) => {
requests.push({method, input});
event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
return {phase:'received'};
};
const round = broker.round();
await round.fetch('https://api.vip98k.com/v1/responses', {method:'POST',body:'{}'});
assert.equal(requests[0].input.invocationPath,'/v1/responses');
assert.deepEqual(requests[0].input.invocationHeaders,{'X-Relay-Route-Option':route});
await assert.rejects(round.fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'}),/只接受一个请求/);
assert.equal(requests.length,1);
});
test('parallel production brokers inherit the native turn selection without revalidating it', async () => {
const project = randomUUID(), selectionId = randomUUID();
const route = {'X-Relay-Route-Option':randomUUID()};
const parent = new Native98kBroker({project,modelRole:'detail'});
parent.start = async method => {
assert.equal(method,'info');
return {accountScope:'fixture',selectionId,invocationHeaders:route};
};
await parent.info();
const received=[];
await Promise.all(['intro','design'].map(async slot => {
const worker=parent.forDetailSlot(slot);
assert.equal(worker.scope,'fixture');
worker.start=async(method,input,event)=>{
assert.equal(method,'request');
received.push({slot,input});
event({type:'headers',status:200,headers:{'content-type':'text/event-stream'}});
return {phase:'received'};
};
await worker.round({inference:true}).fetch('https://api.vip98k.com/v1/responses',{method:'POST',body:'{}'});
}));
assert.equal(received.length,2);
assert.ok(received.every(row=>row.input.selectionId===selectionId));
assert.ok(received.every(row=>row.input.invocationHeaders['X-Relay-Route-Option']===route['X-Relay-Route-Option']));
parent.bind({project,scope:'fixture',modelRole:'detail'});
assert.equal(parent.forDetailSlot('new-turn').selectionId,undefined);
});
test('an exit signal during native broker startup prevents the original request from being sent', async () => {
let admit, enter;
const startup = new Promise(resolve => { admit = resolve; });
const entered = new Promise(resolve => { enter = resolve; });
const broker = new Native98kBroker({project:randomUUID()});
const abort = new AbortController();
const requests = [];
broker.scope = 'fixture';
broker.open = async () => {
enter();
await startup;
broker.child = {stdin:{write:bytes => requests.push(bytes)},kill(){}};
};
const pending = broker.round().fetch('https://api.vip98k.com/v1/chat/completions',
{method:'POST',body:'{}',signal:abort.signal});
await entered;
abort.abort(Error('退出已停止接单'));
admit();
await assert.rejects(pending, /退出已停止接单/);
assert.deepEqual(requests, []);
});
test('forcing the daemon model bridge closed also closes its goal and slot processes', async t => {
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
t.after(() => cleanup(profile));
const killed = [];
let serial = 0;
const parent = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => {
const pid = ++serial;
const child = new EventEmitter();
child.stdin = new PassThrough();
child.stdout = new PassThrough();
child.stderr = new PassThrough();
child.kill = () => {
killed.push(pid);
child.stdout.end();
child.stderr.end();
child.emit('close',0);
};
return child;
}});
await parent.open();
await parent.forDetailSlot('goal').open();
await parent.forDetailSlot('cover').open();
await parent.close({force:true});
assert.deepEqual(killed.sort(), [1,2,3]);
await assert.rejects(parent.forDetailSlot('late').open(), /模型桥已关闭/);
});
test('Pi sends an inline image and decodes a streamed function on both OpenAI APIs', async () => {
const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jNHsAAAAASUVORK5CYII=';
const tool = {name:'record_color',description:'Record the observed color',parameters:{type:'object',properties:{color:{type:'string'}},required:['color']}};
const args = '{"color":"green"}';
const call = {id:'fc_route',type:'function_call',status:'completed',call_id:'call_route',name:tool.name,arguments:args};
const event = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({type,...fields}) + '\n\n';
const frame = value => 'data: ' + JSON.stringify(value) + '\n\n';
for (const responses of [false,true]) {
const api = responses ? 'openai-responses' : 'openai-completions';
const adapter = responses ? openAIResponsesApi() : openAICompletionsApi();
const model = {id:responses?'gpt-6.1-sol':'gemini-3.8-flash',api,provider:'jiansun-native-98k',input:['text','image'],
baseUrl:'https://api.vip98k.com/v1',name:api,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},
compat:{supportsStore:false,supportsReasoningEffort:false}};
const chunk = (delta,finish_reason=null) => frame({id:'synthetic',model:model.id,choices:[{index:0,delta,finish_reason}]});
const raw = responses
? event('response.output_item.added',{output_index:0,item:{...call,arguments:'',status:'in_progress'}}) +
event('response.function_call_arguments.delta',{output_index:0,delta:args}) +
event('response.output_item.done',{output_index:0,item:call}) +
event('response.completed',{response:{model:model.id,status:'completed',output:[call]}})
: chunk({tool_calls:[{index:0,id:'call_route',type:'function',function:{name:tool.name,arguments:'{"color":'}}]}) +
chunk({tool_calls:[{index:0,function:{arguments:'"green"}'}}]}) +
chunk({},'tool_calls')+'data: [DONE]\n\n';
let sent = 0;
const stream = adapter.streamSimple(model,normalizeContext({tools:[tool],messages:[
{role:'user',content:[{type:'text',text:'Read the image and call record_color'},{type:'image',mimeType:'image/png',data:pixel}],timestamp:0}
]}),{apiKey:'local-test',maxRetries:0,maxTokens:256,fetch:async (url,init)=>{
sent++;
assert.equal(new URL(url).pathname,responses?'/v1/responses':'/v1/chat/completions');
const payload=JSON.parse(init.body);
assert.equal(payload.stream,true);
const picture=(responses?payload.input:payload.messages).find(item=>item.role==='user').content[1];
assert.equal(responses?picture.image_url:picture.image_url.url,'data:image/png;base64,'+pixel);
assert.equal(responses?payload.tools[0].name:payload.tools[0].function.name,tool.name);
return new Response(raw,{headers:{'content-type':'text/event-stream'}});
}});
for await (const _event of stream) {}
const result=await stream.result();
assert.equal(sent,1);
assert.equal(result.stopReason,'toolUse',result.errorMessage);
assert.deepEqual(result.content.find(item=>item.type==='toolCall').arguments,{color:'green'});
assert.deepEqual(auditResponse(raw,responses?'openai-responses':'openai-chat').calls,[{name:tool.name,arguments:{color:'green'}}]);
}
});
test('a retained Responses function call is audited and decoded without a network fetch', async () => {
const model = {id:'route-model',api:'openai-responses',provider:'jiansun-native-98k',input:['text','image'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0}};
const response = {model:model.id,status:'completed',output:[
{id:'fc_route',type:'function_call',status:'completed',call_id:'call_route',name:'record_color',arguments:'{"color":"green"}'},
]};
const record = {phase:'received',terminal:true,model:{id:model.id,protocol:'openai-responses'},raw:Buffer.from(JSON.stringify(response)).toString('base64')};
const message = await parseReceipt(record,model,'native-tools',[]);
assert.equal(message.stopReason,'toolUse');
assert.deepEqual(message.content[0].arguments,{color:'green'});
response.output[0].arguments = '{"color":';
await assert.rejects(parseReceipt({...record,raw:Buffer.from(JSON.stringify(response)).toString('base64')},model,'native-tools',[]));
});
const sse = (delta, finish) => `data: ${JSON.stringify({ id: 'wire', model: 'qa', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`;
async function setup(reply, finish = async valid => { assert.equal(valid, true); return {phase:'complete'}; }, production, recovery = production) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
const scope = 'f'.repeat(64), store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'A', categoryId: 'desk', platform: 'qa', version: '1', source: 'qa', rules: [] });
const requests = [];
const ids = [];
const retries = [];
const broker = { info: async () => ({ accountScope: scope, model: recovery?.model ?? { id: 'qa', protocol: 'openai-chat' }, thinkingLevel: recovery?.thinkingLevel, pending: [] }), round({retryOf}={}) {
if(retryOf) retries.push(retryOf);
const id=randomUUID();
return { id, fetch: async (_url, init) => {
const p = JSON.parse(init.body); requests.push(p); ids.push(id);
const result=reply(p,requests.length);
return result instanceof Response ? result : new Response(result,{headers:{'content-type':'text/event-stream'}});
}, finish };
} };
const canvas=(production||recovery?.canvas)&&{begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},
activity:async()=>{},delta:async()=>{},end:async()=>{},finishProduction:async input=>productionExportReceipt(input),...(production??recovery).canvas};
const variantId=randomUUID();
const outputs=production?.outputs??[{outputId:'detail',variantId}];
const productionGoal=production&&{outputId:production.outputs?null:'detail',variantId:production.outputs?null:variantId,
workspaceId:randomUUID(),requestedOutputs:outputs,pendingOutputs:outputs,deadline:production.deadline,
template:production.template};
if(recovery)Object.assign(broker,{forDetailSlot:()=>broker,close:async()=>{},
status:async()=>({pending:[]}),isUnconfirmed:()=>Boolean(recovery.read),read:recovery.read,recover:recovery.recover});
const host = await DetailPiAgent.open({ store, broker, callBudget: production?.callBudget??3, canvas, productionGoal });
if(production&&productionGoal.outputId)stubProductionOperations(host,productionGoal,{
plan_production:args=>production.plan?.(args)??{pendingText:0},
finish_production:async()=>({text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:1}}),
});
return { host, store, requests, ids, retries, close: async () => { await host.dispose(); await cleanup(dir); } };
}
test('Pi loads the Skill and opens a project-selected output with the same session and tool declarations',async()=>{
const outputs=[{outputId:'detail',variantId:randomUUID()},{outputId:'gallery',variantId:randomUUID()}];
const template={id:'fixture',version:'3',enterprise:true,resourceSetId:'published'};
const instruction='先准备画册,再制作详情页。';
const bindings=[];
const catalogs=[];
const x=await setup((payload,n)=>{
const call=(name,args)=>sse({tool_calls:[{index:0,id:'binding-'+n,type:'function',
function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
assert.ok(payload.tools.some(row=>row.function?.name==='open_production_output'));
assert.ok(payload.tools.some(row=>row.function?.name==='finish_production'));
if(n>1){
assert.deepEqual(payload.tools,x.requests[0].tools);
assert.equal(payload.messages[0].content,x.requests[0].messages[0].content);
}
if(n===1){
assert.match(JSON.stringify(payload.messages),/requestedOutputs.*gallery/u);
return call('read',{path:x.host.productionSkills.resource.skills[0].filePath});
}
if(n===2)return call('plan_production',{});
if(n===3)return call('reconcile_image_slots',{});
if(n===4){
assert.match(JSON.stringify(payload.messages),new RegExp(instruction,'u'));
const receipt=payload.messages.findLast(message=>message.role==='tool');
assert.deepEqual(JSON.parse(receipt.content),{scope:'project',results:[]});
return call('native_catalog',{id:'layer.setProps'});
}
if(n===5){
assert.match(JSON.stringify(payload.messages),/production_canvas_pending/u);
return call('open_production_output',outputs[1]);
}
if(n===6){
assert.match(JSON.stringify(payload.messages),/gallery.*revision/u);
return call('native_catalog',{id:'layer.setProps'});
}
if(n===7){
assert.match(JSON.stringify(payload.messages),/requiresRevisionLease/u);
return call('finish_production',{revision:1});
}
return sse({content:'已核对画册。'},'stop');
},undefined,{outputs,template,callBudget:8,canvas:{
imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'gallery',productVariantId:outputs[1].variantId,
template:{contentHash:'fixture'},totalSlots:0,slots:[]}),
requestWrite(){assert.fail('selection should not ask for canvas write access');},
nativeCatalog:async({id})=>{
catalogs.push(id);
if(!bindings.length)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:1,items:[{id,requiresRevisionLease:true}]};
},
nativeCall(){assert.fail('catalog discovery should not dispatch an edit');},
openProductionOutput:async args=>{
bindings.push(args);
stubProductionOperations(x.host,args,{
finish_production:async({revision})=>({production:{...args,canvasRevision:revision,complete:true}})});
return {...args,revision:1,pendingOutputs:[outputs[0]]};
},
}});
try{
x.host.productEvidence={product:{name:'灯具',brandName:'测试品牌',categoryName:'灯具'}};
x.host.loadProductionKnowledge=async selection=>{
assert.equal(selection.outputId,undefined);
assert.equal(selection.releaseId,'3');
return {skills:[{fileId:'entry',revision:'3',kind:'skill',path:'fixture/SKILL.md',
text:'---\nname: fixture\ndescription: Fixture project order\n---\n'+instruction}],rules:[]};
};
const response=await x.host.prompt('制作本轮所选输出');
assert.deepEqual(bindings,[outputs[1]]);
assert.deepEqual(catalogs,['layer.setProps','layer.setProps']);
assert.equal(response.production.outputId,'gallery');
assert.equal(response.production.complete,true);
assert.equal(x.requests.length,7);
assert.ok(x.host.manager.getBranch().some(row=>row.customType==='pi-goal'&&row.data.goal.status==='complete'));
}finally{await x.close();}
});
test('ordinary chat resumes the same turn through Pi after a rate limit', async () => {
const x = await setup((_p, n) => n === 1
? new Response(JSON.stringify({error:{message:'Rate limit exceeded'}}),{status:429,headers:{'retry-after':'0'}})
: sse({content:'可以继续处理。'}, 'stop'),
async valid => valid ? {phase:'complete'} : {phase:'failed',failureCode:'rate_limit_exceeded'});
try {
const next = await x.host.prompt('请先说明当前结果');
assert.equal(next.text, '可以继续处理。');
assert.equal(x.requests.length, 2);
assert.deepEqual(x.requests[0].messages,x.requests[1].messages);
assert.notEqual(x.ids[0],x.ids[1]);
} finally { await x.close(); }
});
test('an HTTP 503 native inference receipt reaches Pi retry in the same one-click goal', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-'));
let host;
t.after(async()=>{ await host?.dispose(); await cleanup(dir); });
const scope = 'b'.repeat(64), project=randomUUID();
const store = await ProjectStore.open(dir, {scope,project}, {brandId:'qa',shopId:'shop',categoryId:'qa',platform:'qa',version:'1',source:'qa',rules:[]});
const requests=[], finished=[], operations=[];
const originalId=randomUUID();
const broker = new Native98kBroker({project,profile:dir,modelRole:'detail'});
broker.scope=scope;
broker.info=async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-responses',supportsImageInput:true},pending:[]});
broker.status=async()=>({pending:[]});
broker.forDetailSlot=()=>broker;
const event=(type,details)=>'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n';
const item={id:'fc_ok',type:'function_call',call_id:'call_ok',name:'finish_production',
arguments:JSON.stringify({revision:7,scope:"all"})};
const response=event('response.output_item.added',{output_index:0,item:{...item,arguments:''}})
+event('response.function_call_arguments.delta',{output_index:0,delta:item.arguments})
+event('response.output_item.done',{output_index:0,item})
+event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
broker.start=async(method,input,emit)=>{
if(method==='finish'){finished.push(input.id);return {phase:'complete'};}
assert.equal(method,'request');
requests.push(input);
const success=requests.length>1;
emit({type:'headers',status:success?200:503,requestId:success?randomUUID():originalId,
headers:{'content-type':success?'text/event-stream':'application/json'},bodyHash:'native-wire'});
const error=JSON.stringify({error:{code:'service_unavailable',type:'server_error',message:'Service temporarily unavailable'}});
emit({type:'chunk',data:Buffer.from(success?response:error).toString('base64')});
return success?{phase:'complete'}:{phase:'unknown',requestId:originalId};
};
const canvas={begin:async()=>({}),read:async()=>({conversationActive:true}),detailImages(){},activity:async()=>{},delta:async()=>{},end:async()=>{},finishProduction:async input=>productionExportReceipt(input)};
const variantId=randomUUID();
const productionGoal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],
deadline:Math.floor(Date.now()/1000)+90};
host=await DetailPiAgent.open({store,broker,canvas,productionGoal,callBudget:4});
stubProductionOperations(host,productionGoal,{finish_production:async input=>{
operations.push(input);
return {text:'已核对导出。',production:{...productionGoal,complete:true,canvasRevision:input.revision}};
}});
const resumed=await host.prompt('继续制作当前画布');
assert.equal(resumed.production.complete,true);
assert.deepEqual(operations,[{revision:7,scope:"all"}]);
assert.equal(resumed.production.finalized,true);
assert.deepEqual(finished,[]);
assert.notEqual(requests[0].id,requests[1].id);
assert.equal(requests[0].body,requests[1].body);
});
test('the one-click goal resumes on changed fields at the same count without naming the next tool',async()=>{
const plan=n=>sse({tool_calls:[{index:0,id:'plan-'+n,type:'function',function:{name:'plan_production',arguments:'{}'}}]},'tool_calls');
let plans=0;
const x=await setup((_,n)=>{
if(n===1||n===3)return plan(n);
if(n===5)return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
return sse({content:'本次复核有进展。'},'stop');
},undefined,{
callBudget:6,plan:()=>({outputId:'detail',variantId:'oak',pendingText:1,field:++plans===1?'标题':'规格'}),
progress:()=>({state:{fields:[plans===1?'标题':'规格']}}),
});
try {
const result=await x.host.prompt('完成整套制作');
assert.equal(result.production.complete,true);
assert.equal(plans,2);
assert.match(JSON.stringify(x.requests[4].messages),/同范围已有更新回执/);
const oldPlan=x.host.manager.getBranch().find(({message})=>message?.role==='toolResult'&&message?.toolCallId==='plan-1')?.message;
assert.equal(JSON.parse(oldPlan.content[0].text).field,'标题');
for(const request of [x.requests[2],x.requests[4]]){
const reminders=request.messages.filter(message=>JSON.stringify(message).includes('继续当前制作目标'));
assert.equal(reminders.length,1);
const [continuation]=reminders;
assert.doesNotMatch(JSON.stringify(request.messages), /prompt-to-artifact checklist|PR state/u);
assert.doesNotMatch(JSON.stringify(continuation),/调用 (?:plan_production|write_copy_fields)/);
}
} finally { await x.close(); }
});
test('a managed inference interruption retries without executing its partial tool', async () => {
let plans=0;
const lookedUp=[];
const call={tool_calls:[{index:0,id:'plan',type:'function',
function:{name:'plan_production',arguments:'{}'}}]};
const x=await setup((_,n)=>n===1?sse(call,null).replace('data: [DONE]','')
:n===2?sse(call,'tool_calls'):sse({tool_calls:[{index:0,id:'finish',type:'function',
function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls'),
async()=>({phase:'complete'}),{
deadline:Math.floor(Date.now()/1000)+600,callBudget:4,
plan:()=>{plans++;return {pendingText:0};},
progress:()=>({state:{waitingOnOriginals:true}}),
},{
read:async()=>({phase:'unknown',recovery:{status:410}}),
recover:async id=>{lookedUp.push(id);},
});
try {
assert.equal((await x.host.prompt('开始整套制作')).production.complete,true);
assert.deepEqual(lookedUp,[]);
assert.deepEqual(x.retries,[]);
assert.equal(plans,1);
assert.equal(x.requests.length,3);
} finally {await x.close();}
});
test('a broken model stream stops after the three native retries', async t => {
const x=await setup(()=>new Response(new ReadableStream({
start(controller) { controller.error(new TypeError('network error: mock stream disconnected')); },
}),{headers:{'content-type':'text/event-stream'}}));
x.host.callBudget=10;
t.after(()=>x.close());
const settings=x.host.session.settingsManager;
const retry=settings.getRetrySettings();
settings.getRetrySettings=()=>({...retry,baseDelayMs:1,maxDelayMs:1});
await assert.rejects(x.host.prompt('核对进度'),/network error|network connection|connection error/i);
assert.equal(retry.maxRetries,3);
assert.equal(x.requests.length,4);
assert.equal(new Set(x.ids).size,4);
});
test('actual native Pi wire sends function schemas, executes typed call and accepts a plain final reply', async () => {
const x = await setup((_p, n) => n === 1 ? sse({ tool_calls: [{ index: 0, id: 'call-memory', type: 'function', function: { name: 'memory_set', arguments: JSON.stringify({ key: 'color', value: '胡桃色', evidence: '测试颜色是胡桃色' }) } }] }, 'tool_calls') : sse({ content: '已记录胡桃色' }, 'stop'));
try {
const r = await x.host.prompt('测试颜色是胡桃色,请记住。', { requiredTool: 'memory_set' });
assert.equal(r.text, '已记录胡桃色');
assert.equal((await x.store.context()).confirmedMemory.color.value, '胡桃色');
assert.equal(x.requests.length, 2);
assert.deepEqual(x.requests[0].tool_choice, { type: 'function', function: { name: 'memory_set' } });
assert.equal(x.requests[0].parallel_tool_calls, false);
assert.ok(x.requests[0].tools.some(t => t.type === 'function' && t.function.name === 'memory_set'));
assert.ok(x.requests[1].messages.some(m => m.role === 'tool' && m.tool_call_id === 'call-memory'));
assert.equal(x.requests[0].response_format, undefined);
} finally { await x.close(); }
});
test('native Pi preserves a required named tool across a retry on a string-only Responses route', async () => {
const args = JSON.stringify({key:'color',value:'米色',evidence:'布面颜色是米色'});
const call = {type:'function_call',id:'fc_required',call_id:'call_required',status:'completed',name:'memory_set',arguments:args};
const text = {type:'message',id:'msg_required',role:'assistant',status:'completed',
content:[{type:'output_text',text:'已记录米色。',annotations:[]}]};
const event = (type, fields) => 'event: ' + type + '\ndata: ' + JSON.stringify({type,...fields}) + '\n\n';
const complete = item => event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
const fixture = {thinkingLevel:'low',model:{id:'qa',protocol:'openai-responses',supportsImageInput:true,requireSingleTool:true,
reasoning:true,reasoningEfforts:['low','medium','high'],requiresOutputLimit:false,maxTokens:128_000}};
const x = await setup((_payload, round) => round === 1
? event('response.created',{response:{id:'resp_lost',status:'in_progress'}})
: round === 2
? event('response.output_item.added',{output_index:0,item:{...call,arguments:'',status:'in_progress'}})
+ event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(0,12)})
+ event('response.function_call_arguments.delta',{output_index:0,delta:args.slice(12)})
+ event('response.output_item.done',{output_index:0,item:call}) + complete(call)
: event('response.output_item.added',{output_index:0,item:{...text,content:[],status:'in_progress'}})
+ event('response.content_part.added',{output_index:0,content_index:0,part:{...text.content[0],text:''}})
+ event('response.output_text.delta',{output_index:0,content_index:0,delta:text.content[0].text})
+ event('response.output_item.done',{output_index:0,item:text}) + complete(text),
async valid => ({phase:valid?'complete':'unknown'}), undefined, fixture);
const reference = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAgACADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAYH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AkgIpngAAAAAD/9k=';
try {
assert.equal(x.host.session.thinkingLevel,'low');
assert.equal((await x.host.prompt('/thinking high')).rounds,0);
assert.equal(x.host.session.thinkingLevel,'high');
await x.host.prompt('布面颜色是米色,请记住。', {requiredTool:'memory_set',referenceContent:[{label:'产品原图',image:reference}]});
assert.equal(x.requests[0].tool_choice,'required');
assert.equal(x.requests[0].reasoning.effort,'high');
assert.equal(x.requests[0].max_output_tokens,undefined);
assert.deepEqual(x.requests[0].tools.map(tool=>tool.name),['memory_set']);
assert.equal(x.requests[1].tool_choice,'required');
assert.deepEqual(x.requests[1].tools.map(tool=>tool.name),['memory_set']);
assert.notEqual(x.ids[0], x.ids[1]);
const parts = x.requests[0].input.flatMap(item=>Array.isArray(item.content)?item.content:[]);
assert.match(parts.find(part=>part.type==='input_image')?.image_url ?? '', /^data:image\/(?:jpeg|png);base64,/);
assert.equal((await x.store.context()).confirmedMemory.color.value,'米色');
assert.equal(x.requests[2].tool_choice,undefined);
} finally { await x.close(); }
});
test('Pi reports malformed tool arguments and never executes a length-stopped write', async () => {
for (const [args, finish] of [['{"key":"color","value":"红色","evidence":"测试颜色是红色"', 'tool_calls'],
['{"key":"color","value":"红色","evidence":"测试颜色是红色"}', 'length']]) {
const x = await setup((payload, n) => {
if (n===1) return sse({tool_calls:[{index:0,id:'partial',type:'function',function:{name:'memory_set',arguments:args}}]},finish);
assert.equal(finish,'tool_calls');
assert.ok(payload.messages.some(message=>message.role==='tool'&&message.tool_call_id==='partial'));
return sse({content:'本轮未写入。'},'stop');
});
try {
if (finish === 'length') await assert.rejects(x.host.prompt('测试颜色是红色'), /达到线路上限/);
else assert.equal((await x.host.prompt('测试颜色是红色')).text,'本轮未写入。');
assert.deepEqual((await x.store.context()).confirmedMemory, {});
assert.equal(x.requests.length,finish==='length'?1:2);
} finally { await x.close(); }
}
});
test('required tool returned as prose is a known protocol failure with one POST and no execution', async () => {
const x = await setup(() => sse({ content: 'invoke tool memory_set with color red' }, 'stop'));
try {
await assert.rejects(x.host.prompt('测试颜色是红色', { requiredTool: 'memory_set' }), /未返回要求的标准函数调用/);
assert.equal(x.requests.length, 1); assert.deepEqual((await x.store.context()).confirmedMemory, {});
} finally { await x.close(); }
});
test('a literal marker in a normal explanation is ordinary text, never a command or a repair trigger', async () => {
const x = await setup(() => sse({ content: '结束标记的示例是 <|eos|>。' }, 'stop'));
try { const r = await x.host.prompt('解释一个结束标记,不要调用工具'); assert.match(r.text, /结束标记/); assert.equal(x.requests.length, 1); }
finally { await x.close(); }
});
test('wire audit detects complete SSE with a literal early EOS instead of blaming the browser', () => {
const a = auditResponse(sse({ content: '{"reply":"未结束<|eos|>' }, 'stop'), 'openai-chat');
assert.equal(a.literalEos, true); assert.deepEqual(a.finishes, ['stop']);
});
test('a terminal marker without a completion reason remains unproven and cannot execute a tool', () => {
assert.throws(() => auditResponse(sse({ content: '只有前缀' }, null), 'openai-chat'), /缺少完成原因/);
const broken={tool_calls:[{index:0,function:{name:'review_candidate',arguments:'{"candidateId":'}}]};
assert.throws(() => auditResponse(sse(broken,null),'openai-chat'),error=>!(error instanceof InvalidToolReply)&&/缺少完成原因/.test(error.message));
assert.throws(() => auditResponse(sse(broken,'tool_calls'),'openai-chat'),InvalidToolReply);
});
test('JSON compatibility errors distinguish complete prose from a broken JSON envelope', () => {
const c = normalizeContext({ messages: [] });
assert.throws(() => decodeToolReply('产品编号与颜色核对正确。', c, 'id'), /文字而非约定的JSON/);
assert.throws(() => decodeToolReply('{"reply":"只返回一半<|eos|>', c, 'id'), /提前结束标记/);
assert.throws(() => decodeToolReply('{"reply":"未闭合', c, 'id'), /JSON指令未完整/);
});
async function compactionFixture({ withCanvas, callBudget = 4, large = false, pendingStep, rateLimit = false } = {}) {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-')), scope = '9'.repeat(64);
const store = await ProjectStore.open(dir, { scope, project: randomUUID() }, { brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', source: 'qa', version: '1', rules: [] });
const manager = SessionManager.create(store.dir, path.join(store.dir, 'sessions'));
for (let i = 0; i < (large ? 45 : 26); i++) {
manager.appendMessage({ role: 'user', content: `archive-marker-${i}: ` + 'x'.repeat(large ? 3000 : 1600), timestamp: Date.now() });
manager.appendMessage({ role: 'assistant', api: 'openai-completions', provider: 'jiansun-native-98k', model: 'qa', content: [{ type: 'text', text: 'Synthetic, not a live model reply. ' + 'y'.repeat(large ? 3000 : 1600) }], stopReason: 'stop', timestamp: Date.now(), usage: { input: large?50000:5000, output: 500, cacheRead: 0, cacheWrite: 0, totalTokens: large?50500:5500, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });
}
await atomic(path.join(store.dir, 'session.json'), { file: manager.getSessionFile() });
let calls = 0, canvasCalls = 0;
const canvas = withCanvas ? { read() { canvasCalls++; throw Error('no canvas edit run during compaction'); }, delta() { canvasCalls++; throw Error('must not show internal summary'); } } : undefined;
const transport = { info: { accountScope: scope, model: { id: 'qa', protocol: 'openai-chat', contextWindow:64000, contextWindowSource:'fixture' }, pending: [] }, stream(model) {
calls++;
const stream = createAssistantMessageEventStream();
const message = { role: 'assistant', api: model.api, provider: model.provider, model: model.id, content: [{ type: 'text', text: 'Summary: original evidence remains archived.' }], stopReason: 'stop', timestamp: Date.now(), usage: { input: 5000, output: 20, cacheRead: 0, cacheWrite: 0, totalTokens: 5020, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
queueMicrotask(() => { stream.push({ type: 'start', partial: message }); stream.push({ type: 'text_delta', contentIndex: 0, delta: message.content[0].text, partial: message }); stream.push({ type: 'done', reason: 'stop', message }); stream.end(message); });
return stream;
} };
let goal, broker;
if (pendingStep) {
const variantId=randomUUID();
goal={outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}]};
const goalScope='product/goal/'+variantId+'/detail';
transport.info.pending=[{id:randomUUID(),modelRole:'detail',phase:'unknown',
detailSlot:pendingStep==='goal'?goalScope:'product/review/'+randomUUID()}];
canvas.detailImages=()=>{};
broker = {
info:async()=>transport.info,
round(){throw Error('production summary must use its matching goal scope');},
forDetailSlot(value) {
assert.equal(value,goalScope);
return {round:()=>({
id:randomUUID(),
fetch:async(_url,{body})=>{
calls++;
assert.equal(JSON.parse(body).tools,undefined);
if (rateLimit && calls === 1) {
return new Response('data: {"error":{"code":"rate_limit_exceeded","type":"server_error"}}\n\n',
{headers:{'content-type':'text/event-stream'}});
}
return new Response(sse({content:'Summary: original evidence remains archived.'},'stop'),
{headers:{'content-type':'text/event-stream'}});
},
finish:async()=>rateLimit && calls === 1 ? {phase:'failed',failureCode:'rate_limit_exceeded'} : {phase:'complete'},
}),close:async()=>{}};
},
};
}
const host = await DetailPiAgent.open({ store, transport:broker?undefined:transport, broker, canvas, callBudget, productionGoal:goal });
return { host, get calls() { return calls; }, get canvasCalls() { return canvasCalls; }, close: async () => { await host.dispose(); await cleanup(dir); } };
}
test('compaction with a connected canvas does not call an inactive edit run or show the internal summary', async () => {
const x = await compactionFixture({ withCanvas: true });
try {
const result = await x.host.compact();
assert.match(result.summary, /original evidence/); assert.ok(x.calls > 0); assert.equal(x.canvasCalls, 0);
assert.ok(x.host.manager.getEntries().some(e => e.type === 'message' && e.message.role === 'user' && e.message.content.includes('archive-marker-0')));
} finally { await x.close(); }
});
test('the Pi defaults compact from the native session threshold',async()=>{
const x=await compactionFixture({large:true});
try {
const settings=x.host.session.settingsManager;
assert.deepEqual(settings.getCompactionSettings(x.host.session.model),{enabled:true,reserveTokens:16384,keepRecentTokens:20000});
assert.deepEqual(Object.fromEntries(Object.entries(settings.getRetrySettings()).filter(([k])=>['enabled','maxRetries','baseDelayMs'].includes(k))),
{enabled:true,maxRetries:3,baseDelayMs:2000});
await x.host.prompt('继续');
assert.equal(x.calls,3);
const checkpoints=x.host.manager.getEntries().filter(entry=>entry.type==='compaction');
assert.equal(checkpoints.length,1);
assert.ok(x.host.manager.getEntries().some(entry=>entry.message?.role==='user'&&entry.message.content.includes('archive-marker-0')));
} finally {await x.close();}
});
test('native compaction retries its own interrupted summary', async()=>{
const x=await compactionFixture({withCanvas:true,pendingStep:'review',rateLimit:true});
try {
assert.match((await x.host.compact()).summary,/original evidence/);
assert.equal(x.calls,2);
assert.equal(x.canvasCalls,0);
assert.equal(x.host.manager.getEntries().filter(entry=>entry.type==='compaction').length,1);
} finally {await x.close();}
});
test('the model receives exact reference identities and instructions for acting on them', async()=>{
const x=await setup(()=>sse({content:'已核对。'},'stop'));
try {
const candidate={label:'椅背候选',source:'图片资源',kind:'candidate',nativeLayerId:1502,component:'layer',
layerKind:'Smart Object',slotId:'M04-I01',fieldId:'hero',candidateId:'candidate-2',taskId:'task-2',
outputId:'detail',productVariantId:'wood',documentId:7};
const mask={label:'像素蒙版',kind:'layer',nativeLayerId:1503,component:'pixelMask'};
await x.host.prompt('评估这张候选图和蒙版', {referenceContent:[candidate, mask]});
const wire=x.requests[0].messages;
const text=wire.findLast(message=>message.role==='user').content;
const quoted=JSON.parse((typeof text==='string' ? text : text.find(item=>item.type==='text').text).split('以下文字为引用内容):')[1]);
assert.deepEqual(quoted, [candidate,{...mask,source:'发送时的画布图层'}]);
const system=wire.find(message=>message.role==='system').content;
for (const term of ['用户明确指代的对象','pixelMask','adopt_production_image','以该 candidateId 为父版本','保留模板原图定义']) {
assert.match(system,new RegExp(term));
}
} finally {await x.close();}
});
test('a production goal carries candidate and slot references with their actual image into the request',async()=>{
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
const slot={kind:'slot',label:'椅背图位',slotId:'back',outputId:'detail',productVariantId:'oak'};
const candidate={...slot,kind:'candidate',label:'椅背第二版',candidateId:'back-v2'};
const refinement={slotId:slot.slotId,reworkCandidateId:candidate.candidateId,prompt:'椅背居中,保留原商材。'};
const call=(name,args)=>sse({tool_calls:[{index:0,id:name,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
const x=await setup((_payload,n)=>n===1?call('prepare_image_request',refinement):
n===2?call('finish_production',{revision:1}):sse({content:'已核对。'},'stop'),undefined,{deadline:1});
const received=[];
try {
const {outputId,variantId}=x.host.productionGoal;
const operations=await x.host.productionWork.get(JSON.stringify([outputId,variantId]));
operations.prepare_image_request=async args=>{
received.push(args);
return {requestId:'refinement-draft',reworkOf:args.reworkCandidateId};
};
await x.host.prompt('引用第二版,微调椅背构图。',{referenceContent:[slot,{...candidate,image,mimeType:'image/png'}]});
const reference=x.requests[0].messages.find(row=>Array.isArray(row.content)&&
row.content.some(part=>part.type==='text'&&part.text.includes('椅背第二版')));
const request=JSON.parse(reference.content.find(part=>part.type==='text').text);
const quoted=JSON.parse(request.request.split('以下文字为引用内容):')[1]);
assert.deepEqual(quoted,[
{...slot,source:'本轮引用'},
{...candidate,source:'候选图',image:1},
]);
assert.ok(reference.content.some(part=>part.type==='image_url'&&part.image_url.url===`data:image/png;base64,${image}`));
assert.deepEqual(received,[refinement]);
} finally {await x.close();}
});
test('the model receives prior images and original tool receipts through Pi', async()=>{
const x=await setup((payload,n)=>{
if(n===1) return sse({tool_calls:[{index:0,id:'context-1',type:'function',function:{name:'context_read',arguments:'{}'}}]},'tool_calls');
return sse({content:'继续核对。'},'stop');
});
try {
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
await x.host.prompt('继续');
const tool=x.requests[1].messages.find(message=>message.tool_call_id==='context-1');
assert.ok(tool);
assert.ok(x.requests[2].messages.some(message=>message.tool_call_id==='context-1'&&message.content===tool.content));
assert.ok(x.requests[2].messages.some(message=>Array.isArray(message.content)&&message.content.some(x=>x.type==='image_url')),
JSON.stringify({model:x.host.session.model.input,session:x.host.session.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]),
wire:x.requests.map(payload=>payload.messages.map(message=>[message.role,
Array.isArray(message.content)?message.content.map(x=>x.type):typeof message.content]))}));
} finally {await x.close();}
});
test('main requests keep their original identity without saving a copy of the request body',async t=>{
const setting='XIAOYI_DUMP_RAW_PAYLOADS';
const previous=process.env[setting];
delete process.env[setting];
t.after(()=>{if(previous===undefined)delete process.env[setting];else process.env[setting]=previous;});
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
const url=`data:image/png;base64,${image}`;
const x=await setup(()=>sse({content:'已查看。'},'stop'));
t.after(x.close);
const readImageUrl=payload=>payload.messages.flatMap(row=>Array.isArray(row.content)?row.content:[])
.find(part=>part.type==='image_url')?.image_url.url;
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
assert.equal(readImageUrl(x.requests.at(-1)),url);
await assert.rejects(fs.access(path.join(x.store.dir,'payloads')), {code:'ENOENT'});
const journal=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');
assert.equal(journal.includes(image),false);
const events=journal.trim().split('\n').map(line=>JSON.parse(line));
const budget=events.find(event=>event.type==='context_budget');
assert.equal(budget.originalChars-budget.inputChars,image.length);
const requests=events.filter(event=>event.type==='provider_started');
assert.deepEqual(requests.map(event=>event.id),x.ids);
assert.ok(events.some(event=>event.type==='usage' && event.id===x.ids[0] && event.purpose==='conversation'));
assert.ok(events.some(event=>event.type==='provider_finished' && event.id===x.ids[0]));
process.env[setting]='1';
await x.host.prompt('继续核对');
const debugFile=path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json');
const archived=JSON.parse(await fs.readFile(debugFile,'utf8'));
assert.equal(readImageUrl(archived),url);
assert.equal(Object.hasOwn(archived,'headers'),false);
});
test('a worker can change course after many identical calls without terminating',async t=>{
const calls=[], imageCounts=[];
const image={type:'image',mimeType:'image/png',
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='};
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));
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:{}});
t.after(x.close);
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},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']);
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()=>{
const x=await setup(()=>sse({content:'已核对。'},'stop'));
try {
const {cwd,tools}=await projectTools(x.host);
const tool=name=>tools.find(row=>row.name===name);
await tool('write').execute('1',{path:'notes.md',content:'品牌说明'});
const result=await tool('read').execute('2',{path:'notes.md'});
assert.match(result.content[0].text,/品牌说明/);
assert.ok((await fs.readFile(path.join(cwd,'notes.md'),'utf8')).includes('品牌'));
await assert.rejects(tool('write').execute('3',{path:'../outside.txt',content:'无'}),/工作目录之外/);
await assert.rejects(tool('read').execute('4',{path:'../session.json'}),/工作目录之外/);
assert.ok(tool('bash'));
} finally {await x.close();}
});
test('a canvas can complete more than 20 edits and cancellation stops waiting',async()=>{
let rev=0, dispatched=0, apply=true;
const canvas=new StdioCanvas(async action=>{
if(action==='pi-edit'){dispatched++;if(apply)rev++;}
if(action==='pi-state')return {allowed:true,revision:rev,queued:!apply};
return {};
},1);
await canvas.begin('更新当前模板');
for(let index=0;index<21;index++)await canvas.edit({command:'text'},index);
apply=false;
const signal=AbortSignal.timeout(150);
await assert.rejects(canvas.edit({command:'text'},rev,signal),{name:'AbortError'});
assert.equal(dispatched,22);
});
test('first canvas save failure leaves the original run usable; a lost open ACK is observed without replay', async () => {
const target={outputId:'detail',variantId:'wood'};
const dispatched=[];
let attempts=0, binding;
const canvas=new StdioCanvas(async(action,input)=>{
if(action==='pi-begin')return {};
assert.equal(input.run,canvas.run);
assert.equal(input.documentId,1);
if(action==='pi-production-open'){
dispatched.push({outputId:input.outputId,variantId:input.variantId});
if(++attempts===1)return {openingProductionCanvas:true};
throw new BridgeError('画布未确认操作','transport_interrupted',{retryable:true,dispatched:true});
}
if(action==='pi-native-catalog'){
if(!binding)throw new BridgeError('请先打开工作画布','production_canvas_pending',{retryable:true});
return {revision:binding.revision};
}
assert.equal(action,'pi-state');
if(attempts===1)return {conversationActive:true,error:'当前草稿保存失败'};
binding={...target,revision:2,pendingOutputs:[]};
return {conversationActive:true,productionCanvas:binding};
},1);
await canvas.begin('制作详情页');
const first=canvas.openProductionOutput(target);
await Promise.all([
assert.rejects(first,{category:'production_canvas_open_failed',message:'当前草稿保存失败',retryable:true}),
assert.rejects(canvas.nativeCatalog(),{category:'production_canvas_pending',dispatched:false}),
]);
assert.deepEqual(await canvas.openProductionOutput(target),binding);
assert.deepEqual(await canvas.nativeCatalog(),{revision:2});
assert.deepEqual(dispatched,[target,target]);
});
test('private pipes carry a new canvas lease while one conversation waits for the original export receipt',async()=>{
const runs=new Set();
const variantId=randomUUID();
const detail={outputId:'detail',variantId};
const main={outputId:'main_images',variantId};
let binding, operationId;
const canvas=new StdioCanvas(async(action,input)=>{
runs.add(input.run);
if(action==='pi-begin')return {conversationActive:true};
if(action==='pi-production-open'){
assert.deepEqual(input.canvasBinding?.documentKey,binding?.documentKey);
const previousSave=binding?{saved:true,revision:binding.revision,documentKey:binding.documentKey}:null;
const documentKey={workspaceId:'workspace',outputId:input.outputId,variantId};
binding={outputId:input.outputId,variantId,documentKey,writeEpoch:(binding?.writeEpoch??0)+1,
revision:7,previousSave,pendingOutputs:[detail,main]};
return {conversationActive:true,productionCanvas:binding};
}
assert.deepEqual(input.canvasBinding,{documentKey:binding.documentKey,writeEpoch:binding.writeEpoch});
if(action==='pi-production-finish'){
operationId=input.operationId;
assert.equal(input.canvasRevision,7);
return {operationId,pending:true};
}
assert.equal(action,'pi-production-finish-status');
assert.equal(input.operationId,operationId);
return {operationId,canvasRevision:7,complete:true,files:[{path:'main.jpg'}],generationId:'verified-main',
pendingOutputs:[detail]};
},13);
await canvas.begin('制作两个成品');
const first=await canvas.openProductionOutput(detail);
const second=await canvas.openProductionOutput(main);
assert.equal(second.writeEpoch,first.writeEpoch+1);
assert.deepEqual(second.previousSave,{saved:true,revision:7,documentKey:first.documentKey});
const receipt=await canvas.finishProduction({...main,complete:true,canvasRevision:7});
assert.equal(receipt.generationId,'verified-main');
assert.deepEqual(receipt.pendingOutputs,[detail]);
await canvas.openProductionOutput(detail);
assert.equal(runs.size,1);
});
test('canvas search keeps the screen and keyword when a layer argument is also present',()=>{
assert.deepEqual(canvasReadQuery({layer:999,screen:'第二屏',screenId:41,filter:'材质',maxDepth:0,mode:'layers',offset:0}),
{screenId:41,filter:'材质',mode:'layers',offset:0});
assert.deepEqual(canvasReadQuery({layer:41,screen:'',filter:' '}),{layer:41});
assert.deepEqual(canvasReadQuery({screen:'',filter:''}),{offset:0});
});
test('the Pi canvas contract forwards a deeper group summary with the requested scope',()=>{
const query={screenId:90,maxDepth:6};
assert.ok(Value.Check(canvasReadParameters,query));
assert.deepEqual(canvasReadQuery(query),{mode:'summary',screenId:90,maxDepth:6,offset:0});
});
test('production exposes native controls and reads with other file tools deferred',async()=>{
const x=await setup(payload=>{
const names=payload.tools.map(row=>row.function.name);
for(const name of ['native_catalog','native_call','native_reconcile','codemode','tool_search','read']){
assert.ok(names.includes(name),name);
}
for(const name of ['write','edit','ls','find','grep','bash']) assert.ok(!names.includes(name),name);
return sse({tool_calls:[{index:0,id:'finish',type:'function',function:{name:'finish_production',arguments:'{"revision":1}'}}]},'tool_calls');
},undefined,{progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{nativeCatalog(){},nativeCall(){},nativeReconcile(){}}});
try {
assert.equal(x.host.session.agent.toolExecution,'parallel');
const names=x.host.session.getActiveToolNames();
assert.ok(names.includes('codemode'));
assert.ok(names.includes('tool_search'));
assert.ok(names.includes('read'));
assert.ok(x.host.session.getToolDefinition('write'));
assert.equal((await x.host.prompt('核对制作工具')).production.complete,true);
assert.equal(x.requests.length,1);
} finally {await x.close();}
});
test('Pi runs independent production reads from the same model turn concurrently',async()=>{
let release;
const gate=new Promise(resolve=>{release=resolve;});
const started=[];
const read=async name=>{
started.push(name);
if(started.length===2)release();
await gate;
return {items:[]};
};
const x=await setup((_,round)=>{
const calls=round===1?['plan_production','native_catalog']:['finish_production'];
return sse({tool_calls:calls.map((name,index)=>({index,id:name,type:'function',
function:{name,arguments:round===1?'{}':'{"revision":1}'}}))},'tool_calls');
},undefined,{plan:()=>read('plan_production'),canvas:{
nativeCatalog:()=>read('native_catalog'),nativeCall(){},
}});
const result=x.host.prompt('读取制作计划和原生命令目录');
try{
await Promise.race([gate,new Promise((_,reject)=>{
const timer=setTimeout(()=>reject(Error('同批只读工具没有并发开始')),2000);
timer.unref();
})]);
assert.equal(started.length,2);
assert.equal((await result).production.complete,true);
}finally{
release();
try{await result;}finally{await x.close();}
}
});
test('production publishes direct native commands and no duplicate conversation tools',async()=>{
const executed=[];
const x=await setup((_,request)=>{
const name=request===1?'native_call':request===2?'tool_search':'finish_production';
const args=request===1?{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}:
request===2?{query:'bash',limit:1}:{revision:1};
return sse({tool_calls:[{index:0,id:'edit-'+request,type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
},undefined,{
progress:()=>({state:{waitingOnOriginals:true}}),
canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async revision=>({allowed:true,revision}),
nativeReconcile(){}, readTemplateImage(){}, preview(){}, copyOptions(){}, copyFields(){},
workflowRead:async()=>({available:false,version:1}), workflowNavigate(){}, workflowPropose(){}, workflowExecute(){}, workflowPoll(){},
edit:async()=>{assert.fail('production must use the original native command receipt');},
nativeCall:async args=>{executed.push(args);return {completed:true,executed:true,revision:2};},
},
});
try{
for(const name of ['canvas_read','canvas_edit','canvas_template_image','canvas_preview','copywriting_options',
'copywriting_fields','workflow_read','workflow_navigate','workflow_execute','workflow_propose']) {
assert.equal(x.host.session.getToolDefinition(name),undefined,name);
}
for(const name of ['plan_production','native_catalog','native_call','native_reconcile','read','bash','tool_search','codemode']){
assert.ok(x.host.session.getToolDefinition(name),name);
}
for(const name of ['read_image_request','freeze_image_request']){
assert.equal(x.host.session.getToolDefinition(name),undefined,name);
}
for(const name of ['plan_production','native_catalog','read_copy_fields','read_slot_images','review_image_slots','read_output_screen']){
assert.notEqual(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
for(const name of ['native_call','prepare_image_request','dispatch_image_request','transform_slot_image','finish_production']){
assert.equal(x.host.session.getToolDefinition(name).executionMode,'sequential',name);
}
assert.equal((await x.host.prompt('完成制作')).production.complete,true);
const initialNames=x.requests[0].tools.map(tool=>tool.function.name);
assert.ok(initialNames.includes('read'));
assert.ok(x.requests[2].tools.some(tool=>tool.function.name==='bash'));
for (const name of ['bash','edit','write','find','grep','ls','memory_set','memory_search','context_read']) {
assert.ok(!initialNames.includes(name),name);
}
assert.deepEqual(executed,[{revision:1,method:'engine.execute',params:{command:'type.edit',params:{layer:2,text:'New'}}}]);
const row=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='edit-1')?.message;
assert.equal(JSON.parse(row.content[0].text).executed,true);
}finally{await x.close();}
});
test('a temporary write wait and a rejected native edit can be corrected in the same production turn', async () => {
let leases = 0, edits = 0;
const x = await setup((_, request) => {
const name = request <= 2 ? 'native_call' : 'finish_production';
const args = request <= 2
? {revision: 1, method: 'engine.execute', params: {command: 'type.edit', params: {
layer: 2, text: request === 1 ? 'A title that cannot fit' : 'New', expectedText: 'Old',
}}}
: {revision:1};
return sse({tool_calls: [{index: 0, id: `tool-${request}`, type: 'function',
function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls');
}, undefined, {
callBudget: 4,
progress: () => ({state: {waitingOnOriginals: true}}),
canvas: {
nativeCatalog() {}, nativeReconcile() {},
requestWrite: async revision => ++leases === 1
? {allowed: false, revision, retryWrite: true, detailWriteWaiting: true}
: {allowed: true, revision},
nativeCall: async () => {
if (++edits === 1) throw new BridgeError('画布已修改,请先读取当前修订','revision_conflict',{dispatched:false});
return {completed:true,executed:true,revision:2};
},
},
});
try {
assert.equal((await x.host.prompt('完成制作')).production.complete, true);
assert.equal(leases, 3);
assert.equal(edits, 2);
const rejected = x.host.manager.getBranch().find(({message})=>message?.toolCallId==='tool-1')?.message;
assert.match(rejected.content[0].text,/画布已修改,请先读取当前修订/u);
assert.equal(x.requests.length, 3);
assert.equal(x.host.canvasOperations.original, undefined);
} finally { await x.close(); }
});
test('a new revision while a native write is waiting never dispatches the old command', async () => {
let reads=0;
const x=await setup((_,attempt)=>sse({tool_calls:[{index:0,id:'native-wait-'+attempt,type:'function',function:attempt===1
? {name:'native_call',arguments:JSON.stringify({revision:1,method:'engine.execute',
params:{command:'type.edit',params:{layer:2,text:'草稿'}}})}
: {name:'finish_production',arguments:'{"revision":2}'}}]},'tool_calls'),undefined,{
progress:()=>({}),
canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async()=>({allowed:false,revision:++reads===1?1:2,retryWrite:true,detailWriteWaiting:true}),
nativeCall:async()=>assert.fail('stale native call must not dispatch'),
},
});
try {
assert.equal((await x.host.prompt('写入确认的修改')).production.complete,true);
assert.equal(reads,2);
const rejected=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='native-wait-1')?.message;
assert.match(rejected.content[0].text,/写入修订已变化/u);
assert.equal(x.host.canvasOperations.original,undefined);
} finally {await x.close();}
});
test('production syncs a single-layer presentation edit to the latest authorized revision before dispatch', async () => {
const writes = [], dispatched = [], events = [];
let dirty = 0;
const host = {
productionGoal:{}, productionWork:new Map([[JSON.stringify([undefined,undefined]),{markProgressDirty:()=>dirty++}]]),
store:{appendEvent:async event=>events.push(event)},
canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async revision=>{
writes.push(revision);
if(revision===4)return {revision:5,retryWrite:true,detailWriteWaiting:true};
if(revision===5)return {revision:6,retryWrite:true};
return {revision,allowed:true};
},
nativeCall:async args=>{
dispatched.push(args);
return {completed:true,executed:true,revision:7};
},
},
};
const [,call]=nativeTools(host,(_name,_description,_schema,execute)=>({execute}));
const args={revision:4,method:'engine.execute',params:{command:'layer.setProps',params:{layer:23,opacity:0.8}}};
assert.equal((await call.execute(args)).revision,7);
assert.deepEqual(writes,[4,5,6]);
assert.deepEqual(dispatched,[{...args,revision:6}]);
assert.equal(args.revision,4);
assert.equal(dirty,1);
assert.equal(events.at(-1).revision,7);
});
test('production native writes stop on revoked permission, stale targets or a native rejection', async () => {
const base={revision:4,method:'engine.execute',params:{command:'layer.setProps',params:{layer:23,visible:false}}};
for(const {args=base,reply,error,dispatch=false} of [
{reply:{revision:6,retryWrite:true,detailWriteWaiting:true,writeBlocked:true},error:{category:'write_revoked'}},
{reply:{revision:6,allowed:true},error:{category:'revision_conflict'}},
{args:{...base,params:{command:'layer.setProps',params:{visible:false}}},
reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}},
{args:{...base,params:{command:'layer.setProps',params:{layers:[23,24],visible:false}}},
reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}},
{args:{...base,params:{command:'layer.setProps',params:{layer:23,locks:{all:false}}}},
reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}},
{args:{...base,params:{command:'edit.transform',params:{layer:23,dx:5}}},
reply:{revision:6,retryWrite:true},error:{category:'revision_conflict'}},
{reply:{revision:6,retryWrite:true},error:/当前图层已锁定/,dispatch:true},
]) {
const writes=[],dispatched=[];
const host={productionGoal:{},store:{},canvas:{
nativeCatalog:async({id})=>({items:[{id,requiresRevisionLease:true}]}),
requestWrite:async rev=>{
writes.push(rev);
return writes.length===1?reply:{revision:rev,allowed:true};
},
nativeCall:async input=>{
dispatched.push(input);
return {completed:true,executed:false,revision:6,error:'当前图层已锁定'};
},
}};
const [,call]=nativeTools(host,(_name,_description,_schema,execute)=>({execute}));
await assert.rejects(call.execute(args),error);
assert.deepEqual(writes,dispatch?[4,6]:[4]);
assert.deepEqual(dispatched,dispatch?[{...args,revision:6}]:[]);
assert.equal(host.canvasOperations.original,undefined);
}
});
test('production native queries follow the catalog without requesting a canvas write lease', async () => {
const commands=[];
const calls=[
{name:'native_call',args:{revision:1,method:'engine.execute',params:{command:'document.inspect',params:{}}}},
{name:'native_call',args:{revision:1,method:'result.read',params:{resultId:3,pointer:'/layers',offset:0}}},
{name:'finish_production',args:{revision:1}},
];
const x = await setup((_, request) => {
const {name,args}=calls[request-1];
return sse({tool_calls: [{index: 0, id: `native-${request}`, type: 'function',
function: {name, arguments: JSON.stringify(args)}}]}, 'tool_calls');
}, undefined, {
progress: () => ({state: {waitingOnOriginals: true}}),
canvas: {
nativeCatalog: async ({id}) => ({items: [{id, requiresRevisionLease: false}]}),
requestWrite() { assert.fail('read-only operation requested a write lease'); },
nativeCall: async ({method,params}) => {
commands.push({method,params});
const result=method==='result.read'?{items:[{id:7}],nextOffset:null}:{resultRef:{resultId:3}};
return {completed:true,executed:true,result};
},
},
});
try {
assert.equal((await x.host.prompt('核对当前画布')).production.complete, true);
assert.deepEqual(commands,calls.slice(0,2).map(({args:{method,params}})=>({method,params})));
const read=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='native-2')?.message;
assert.deepEqual(JSON.parse(read.content[0].text).result.items,[{id:7}]);
} finally { await x.close(); }
});
test('ordinary discussion can still navigate the product views without writes', async () => {
const viewed=[];
const x=await setup((_,n)=>n===1?sse({tool_calls:[{index:0,id:'view-1',type:'function',
function:{name:'workflow_navigate',arguments:'{"stage":"canvas","outputId":"main_images"}'}}]},'tool_calls')
:sse({content:'已打开主图。'},'stop'),undefined,undefined,{
canvas:{
workflowNavigate:async args=>{
viewed.push(args);
return {navigated:true,executed:false,outputId:args.outputId,version:1};
},
requestWrite() {assert.fail('navigation requested a write');},
},
});
try {
assert.equal((await x.host.prompt('查看主图布局')).text,'已打开主图。');
const message=x.host.manager.getBranch().find(({message})=>message?.toolCallId==='view-1')?.message;
assert.deepEqual(viewed,[{stage:'canvas',outputId:'main_images'}]);
assert.equal(JSON.parse(message.content[0].text).outputId,'main_images');
} finally {await x.close();}
});
test('reading a fresh production goal never starts the strategy, image workers, or canvas writes', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-production-read-'));
t.after(() => cleanup(dir));
const host = {
productionGoal: {outputId:'detail',variantId:'walnut'},
store:productionStore(dir),
runDetailAgent() {assert.fail('a read started production');},
canvas: {
workflowRead: async () => ({available:true,canvasFirst:true,outputId:'detail',productVariantId:'walnut',
template:{contentHash:'desk-version'},totalSlots:1,slots:[{id:'desk',fieldId:'cover',label:'主视觉',candidates:[]}]}),
detailCopyFields: async ({pageId}) => ({
fields:[{layer:6,page:'intro'},{layer:9,page:'specs'}].filter(field=>!pageId||field.page===pageId),
}),
read:async()=>({revision:3}),
imageRequest: async stage => {assert.equal(stage,'pending');return [];},
detailRender: async () => ({page:0,revision:3,images:[]}),
},
};
assert.equal((await callProductionTool(host,'plan_production',{})).pictures.length,1);
assert.equal((await callProductionTool(host,'review_image_slots',{slotIds:['desk']})).pictures[0].id,'desk');
assert.deepEqual((await callProductionTool(host,'read_copy_fields',{pageId:'specs'})).fields,[{layer:9,page:'specs'}]);
assert.equal((await callProductionTool(host,'read_output_screen',{page:0})).details.revision,3);
assert.equal((await host.productionWork.get(JSON.stringify(['detail','walnut']))).active,0);
});
test('production loads project prompt templates without discovering project skills', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-project-resources-'));
t.after(() => cleanup(dir));
const cwd = path.join(dir, 'workspace');
const skillDir = path.join(cwd, '.pi', 'skills', 'desk-copy');
const promptDir = path.join(cwd, '.pi', 'prompts');
await fs.mkdir(skillDir, {recursive: true});
await fs.mkdir(promptDir, {recursive: true});
await fs.writeFile(path.join(skillDir, 'SKILL.md'),
'---\nname: desk-copy\ndescription: Write usable desk copy.\n---\nShow the available work surface.');
await fs.writeFile(path.join(promptDir, 'fixture-copy.md'),
'---\ndescription: Write a fixture headline.\n---\nDescribe the work surface.');
const {resourceLoader} = await createPhotoCraftExtensions({workingDirectory: cwd, store: {dir}}, [], {includeGoal: true});
assert.ok(!resourceLoader.getSkills().skills.some(skill => skill.name === 'desk-copy'));
assert.equal(resourceLoader.getPrompts().prompts.find(prompt => prompt.name === 'fixture-copy')?.content,
'Describe the work surface.');
});
test('Pi serializes shared cache affinity for the same kind of production worker', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-worker-cache-'));
const scope = 'a'.repeat(64), project = randomUUID();
const store = await ProjectStore.open(root, {scope,project},
{brandId:'qa',shopId:'qa',categoryId:'qa',platform:'qa',version:'1',source:'fixture',rules:[]});
const bodies = [];
const broker = new Native98kBroker({project,profile:root});
broker.scope = scope;
broker.info = async () => ({accountScope:scope,model:{id:'qa',protocol:'openai-responses',supportsImageInput:true},pending:[]});
broker.status = async () => ({pending:[]});
broker.forDetailSlot = () => broker;
const event = (type,details) => 'event: '+type+'\ndata: '+JSON.stringify({type,...details})+'\n\n';
const item = {type:'message',id:'msg_test',role:'assistant',status:'completed',
content:[{type:'output_text',text:'Read complete.',annotations:[]}]};
const response = event('response.output_item.added',{output_index:0,item:{...item,content:[]}})
+event('response.output_text.delta',{output_index:0,content_index:0,delta:'Read complete.'})
+event('response.output_item.done',{output_index:0,item})
+event('response.completed',{response:{model:'qa',status:'completed',output:[item]}});
broker.start = async (method,input,emit) => {
if (method === 'finish') return {phase:'complete'};
assert.equal(method,'request');
bodies.push(typeof input.body === 'string' ? JSON.parse(input.body) : input.body);
emit({type:'headers',status:200,requestId:randomUUID(),headers:{'content-type':'text/event-stream'},bodyHash:'synthetic'});
emit({type:'chunk',data:Buffer.from(response).toString('base64')});
return {phase:'complete'};
};
const production = new AbortController();
const host = await DetailPiAgent.open({store,broker,productionSignal:production.signal,
canvas:{read:async()=>({conversationActive:true})}});
t.after(async()=>{await host.dispose();await cleanup(root);});
for (const [slot,worker] of [['slot-a','review'],['slot-b','review'],['slot-c','worker']]) {
await host.runDetailAgent(slot,'Synthetic fixture system','Inspect the synthetic fixture.',[],[],'product/'+worker+'/'+slot);
}
assert.equal(bodies.length,3);
const session = host.manager.getSessionId();
assert.deepEqual(bodies.map(body=>body.prompt_cache_key),[session+':review',session+':review',session+':worker']);
const enter=Promise.withResolvers();
const round=broker.round.bind(broker);
let interrupted=0;
broker.round=()=>({id:randomUUID(),fetch:async()=>{
interrupted++;
throw Error('network error: synthetic disconnect');
},finish:async()=>{throw Error('network error: synthetic disconnect');}});
await assert.rejects(host.runDetailAgent('slot-interrupted','Synthetic system','Inspect fixture.',[],[],
'product/review/slot-interrupted'),/synthetic disconnect/u);
assert.equal(interrupted,4);
let stoppedCalls=0;
broker.round=options=>({...round(options),fetch:(_address,{signal})=>{
stoppedCalls++;
enter.resolve();
return new Promise((_resolve,reject)=>signal.addEventListener('abort',()=>reject(signal.reason),{once:true}));
}});
const worker=host.runDetailAgent('slot-d','Synthetic system','No further work after stop.',[],[],'product/review/slot-d');
const stopped=assert.rejects(worker,/制作已停止/u);
await enter.promise;
production.abort(Error('本轮制作已停止'));
await stopped;
assert.equal(stoppedCalls,1);
});