gongxiangp2/apps/detail-agent-pi/test/model-switch-compat.test.mjs

70 lines
4.1 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { ModelRuntime } from '@earendil-works/pi-coding-agent';
import { openAgent } from './fake-canvas.mjs';
import { assistant, piInfo, piProject, replyStream } from './pi-compat-fixture.mjs';
test('Pi records live and restored model and thinking selections across native APIs',async t=>{
const store=await piProject(t);
const catalog=await ModelRuntime.create({authPath:path.join(store.dir,'catalog-auth.json'),modelsPath:null,
modelsStorePath:path.join(store.dir,'catalog-cache'),refreshOnCreate:false,allowModelNetwork:false});
const anthropic=catalog.getModels('anthropic').find(model=>model.compat?.forceAdaptiveThinking);
const responses=catalog.getModels('openai').find(model=>model.api==='openai-responses');
const chat=catalog.getModels('deepseek').find(model=>model.api==='openai-completions' && model.compat);
assert.ok(anthropic && responses && chat);
const selection=(model,protocol,level='off')=>({...piInfo(store,{id:model.id,protocol}),thinkingLevel:level});
let info=selection(anthropic,'anthropic-messages','high');
const seen=[];
const broker={
info:async()=>info,
round(){return {id:'chat-round',fetch:async (_url,init)=>{
const payload=JSON.parse(init.body);
const calls=payload.messages.flatMap(message=>message.tool_calls??[]);
const results=payload.messages.filter(message=>message.role==='tool');
assert.equal(calls.length,2);
assert.deepEqual(results.map(result=>result.tool_call_id),calls.map(call=>call.id));
assert.equal(new Set(calls.map(call=>call.id)).size,2);
assert.ok(calls.every(call=>call.id.length<=40));
assert.equal(payload.parallel_tool_calls,undefined);
return new Response('data: '+JSON.stringify({id:'fixture',model:chat.id,
choices:[{index:0,delta:{content:'已切换'},finish_reason:'stop'}]})+'\n\ndata: [DONE]\n\n',
{headers:{'content-type':'text/event-stream'}});
}};},
};
let host;
try {
host=await openAgent({store,broker,transport:{info,stream(model,_context,options){
seen.push([model.api,options.reasoning??'off']);
return replyStream(model,'已记录');
}}});
for(const [model,protocol,level] of [[anthropic,'anthropic-messages','high'],[responses,'openai-responses','off']]){
info=selection(model,protocol,level);
await host.prompt('记录所选模型');
assert.equal(host.session.model.id,model.id);
assert.equal(host.session.thinkingLevel,level);
assert.deepEqual(host.session.model.compat,{...model.compat,supportsStore:false,supportsMessageThreads:false});
}
assert.deepEqual(seen,[['anthropic-messages','high'],['openai-responses','off']]);
const longIds=['a','b'].map(suffix=>'toolu_'+ 'x'.repeat(65)+suffix);
host.manager.appendMessage(assistant({id:anthropic.id,api:'anthropic-messages',provider:'jiansun-native-98k'},
longIds.map(id=>({type:'toolCall',id,name:'canvas_read',arguments:{layer:1}})),'toolUse'));
for (const toolCallId of longIds) host.manager.appendMessage({role:'toolResult',toolCallId,toolName:'canvas_read',
content:[{type:'text',text:'已读'}],isError:false,timestamp:Date.now()});
const file=host.manager.getSessionFile();
await host.dispose();
host=null;
info=selection(chat,'openai-chat');
host=await openAgent({store,broker,callBudget:1});
assert.equal(host.session.model.api,'openai-completions');
assert.equal(host.session.thinkingLevel,'off');
assert.deepEqual(host.session.model.compat,{...chat.compat,supportsStore:false,supportsMessageThreads:false});
assert.equal((await host.prompt('继续聊天')).text,'已切换');
const entries=(await fs.readFile(file,'utf8')).trim().split('\n').map(JSON.parse);
assert.deepEqual(entries.filter(entry=>entry.type==='model_change').map(entry=>entry.modelId),[anthropic.id,responses.id,chat.id]);
assert.deepEqual(entries.filter(entry=>entry.type==='thinking_level_change').map(entry=>entry.thinkingLevel),['high','off']);
} finally { await host?.dispose(); }
});