gongxiangp2/apps/detail-agent-pi/test/context-usage.test.mjs

145 lines
7.8 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { foldSupersededProductionReads } from '../src/context-usage.mjs';
import { describeProductionOutput } from '../src/production-goal.mjs';
import { ProjectStore } from '../src/store.mjs';
const text = text=>({type:'text',text});
const target={outputId:'detail',variantId:'oak',documentKey:{templateVersion:3}};
const receipt = (id,name,details,args={},content=[text(JSON.stringify(details))],metadata={})=>[
{role:'assistant',content:[{type:'toolCall',id,name,arguments:args}]},
{role:'toolResult',toolName:name,toolCallId:id,content,details,...metadata},
];
const original = (messages,id)=>messages.find(message=>message.toolCallId===id);
test('a worker failure remains readable without a durable Pi session result',async t=>{
const dir=await mkdtemp(path.join(tmpdir(),'xiaoyi-receipt-'));
t.after(()=>rm(dir,{recursive:true,force:true}));
const host={dir};
const manager={getBranch:()=>[]};
const read=id=>ProjectStore.prototype.readToolReceipt.call(host,manager,id,0);
assert.equal(await read('review-1'),null);
const event={type:'tool_execution_end',toolCallId:'review-1',isError:true,
failureCategory:'tool_failed',message:'本屏文案字段不匹配'};
await writeFile(path.join(dir,'events.jsonl'),JSON.stringify(event)+'\n');
assert.deepEqual(await read('review-1'),{toolCallId:'review-1',text:event.message,
failureCategory:event.failureCategory,nextOffset:null});
});
const verify = (messages,foldedIds,fullIds)=>{
const projected=foldSupersededProductionReads(messages);
for(const id of foldedIds) {
assert.match(original(projected,id).content.map(block=>block.text).join('\n'),
new RegExp(`旧回执编号:${id},可用 memory_search 读取`));
assert.ok(original(messages,id).details);
}
for(const id of fullIds) assert.equal(original(projected,id),original(messages,id),id);
return projected;
};
test('opening the same output folds an older binding and retains its save result',async()=>{
const previousSave={saved:true,path:'saved.psd',revision:8};
const messages=[
...receipt('old','open_production_output',{...target,previousSave}),
...receipt('other','open_production_output',{...target,variantId:'walnut'}),
...receipt('new','open_production_output',{...target,revision:10}),
...receipt('denied','open_production_output',{...target,accepted:false}),
];
const projected=verify(messages,['old'],['other','new','denied']);
assert.match(original(projected,'old').content[0].text,/saved\.psd/);
const manager={getBranch:()=>messages.map(message=>({type:'message',message}))};
assert.equal((await ProjectStore.prototype.readToolReceipt(manager,'old',0)).text,
original(messages,'old').content[0].text);
});
test('the displayed output binding retains identity and save facts once',()=>{
const binding={...target,documentKey:{...target.documentKey,outputId:'detail',variantId:'oak'},
previousSave:{saved:true,revision:8}, revision:9, switchMs:400, writeEpoch:3};
assert.deepEqual(describeProductionOutput(binding),{...target,previousSave:{saved:true,revision:8},revision:9});
assert.equal(binding.documentKey.variantId,'oak');
assert.equal(describeProductionOutput({...binding,documentKey:{variantId:'walnut'}}).documentKey.variantId,'walnut');
});
test('screen text folds by canvas and page across single and combined reads',()=>{
const page0={page:0,revision:1}, page1={page:1,revision:1}, page2={page:2,error:'画面未就绪'};
const image={type:'image',data:'preview'};
const messages=[
...receipt('open','open_production_output',target),
...receipt('batch','read_output_screen',{screens:[page0,page1,page2]}, {},
[text(JSON.stringify(page0)),image,text(JSON.stringify(page1)),text(JSON.stringify(page2))]),
...receipt('new','read_output_screen',{...page0,...target},{},[text(JSON.stringify(page0)),image]),
...receipt('switch','open_production_output',{...target,variantId:'walnut'}),
...receipt('other','read_output_screen',page1),
...receipt('error','read_output_screen',{...page1,...target,error:'画面未就绪'},{},[text(JSON.stringify({...page1,error:'画面未就绪'}))]),
...receipt('unstable','read_output_screen',{...page1,...target,screenChanged:true},{},[text(JSON.stringify({...page1,screenChanged:true}))]),
];
const projected=verify(messages,['batch'],['new','other','error','unstable']);
assert.deepEqual(original(projected,'batch').content.slice(1),[image,text(JSON.stringify(page1)),text(JSON.stringify(page2))]);
assert.deepEqual(original(projected,'batch').details.screens,[page1,page2]);
});
test('native reads fold only successful equivalent reads on the same document and layer',()=>{
const native=(id,command,documentId,params,result={},extra={})=>
receipt(id,'native_call',{executed:true,changed:false,state:{documentId},result,...extra},
{method:'engine.execute',params:{command,params}});
const messages=[
...native('old','document.inspect',1,{}),
...native('separate','document.inspect',2,{}),
...native('indexed','document.inspect',1,{document:3}),
...native('new','document.inspect',1,{}),
...native('layer-old','type.info',1,{}, {layer:4}),
...native('layer-other','type.info',1,{layer:5}, {layer:5}),
...native('layer-new','type.info',1,{layer:4}, {layer:4}),
...native('edit','type.edit',1,{layer:4,text:'文案'}, {},{changed:true}),
...native('tree-old','layer.list',1,{}),
...receipt('switch','open_production_output',target),
...native('tree-other','layer.list',1,{}),
...native('tree-new','layer.list',1,{}),
];
verify(messages,['old','layer-old','tree-other'],
['separate','indexed','new','layer-other','layer-new','edit','tree-old','tree-new']);
});
test('catalog pages and document scopes retain distinct query results',()=>{
const catalog=(id,documentId,args)=>receipt(id,'native_catalog',{documentId,matchMode:'search',items:[]},args);
verify([
...catalog('old',1,{filter:'type'}),
...catalog('page',1,{filter:'type',offset:10}),
...catalog('other',2,{filter:'type'}),
...catalog('new',1,{filter:'type',limit:10}),
],['old'],['page','other','new']);
});
test('scripts fold only identical displayed output from complete read-only calls',()=>{
const read={name:'type.info',status:'ok',arguments:{}};
const call={...read,name:'native_call',arguments:{method:'engine.execute',params:{command:'type.info',params:{layer:4}}}};
const script=(id,calls,output,complete=true,details={})=>receipt(id,'codemode',details,{},
[text(`Script completed\nWall time ${id} seconds\nOutput:\n`),text(output)],
{nestedCalls:{calls,complete}});
verify([
...script('old',[call],'同一文案'),
...script('modified',[call],'脚本派生事实'),
...script('mixed',[call,{...read,name:'write_copy_fields'}],'同一文案'),
...script('partial',[call],'同一文案',false),
...script('truncated',[call],'同一文案',true,{fullOutputPath:'output.txt'}),
...script('new',[call],'同一文案'),
],['old'],['modified','mixed','partial','truncated','new']);
});
test('duplicate product notes reference the full text and preserve distinct notes and plan scopes',()=>{
const note='商品规格和选购备注。'.repeat(30);
const plan=(id,note,slotIds)=>receipt(id,'plan_production',{...target,product:{note},pictures:slotIds},{slotIds});
const messages=[
...plan('older',note,['A']),
...plan('different','已修改的商品备注',['B']),
...plan('new',note,['C']),
];
const projected=verify(messages,['older'],['different','new']);
const previous=JSON.parse(original(projected,'older').content[0].text);
assert.deepEqual(previous.pictures,['A']);
assert.equal(previous.product.note,undefined);
assert.equal(original(messages,'older').details.product.note,note);
});