okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1631a9fde
main
1// The 0.2.7 GitHub items done in f-027-gh-app: the Power card's readings (#3628), the finished-work sound (#3586), approval 2// notifications and the tray choice (#3477), the pinned port (#3402). Hermetic: scratch folders and fake fetch/spawn only. 3import test from 'node:test' ; 4import assert from 'node:assert/strict' ; 5import { mkdtempSync , readFileSync , rmSync , writeFileSync } from 'node:fs' ; 6import { tmpdir } from 'node:os' ; 7import { join } from 'node:path' ; 8import { EventEmitter } from 'node:events' ; 9import { build } from 'esbuild' ; 10import { pickTemperatures , readLinuxTemperatures , parseSsdLine , createWindowsSsdReader } from '../server/temperature-telemetry.mjs' ; 11import { addEnergy , energyWh } from '../server/energy-meter.mjs' ; 12import { cleanPrefs , readShellPrefs , writeShellPrefs , parsePortNotice , createShellNotifier , validPort , DEFAULTS } from '../server/shell-prefs.mjs' ; 13import { parseNvidiaReadings } from '../server/device-probes.mjs' ; 14 15const compiled = await build ({ stdin :{ contents :"export * from './src/lib/attention'; export * from './src/lib/i18n';" , resolveDir :process . cwd () }, bundle :true , write :false , format :'esm' , platform :'node' , loader :{ '.json' :'json' } }); 16const A = await import ( `data:text/javascript;base64, ${ Buffer . from ( compiled . outputFiles [ 0 ]. text ). toString ( 'base64' )} ` ); 17for ( const l of [ 'zh' , 'ja' , 'de' , 'es' , 'ru' , 'pt' , 'ko' , 'fr' ]) await A . loadCatalog ( l ); // the non-English catalogs load on first use (src/lib/i18n.ts loadCatalog); load them before the first tr() 18 19test ( 'temperatures: the hottest processor and drive sensor, nothing invented' , () => { 20assert . deepEqual ( pickTemperatures ([{ name :'coretemp' , temps :[ 51000 , 56000 ] }, { name :'nvme' , temps :[ 41850 ] }, { name :'amdgpu' , temps :[ 70000 ] }]), { cpuTempC :56 , ssdTempC :42 }); 21assert . deepEqual ( pickTemperatures ([{ name :'nvme' , temps :[ - 1 , 0 , 200000 ] }]), { cpuTempC :null , ssdTempC :null }); 22assert . deepEqual ( pickTemperatures ([]), { cpuTempC :null , ssdTempC :null }); 23}); 24 25test ( 'Linux hwmon folders are read through the injected file functions' , async () => { 26const files = { '/h/hwmon0/name' :'k10temp\n' , '/h/hwmon0/temp1_input' :'48500\n' , '/h/hwmon1/name' :'nvme\n' , '/h/hwmon1/temp1_input' :'39000\n' , '/h/hwmon2/name' :'acpitz\n' }; 27const dirs = { '/h' :[ 'hwmon0' , 'hwmon1' , 'hwmon2' ], '/h/hwmon0' :[ 'name' , 'temp1_input' ], '/h/hwmon1' :[ 'name' , 'temp1_input' ], '/h/hwmon2' :[ 'name' ] }; 28const read = async path => { if ( ! ( path in files )) throw new Error ( 'ENOENT' ); return files [ path ]; }; 29const list = async path => { if ( ! ( path in dirs )) throw new Error ( 'ENOENT' ); return dirs [ path ]; }; 30assert . deepEqual ( await readLinuxTemperatures ({ base :'/h' , read, list}), { cpuTempC :49 , ssdTempC :39 }); 31assert . deepEqual ( await readLinuxTemperatures ({ base :'/missing' , read, list}), { cpuTempC :null , ssdTempC :null }); 32}); 33 34test ( 'the Windows SSD loop gives a value only for a plausible line and goes stale' , () => { 35assert . equal ( parseSsdLine ( 'ssd 53' ), 53 ); 36assert . equal ( parseSsdLine ( 'ssd -' ), null ); 37assert . equal ( parseSsdLine ( 'ssd 400' ), null ); 38assert . equal ( parseSsdLine ( 'something else' ), undefined ); 39let clock = 1000 ; 40const child = Object . assign ( new EventEmitter (), { stdout :Object . assign ( new EventEmitter (), { unref () {} }), unref () {}, kill () {} }); 41const reader = createWindowsSsdReader ({ spawnFn :() => child , now :() => clock }); 42assert . equal ( reader . read (), null , 'no line yet' ); 43child . stdout . emit ( 'data' , 'ssd 47\r\n' ); 44assert . equal ( reader . read (), 47 ); 45clock += 10 * 60 * 1000 ; 46assert . equal ( reader . read (), null , 'an old value is not shown' ); 47}); 48 49test ( 'GPU energy adds up the held power over the time between ticks, at most 5 s of a gap' , () => { 50const before = energyWh (); 51addEnergy ( 360 , 10_000 ); // first tick: nothing to add yet 52assert . equal ( energyWh (), before ); 53addEnergy ( 360 , 11_000 ); // 360 W for 1 s = 0.1 Wh 54assert . ok ( Math . abs ( energyWh () - before - 0.1 ) < 1e-9 ); 55addEnergy ( 360 , 3_600_000 ); // a sleep of an hour counts as 5 s only 56assert . ok ( Math . abs ( energyWh () - before - 0.6 ) < 1e-9 ); 57addEnergy ( null , 3_601_000 ); // no reading: nothing added 58assert . ok ( Math . abs ( energyWh () - before - 0.6 ) < 1e-9 ); 59}); 60 61test ( 'nvidia-smi fan and clock are read, an unsupported field is no reading' , () => { 62const [ a ] = parseNvidiaReadings ( 'GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, 35, 1800' ); 63assert . equal ( a . fanPct , 35 ); assert . equal ( a . clockMhz , 1800 ); 64const [ b ] = parseNvidiaReadings ( 'GPU-1, 41, 5, 1024, 30.5, 200, 4, 4, 16, [N/A], [N/A]' ); 65assert . equal ( b . fanPct , null ); assert . equal ( b . clockMhz , null ); 66const [ c ] = parseNvidiaReadings ( 'GPU-1, 41, 5, 1024' ); 67assert . equal ( c . fanPct , null ); 68}); 69 70test ( 'the readings strip lists only what this PC can read and the Settings has the price' , () => { 71const monitor = readFileSync ( new URL ( '../src/screens/Monitor.tsx' , import . meta. url ), 'utf8' ); 72for ( const label of [ 'Energy since start' , 'Cost since start' , 'GPU fan' , 'GPU clock' , 'CPU temperature' , 'SSD temperature' ]) assert . ok ( monitor . includes ( `' ${ label } '` ), label ); 73assert . match ( monitor , / \.filter\(\(line\): line is / ); 74assert . match ( monitor , / readingsStrip\.length \? <section className="st-card monitor-readings" / , 'the whole strip is left out when no reading is available' ); 75assert . doesNotMatch ( monitor , / lines=\{ / , 'the Power card keeps its old height' ); 76const settings = readFileSync ( new URL ( '../src/screens/Settings.tsx' , import . meta. url ), 'utf8' ); 77assert . match ( settings , / label: 'Electricity price' / ); 78}); 79 80test ( 'shell prefs: defaults, a valid port, automatic, a refused port, the tray, the language' , () => { 81const dir = mkdtempSync ( join ( tmpdir (), 'strata-shell-prefs-' )); 82try { 83const file = join ( dir , 'sub' , 'shell-prefs.json' ); 84assert . deepEqual ( readShellPrefs ( file ), DEFAULTS ); 85assert . deepEqual ( writeShellPrefs ({ port :47900 }, file ), { port :47900 , tray :false , language :'en' }); 86assert . deepEqual ( writeShellPrefs ({ tray :true , language :'de' }, file ), { port :47900 , tray :true , language :'de' }); 87assert . throws (() => writeShellPrefs ({ port :80 }, file ), / between 1024 and 65535 / ); 88assert . throws (() => writeShellPrefs ({ port :70000 }, file ), / between 1024 and 65535 / ); 89assert . equal ( readShellPrefs ( file ). port , 47900 , 'a refused port changes nothing' ); 90assert . equal ( writeShellPrefs ({ port :null }, file ). port , 0 ); 91assert . equal ( writeShellPrefs ({ language :'xx' }, file ). language , 'de' , 'an unknown language is ignored' ); 92writeFileSync ( file , '{ not json' ); 93assert . deepEqual ( readShellPrefs ( file ), DEFAULTS ); 94assert . deepEqual ( cleanPrefs ({ port :'47831' , tray :'yes' , language :'ko' }), { port :0 , tray :false , language :'ko' }); 95assert . ok ( validPort ( 1024 ) && validPort ( 65535 ) && ! validPort ( 1023 ) && ! validPort ( 65536 ) && ! validPort ( 47.5 )); 96} finally { rmSync ( dir , { recursive :true , force :true }); } 97}); 98 99test ( 'the busy-port notice and the shell notifier come only from the shell' , async () => { 100assert . deepEqual ( parsePortNotice ( 'busy:47831:51234' ), { wanted :47831 , used :51234 }); 101assert . equal ( parsePortNotice ( 'busy:x:1' ), null ); 102assert . equal ( parsePortNotice ( undefined ), null ); 103assert . equal ( createShellNotifier ({ env :{} }), null , 'a browser or a source checkout has no shell' ); 104assert . equal ( createShellNotifier ({ env :{ STRATA_SHELL_BRIDGE :'http://example.com:1' , STRATA_SHELL_TOKEN :'t' } }), null , 'only a loopback bridge' ); 105const seen = []; 106const notifier = createShellNotifier ({ env :{ STRATA_SHELL_BRIDGE :'http://127.0.0.1:5555' , STRATA_SHELL_TOKEN :'secret' }, fetcher :async ( url , init ) => { seen . push ([ url , init ]); return { ok :true , json :async () => ({ shown :true }) }; } }); 107assert . deepEqual ( await notifier . notify ({ title :'Strata needs your answer' , body :'a & b?' }), { shown :true }); 108assert . equal ( seen [ 0 ][ 0 ], 'http://127.0.0.1:5555/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F' ); 109assert . equal ( seen [ 0 ][ 1 ]. headers . authorization , 'Bearer secret' ); 110assert . equal ( seen [ 0 ][ 1 ]. method , 'POST' ); 111}); 112 113test ( 'the finished-work sound is opt-in, quiet for quick answers in front, and never twice in a row' , async () => { 114const base = { enabled :true , durationMs :20_000 , focused :true , now :1_000_000 }; 115assert . equal ( A . shouldPlayDone ({ ...base , enabled :false }), false ); 116assert . equal ( A . shouldPlayDone ({ ...base , durationMs :1000 }), false , 'a quick answer with the window in front' ); 117assert . equal ( A . shouldPlayDone ({ ...base , durationMs :1000 , focused :false }), true , 'the window is in the background' ); 118assert . equal ( A . shouldPlayDone ( base ), true , 'work that took a while' ); 119const played = []; 120assert . equal ( A . playDoneSound ( url => ({ volume :0 , play () { played . push ( url ); return Promise . resolve (); } })), true ); 121assert . deepEqual ( played , [ '/strata-done-sound.wav' ]); 122assert . equal ( A . shouldPlayDone ({ ...base , now :Date . now () + 100 }), false , 'a second chime within two seconds is skipped' ); 123assert . equal ( A . playDoneSound (() => { throw new Error ( 'no audio' ); }), false , 'a missing audio device is not an error' ); 124const wav = readFileSync ( new URL ( '../public/strata-done-sound.wav' , import . meta. url )); 125assert . equal ( wav . toString ( 'latin1' , 0 , 4 ), 'RIFF' ); 126assert . equal ( wav . toString ( 'latin1' , 8 , 12 ), 'WAVE' ); 127}); 128 129test ( 'approval notifications: shell first, the page second, nothing when off or when Strata is in front' , async () => { 130const notice = { title :'T' , body :'B' }; 131const seen = []; 132assert . equal ( await A . showNotice ( notice , { post :async () => ({ shown :true }), page :() => { seen . push ( 'page' ); return true ; } }), true ); 133assert . deepEqual ( seen , []); 134assert . equal ( await A . showNotice ( notice , { post :async () => ({ shown :false }), page :() => { seen . push ( 'page' ); return true ; } }), true ); 135assert . equal ( await A . showNotice ( notice , { post :async () => { throw new Error ( 'no shell' ); }, page :() => { seen . push ( 'page2' ); return false ; } }), false ); 136assert . deepEqual ( seen , [ 'page' , 'page2' ]); 137assert . equal ( await A . approvalNeeded ( false , 'write_file' , false ), false ); 138assert . equal ( await A . approvalNeeded ( true , 'write_file' , true ), false , 'the person is looking at Strata' ); 139A . setTranslationLanguage ( 'de' ); 140assert . match ( A . approvalNotice ( 'write_file' ). body , / write_file / ); 141assert . notEqual ( A . approvalNotice ( 'write_file' ). title , 'Strata needs your answer' ); 142A . setTranslationLanguage ( 'en' ); 143assert . equal ( A . approvalNotice ( '' ). body , 'The assistant wants to use a tool. Open Strata to approve or deny.' ); 144}); 145 146test ( 'every new string exists in all eight languages with the same slots, and does not collide with another catalog' , async () => { 147const languages = [ 'en' , 'zh' , 'ja' , 'de' , 'fr' , 'es' , 'ru' , 'pt' , 'ko' ]; 148const read = async name => JSON . parse ( readFileSync ( new URL ( `../src/locales/ ${ name } .json` , import . meta. url ), 'utf8' )); 149const withFrench = languages ; 150const gh = Object . fromEntries ( await Promise . all ( withFrench . map ( async l => [ l , await read ( `gh- ${ l } ` )]))); 151const slots = text => [ ...text . matchAll ( / \{\d + \} / g )]. map ( m => m [ 0 ]). sort (); 152const others = new Set (); 153for ( const name of [ 'en' , 'tune-en' , 'tools-en' , 'fix-en' ]) for ( const v of Object . values ( await read ( name ))) others . add ( v ); 154for ( const l of withFrench ) { 155assert . deepEqual ( Object . keys ( gh [ l ]), Object . keys ( gh . en ), l ); 156for ( const [ id , source ] of Object . entries ( gh . en )) { 157assert . ok ( gh [ l ][ id ]. trim (), ` ${ l } : ${ id } is empty` ); 158assert . deepEqual ( slots ( gh [ l ][ id ]), slots ( source ), ` ${ l } : ${ id } ` ); 159if ( l !== 'en' ) assert . notEqual ( gh [ l ][ id ], source , ` ${ l } : ${ id } is still English` ); 160} 161} 162for ( const [ id , text ] of Object . entries ( gh . en )) assert . ok ( ! others . has ( text ), `already in another catalog: ${ id } ${ text } ` ); 163const busyId = Object . keys ( gh . en ). find ( id => gh . en [ id ]. startsWith ( 'Port {0} is used by another program' )); 164for ( const l of languages ) { 165A . setTranslationLanguage ( l ); 166assert . equal ( A . tr ( 'Energy since start' ), gh [ l ]. gh01 , l ); 167assert . equal ( A . tr ( 'Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.' , [ 47831 , 51234 ]), 168gh [ l ][ busyId ]. replaceAll ( '{0}' , '47831' ). replaceAll ( '{1}' , '51234' ), l ); 169} 170A . setTranslationLanguage ( 'en' ); 171}); 172 173test ( 'the interface size scales the whole page, up to 200 percent, and a saved value is checked (#3970)' , () => { 174const store = readFileSync ( new URL ( '../src/lib/store.ts' , import . meta. url ), 'utf8' ); 175assert . match ( store , / setProperty\('zoom', state\.uiScale === 1 \? '' : String\(state\.uiScale\)\) / ); 176assert . match ( store , / setProperty\('--st-ui-scale', '1'\) / , 'the token stays at 1 so nothing is scaled twice' ); 177assert . match ( store , / UI_SCALES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\] / ); 178assert . match ( readFileSync ( new URL ( '../src/lib/default-sizes.ts' , import . meta. url ), 'utf8' ), / UI_SCALE_CHOICES = \[0\.9, 1, 1\.1, 1\.25, 1\.5, 1\.75, 2\] / ); 179assert . match ( store , / savedSizes\(parsed, CONTENT_FS_MIN, CONTENT_FS_MAX\) / , 'a saved value is checked' ); 180const settings = readFileSync ( new URL ( '../src/screens/Settings.tsx' , import . meta. url ), 'utf8' ); 181assert . match ( settings , / Makes all text, buttons and menus in Strata larger or smaller\. / ); 182}); 183 184test ( 'the port, tray, sound and notification rows are in Settings, and only the desktop app shows the port and the tray' , () => { 185const settings = readFileSync ( new URL ( '../src/screens/Settings.tsx' , import . meta. url ), 'utf8' ); 186assert . match ( settings , / label: 'Sound when work finishes' / ); 187assert . match ( settings , / label: 'Notify me when Strata needs an answer' / ); 188assert . match ( settings , / \.\.\.\(shell\?\.tray \? \[\{ section: 'General', label: 'Minimise to tray' / ); 189assert . match ( settings , / \.\.\.\(shell\?\.desktop \? \[\{ section: 'General', label: 'App port' / ); 190const store = readFileSync ( new URL ( '../src/lib/store.ts' , import . meta. url ), 'utf8' ); 191assert . match ( store , / frame\.code === 'waiting-approval' / ); 192assert . match ( store , / workFinished\(state\.doneSound / ); 193assert . match ( store , / announcePortNotice / ); 194}); 195 196test ( 'the host route for the shell: a browser has no shell, the port choice is saved and checked, a notification is not shown' , { timeout :40000 }, async t => { 197const { spawn} = await import ( 'node:child_process' ); 198const { once} = await import ( 'node:events' ); 199const { createServer} = await import ( 'node:net' ); 200const { mkdirSync} = await import ( 'node:fs' ); 201const free = async () => { 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 ; }; 202const home = mkdtempSync ( join ( tmpdir (), 'strata-shell-route-' )); 203let child , exited ; 204t . after ( async () => { if ( child && child . exitCode === null ) { child . kill (); await exited ; } rmSync ( home , { recursive :true , force :true , maxRetries :3 }); }); 205mkdirSync ( join ( home , 'data' )); 206const port = await free (), base = `http://127.0.0.1: ${ port } ` ; 207const 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 free ()), STRATA_TUNNEL_PORT :String ( await free ()), STRATA_BIND :'127.0.0.1' , STRATA_REAL_ENGINE :'0' , STRATA_AGENT :'off' , STRATA_NO_ACQUIRE :'1' , STRATA_PORT_NOTICE :'busy:47831:' + port , STRATA_TEST_LOCALE :'de-DE' , LOCALAPPDATA :join ( home , 'Local' ), APPDATA :join ( home , 'Roaming' ), XDG_DATA_HOME :join ( home , 'xdg-data' ), XDG_STATE_HOME :join ( home , 'xdg-state' ), XDG_CONFIG_HOME :join ( home , 'xdg-config' ) }; 208delete env . STRATA_SHELL_BRIDGE ; delete env . STRATA_SHELL_TOKEN ; 209child = spawn ( process . execPath , [ 'server/index.mjs' ], { cwd :join ( import . meta. dirname , '..' ), windowsHide :true , stdio :'ignore' , env}); 210exited = once ( child , 'exit' ); 211let up = false ; 212for ( let n = 0 ; n < 150 && ! up ; n ++ ) { try { up = ( await fetch ( base + '/api/health' )). ok ; } catch { /* not yet */ } if ( ! up ) await new Promise ( r => setTimeout ( r , 100 )); } 213assert . ok ( up , 'the fixture host started' ); 214const get = async path => ( await fetch ( base + path )). json (); 215const post = ( path , body ) => fetch ( base + path , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ( body ) }); 216const first = await get ( '/api/shell' ); 217assert . equal ( first . desktop , false ); assert . equal ( first . tray , false ); assert . equal ( first . port , port ); assert . equal ( first . defaultPort , 47831 ); 218assert . equal ( first . pinnedPort , null ); assert . equal ( first . minimizeToTray , false ); 219assert . deepEqual ( first . portNotice , { wanted :47831 , used :port }); 220assert . deepEqual ( await get ( '/api/locale' ), { locale :'de-DE' , region :'DE' , currency :null , source :'test' }, 'the host names the regional format; the page maps it to a currency' ); 221const saved = await post ( '/api/shell/prefs' , { port :47900 , tray :true , language :'de' }); 222assert . equal ( saved . status , 200 ); 223const after = await saved . json (); 224assert . equal ( after . pinnedPort , 47900 ); assert . equal ( after . minimizeToTray , true ); 225assert . deepEqual ( JSON . parse ( readFileSync ( join ( home , 'shell-prefs.json' ), 'utf8' )), { port :47900 , tray :true , language :'de' }); 226const refused = await post ( '/api/shell/prefs' , { port :80 }); 227assert . equal ( refused . status , 400 ); 228assert . match (( await refused . json ()). error , / between 1024 and 65535 / ); 229assert . equal (( await get ( '/api/shell' )). pinnedPort , 47900 , 'a refused port changes nothing' ); 230assert . equal (( await ( await post ( '/api/shell/prefs' , { port :null })). json ()). pinnedPort , null ); 231assert . deepEqual ( await ( await post ( '/api/shell/notify' , { title :'T' , body :'B' })). json (), { shown :false }); 232});