447 lines
28 KiB
JavaScript
447 lines
28 KiB
JavaScript
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 { createAssistantMessageEventStream, getCurrentSystemPrompt } from '@earendil-works/pi-ai/compat';
|
||
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
||
import { openAgent } from './fake-canvas.mjs';
|
||
import { ProjectStore, atomic } from '../src/store.mjs';
|
||
import { StdioCanvas } from '../src/stdio-canvas.mjs';
|
||
import { NativeControlClient as NativeCanvas } from '../src/native-control-client.mjs';
|
||
import { workflowContext, workflowResult } from '../src/workflow-context.mjs';
|
||
import { executeWorkflow } from '../src/workflow-execute.mjs';
|
||
import { cleanup } from './cleanup.mjs';
|
||
import { openXiaoyiSkills } from '../src/xiaoyi-release.mjs';
|
||
import { xiaoyiFixture } from './xiaoyi-fixture.mjs';
|
||
|
||
const scope = '8'.repeat(64);
|
||
const binding = { brandId:'qa',shopId:'qa',categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',rules:[] };
|
||
const info = { accountScope:scope,accountId:'local-qa',origin:'https://platform.test',
|
||
model:{id:'qa-workflow',protocol:'openai-chat',contextWindow:131072,contextWindowSource:'fixture'},pending:[] };
|
||
function readContext(context) {
|
||
const result=context.messages.findLast(message=>message.role==='toolResult'&&message.toolName==='context_read'&&!message.isError);
|
||
return result&&JSON.parse(result.content[0].text);
|
||
}
|
||
function stream(content) {
|
||
const out = createAssistantMessageEventStream();
|
||
const message = { role:'assistant',api:'openai-completions',provider:'jiansun-native-98k',model:info.model.id,content,
|
||
stopReason:content.some(c=>c.type==='toolCall')?'toolUse':'stop',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(()=>{out.push({type:'start',partial:message});out.push({type:'done',reason:message.stopReason,message});out.end(message);});
|
||
return out;
|
||
}
|
||
const tool = (name,args,id='workflow-call') => [{type:'toolCall',id,name,arguments:args}];
|
||
const answer = text => [{type:'text',text}];
|
||
|
||
test('a timed-out context meter cannot discard a finished model reply', async () => {
|
||
const calls=[];
|
||
const canvas=new StdioCanvas(async(action,input)=>{
|
||
calls.push(action);
|
||
assert.equal(input.run,'run');
|
||
if(action==='pi-context-usage')throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted');
|
||
return {ok:true};
|
||
},7);
|
||
canvas.run='run';
|
||
await canvas.contextUsage({outputTokens:12});
|
||
await canvas.end('已完成复核');
|
||
assert.deepEqual(calls,['pi-context-usage','pi-end']);
|
||
});
|
||
|
||
test('production queries the same operation after the canvas misses a reply',async()=>{
|
||
const calls=[];
|
||
let originalPending=true;
|
||
const canvas=new StdioCanvas(async(action,input)=>{
|
||
calls.push({action,input});
|
||
if(action==='pi-workflow-execute')throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted');
|
||
if(action==='pi-workflow-reconcile'){
|
||
const phase=originalPending?'submitted':'complete';
|
||
originalPending=false;
|
||
return {...input,candidateId:'retained-original',phase};
|
||
}
|
||
throw Error('unexpected canvas call '+action);
|
||
},7);
|
||
canvas.run='same-run';
|
||
const host={canvas,store:{appendEvent:async()=>{}},readWorkflow:async()=>assert.fail('the batch trusts the original receipt')};
|
||
const result=await executeWorkflow(host,{intent:'generate_candidate',outputId:'detail',slotId:'hero',productVariantId:'wood'},undefined,{detailBatch:true});
|
||
assert.equal(result.operation.candidateId,'retained-original');
|
||
assert.ok(!host.canvasOperations.original);
|
||
assert.deepEqual(calls.map(({action})=>action),['pi-workflow-execute','pi-workflow-reconcile','pi-workflow-reconcile']);
|
||
assert.ok(calls.every(({input})=>input.operationId===calls[0].input.operationId&&input.run==='same-run'&&input.documentId===7));
|
||
});
|
||
|
||
test('production rereads the same bound candidate after a local image receipt times out',async()=>{
|
||
const calls=[];
|
||
const canvas=new StdioCanvas(async(action,input)=>{
|
||
calls.push({action,input});
|
||
if(calls.length===1)throw new BridgeError('画布未确认操作,请保留当前状态','transport_interrupted');
|
||
return {candidateId:input.candidateId};
|
||
},7);
|
||
canvas.run='same-run';
|
||
assert.deepEqual(await canvas.detailImages('hero','original',{adopted:true}),{candidateId:'original'});
|
||
const action={action:'pi-detail-images',input:{slotId:'hero',candidateId:'original',adopted:true,run:'same-run',documentId:7}};
|
||
assert.deepEqual(calls,[action,action]);
|
||
});
|
||
|
||
test('a missed production status update does not block work or replay the update',async()=>{
|
||
const calls=[];
|
||
const canvas=new StdioCanvas(async(action,input)=>{
|
||
calls.push({action,input});
|
||
throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted');
|
||
},7);
|
||
await canvas.delta('等待生图',undefined,{heading:'等待生图'});
|
||
await assert.rejects(canvas.delta('常规对话'),/原操作不会重发/u);
|
||
assert.equal(calls.length,2);
|
||
});
|
||
|
||
function evidence(project,color='胡桃色',brandId='native-brand',categoryId='native-category',length='') {
|
||
return {accountScope:scope,project,documentId:7,revision:1,brief:{name:'电脑桌',brandId,categoryId,colorName:color,dimensions:{length,width:'',height:'',unit:'mm'}},
|
||
facts:{status:'ready',items:[{text:'长方形桌面',source:'产品实拍'}],missing:['木种和承重未确认']},sellingPoints:{selected:[],batches:[]},plan:{status:'idle',screens:[]}};
|
||
}
|
||
function baseCanvas() {
|
||
return {activities:[],writes:0,grants:0,async begin(){},async read(){return {conversationActive:true,allowed:false,writeBlocked:false,revision:1,context:{id:7,name:'本机画布',width:1440,height:1800,layers:[]}};},
|
||
async requestWrite(){this.grants++;throw Error('not used');},async edit(){this.writes++;throw Error('not used');},async activity(text){this.activities.push(text);},async delta(){},async end(){}};
|
||
}
|
||
async function fixture(reply,{adapter='full',execute=false,broker,history=false,nativeEvidence=true,nativeBrandId='native-brand',nativeCategoryId='native-category'}={}) {
|
||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project};
|
||
const store=await ProjectStore.open(root,identity,binding,{continuous:true}),canvas=baseCanvas();
|
||
if(history){
|
||
const manager=SessionManager.create(store.dir,path.join(store.dir,'sessions'));
|
||
for(let i=0;i<48;i++){
|
||
manager.appendMessage({role:'user',content:`本地旧讨论${i}:`+'资料'.repeat(500),timestamp:Date.now()});
|
||
manager.appendMessage({role:'assistant',api:'openai-completions',provider:'jiansun-native-98k',model:info.model.id,content:answer('本地mock历史说明。'.repeat(100)),stopReason:'stop',timestamp:Date.now(),usage:{input:5000,output:500,cacheRead:0,cacheWrite:0,totalTokens:5500,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}});
|
||
}
|
||
await atomic(path.join(store.dir,'session.json'),{file:manager.getSessionFile()});
|
||
}
|
||
const native={version:1,stage:'materials',color:'胡桃色',brandId:nativeBrandId,categoryId:nativeCategoryId,length:'',reads:[],navigations:[],proposals:[],generated:0};
|
||
canvas.workflowRead=async args=>{
|
||
native.reads.push(structuredClone(args));
|
||
return {available:adapter!=='unavailable',version:native.version,stage:native.stage,section:args.section||'overview',revisions:{canvas:1,creation:native.version,slots:0},
|
||
productEvidence:adapter==='unavailable'?null:evidence(project,native.color,native.brandId,native.categoryId,native.length),outputs:[{id:'detail',name:'详情',count:5}]};
|
||
};
|
||
if(adapter==='full'){
|
||
canvas.workflowNavigate=async args=>{native.navigations.push(args);native.stage=args.stage;return {available:true,version:native.version,stage:native.stage,outputId:args.outputId};};
|
||
canvas.workflowPropose=async args=>{native.proposals.push(args);if(args.version!==native.version)throw Error('工作流版本已变化,请重新读取;未添加建议');if(args.instruction?.trim()&&args.intent!=='selling_points')throw Error('补充要求仅用于卖点表达方向,其他提案使用当前配置');return {proposed:true,awaitingReview:true,executed:false,version:native.version,proposal:{...args,title:'拟定页面方案',awaitingReview:true,executed:false}};};
|
||
}
|
||
if(execute){canvas.workflowExecute=async args=>({operationId:args.operationId,phase:'submitted'});canvas.workflowPoll=async operationId=>({operationId,phase:'complete'});}
|
||
const calls=[];
|
||
const transport={info,stream(_model,context){calls.push({context,evidence:readContext(context)});return stream(reply(context,calls.length,native,canvas));}};
|
||
const host=await openAgent({store,canvas,transport,broker,projectEvidence:nativeEvidence?evidence(project,'胡桃色',native.brandId,native.categoryId):undefined,documentId:7});
|
||
return {root,project,identity,store,canvas,native,calls,host,async close(){await host.dispose();await cleanup(root);}};
|
||
}
|
||
|
||
test('each SDK step reads live workflow and product state while suggestions stay review-only',async()=>{
|
||
const x=await fixture((_context,n,native)=>{
|
||
if(n===1)return tool('workflow_read',{section:'materials'},'read-materials');
|
||
if(n===2)return tool('context_read',{},'read-current');
|
||
if(n===3)return tool('workflow_navigate',{stage:'plan',outputId:'detail'},'show-plan');
|
||
if(n===4)return tool('workflow_propose',{version:native.version,intent:'plan',outputId:'detail'},'propose-plan');
|
||
return answer('已添加待审核建议,尚未生成页面。');
|
||
});
|
||
const read=x.canvas.workflowRead;
|
||
x.canvas.workflowRead=async args=>{
|
||
if(args.section==='materials'){x.native.version=2;x.native.color='米白色';x.native.length='1400';}
|
||
return read(args);
|
||
};
|
||
try{
|
||
const result=await x.host.prompt('先看当前资料,再展示方案步骤并列出建议,暂不执行。');
|
||
assert.match(result.text,/待审核/);
|
||
assert.equal(x.calls.length,5);
|
||
assert.equal(x.calls[0].evidence,undefined);
|
||
assert.equal(x.calls[1].evidence,undefined);
|
||
for(const call of x.calls.slice(2)){
|
||
assert.equal(call.evidence.currentWorkflow.version,2);
|
||
assert.equal(call.evidence.currentProduct.product.colorName,'米白色');
|
||
assert.equal(call.evidence.currentProduct.dimensions.length,'1400');
|
||
const system=getCurrentSystemPrompt(call.context.messages);
|
||
assert.doesNotMatch(system,/当前项目与画布事实/u);
|
||
assert.ok(!JSON.stringify(call.evidence.currentWorkflow).includes('productEvidence'));
|
||
}
|
||
assert.equal(x.native.reads.filter(v=>v.section==='overview').length,2);
|
||
assert.equal(x.native.navigations.length,1);assert.equal(x.native.proposals.length,1);assert.equal(x.native.generated,0);
|
||
assert.equal(x.canvas.writes,0);assert.equal(x.canvas.grants,0);
|
||
for(const label of ['读取创作进度','切换创作视图','添加待审核建议'])assert.ok(x.canvas.activities.some(a=>a.includes(label)));
|
||
const proposal=x.host.session.messages.find(m=>m.role==='toolResult'&&m.toolName==='workflow_propose');
|
||
const card=JSON.parse(proposal.content[0].text);
|
||
assert.equal(card.executed,false);assert.equal(card.proposal.intent,'plan');assert.equal(card.proposal.outputId,'detail');
|
||
assert.equal(card.proposal.title,'拟定页面方案');assert.equal(card.proposal.awaitingReview,true);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('unavailable live data never revives an old product',async()=>{
|
||
const x=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('仅讨论当前可确认的资料。'),{adapter:'unavailable'});
|
||
try{
|
||
await x.host.prompt('先聊一下当前资料。');
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.available,false);assert.equal(x.calls[1].evidence.currentProduct.state,'unavailable');assert.ok(!JSON.stringify(x.calls[1].evidence.currentProduct).includes('胡桃色'));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('a stale proposal stays an SDK tool error and is never retried or executed',async()=>{
|
||
const x=await fixture((context,n)=>{
|
||
if(n===1)return tool('workflow_propose',{version:1,intent:'analyze'},'stale-proposal');
|
||
const failure=context.messages.find(m=>m.role==='toolResult'&&m.toolName==='workflow_propose');
|
||
assert.equal(failure.isError,true);assert.match(failure.content[0].text,/工作流版本已变化/);
|
||
return answer('资料已更新,原建议未添加,也未执行分析。');
|
||
});
|
||
x.native.version=2;
|
||
try{await x.host.prompt('先提出分析建议。');assert.equal(x.native.proposals.length,1);assert.equal(x.native.generated,0);assert.equal(x.calls.length,2);}
|
||
finally{await x.close();}
|
||
});
|
||
|
||
test('foreign live evidence rejects before inference and memory_set cannot mutate native product data',async()=>{
|
||
const foreign=await fixture(()=>{throw Error('must not infer with foreign evidence');});
|
||
foreign.canvas.workflowRead=async()=>({available:true,version:1,section:'overview',productEvidence:{...evidence(foreign.project),accountScope:'9'.repeat(64)}});
|
||
try{await assert.rejects(foreign.host.prompt('读取资料。'),/不属于当前账户和项目/);assert.equal(foreign.calls.length,0);}
|
||
finally{await foreign.close();}
|
||
const x=await fixture((_context,n)=>n===1?tool('memory_set',{key:'color',value:'米白色',evidence:'颜色是米白色'},'remember-only'):answer('已记录讨论内容,产品资料尚未修改。'));
|
||
try{
|
||
await x.host.prompt('我在讨论中确认颜色是米白色,请先记住。');
|
||
assert.equal((await x.store.context()).confirmedMemory.color.value,'米白色');
|
||
assert.equal(x.host.productEvidence.product.colorName,'胡桃色');
|
||
assert.equal(x.native.color,'胡桃色');assert.equal(x.native.proposals.length,0);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('brand or category changes stop before inference or tools and require a new rule-bound turn',async()=>{
|
||
for(const key of ['brandId','categoryId'])for(const phase of ['before-provider','before-tool']){
|
||
const x=await fixture((_context,n,native)=>{
|
||
if(n===1){native[key]='changed-native-id';return tool('memory_set',{key:'color',value:'米白色',evidence:'颜色是米白色'},'must-not-remember');}
|
||
throw Error('must not infer with a new product and old rules');
|
||
},{nativeBrandId:'',nativeCategoryId:''});
|
||
let reopened,disposed=false;
|
||
try{
|
||
if(phase==='before-provider')x.native[key]='changed-native-id';
|
||
const ledger=path.join(x.store.memoryDir,'user-evidence.jsonl');
|
||
await assert.rejects(x.host.prompt('我确认颜色是米白色,请记录事实。'),/品牌或品类已变化/);
|
||
assert.equal(x.calls.length,phase==='before-provider'?0:1);
|
||
assert.deepEqual((await x.store.context()).confirmedMemory,{});
|
||
if(phase==='before-provider')await assert.rejects(fs.stat(ledger),{code:'ENOENT'});
|
||
assert.equal(x.canvas.writes,0);assert.equal(x.canvas.grants,0);assert.equal(x.native.proposals.length,0);
|
||
const calls=x.calls.length;
|
||
await assert.rejects(x.host.prompt('继续刚才的讨论。'),/品牌或品类已变化/);
|
||
assert.equal(x.calls.length,calls);
|
||
await x.host.dispose();disposed=true;
|
||
const updated=await ProjectStore.open(x.root,x.identity,{...binding,brandId:'new-rule-brand',categoryId:'new-rule-category',version:'2',rules:['新回合已加载新规则']},{continuous:true});
|
||
const next=[];
|
||
reopened=await openAgent({store:updated,canvas:x.canvas,documentId:7,projectEvidence:evidence(x.project,x.native.color,x.native.brandId,x.native.categoryId),
|
||
transport:{info,stream(_model,context){
|
||
next.push(readContext(context));
|
||
return stream(next.length===1?tool('context_read',{}):answer('已按新回合的规则继续讨论。'));
|
||
}}});
|
||
await reopened.prompt('按当前产品重新讨论,不修改画布。');
|
||
assert.equal(next.length,2);assert.equal(next[1].snapshot.brandId,'new-rule-brand');assert.equal(next[1].snapshot.categoryId,'new-rule-category');
|
||
assert.equal(next[1].currentProduct.product[key],'changed-native-id');
|
||
assert.deepEqual(next[1].confirmedMemory,{});assert.equal(x.canvas.writes,0);
|
||
}finally{await reopened?.dispose();if(!disposed)await x.host.dispose();await cleanup(x.root);}
|
||
}
|
||
// An adapter without initial native evidence may establish its first live
|
||
// binding, while a native empty ID above remains a real immutable binding.
|
||
const initial=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('首次读取的本机资料已可用于讨论。'),{nativeEvidence:false});
|
||
try{await initial.host.prompt('读取当前资料。');assert.equal(initial.calls.length,2);assert.equal(initial.calls[1].evidence.currentProduct.product.brandId,'native-brand');}
|
||
finally{await initial.close();}
|
||
});
|
||
|
||
test('a temporary Windows journal lock commits the same candidate receipt once', {
|
||
skip: process.platform !== 'win32',
|
||
}, async t => {
|
||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-production-receipt-'));
|
||
t.after(() => cleanup(root));
|
||
const file = path.join(root, 'production-detail.json');
|
||
const before = { state: 'candidate', requestId: 'original' };
|
||
const next = { ...before, state: 'reviewed' };
|
||
await atomic(file, before);
|
||
const rename = fs.rename;
|
||
let attempts = 0;
|
||
let temp;
|
||
t.mock.method(fs, 'rename', async (source, target) => {
|
||
assert.equal(target, file);
|
||
temp ??= source;
|
||
assert.equal(source, temp);
|
||
assert.deepEqual(JSON.parse(await fs.readFile(file, 'utf8')), before);
|
||
if (++attempts <= 2) throw Object.assign(new Error('journal temporarily locked'), { code: 'EPERM' });
|
||
return rename(source, target);
|
||
});
|
||
await atomic(file, next);
|
||
assert.equal(attempts, 3);
|
||
assert.deepEqual(JSON.parse(await fs.readFile(file, 'utf8')), next);
|
||
assert.deepEqual(await fs.readdir(root), ['production-detail.json']);
|
||
});
|
||
|
||
test('a Windows context meter cache lock leaves the active reply and meter available',async t=>{
|
||
const x=await fixture(()=>answer('商品原图已核对。'));
|
||
try{
|
||
const rename=fs.rename;
|
||
let prevented=0;
|
||
t.mock.method(fs,'rename',async (source,target)=>{
|
||
if (path.basename(target)!=='context-usage.json') return rename(source,target);
|
||
prevented++;
|
||
throw Object.assign(new Error('existing meter file temporarily locked'),{code:'EPERM'});
|
||
});
|
||
const result=await x.host.prompt('核对商品原图。');
|
||
assert.match(result.text,/商品原图已核对/);
|
||
assert.equal(prevented, process.platform === 'win32' ? 4 : 1);
|
||
assert.ok(x.host.contextUsage);
|
||
const files=await fs.readdir(x.store.root);
|
||
assert.ok(!files.some(file=>/^context-usage\.json\..*\.tmp$/.test(file)));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('proposal instructions describe only selling-point direction and other intents reject them without executing',async()=>{
|
||
const x=await fixture((context,n,native)=>{
|
||
if(n===1){assert.match(getCurrentSystemPrompt(context.messages),/instruction仅用于selling_points/);return tool('workflow_propose',{version:native.version,intent:'plan',instruction:'改为12屏、750px'},'invalid-plan-instruction');}
|
||
if(n===2){const result=context.messages.find(m=>m.role==='toolResult'&&m.toolCallId==='invalid-plan-instruction');assert.equal(result.isError,true);assert.match(result.content[0].text,/补充要求仅用于卖点/);return tool('workflow_propose',{version:native.version,intent:'selling_points',instruction:'面向小户型,保持事实依据。'},'points-direction');}
|
||
return answer('已列出待审核的卖点方向,尚未生成或修改页面配置。');
|
||
});
|
||
try{
|
||
await x.host.prompt('先讨论卖点方向,不改当前页面尺寸。');
|
||
assert.equal(x.native.proposals.length,2);assert.equal(x.native.generated,0);assert.equal(x.canvas.writes,0);
|
||
const result=x.host.session.messages.find(m=>m.role==='toolResult'&&m.toolCallId==='points-direction');
|
||
const proposal=JSON.parse(result.content[0].text).proposal;
|
||
assert.equal(proposal.intent,'selling_points');assert.equal(proposal.instruction,'面向小户型,保持事实依据。');assert.equal(proposal.executed,false);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('unsaved native drafts keep prior analysis stale and compaction does not refresh or navigate the UI',async()=>{
|
||
const x=await fixture((_context,n)=>n===1?tool('context_read',{}):answer('草稿尚未保存,旧分析不能作为新依据;先等待用户核对。'),{history:true});
|
||
const read=x.canvas.workflowRead;
|
||
x.canvas.workflowRead=async args=>{
|
||
const value=await read(args);
|
||
value.uiDirty=true;value.dirty=true;value.draftDirty=true;value.writeBlocked=false;value.factsStatus='stale';value.planConfirmed=false;
|
||
value.selected=['batch:0'];value.batchCount=1;
|
||
value.capabilities={imageDispatchAllowed:false,copyDispatchAllowed:false,localApplyAllowed:false};
|
||
value.productEvidence.facts.status='stale';
|
||
value.productEvidence.sellingPoints={selected:['batch:0'],batches:[{id:'batch',items:['旧卖点']}],stale:true};
|
||
value.productEvidence.plan.status='stale';
|
||
return value;
|
||
};
|
||
try{
|
||
await x.host.prompt('讨论当前还没保存的资料草稿。');
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.uiDirty,true);
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.draftDirty,true);
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.writeBlocked,false);
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.factsStatus,'stale');
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.planConfirmed,false);
|
||
assert.equal(x.calls[1].evidence.currentWorkflow.batchCount,1);
|
||
assert.deepEqual(x.calls[1].evidence.currentWorkflow.selected,['batch:0']);
|
||
assert.deepEqual(x.calls[1].evidence.currentWorkflow.capabilities,{imageDispatchAllowed:false,copyDispatchAllowed:false,localApplyAllowed:false});
|
||
assert.equal(x.calls[1].evidence.currentProduct.factsStatus,'stale');
|
||
assert.deepEqual(x.calls[1].evidence.currentProduct.selectedSellingPoints,[]);
|
||
assert.equal(x.calls[1].evidence.currentProduct.plan.status,'stale');
|
||
assert.match(getCurrentSystemPrompt(x.calls[0].context.messages),/version只用于上下文一致性,不代表方案已确认/);
|
||
const reads=x.native.reads.length;
|
||
await x.host.compact();
|
||
assert.equal(x.native.reads.length,reads);
|
||
assert.equal(x.native.navigations.length,0);assert.equal(x.native.proposals.length,0);assert.equal(x.native.generated,0);
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
test('stdio and socket adapters route only the three typed workflow actions without network',async()=>{
|
||
const sent=[];
|
||
const stdio=new StdioCanvas(async(action,input)=>{sent.push({action,input});return {ok:true};},7);stdio.run='same-run';
|
||
await stdio.workflowRead({section:'plan'});await stdio.workflowNavigate({stage:'slots',outputId:'sku_images'});await stdio.workflowPropose({version:3,intent:'export'});
|
||
assert.deepEqual(sent.map(q=>q.action),['pi-workflow-read','pi-workflow-navigate','pi-workflow-propose']);
|
||
assert.ok(sent.every(q=>q.input.run==='same-run'&&q.input.documentId===7));
|
||
const socket=Object.create(NativeCanvas.prototype),calls=[];socket.run='socket-run';socket.call=async(method,params)=>{calls.push({method,params});return {};};
|
||
await socket.workflowRead({section:'overview'});await socket.workflowNavigate({stage:'canvas'});await socket.workflowPropose({version:3,intent:'review_plan'});
|
||
assert.ok(calls.every(q=>q.method==='jiansun.action'&&q.params.input.run==='socket-run'));
|
||
assert.deepEqual(calls.map(q=>q.params.action),['pi-workflow-read','pi-workflow-navigate','pi-workflow-propose']);
|
||
});
|
||
|
||
test('a generated candidate keeps its receipt in the Pi transcript and the model replies', async () => {
|
||
let originalOperation;
|
||
const x = await fixture((context, round) => {
|
||
if (round === 1) return tool('workflow_execute', {
|
||
version: 1, intent: 'generate_candidate', outputId: 'detail', slotId: 'hero', productVariantId: 'walnut',
|
||
}, 'generate-hero');
|
||
if (round === 3) return answer('这是另一轮对话。');
|
||
return answer('已生成一张候选,回执已归档。');
|
||
}, { execute: true });
|
||
const originalExecute = x.canvas.workflowExecute;
|
||
x.canvas.workflowExecute = async args => {
|
||
x.native.generated++;
|
||
originalOperation = args.operationId;
|
||
return originalExecute(args);
|
||
};
|
||
x.canvas.workflowPoll = async operationId => ({
|
||
operationId, phase: 'complete', candidateId: 'new-hero', message: '图片已生成',
|
||
});
|
||
const replies = [];
|
||
x.canvas.end = async text => replies.push(text);
|
||
try {
|
||
const result = await x.host.prompt('生成一张首屏候选图。');
|
||
const projected = x.calls[1].context.messages.find(m => m.toolCallId === 'generate-hero');
|
||
const receipt = JSON.parse(projected.content[0].text);
|
||
assert.equal(receipt.operation.phase, 'complete');
|
||
assert.equal(receipt.operation.operationId, originalOperation);
|
||
assert.equal(receipt.operation.candidateId, 'new-hero');
|
||
assert.equal(receipt.operation.slotId, 'hero');
|
||
assert.equal(receipt.archivedWorkflowResult, undefined);
|
||
assert.equal(result.text,'已生成一张候选,回执已归档。');
|
||
assert.deepEqual(replies, [result.text]);
|
||
assert.equal(x.native.generated, 1);
|
||
const next = await x.host.prompt('只聊一下当前资料。');
|
||
assert.equal(next.text, '这是另一轮对话。');
|
||
assert.equal(x.native.generated, 1);
|
||
} finally { await x.close(); }
|
||
});
|
||
|
||
test('a known local rejection returns the host reason and the agent decides without a reconciliation loop',async()=>{
|
||
const x=await fixture((context,n)=>{
|
||
if(n===1)return tool('workflow_execute',{version:1,intent:'generate_candidate',outputId:'detail',slotId:'hero',productVariantId:'walnut'});
|
||
const rejected=context.messages.findLast(message=>message.role==='toolResult'&&message.toolName==='workflow_execute');
|
||
return answer(rejected.content[0].text.includes('当前画布修订已变化')?'画布修订已变化,先重新读取再决定。':'没有收到宿主原因。');
|
||
},{execute:true});
|
||
x.canvas.documentId=7;
|
||
x.canvas.begin=async()=>{x.canvas.run='rejected-run';};
|
||
const read=x.canvas.workflowRead;
|
||
x.canvas.workflowRead=async input=>({...await read(input),revisions:{canvas:1}});
|
||
let executions=0;
|
||
x.canvas.workflowExecute=async({operationId})=>{
|
||
executions++;
|
||
return {operationId,phase:'not_dispatched',accepted:false,dispatched:false,run:'rejected-run',documentId:7,
|
||
baseRevision:1,accountId:info.accountId,origin:info.origin,projectLocalId:`${info.origin}|${info.accountId}|${x.project}`,
|
||
error:{code:'local_precondition_failed',message:'当前画布修订已变化'}};
|
||
};
|
||
x.canvas.workflowPoll=async()=>assert.fail('no registered operation to poll');
|
||
try{
|
||
const result=await x.host.prompt('生成第一张候选,不采纳');
|
||
assert.equal(result.text,'画布修订已变化,先重新读取再决定。');
|
||
assert.equal(executions,1);
|
||
assert.equal(x.calls.length,2);
|
||
assert.equal(x.host.canvasOperations.original,undefined);
|
||
assert.equal(x.canvas.writes,0);
|
||
assert.ok(x.host.session.messages.some(message=>message.role==='toolResult'&&message.toolName==='workflow_execute'&&message.isError));
|
||
}finally{await x.close();}
|
||
});
|
||
|
||
|
||
test('normal conversation reads the pinned Xiaoyi rules without the general knowledge key', async () => {
|
||
const x = await fixture((_context, n) => n === 1 ? tool('context_read', {}) : answer('已读取本项目规则。'));
|
||
const entry = '规则/SKILL.md';
|
||
const supplement = '规则/补充.md';
|
||
const fetch = xiaoyiFixture('desk', 'v1', entry, {
|
||
[entry]: '---\nname: desk-rules\ndescription: Desk design rules.\n---\n首屏必须呈现产品全貌。',
|
||
[supplement]: '颜色以已确认资料为准。',
|
||
}, { supplement });
|
||
try {
|
||
await openXiaoyiSkills(x.store, 'desk', undefined, undefined, fetch);
|
||
const read = x.canvas.workflowRead;
|
||
x.canvas.workflowRead = async args => ({
|
||
...await read(args),
|
||
template: { id: 'desk', enterprise: true, knowledgeVersion: 'desk@v1' },
|
||
});
|
||
x.host.enterpriseContext = { load: async () => assert.fail('一般知识库不应被调用') };
|
||
await x.host.prompt('请读取当前模板规则。');
|
||
const context = x.calls[1].evidence;
|
||
assert.equal(context.currentWorkflow.template.knowledgeVersion, 'desk@v1');
|
||
assert.equal(context.enterpriseKnowledge.execution.knowledgeVersion, 'desk@v1');
|
||
assert.deepEqual(context.enterpriseKnowledge.rules.map(rule => rule.path), [entry, supplement]);
|
||
assert.match(context.enterpriseKnowledge.rules[0].text, /首屏必须呈现产品全貌/);
|
||
assert.match(context.enterpriseKnowledge.rules[1].text, /颜色以已确认资料为准/);
|
||
} finally {
|
||
await x.close();
|
||
}
|
||
});
|