gongxiangp2/apps/detail-agent-pi/test/steer-interjection.test.mjs

119 lines
6.5 KiB
JavaScript

import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { EventEmitter, once } from 'node:events';
import { PassThrough } from 'node:stream';
import test from 'node:test';
import { startDaemon } from '../src/desktop-daemon.mjs';
import { observeCanvasCalls } from '../src/desktop-host.mjs';
import { StdioCanvas } from '../src/stdio-canvas.mjs';
import { runPiProductionGoal, settleProductionGoal } from '../src/production-goal.mjs';
import { openAgent } from './fake-canvas.mjs';
import { piInfo, piProject, replyStream } from './pi-compat-fixture.mjs';
test('daemon delivers native steer and follow-up, clears queues, and aborts chat by run identity', {timeout:15_000},async t=>{
const store=await piProject(t);
const input=new PassThrough(), output=new PassThrough(), events=new EventEmitter();
const startup=Promise.withResolvers(), first=Promise.withResolvers();
const firstStarted=Promise.withResolvers(), finalStarted=Promise.withResolvers();
const frames=[], observed=[], replies=[];
const runId=randomUUID();
const identity={...store.identity,documentId:7};
output.on('data',bytes=>{
const frame=JSON.parse(bytes.toString());
frames.push(frame);
events.emit('frame');
});
const waitFor=async predicate=>{
const signal=AbortSignal.timeout(8000);
while(!frames.some(predicate)) await once(events,'frame',{signal});
return frames.find(predicate);
};
const send=value=>input.write(JSON.stringify(value)+'\n');
const control=async(type,fields={})=>{
const id=randomUUID();
send({type,id,runId,...identity,...fields});
return waitFor(frame=>frame.type===type+'_ack'&&frame.id===id);
};
const daemon=startDaemon({input,output,parentAlive:()=>true,exit:()=>{},
brokerFactory:()=>({close:async()=>{}}),
async runSession(_config,call,_broker,_recovery,signal,_auth,onHostReady){
await startup.promise;
const canvas=new StdioCanvas(observeCanvasCalls(store,call),identity.documentId);
const host=await openAgent({store,productionSignal:signal,
canvas:{queueUpdate:canvas.queueUpdate.bind(canvas),userDelivered:canvas.userDelivered.bind(canvas),
reply:async text=>replies.push(text)},
transport:{info:piInfo(store),stream(model,context){
const users=context.messages.filter(message=>message.role==='user').map(message=>JSON.stringify(message.content));
observed.push(users);
if(observed.length===1) firstStarted.resolve();
if(observed.length===3) finalStarted.resolve();
const wait=observed.length===1?first.promise:observed.length===3?
once(signal,'abort').then(()=>{throw signal.reason;}):Promise.resolve();
return replyStream(model,'第'+observed.length+'段回复',wait);
}},
});
const abort=()=>{void host.session.abort();};
signal.addEventListener('abort',abort,{once:true});
try {
onHostReady(host);
return await host.prompt('开始讨论');
} finally {
signal.removeEventListener('abort',abort);
await host.dispose();
}
}});
try {
assert.equal((await control('steer',{text:'无任务'})).reason,'no_active_run');
send({type:'run',runId,config:identity});
assert.equal((await control('steer',{text:'启动中'})).reason,'starting');
startup.resolve();
await firstStarted.promise;
assert.equal((await control('steer',{text:'错画布',documentId:8})).reason,'scope_mismatch');
assert.equal((await control('steer',{text:'撤回插话'})).disposition,'queued');
assert.equal((await control('steer',{text:'撤回追问',behavior:'followUp'})).disposition,'queued');
const {steering,followUp,error}=await control('clear_queue');
assert.deepEqual({steering,followUp,error},{steering:['撤回插话'],followUp:['撤回追问'],error:null});
assert.equal((await control('steer',{text:'插话',referenceContent:[{label:'参考图层',nativeLayerId:12}]})).accepted,true);
assert.equal((await control('steer',{text:'追问',behavior:'followUp'})).accepted,true);
assert.ok(frames.some(frame=>frame.type==='presentation'&&frame.action==='pi-queue-update'));
first.resolve();
const delivered=await waitFor(frame=>frame.action==='pi-user-delivered'&&frame.input.behavior==='followUp');
assert.equal(delivered.input.text,'追问');
assert.equal(typeof delivered.input.timestamp,'number');
assert.deepEqual(frames.filter(frame=>frame.action==='pi-user-delivered')
.map(({input})=>[input.text,input.behavior]),[['插话','steer'],['追问','followUp']]);
assert.deepEqual(replies,['第1段回复','第2段回复']);
await finalStarted.promise;
assert.match(observed.at(-1).join('\n'),/参考图层/u);
assert.doesNotMatch(observed.at(-1).join('\n'),/撤回/u);
send({type:'abort_run',runId,...identity,project:'wrong-project'});
assert.equal((await control('clear_queue')).error,null);
send({type:'abort_run',runId,...identity});
const complete=await waitFor(frame=>frame.type==='complete'&&frame.runId===runId);
assert.match(complete.value.error,/本轮已停止/u);
assert.ok(frames.every(frame=>frame.type!=='fatal'));
} finally { first.resolve(); await daemon.stop(); }
});
test('production continues after an interjection and carries platform facts in the goal request',async t=>{
const store=await piProject(t);
const goal={status:'active',objective:'fixture'};
const sent=[];
const host={manager:{getBranch:()=>[{type:'custom',customType:'pi-goal',data:{goal}}]},
store,productionGoal:{requestedOutputs:[{outputId:'detail',label:'详情页'}]},
productEvidence:{platformFacts:{shared:{claims:['已核对']}}},
session:{pendingMessageCount:1,messages:[],prompt:async text=>sent.push(text),waitForIdle:async()=>{},
sendCustomMessage:async message=>sent.push(message),clearQueue:()=>sent.push('clear')}};
const start={role:'custom',customType:'pi-goal-event',details:{kind:'continuation'}};
const end={role:'assistant',content:[{type:'text',text:'已收到'}],stopReason:'stop'};
await settleProductionGoal(host,{messages:[start,end]});
host.session.pendingMessageCount=0;
await settleProductionGoal(host,{messages:[start,{role:'user'},end]});
assert.deepEqual(sent,[]);
await settleProductionGoal(host,{messages:[start,end]});
assert.deepEqual(sent,['/goal pause','clear']);
sent.length=0;
await runPiProductionGoal(host,'开始制作',false);
assert.deepEqual(JSON.parse(sent[0].content).platformFacts,host.productEvidence.platformFacts);
});