okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
8.0 KiB96 linesraw
1/** Behavioral checks use only disposable files and a loopback mock API. */
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,rmSync} from 'node:fs';
5import {tmpdir} from 'node:os';
6import {join} from 'node:path';
7import {spawn} from 'node:child_process';
8import {once} from 'node:events';
9import {createServer} from 'node:net';
10import {createModelProviders} from '../server/model-providers.mjs';
11import {createMockModelApi} from './mock-model-api.mjs';
12import {createVisionProbe} from '../server/vision-probe.mjs';
13import {ROOMY_HOST} from './helpers/hardware.mjs';
14const choices={Off:'none',Low:'low',Medium:'medium',High:'high',Max:'high'};
15const history=[{role:'user',content:'Earlier question'},{role:'assistant',content:'Earlier answer'}];
16async function fixture(t,options={}){
17 const mock=await createMockModelApi(),directory=mkdtempSync(join(tmpdir(),'strata-api-effort-'));
18 t.after(async()=>{await mock.close();rmSync(directory,{recursive:true,force:true});});
19 const probe=createVisionProbe(),service=createModelProviders({directory,knownThinks:(c,id)=>probe.knownThinks(c,id)});
20 const connection=service.save({kind:'custom',name:'Fixture',baseUrl:mock.baseUrl,protocol:'openai-chat',apiKey:'fixture-key',models:[{id:'mock-reasoning',reasoning:true}],...options}).connections[0];
21 return {mock,service,connection,probe,selection:{connectionId:connection.id,modelId:connection.models[0].id}};
22}
23test('saved reasoning models receive all official composer choices with the remaining request unchanged',async t=>{
24 const f=await fixture(t);
25 for(const [thinking,effort] of Object.entries(choices)){
26  const frames=[];await f.service.stream({selection:f.selection,message:'Next question',history,systemPrompt:'Fixture instructions',thinking,thinkingBudget:1234,onFrame:f=>frames.push(f)});
27  const request=f.mock.requests.at(-1);
28  assert.equal(request.path,'/v1/chat/completions');assert.equal(request.headers.authorization,'Bearer fixture-key');
29  assert.deepEqual(request.body,{model:'mock-reasoning',messages:[{role:'system',content:'Fixture instructions'},...history,{role:'user',content:'Next question'}],stream:true,reasoning_effort:effort});
30  assert.equal(frames.at(-1).type,'done');
31 }
32});
33test('invalid or omitted efforts keep the provider default',async t=>{
34 const f=await fixture(t);
35 for(const thinking of [undefined,null,false,1,{},'','Default','Provider Default','ultra','none','__proto__']){
36  await f.service.stream({selection:f.selection,message:'Test',thinking,onFrame:()=>{}});
37  assert.equal(Object.hasOwn(f.mock.requests.at(-1).body,'reasoning_effort'),false);
38 }
39});
40
41test('direct OpenRouter chat uses the same effort format and Max mapping as agent chat',async t=>{
42 const f=await fixture(t,{kind:'provider',provider:'openrouter'});
43 for(const [thinking,effort] of Object.entries({...choices,Max:'xhigh'})){
44  await f.service.stream({selection:f.selection,message:'Test',thinking,onFrame:()=>{}});
45  const payload=f.mock.requests.at(-1).body;
46  assert.deepEqual(payload.reasoning,{effort});
47  assert.equal(Object.hasOwn(payload,'reasoning_effort'),false);
48 }
49});
50test('saved false and unknown support cannot be overridden by request capability fields',async t=>{
51 for(const reasoning of [false,null]){
52  const f=await fixture(t,{models:[{id:'mock-chat',reasoning}]});
53  await f.service.stream({selection:{...f.selection,reasoning:true,thinks:true},message:'Test',thinking:'High',reasoning:true,thinks:true,onFrame:()=>{}});
54  assert.equal(Object.hasOwn(f.mock.requests.at(-1).body,'reasoning_effort'),false);
55 }
56});
57test('host-owned probe support is used only when the saved answer is unknown',async t=>{
58 for(const reasoning of [null,false]){
59  const f=await fixture(t,{models:[{id:'mock-reasoning',reasoning}]});
60  await f.probe.check(f.service.resolve(f.selection).connection,'mock-reasoning');assert.equal(f.probe.knownThinks(f.connection,'mock-reasoning'),true);
61  await f.service.stream({selection:f.selection,message:'Test',thinking:'Low',onFrame:()=>{}});
62  assert.equal(f.mock.requests.at(-1).body.reasoning_effort,reasoning===false?undefined:'low');
63 }
64});
65test('Responses and Anthropic retain their existing payloads even for reasoning models',async t=>{
66 for(const protocol of ['openai-responses','anthropic']){
67  const f=await fixture(t,{protocol});await f.service.stream({selection:f.selection,message:'Test',onFrame:()=>{}});const before=f.mock.requests.at(-1).body;
68  await f.service.stream({selection:f.selection,message:'Test',thinking:'Max',thinkingBudget:1234,onFrame:()=>{}});assert.deepEqual(f.mock.requests.at(-1).body,before);
69 }
70});
71async function freePort(){const s=createServer();await new Promise(r=>s.listen(0,'127.0.0.1',r));const p=s.address().port;await new Promise(r=>s.close(r));return p;}
72test('host forwards incoming composer choices using saved and probed support without trusting client capabilities',{timeout:30000},async t=>{
73 const mock=await createMockModelApi(),home=mkdtempSync(join(tmpdir(),'strata-api-effort-host-'));
74 let child,exited;
75 t.after(async()=>{if(child&&child.exitCode===null){child.kill();await exited;}await mock.close();rmSync(home,{recursive:true,force:true,maxRetries:3});});
76 mkdirSync(join(home,'data'));writeFileSync(join(home,'spy.log'),'');
77 // No picker/discovery call precedes the first chat: this also exercises cold probe routing.
78 const models=[{id:'mock-chat',reasoning:true},{id:'mock-reasoning',reasoning:null},{id:'plain',reasoning:false},{id:'unknown',reasoning:null}];
79 writeFileSync(join(home,'data','model-providers.json'),JSON.stringify([{id:'fixture',kind:'custom',name:'Fixture',baseUrl:mock.baseUrl,protocol:'openai-chat',apiKey:'fixture-key',models}]));
80 const port=await freePort(),base=`http://127.0.0.1:${port}`;
81 const env={...process.env,STRATA_HOME:home,STRATA_MODELS_DIR:join(home,'models'),STRATA_WORKSPACE:join(home,'work'),STRATA_SETTINGS_FILE:join(home,'settings.json'),STRATA_COMPONENTS_DIR:join(home,'components'),STRATA_CONTROL_DIR:join(home,'no-control'),STRATA_HARNESS_DIR:join(home,'no-harness'),STRATA_NATIVE_REPO:join(home,'no-repo'),STRATA_PORT:String(port),STRATA_SHARE_PORT:String(await freePort()),STRATA_TUNNEL_PORT:String(await freePort()),STRATA_BIND:'127.0.0.1',STRATA_REAL_ENGINE:'0',STRATA_TEST_HARDWARE:ROOMY_HOST,STRATA_AGENT:'off',STRATA_NO_ACQUIRE:'1',ACQUIRE_SPY_LOG:join(home,'spy.log')};
82 child=spawn(process.execPath,['--import','./tests/helpers/acquire-spy.mjs','server/index.mjs'],{cwd:join(import.meta.dirname,'..'),windowsHide:true,stdio:'ignore',env});
83 exited=once(child,'exit');
84 let up=false;for(let n=0;n<100&&!up;n++){try{up=(await fetch(base+'/api/health')).ok;}catch{}if(!up)await new Promise(r=>setTimeout(r,100));}assert.ok(up,'fixture host started');
85 const before=readFileSync(join(home,'data','model-providers.json'),'utf8');
86 for(const model of models)for(const [thinking,effort] of Object.entries(choices)){
87  const res=await fetch(base+'/api/chat/stream',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({message:'Next question',history,thinking,thinkingBudget:1234,agent:false,useTools:false,mode:'bypass',remoteModel:{connectionId:'fixture',modelId:model.id,reasoning:true,thinks:true}})});
88  assert.equal(res.status,200);const frames=(await res.text()).trim().split('\n').map(JSON.parse);
89  assert.equal(frames.some(f=>f.type==='error'),false,JSON.stringify(frames));assert.equal(frames.at(-1).type,'done');
90  const request=mock.requests.filter(r=>r.path==='/v1/chat/completions').at(-1);
91  assert.equal(request.body.model,model.id);assert.equal(request.headers.authorization,'Bearer fixture-key');assert.deepEqual(request.body.messages.slice(-3),[...history,{role:'user',content:'Next question'}]);
92  assert.equal(request.body.reasoning_effort,['plain','unknown'].includes(model.id)?undefined:effort);assert.equal(Object.hasOwn(request.body,'reasoning_budget_tokens'),false);
93 }
94 assert.equal(readFileSync(join(home,'data','model-providers.json'),'utf8'),before);
95 assert.equal(readFileSync(join(home,'spy.log'),'utf8'),'','no external requests or software acquisition');
96});