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

493 lines
36 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { openAgent } from './fake-canvas.mjs';
import {ProjectStore,atomic} from '../src/store.mjs';
import {productContext} from '../src/project-context.mjs';
import {cleanup} from './cleanup.mjs';
const scope='6'.repeat(64),binding=shop=>({brandId:shop,shopId:shop,categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',brandName:shop,rules:[shop==='unconfigured'?'品牌规则未配置,不编造品牌规范':shop+'专属规则']});
const evidence=(project,color='胡桃色')=>({accountScope:scope,project,documentId:7,revision:2,brief:{name:'测试电脑桌',colorName:color,dimensions:{length:'',width:'',height:'',unit:'mm'}},facts:{status:'ready',items:[{text:'长方形桌面',source:'已核对实拍'}],missing:['尺寸、承重、木种未确认']},sellingPoints:{selected:['batch:0'],batches:[{id:'batch',items:['长方形桌面']}],stale:false},plan:{status:'confirmed',screens:[{name:'首屏',body:'展示当前产品',imagePrompt:'不得重复注入的大段生图提示'.repeat(1000)}]}});
const sse=(delta,finish='stop')=>`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})}\n\ndata: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:finish}]})}\n\ndata: [DONE]\n\n`;
const tool=(name,args)=>sse({tool_calls:[{index:0,id:randomUUID(),type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
function canvas(){
return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题',
async begin(){this.allowed=false;this.writeBlocked=false;},
async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};},
async readCanvas(){const state=await this.read();if(state.conversationActive===false)throw Error('原项目已切换,未读取其他项目的画布');return {...state,context:{...state.context,references:state.context.requestScope?.references}};},
async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw new BridgeError('用户已接手,写入未获许可','write_revoked');this.allowed=true;return this.read();},
async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();},
async delta(){},async activity(){},async end(){this.allowed=false;}};
}
async function fixture(reply,{shop='unconfigured',reuseOpeningInfo=false,workflowRead}={}){
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project},store=await ProjectStore.open(root,identity,binding(shop),{continuous:true});
const requests=[],native=canvas(),events=[];
if(workflowRead)native.workflowRead=workflowRead;
const broker={info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[]}),round(){const id=randomUUID();return {id,fetch:async(_url,init)=>{const payload=JSON.parse(init.body);requests.push(payload);const response=reply(payload,requests.length,native);return response instanceof Response?response:new Response(response,{headers:{'content-type':'text/event-stream'}});},finish:async()=>({phase:'complete'})};}};
let infoCalls=0;
const readInfo=broker.info;
broker.info=async()=>{infoCalls++;return readInfo();};
const brokerInfo=reuseOpeningInfo?await broker.info():undefined;
let host=await openAgent({store,broker,brokerInfo,canvas:native,projectEvidence:evidence(project),documentId:7,onEvent:e=>events.push(e)});
return {root,identity,store,broker,native,requests,events,get infoCalls(){return infoCalls;},get host(){return host;},async reopen(shop,color='胡桃色'){await host.dispose();const next=await ProjectStore.open(root,identity,binding(shop),{continuous:true});host=await openAgent({store:next,broker,canvas:native,projectEvidence:evidence(project,color),documentId:7,onEvent:e=>events.push(e)});return next;},async close(){await host.dispose();await cleanup(root);}};
}
test('three plain native-wire turns discuss product facts without JSON or a canvas write grant',async()=>{
const x=await fixture(()=>sse({content:'可以先讨论布局。尺寸、承重与木种尚未确认。'}));
try{
for(const prompt of ['先聊一下这款产品的页面思路','为什么这样排?尺寸和承重能写吗?','给我两个表达方向,先不修改画布'])assert.match((await x.host.prompt(prompt)).text,/先讨论/);
assert.equal(x.requests.length,3);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
assert.ok(x.events.some(e=>e.type==='text_delta'));
for(const payload of x.requests){
assert.equal(payload.tool_choice,undefined);assert.equal(payload.response_format,undefined);
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
assert.doesNotMatch(system,/当前项目与画布事实|测试电脑桌|胡桃色/u);
assert.ok(!system.includes('不得重复注入的大段生图提示'));assert.ok(!system.includes('mustNotDuplicate'));
}
}finally{await x.close();}
});
test('a quoted text layer survives canvas reads and is edited instead of the live selection',async()=>{
const reference={kind:'layer',label:'首页标题',nativeLayerId:1,component:'layer',layerKind:'Type',text:'原始标题'};
const x=await fixture((_payload,n)=>{
if(n===1)return tool('canvas_read',{layer:1});
if(n===2)return tool('canvas_edit',{revision:1,command:'type.edit',params:{layer:1,text:'新标题'},label:'修改引用标题'});
return sse({content:'已修改引用标题。'});
});
const begin=x.native.begin.bind(x.native), read=x.native.read.bind(x.native), edit=x.native.edit.bind(x.native);
x.native.begin=async()=>{
await begin();
return {context:{requestScope:{references:[reference]}}};
};
x.native.read=async()=>{
const state=await read();
state.context.layers.push({id:2,name:'实时选中的另一层',kind:'Type',text:'保留',locked:{}});
Object.assign(state.context,{selected:[2],liveSelected:[2],requestScope:{references:[reference]}});
return state;
};
x.native.edit=(input,revision)=>{
assert.equal(input.params.layer,1);
return edit(input,revision);
};
try {
await x.host.prompt('把引用标题改成新标题。',{referenceContent:[reference]});
const receipt=JSON.parse(x.requests[1].messages.findLast(row=>row.role==='tool').content);
assert.deepEqual(receipt.context.references,[reference]);
assert.deepEqual(receipt.context.selected,[2]);
assert.equal(x.native.text,'新标题');
assert.equal(x.native.writes,1);
assert.equal((await x.native.read()).context.layers[1].text,'保留');
} finally {await x.close();}
});
test('a history lookup with a missing receipt still searches the current project',async()=>{
const x=await fixture((_payload,n)=>n===1?tool('memory_search',{toolCallId:'/',query:'原始输入'})
:n===3?tool('memory_search',{toolCallId:'',query:'原始输入'}):sse({content:'已查询。'}));
try {
await x.host.prompt('原始输入,查找项目历史。');
const missing=x.requests[1].messages.find(message=>message.role==='tool');
const result=JSON.parse(missing.content);
assert.equal(result.toolCallId,'/');
assert.equal(result.found,false);
assert.ok(result.matches.some(row=>row.role==='user'&&row.text.includes('原始输入')));
await x.host.prompt('继续查询。');
const latest=x.requests[3].messages.filter(message=>message.role==='tool').at(-1);
assert.ok(JSON.parse(latest.content).some(row=>row.role==='user'&&row.text.includes('原始输入')));
assert.equal(x.native.requests,0);
assert.equal(x.native.writes,0);
} finally { await x.close(); }
});
test('an enterprise project supports immediate conversation and fetches rules only when asked',async()=>{
const provenance='当前企业模板条款正文';
const x=await fixture((_payload,n)=>n===2?tool('context_read',{topic:'sources'}):sse({content:'使用当前项目资料。'}));
const sections=[];
x.native.workflowRead=async({section})=>{
sections.push(section);
return {available:true,version:1,section,canvasFirst:true,outputId:'detail',
template:{id:'selected-template',version:'fixed-release',enterprise:true},
productEvidence:evidence(x.identity.project)};
};
let knowledgeReads=0;
x.host.enterpriseContext={async load(){knowledgeReads++;return {skills:[{text:provenance}],rules:[]};}};
try{
await x.host.prompt('你好,知道现在在做什么吗?');
assert.equal(knowledgeReads,0);
assert.ok(!JSON.stringify(x.requests[0].messages).includes('测试电脑桌'));
await x.host.prompt('请查一下这个模板的规则来源');
assert.equal(knowledgeReads,1);
assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance)&&m.content.includes('测试电脑桌')));
await x.host.prompt('谢谢,继续聊一下');
assert.equal(knowledgeReads,1);
assert.ok(JSON.stringify(x.requests[3].messages).includes(provenance));
assert.ok(sections.every(section=>section==='overview'));
assert.equal(x.native.writes,0);
}finally{await x.close();}
});
test('the first desktop turn reuses its opening model check and logs first text timing',async()=>{
const x=await fixture(()=>sse({content:'可以继续聊天。'}),{reuseOpeningInfo:true});
try{
await x.host.prompt('你好');
assert.equal(x.infoCalls,1);
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
const finished=events.find(event=>event.type==='provider_finished');
assert.ok(Number.isFinite(finished.responseHeadersMs));
assert.ok(finished.firstTextMs>=finished.responseHeadersMs);
await x.host.prompt('继续聊');
assert.equal(x.infoCalls,2);
}finally{await x.close();}
});
test('a model response arriving after cancellation keeps its receipt and cannot supply tools to the next turn',async()=>{
const arrived=Promise.withResolvers(),release=Promise.withResolvers();
const record='title-from-revoked-epoch';
const abort=new AbortController();
const x=await fixture((_payload,n)=>n===1?new Response(new ReadableStream({
async start(stream){
arrived.resolve();
await release.promise;
stream.enqueue(new TextEncoder().encode(tool('canvas_edit',{revision:1,command:'type.edit',params:{layer:1,text:record},label:'旧内容'})));
stream.close();
},
}),{headers:{'content-type':'text/event-stream'}}):sse({content:'新一轮正常完成。'}));
try {
x.host.productionSignal=abort.signal;
const first=x.host.prompt('旧回合');
await arrived.promise;
abort.abort(Error('回合已停止'));
release.resolve();
await assert.rejects(first,/停止/);
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
const finished=journal.find(e=>e.type==='provider_finished');
assert.equal(finished.stopReason,'aborted');
assert.equal(x.host.contextUsage.phase,'ready');
assert.equal(finished.status,'cancelled');
assert.equal(finished.consumption,'discarded_after_cancel');
x.host.productionSignal=new AbortController().signal;
assert.equal((await x.host.prompt('新回合')).text,'新一轮正常完成。');
assert.equal(x.native.writes,0);
assert.equal(x.requests.length,2);
assert.ok(!JSON.stringify(x.requests[1]).includes(record));
} finally { await x.close(); }
});
test('project conversation survives restart and first rule binding while old-domain memory is not reinjected',async()=>{
const x=await fixture(()=>sse({content:'当前资料以本轮注入为准。'}));
try{
await x.host.prompt('颜色是胡桃色,风格安静,先讨论。');
await x.store.remember({key:'color',value:'胡桃色',evidence:'颜色是胡桃色'},x.host.session.messages);
await x.host.prompt('继续比较刚才的方案。');
const originalDir=x.store.dir,next=await x.reopen('configured-shop','米白');
assert.equal(next.dir,originalDir);assert.deepEqual((await next.context()).confirmedMemory,{});
assert.notEqual(next.memoryDir,x.store.memoryDir);
assert.equal((await x.store.context()).confirmedMemory.color.value,'胡桃色','original rule-domain evidence remains available in its original file');
const foreign=await ProjectStore.open(x.root,{scope:'7'.repeat(64),project:x.identity.project},binding('configured-shop'),{continuous:true});
const otherProject=await ProjectStore.open(x.root,{scope,project:randomUUID()},binding('configured-shop'),{continuous:true});
assert.notEqual(foreign.dir,next.dir);assert.notEqual(otherProject.dir,next.dir);assert.deepEqual((await foreign.context()).confirmedMemory,{});
await x.host.prompt('接着刚才的讨论,现在颜色以米白为准,为什么?');
const payload=x.requests.at(-1),all=JSON.stringify(payload.messages);
assert.ok(all.includes('继续比较刚才的方案'));assert.ok(all.includes('颜色是胡桃色'));
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
assert.doesNotMatch(system,/米白|configured-shop专属规则/u);
assert.ok(!system.includes('"evidence":"颜色是胡桃色"'),'old memory cannot become current confirmed memory on a rule change');
}finally{await x.close();}
});
test('discussion followed by explicit editing requests permission only for the actual write',async()=>{
const x=await fixture((_payload,n,native)=>{
if(n<3)return sse({content:'先讨论,不修改。'});
if(n===3)return tool('canvas_read',{});
if(n===4)return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'新标题'},label:'修改标题'});
return sse({content:'已按要求修改标题。'});
});
try{
await x.host.prompt('讨论一下配色');await x.host.prompt('解释一下你的建议');assert.equal(x.native.requests,0);
await x.host.prompt('把当前标题改为新标题');
assert.equal(x.native.requests,1);assert.equal(x.native.writes,1);assert.equal(x.native.text,'新标题');
assert.ok(x.requests[3].messages.some(m=>m.role==='tool'&&m.content.includes('"writeBlocked":false')));
}finally{await x.close();}
});
test('current-domain memory requires the user to reconfirm old-shop evidence even when it remains in continuous history',async()=>{
const evidence='当前商品颜色是胡桃色';
const x=await fixture((_payload,n)=>[2,4].includes(n)?tool('memory_set',{key:'color',value:'胡桃色',evidence}):sse({content:'按当前域明确确认的资料处理。'}),{shop:'old-shop'});
try{
await x.host.prompt(evidence+',先讨论旧店铺。');
const next=await x.reopen('new-shop');
assert.ok(x.host.session.messages.some(m=>m.role==='user'&&(typeof m.content==='string'?m.content.includes(evidence):m.content.some(c=>c.type==='text'&&c.text.includes(evidence)))));
await x.host.prompt('现在只讨论新店铺的布局,尚未确认旧资料适用于这里。');
assert.deepEqual((await next.context()).confirmedMemory,{});
assert.ok(x.host.session.messages.some(m=>m.role==='toolResult'&&m.toolName==='memory_set'&&m.isError));
await x.host.prompt('我重新确认:'+evidence+',适用于当前店铺,请记住。');
const memory=(await next.context()).confirmedMemory.color;
assert.equal(memory.value,'胡桃色');assert.equal(memory.bindingHash,next.hash);assert.equal(memory.evidence,evidence);
const oldLedger=await fs.readFile(path.join(x.store.memoryDir,'user-evidence.jsonl'),'utf8');
const newLedger=await fs.readFile(path.join(next.memoryDir,'user-evidence.jsonl'),'utf8');
assert.ok(oldLedger.includes('旧店铺'));assert.ok(!newLedger.includes('先讨论旧店铺'));
}finally{await x.close();}
});
test('an inactive project cannot read another canvas through a tool or dispatch a new discussion using its context',async()=>{
const x=await fixture(()=>sse({content:'A项目的原回复留存。'}));
try{
await x.host.prompt('先讨论A产品,不修改。');
x.native.read=async()=>({conversationActive:false,allowed:false,writeBlocked:true,revision:99,context:{id:8,name:'B项目私有名称',width:750,layers:[{id:91,text:'B的秘密文字'}]}});
const read=x.host.session.agent.state.tools.find(t=>t.name==='canvas_read');
await assert.rejects(read.execute('inactive-read',{},undefined),/项目已切换/);
await assert.rejects(x.host.prompt('仍来自A的迟到要求'),/项目已切换/);
assert.equal(x.requests.length,1);assert.ok(!JSON.stringify(x.requests).includes('B的秘密文字'));
assert.ok(x.host.manager.getEntries().some(e=>e.type==='message'&&e.message.role==='assistant'&&e.message.content.some(c=>c.text==='A项目的原回复留存。')));
}finally{await x.close();}
});
test('switching projects in the middle of the original SSE detaches UI delivery but keeps the complete A reply with one POST',async()=>{
const fragments=['A开始讨论。','A继续解释,保留这一段。','A结尾完整信息。'],full=fragments.join('');
let chunksConsumed=0,deltaAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
const x=await fixture(()=>new Response(new ReadableStream({async start(controller){
for(const content of fragments){controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{content},finish_reason:null}]})}\n\n`));chunksConsumed++;await new Promise(r=>setTimeout(r,30));}
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:'stop'}]})}\n\ndata: [DONE]\n\n`));controller.close();
}}),{headers:{'content-type':'text/event-stream'}}));
const originalRead=x.native.read.bind(x.native);
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
x.native.delta=async()=>{deltaAttempts++;switched=true;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
x.native.activity=async text=>{otherProjectHistory.push(text);throw Error('must not deliver activity into B');};
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
try{
const result=await x.host.prompt('A项目:完整解释后自然结束,不修改画布。');
assert.equal(result.text,full);assert.equal(result.rounds,1);assert.equal(x.requests.length,1);assert.equal(chunksConsumed,3);
assert.equal(deltaAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.writes,0);
const replies=x.host.manager.getEntries().filter(e=>e.type==='message'&&e.message.role==='assistant').map(e=>e.message);
assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full));
assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result');
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse);
assert.equal(journal.filter(e=>e.type==='provider_started').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.stopReason==='stop'));
assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end'));
assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full);
}finally{await x.close();}
});
test('inactive activity delivery preserves the original assistant/tool transcript and stops the next paid model step locally',async()=>{
let activityAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
const x=await fixture(()=>sse({content:'A的完整规则解释,随后只读查询原历史。',tool_calls:[{index:0,id:'read-old-a',type:'function',function:{name:'memory_search',arguments:JSON.stringify({query:'A项目'})}}]},'tool_calls'));
const originalRead=x.native.read.bind(x.native);
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
x.native.activity=async()=>{activityAttempts++;switched=true;throw new BridgeError('操作说明已留在原项目','scope_changed');};
x.native.delta=async text=>{if(switched)otherProjectHistory.push(text);};
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
try{
const result=await x.host.prompt('A项目:解释当前规则,并只读查找A项目的历史。');
assert.match(result.text,/原项目已切换/);assert.equal(x.requests.length,1);assert.equal(result.rounds,1);
assert.equal(activityAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
const messages=x.host.manager.getEntries().filter(e=>e.type==='message').map(e=>e.message);
assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。')));
assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError));
assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error'));
const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_ui_delivery'));
}finally{await x.close();}
});
test('presentation errors leave the original result intact while an end failure is reported once',async()=>{
for(const method of ['delta','activity','end']){
let attempts=0;
const message='本机通知未确认';
const x=await fixture((_payload,n)=>method==='activity'&&n===1?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'}));
x.native[method]=async()=>{attempts++;throw Error(message);};
try{
if(method==='end')await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message));
else assert.equal((await x.host.prompt('当前项目普通讨论')).text,'原回复。');
assert.equal(attempts,method==='activity'?2:1);
assert.equal(x.requests.length,method==='activity'?2:1);
assert.notEqual(x.host.canvasNotificationsDetached,true);
}finally{await x.close();}
}
});
test('handover rejects the proposed write with the host reason and the agent decides the next step',async()=>{
const x=await fixture((_payload,n,native)=>{
if(n===1)return tool('canvas_read',{});
if(n===2){native.writeBlocked=true;return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'不可应用'},label:'修改标题'});}
return sse({content:'用户已接手,这次修改没有应用。'});
});
try{
assert.match((await x.host.prompt('请改标题,过程中用户接手')).text,/已接手/);
assert.equal(x.requests.length,3);assert.equal(x.native.writes,0);assert.equal(x.native.text,'原始标题');
const rejected=x.requests[2].messages.findLast(row=>row.role==='tool');
assert.match(rejected.content,/用户已接手/);
assert.match((await x.host.prompt('先不修改,继续解释另一个方案')).text,/没有应用/);
assert.equal(x.requests.length,4);assert.equal(x.native.writes,0);
}finally{await x.close();}
});
test('a canvas click during discussion blocks writes but does not cut off a read-only discussion or its streamed reply',async()=>{
const x=await fixture((_payload,n,native)=>{
if(n===1){native.writeBlocked=true;return tool('context_read',{});}
return sse({content:'可以继续完整讨论:先用真实外观建立首屏,再解释产品细节。尺寸未确认,所以不写具体数值。'});
});
try{
const result=await x.host.prompt('先讨论页面顺序,不修改画布;我会手动点选查看产品。');
assert.match(result.text,/可以继续完整讨论/);assert.match(result.text,/不写具体数值/);
assert.equal(x.requests.length,2);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
assert.ok(x.native.writeBlocked);assert.ok(x.events.some(e=>e.type==='text_delta'&&e.delta.includes('完整讨论')));
const system=x.requests[1].messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
assert.doesNotMatch(system,/当前项目与画布事实/u);
assert.ok(!x.host.session.messages.some(m=>m.role==='assistant'&&m.content?.some(c=>c.type==='text'&&c.text==='本机:已接手,剩余画布操作已停止。')));
}finally{await x.close();}
});
test('product evidence preserves complete facts and screens and rejects foreign identity',()=>{
const project=randomUUID(),source=evidence(project);
source.facts.items=Array.from({length:100},()=>({text:'事实'.repeat(500),source:'来源'.repeat(500)}));source.facts.missing=Array.from({length:100},()=> '待确认'.repeat(500));
const context=productContext(source,{scope,project,documentId:7});
assert.equal(context.facts.length,100);
assert.equal(context.missing.length,100);
assert.equal(context.facts.at(-1).text,source.facts.items.at(-1).text);
assert.ok(!JSON.stringify(context).includes('imagePrompt'));
for(const identity of [{scope:'7'.repeat(64),project,documentId:7},{scope,project:randomUUID(),documentId:7},{scope,project,documentId:8}])assert.throws(()=>productContext(source,identity),/不属于/);
});
test('output colors reach product evidence as separate image types',()=>{
const project=randomUUID(),source=evidence(project);
source.brief.outputColors={detail:'原木色',sku_images:'雾灰色',main_images:'暖白色',unknown:'省略'};
source.brief.variants=[{id:'oak',colorName:'旧花色',images:[],outputColors:{detail:'胡桃木色',sku_images:'',main_images:'C:\\private\\file'}}];
const context=productContext(source,{scope,project,documentId:7});
assert.deepEqual(context.product.outputColors,{detail:'原木色',sku_images:'雾灰色',main_images:'暖白色'});
assert.deepEqual(context.references.variants[0].outputColors,{detail:'胡桃木色',sku_images:''});
});
test('SKU color plan exposes all SKUs and only the chosen IDs for detail and main images',()=>{
const project=randomUUID(),source=evidence(project);
source.brief.variants=[{id:'oak',colorName:'原木色',images:[],outputColors:{main_images:'旧颜色'}},{id:'white',colorName:'暖白色',images:[]}];
source.brief.outputVariantIds={detail:['oak','white'],main_images:['white'],sku_images:['oak']};
const context=productContext(source,{scope,project,documentId:7});
assert.deepEqual(context.references.variants.map(v=>[v.id,v.colorName]),[['oak','原木色'],['white','暖白色']]);
assert.deepEqual(context.references.outputVariantIds,{detail:['oak','white'],main_images:['white']});
assert.ok(!JSON.stringify(context).includes('旧颜色'));
});
test('legacy transcript migration retains originals and a new conversation can proceed',async()=>{
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};let host;
try{
const legacy=await ProjectStore.open(root,identity,binding('A'));
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
manager.appendMessage({role:'user',content:'原始会话必须保留',timestamp:Date.now()});
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
await legacy.appendEvent({type:'provider_prepared',id:'preserved-request',bindingHash:legacy.hash});
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'preserved-request',phase:'review'}]);
const original=await fs.readFile(manager.getSessionFile(),'utf8');
const stable=await ProjectStore.open(root,identity,binding('B'),{continuous:true});
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
assert.ok((await fs.readFile(path.join(stable.dir,'events.jsonl'),'utf8')).includes('preserved-request'));
let posts=0;
host=await openAgent({store:stable,broker:{
info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}),
round:()=>{
return {id:randomUUID(),fetch:async()=>{
posts++;
return new Response(sse({content:'当前对话可以继续。'}),{headers:{'content-type':'text/event-stream'}});
},finish:async()=>({phase:'complete'})};
},
}});
assert.ok(host.session.messages.some(m=>m.role==='user'&&m.content==='原始会话必须保留'));
assert.equal((await host.prompt('继续当前讨论')).text,'当前对话可以继续。');
assert.equal(posts,1);
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
assert.equal(await fs.readFile(manager.getSessionFile(),'utf8'),original);
}finally{await host?.dispose();await cleanup(root);}
});
test('legacy migration resumes exact partially copied files and publishes the pointer last without overwriting originals',async()=>{
for(const copiedEvents of [false,true]){
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
try{
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
manager.appendMessage({role:'user',content:'迁移原件不得改写',timestamp:Date.now()});
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
await legacy.appendEvent({type:'provider_prepared',id:'old-request',bindingHash:legacy.hash});
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'old-request',phase:'review'}]);
const original=await fs.readFile(manager.getSessionFile()),events=await fs.readFile(path.join(legacy.dir,'events.jsonl'));
const stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,original,{flag:'wx'});
if(copiedEvents)await fs.writeFile(path.join(stableDir,'events.jsonl'),events,{flag:'wx'});
const resumed=await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
assert.equal((await resumed.get('session.json')).file,target);assert.deepEqual(await fs.readFile(target),original);
assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);assert.deepEqual(await fs.readFile(path.join(stableDir,'events.jsonl')),events);
assert.deepEqual(await resumed.get('recovered-tools.json'),[{id:'old-request',phase:'review'}]);
assert.equal((await resumed.get('migration.json')).originalRetained,true);
await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
assert.deepEqual(await fs.readFile(target),original);
}finally{await cleanup(root);}
}
});
test('legacy migration rejects a pre-existing target with different bytes and never publishes a pointer or overwrites it',async()=>{
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
try{
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
manager.appendMessage({role:'user',content:'原件',timestamp:Date.now()});await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
const original=await fs.readFile(manager.getSessionFile()),stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,'different retained bytes',{flag:'wx'});
await assert.rejects(ProjectStore.open(root,identity,binding('new-shop'),{continuous:true}),/迁移目标与原件不一致/);
assert.equal(await fs.readFile(target,'utf8'),'different retained bytes');assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);
await assert.rejects(fs.access(path.join(stableDir,'session.json')),error=>error.code==='ENOENT');
}finally{await cleanup(root);}
});
test('the agent queries actual slot progress with its tools',async()=>{
const slots=Array.from({length:27},(_,index)=>({
id:'slot-'+index,
selectedCandidateId:index<2?'accepted-'+index:null,
candidates:index===2?[{status:'complete'}]:index===3?[{status:'unknown'}]:[],
}));
const offsets=[];
const x=await fixture((_payload,n)=>n<=3?tool('workflow_read',{section:'slots',offset:(n-1)*12}):
sse({content:'27 个图位,已回填 2 个,还有 25 个未回填。其中 1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选。'}), {
workflowRead:async({section,offset=0})=>{
if(section==='slots')offsets.push(offset);
return {available:true,version:18,section,canvasFirst:true,outputId:'detail',productVariantId:'brown',
totalSlots:slots.length,slots:slots.slice(offset,offset+12),productEvidence:evidence(x.identity.project)};
}
});
try{
const result=await x.host.prompt('后面还有几张图没有完成的');
assert.match(result.text,/27 个图位,已回填 2 个,还有 25 个未回填/);
assert.match(result.text,/1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选/);
assert.deepEqual(offsets,[0,12,24]);
assert.equal(result.rounds,4);
assert.equal(x.requests.length,4);
assert.equal(x.native.writes,0);
}finally{await x.close();}
});
test('a desktop turn continues past 12 useful model calls',async()=>{
const x=await fixture((_payload,n)=>n<=12?tool('workflow_read',{section:'slots',offset:n-1}):sse({content:'逐个核对完了。'}));
x.native.workflowRead=async({section,offset=0})=>({available:true,version:1,section,
canvasFirst:true,outputId:'detail',offset,productEvidence:evidence(x.identity.project)});
try{
assert.equal((await x.host.prompt('请逐个核对所有图位的描述')).text,'逐个核对完了。');
assert.equal(x.requests.length,13);
}finally{await x.close();}
});
test('a burst of text and reasoning delivers the complete coalesced reply to the canvas',async()=>{
const chunk=delta=>'data: '+JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})+'\n\n';
const x=await fixture(()=>chunk({reasoning_content:'检查资料'})+chunk({content:'第一段'})+sse({content:'。第二段。'}));
const presented=[];
x.native.delta=async text=>{presented.push(text);};
try{
assert.equal((await x.host.prompt('用两句短话介绍一下你自己')).text,'第一段。第二段。');
assert.deepEqual(presented.filter(Boolean),['第一段。第二段。']);
}finally{await x.close();}
});