Models: a packaged Qwen3.8 model shows the KV format it was saved with (#5374, #5919)

PR #5374 by Hermes Agent, applied on f-1116-gui with one conflict resolved: the
base had removed the DeepSeek helpers the PR's context still showed and added
repairAllControlPaths; only the PR's change to installedInfo is taken (it now
takes the catalog and, in the packaged app, adds kv: savedKv(cfg, model, catalog)),
plus its savedKv and its test, unchanged.
savedKv reads the saved --kv of an ordinary Flash-Next family (qwen, swift,
coder, unsloth, gyro; arch qwen4exp or none) with the launch's own precedence
(user_args over generated args, the last repeated flag wins) and only the four
known formats; anything else stays unknown. Before, the Models page fell back to
int8 after a restart whatever was saved: the Qwen3.8 part of #5919.
Test: tests/native-installed-kv.test.mjs (the PR's): 6 fail on e81a74af3, pass;
with the native-model, packaged-control and kv-choice tests 162/162.
This commit is contained in:
Hermes Agent authored and Niko1221 committed 2026-11-16 16:09:28 +01:00
1 parent e81a74af3f
commit 12121745ce
2 files changed
+101 -2

No files matched your search

+12 -2
View File
@@ -44,6 +44,16 @@ const safeId=value=>typeof value==='string'&&/^[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0
const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));
function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}
/* Saved combined KV for the ordinary Flash-Next families, not an observed engine precision. */
function savedKv(config,model,catalog){
const family=catalog?.families?.find(f=>(f.sizes??[]).some(s=>s.id===model))?.family;
if(!['qwen','swift','coder','unsloth','gyro'].includes(family)||(config.arch&&config.arch!=='qwen4exp'))return undefined;
for(const args of [config.args,config[USER_KEY]])if(args!==undefined&&(!Array.isArray(args)||args.some(a=>typeof a!=='string')))return undefined;
/* Match buildConfig's captured user options over args; generate.cpp takes the last repeated --kv. */
const args=mergeUserArgs(config.args,captureUserArgs(config)),at=args.lastIndexOf('--kv'),value=at<0?undefined:args[at+1];
return ['fp16','int8','q4_0','k8v4'].includes(value)?value:undefined;
}
/** The plain words for "no usable engine": the model still downloads, but loading needs the engine (owner decision 2026-10-18). */
export const ENGINE_NOT_RECOGNISED='Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → About.';
export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},hardwareProbe=()=>[],control=null,ready=null,appUpdater=null,lockWaitMs=60000,lockPollMs=2000,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){
@@ -111,7 +121,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
/* Every folder that holds run configs. Also run before a component job (the engine update test-starts an installed model with its run config) and before a load:
an AppImage's Control lives in /tmp/.mount_<random>, a new name at every start, so a path setup wrote there is gone after the app restarts (QAGUI-LIN 0213). */
function repairAllControlPaths(){try{for(const dir of [preferences.installDir,packagedInstall,installRoot()])repairControlPaths(dir);}catch{/* the read that follows reports a bad folder */}}
function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* The folder this model's own run config keeps its prepared data in: the one that holds its packs/<tag> (or mtp/rt). It is the real data folder of the model, wherever the app's models folder is; a model in the person's own GGUF folder has its pack and draft layer here, not in the app's folder. A layout that only looks like <data>/models/<tag> says nothing: no pack, no folder. */const flagValue=flag=>{const i=cfg.args?.indexOf(flag)??-1;return i>=0&&typeof cfg.args[i+1]==='string'?cfg.args[i+1]:undefined;};const holder=(path,child,name)=>{if(!path||basename(dirname(path)).toLowerCase()!==child||(name&&basename(path).toLowerCase()!==name))return undefined;return dirname(dirname(path));};const runDataFolder=holder(flagValue('--pack'),'packs')??holder(flagValue('--mtp'),'mtp','rt');/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,runDataFolder,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,contextChosen:cfg.ui_context_chosen===true,visionPrepared:!!cfg.vision&&entry.picturesMissing!==true,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:(!!cfg.vision&&entry.picturesMissing!==true)?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionChosen:cfg.ui_vision_chosen===true,visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
function installedInfo(info,catalog){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_.-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* The folder this model's own run config keeps its prepared data in: the one that holds its packs/<tag> (or mtp/rt). It is the real data folder of the model, wherever the app's models folder is; a model in the person's own GGUF folder has its pack and draft layer here, not in the app's folder. A layout that only looks like <data>/models/<tag> says nothing: no pack, no folder. */const flagValue=flag=>{const i=cfg.args?.indexOf(flag)??-1;return i>=0&&typeof cfg.args[i+1]==='string'?cfg.args[i+1]:undefined;};const holder=(path,child,name)=>{if(!path||basename(dirname(path)).toLowerCase()!==child||(name&&basename(path).toLowerCase()!==name))return undefined;return dirname(dirname(path));};const runDataFolder=holder(flagValue('--pack'),'packs')??holder(flagValue('--mtp'),'mtp','rt');/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,...(packaged?{kv:savedKv(cfg,entry.model,catalog)}:{}),ownGgufDir,runDataFolder,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,contextChosen:cfg.ui_context_chosen===true,visionPrepared:!!cfg.vision&&entry.picturesMissing!==true,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:(!!cfg.vision&&entry.picturesMissing!==true)?'yes':'off',draftLayer:cfg.mtp!==false,drafting:cfg.drafting??'auto',/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionChosen:cfg.ui_vision_chosen===true,visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
/* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */
function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');}
@@ -165,7 +175,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
is refreshed in the background. Only the first read, and a forced one after an operation, waits. */
if(refreshing)return !force&&snapshot.available?state():force?refreshing.then(()=>refresh(true)):refreshing; /* a forced read that meets one already running (started before an engine update finished) waits for it and reads again, so it never settles on the old answer */if(!force&&Date.now()-lastRead<45000)return state();
probeDrafting();
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=snapshot.visionReader===true;}}const markImages=c=>markPictures(c,visionReader);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();everRead=true;failedReads=0;if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){failedReads++;snapshot={...snapshot,available:false,error:error.message};lastRead=!everRead&&failedReads<READ_TRIES?Date.now()-45000+RETRY_MS:Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=snapshot.visionReader===true;}}const markImages=c=>markPictures(c,visionReader);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed,catalog),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();everRead=true;failedReads=0;if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){failedReads++;snapshot={...snapshot,available:false,error:error.message};lastRead=!everRead&&failedReads<READ_TRIES?Date.now()-45000+RETRY_MS:Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
}
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
function setDownloadDirectory(input,{insideJob=false}={}){if(!insideJob&&[...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();}
@@ -0,0 +1,89 @@
/** Saved settings projected by the packaged native Control boundary, without starting an engine. */
import './helpers/isolate-profile.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import {EventEmitter} from 'node:events';
import {mkdtempSync,mkdirSync,writeFileSync,readFileSync,readdirSync,rmSync} from 'node:fs';
import {join} from 'node:path';
import {tmpdir} from 'node:os';
import {createNativeControl} from '../server/native-control.mjs';
import {nativeFixture} from './helpers/native-fixture.mjs';
async function installedKv(config,{family='swift',listed=true}={}){
const root=mkdtempSync(join(tmpdir(),'strata-installed-kv-')),install=join(root,'install'),data=join(root,'host'),calls=[];
for(const dir of [install,data])mkdirSync(dir,{recursive:true});
const path=join(install,'strata-swift-iq2_xs.json'),original=JSON.stringify(config);
writeFileSync(path,original);
writeFileSync(join(data,'native-host.json'),JSON.stringify({installDir:install}));
const control={control:{dir:join(root,'control'),python:join(root,'control','python')},version:'fixture',
async installedModels({installDir}){assert.equal(installDir,install);return {install_dir:install,models:[{id:'swift-iq2_xs',name:'Swift IQ2_XS',source_config:path,context_tokens:65536,backend:'cuda',component_status:'present'}]};},
async engine(){return {usable:true,backend:'cuda',engine:{version:'0.1.57',platform:'windows-x86_64',backend:'cuda',root:join(root,'engine')}};}};
const spawnProcess=()=>{
const child=new EventEmitter();child.stdout=new EventEmitter();child.stderr=new EventEmitter();child.exitCode=null;
child.kill=()=>{child.exitCode=0;queueMicrotask(()=>child.emit('exit',0));return true;};
child.stdin={write(line){const m=JSON.parse(line);if(!m.id)return;calls.push(m);
const result=m.method==='initialize'?{}:m.method==='tools/list'?{tools:['strata_models','strata_status'].map(name=>({name}))}:
{structuredContent:m.params.name==='strata_models'?{families:listed?[{family,sizes:[{id:'swift-iq2_xs',model:'IQ2_XS'}]}]:[]}:{hardware:{ram_gb:64,gpus:[]}}};
queueMicrotask(()=>child.stdout.emit('data',Buffer.from(JSON.stringify({id:m.id,result})+'\n')));
}};return child;
};
const native=createNativeControl({directory:data,control,spawnProcess,modelsDirectory:()=>join(root,'models'),hardwareProbe:()=>[],fetcher:()=>{throw new Error('Metadata must not contact an engine.');}});
try{
const state=await native.refresh(true);
assert.equal(state.available,true,state.error);
assert.equal(state.packaged,true);
assert.deepEqual(state.instances,[]);assert.deepEqual(state.jobs,[]);
assert.deepEqual(calls.filter(c=>c.method==='tools/call').map(c=>c.params.name),['strata_status','strata_models']);
assert.equal(readFileSync(path,'utf8'),original,'metadata reads preserve the saved config');
assert.deepEqual(readdirSync(install),['strata-swift-iq2_xs.json'],'no config backup or rewrite');
return JSON.parse(JSON.stringify(state.installed.models[0]));
}finally{await native.close();rmSync(root,{recursive:true,force:true});}
}
for(const kv of ['int8','q4_0','k8v4','fp16'])test(`packaged metadata restores saved ${kv} from its run config`,async()=>{
const model=await installedKv({args:['--kv',kv]});
assert.equal(model.kv,kv);assert.equal(model.ready,true);assert.equal(model.context,65536);
});
test('user_args overrides generated KV; the last repeated flag wins in either layer',async()=>{
for(const config of [
{args:['--kv','int8'],user_args:['--kv','k8v4']},
{args:['--kv','int8','--kv','k8v4']},
{args:['--kv','fp16'],user_args:['--kv','q4_0','--kv','k8v4']},
{args:['--kv','q4_0'],args_written:['--kv','int8'],user_args:['--kv','k8v4']},
{args:[],user_args:['--kv','k8v4']},
])assert.equal((await installedKv(config)).kv,'k8v4');
});
test('removing a written KV flag clears its user override as it does in a Host load',async()=>{
const model=await installedKv({args:[],args_written:['--kv','int8'],user_args:['--kv','k8v4']});
assert.equal(Object.hasOwn(model,'kv'),false);
});
test('absent, malformed or unknown saved KV stays absent without aliases or a default',async()=>{
for(const config of [
{},{kv:'k8v4',args:[]},{cache_type_k:'q8_0',cache_type_v:'q4_0',args:[]},
{args:['--kv']},{args:['--kv','']},{args:['--kv',null]},{args:['--kv',{}]},
{args:['--kv',['k8v4']]},{args:[],user_args:['--kv',['k8v4']]},
{args:['--kv','q8_0']},{args:['--kv','K8V4']},{args:['--kv','future-format']},
{args:['--kv','int8','--kv','unknown']},{args:['--kv','int8','--kv']},
{args:['--kv','int8'],user_args:['--kv','unknown']},
{args:['--kv','int8'],user_args:['--kv']},
])assert.equal(Object.hasOwn(await installedKv(config),'kv'),false,JSON.stringify(config));
});
test('ordinary KV metadata requires a matching Qwen3.8 catalog family',async()=>{
for(const family of ['qwen','swift','coder','unsloth','gyro'])assert.equal((await installedKv({args:['--kv','k8v4']},{family})).kv,'k8v4');
for(const family of ['qwen36','deepseek41','nvfp4','unknown'])assert.equal(Object.hasOwn(await installedKv({args:['--kv','k8v4']},{family}),'kv'),false);
assert.equal(Object.hasOwn(await installedKv({args:['--kv','k8v4']},{listed:false}),'kv'),false);
for(const arch of ['qwen35moe','deepseek41'])assert.equal(Object.hasOwn(await installedKv({arch,args:['--kv','k8v4']}),'kv'),false);
});
test('source-checkout metadata keeps the installer-provided KV value',async()=>{
const f=nativeFixture();try{
const path=join(f.repo,'strata-iq2_xs.json'),config={args:['--kv','k8v4']},original=JSON.stringify(config);
writeFileSync(path,original);
assert.equal((await f.control.refresh(true)).installed.models[0].kv,'int8');
assert.equal(readFileSync(path,'utf8'),original);
}finally{await f.cleanup();}
});