okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1#!/usr/bin/env node 2/** 3* Headless UI flows of the installed app against a packaged host with a FAKE installer and a FAKE engine (nothing is 4* downloaded, no real engine runs; the real Control starts the fake engine through the owner runtime): 5* 6* node apps/desktop/scripts/ui-flows.mjs [--control <staged control>] [--node <node.exe>] [--shots <dir>] [--only download,models,tune,fail,theme] 7* 8* download the onboarding download: ONE combined bar over both files, an ETA in minutes left of Stop, Finish later closes the 9* pop-up with the download still running, the Models screen shows the same progress, Stop stops it 10* models an installed model is the one Models selects and loads, without a download pop-up 11* tune the tuning step offers no picture reading, tunes, writes a RAM budget for "leave 20%", opens chat; reading size 12* fail an engine that stops while loading: the error is in words and the pop-up does not scroll 13* theme the app follows the system light/dark setting 14* Per-user folders are all under a scratch folder. Exit 1 if a check fails. 15*/ 16import { spawn , spawnSync } from 'node:child_process' ; 17import { createHash } from 'node:crypto' ; 18import { copyFileSync , cpSync , existsSync , mkdirSync , mkdtempSync , readFileSync , readdirSync , rmSync , rmdirSync , symlinkSync , writeFileSync } from 'node:fs' ; 19import { createServer } from 'node:net' ; 20import { tmpdir } from 'node:os' ; 21import { dirname , join , resolve } from 'node:path' ; 22import { fileURLToPath , pathToFileURL } from 'node:url' ; 23 24const args = Object . fromEntries ( process . argv . slice ( 2 ). reduce (( acc , a , i , all ) => ( a . startsWith ( '--' ) ?[ ...acc , [ a . slice ( 2 ), all [ i + 1 ]?. startsWith ( '--' ) ?true :all [ i + 1 ]]] :acc ), [])); 25const here = dirname ( fileURLToPath ( import . meta. url )); 26const repoHost = resolve ( here , '../../host' ); 27const staged = resolve ( here , '../src-tauri/resources' ); 28const stagedControl = resolve ( args . control ?? join ( staged , 'control' )); 29const nodeExe = resolve ( args . node ?? join ( staged , 'node' , process . platform === 'win32' ?'node.exe' :'node' )); 30const work = mkdtempSync ( join ( tmpdir (), 'strata-ui-flows-' )); 31const shots = resolve ( args . shots ?? join ( work , 'shots' )); 32mkdirSync ( shots , { recursive :true }); 33const only = new Set ( String ( args . only ?? 'download,models,profile,ui2,ui2d,tune,fail,delete,theme,restart,perf,polish,stop,latest' ). split ( ',' )); 34const isWin = process . platform === 'win32' ; 35const { chromium} = await import ( pathToFileURL ( join ( repoHost , 'node_modules/playwright-core/index.mjs' )). href ). catch (() => import ( 'playwright-core' )); 36const CHROME = process . env . CHROME ?? [ 'C:/Program Files/Google/Chrome/Application/chrome.exe' , '/usr/bin/google-chrome' ]. find ( existsSync ); 37const delay = ms => new Promise ( r => setTimeout ( r , ms )); 38const sha = buf => createHash ( 'sha256' ). update ( buf ). digest ( 'hex' ); 39const freePort = 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 ; }; 40let failed = false ; 41const check = ( ok , label , detail = '' ) => { console . log ( ` ${ ok ? 'ok ' : 'FAIL' } ${ label } ${ detail ? ' ' + detail : '' } ` ); if ( ! ok ) failed = true ; }; 42 43// ------------------------------------------------------------------ the app folder: the real Control with a fake installer 44const control = join ( work , 'control' ); 45mkdirSync ( control , { recursive :true }); 46for ( const name of [ 'python' , 'strata_control' , 'strata_cli' , 'serve' ]) symlinkSync ( join ( stagedControl , name ), join ( control , name ), 'junction' ); 47for ( const name of [ 'strata.py' , 'VERSION' , 'BUNDLE.json' , 'requirements.txt' ]) copyFileSync ( join ( stagedControl , name ), join ( control , name )); 48cpSync ( join ( stagedControl , 'tools' ), join ( control , 'tools' ), { recursive :true }); 49const python = isWin ?join ( control , 'python' , 'python.exe' ) :join ( control , 'python' , 'bin' , 'python3' ); 50 51const FAKE_INSTALLER = String . raw ` 52import json, os, sys, time 53from pathlib import Path 54ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.') 55STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True) 56RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5')) 57def size(model, gb, ram, mid): 58return {'model': model, 'about': model, 'download_gb': gb, 'ram_needed_gb': ram, 'experts_gb': ram - 8, 'on_this_pc': 'fits', 'installed': False, 'images': True, 'experimental': False, 'id': mid} 59CATALOG = {'summary': 'fake', 'families': [{'family': 'qwen', 'title': 'Qwen3.8-Flash-Next', 'about': 'x', 'experimental': False, 'images': True, 'sizes': [ 60size('Q2_0', 66.4, 48, 'q2_0'), size('IQ3_XXS', 75.8, 60, 'iq3_xxs'), size('IQ3_S', 83.6, 62, 'iq3_s')]}], 61'contexts': [8192, 32768, 65536], 'recommendation': {'family': 'qwen', 'model': 'IQ3_XXS', 'title': 'Qwen3.8-Flash-Next IQ3_XXS', 'context': 32768}, 'context_note': ''} 62HARDWARE = {'ram_gb': 63.1, 'cpu': {'name': 'cpu', 'cores': 12}, 'gpus': [{'index': 0, 'name': 'NVIDIA GeForce RTX 5070', 'vram_gb': 11.9, 'usable': True}]} 63TOTAL = 83.6 64def job(): 65f = STATE / 'job.json' 66if not f.exists(): return None 67j = json.loads(f.read_text()) 68if j.get('cancelled'): 69return {'running': False, 'exit_code': 1, 'error': 'stopped', 'result': 'failed'} 70done = min(TOTAL, RATE * (time.time() - j['start'])) 71return {'running': True, 'step': '5/7: downloading Qwen3.8-Flash-Next IQ3_S', 'model': 'IQ3_S', 72'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}} 73def call(name, a): 74if name == 'strata_models': return CATALOG 75if name == 'strata_remove': 76cfg = ROOT / ('strata-%s.json' % a['model']) 77if a.get('confirm') and cfg.exists(): cfg.unlink() 78return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []} 79if name == 'strata_status': return {'summary': 'fake', 'installed': {'models': [{'model': 'iq3_s', 'disk_gb': 83.6, 'disk_bytes': 83600000000}]}, 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []} 80if name == 'strata_install': 81if a.get('cancel'): 82f = STATE / 'job.json' 83if f.exists(): j = json.loads(f.read_text()); j['cancelled'] = True; f.write_text(json.dumps(j)) 84return {'summary': 'stopped', 'install': job()} 85if a.get('confirm'): 86(STATE / 'job.json').write_text(json.dumps({'start': time.time()})) 87return {'summary': 'started', 'plan': {'download_gb': TOTAL}, 'install': job()} 88if not a: return {'summary': 'progress', 'install': job()} 89return {'summary': 'Plan', 'plan': {'title': 'Qwen3.8-Flash-Next IQ3_S', 'download_gb': TOTAL, 'disk_short': None}} 90raise Exception('unknown tool ' + name) 91for line in sys.stdin: 92line = line.strip() 93if not line: continue 94m = json.loads(line) 95if 'id' not in m: continue 96method = m.get('method') 97if method == 'initialize': res = {'protocolVersion': '2024-11-05'} 98elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]} 99else: 100p = m['params'] 101res = {'structuredContent': call(p['name'], p.get('arguments') or {})} 102sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': res}) + '\n'); sys.stdout.flush() 103` ; 104writeFileSync ( join ( control , 'tools' , 'strata_mcp.py' ), FAKE_INSTALLER ); 105 106const FAKE_ENGINE = `import os, sys, json, time 107from pathlib import Path 108if os.environ.get('FAKE_ENGINE_FAIL'): 109print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True) 110sys.exit(3) 111ctx = '4096' 112if '--max-context' in sys.argv: ctx = sys.argv[sys.argv.index('--max-context') + 1] 113print('READY %s stop' % ctx, flush=True) 114for line in sys.stdin: 115if line.strip() == 'QUIT': break 116if line.startswith(('GEN ', 'BGEN ')): 117slot = int(line.split()[1]) if line.startswith('BGEN ') else None 118t0 = time.time(); n = 0 119for ch in os.environ.get('FAKE_REPLY', 'a'): 120print('T %d' % ord(ch), flush=True); n += 1 121if os.environ.get('FAKE_TOKEN_DELAY'): time.sleep(float(os.environ['FAKE_TOKEN_DELAY'])) 122print('DONE %d 12 300.0 %.1f length 0 0 0' % (n, max(1.0, (time.time() - t0) * 1000)), flush=True) 123if slot is not None: print(f'BADM {slot} 0', flush=True) 124` ; 125 126// one scenario = one fresh host with its own per-user folders 127async function scenario ( name , { installed= false , env= {} } = {}, body ) { 128if ( ! only . has ( name )) return ; 129console . log ( `--- ${ name } ` ); 130const dir = join ( work , name ); 131const dirs = { home :join ( dir , 'home' ), appdata :join ( dir , 'appdata' ), local :join ( dir , 'local' ), components :join ( dir , 'local' , 'Strata' , 'components' ), install :join ( dir , 'local' , 'Strata' , 'install' ), state :join ( dir , 'fake-state' ), profiles :join ( dir , 'profiles' ), runtime :join ( dir , 'runtime' ) }; 132for ( const d of [ dirs . home , dirs . appdata , dirs . local , dirs . components , dirs . install , dirs . state , join ( dir , 'models' )]) mkdirSync ( d , { recursive :true }); 133const baseEnv = { ...process . env , STRATA_COMPONENTS_DIR :dirs . components , STRATA_PROFILE_DIR :dirs . profiles , STRATA_RUNTIME_DIR :dirs . runtime , STRATA_HOME :dirs . home , STRATA_MODELS_DIR :join ( dir , 'models' ), APPDATA :dirs . appdata , LOCALAPPDATA :dirs . local , USERPROFILE :dirs . home , XDG_CONFIG_HOME :join ( dir , 'xdg' ), XDG_DATA_HOME :join ( dir , 'xdgdata' ), PYTHONDONTWRITEBYTECODE :'1' , STRATA_ENGINE_BACKEND :'cuda' , FAKE_STATE :dirs . state , ...env }; 134delete baseEnv . STRATA_API_KEY ; delete baseEnv . STRATA_INSTALL_DIR ; 135if ( installed ) { 136const platform = isWin ?'windows-x86_64' :'linux-x86_64' ; 137const folder = join ( dirs . components , 'engine' , `0.1.45- ${ platform } -cuda` ); 138mkdirSync ( folder , { recursive :true }); 139writeFileSync ( join ( folder , 'engine_main.py' ), FAKE_ENGINE ); 140const entry = isWin ?'engine.cmd' :'engine' ; 141writeFileSync ( join ( folder , entry ), isWin ?`@echo off\r\n" ${ python } " "%~dp0engine_main.py" %*\r\n` :`#!/bin/sh\nexec " ${ python } " "$(dirname "$0")/engine_main.py" "$@"\n` ); 142const files = [ entry , 'engine_main.py' ]. map ( p => { const b = readFileSync ( join ( folder , p )); return { path :p , sha256 :sha ( b ), bytes :b . length }; }); 143writeFileSync ( join ( folder , 'engine-component.json' ), JSON . stringify ({ schema_version :1 , id :'strata-engine' , version :'0.1.45' , platform, backend :'cuda' , entrypoint :entry , files})); 144const tok = join ( dirs . install , 'tokenizer' ); 145mkdirSync ( tok , { recursive :true }); 146const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n` ; 147const made = spawnSync ( python , [ '-c' , script , tok ], { cwd :control , env :{ ...baseEnv , PYTHONNOUSERSITE :'1' }, encoding :'utf8' }); 148if ( made . status !== 0 ) throw new Error ( 'tokenizer fixture: ' + made . stderr ); 149writeFileSync ( join ( dirs . install , 'strata-iq3_s.json' ), JSON . stringify ({ exe :'component:strata-engine' , backend :'cuda' , tokenizer :tok , args :[ '--max-context' , '32768' , '--pool-workers' , '12' ], cwd :dir , model_name :'stub' , host :'127.0.0.1' , port :0 , kv :'int8' })); 150} 151const port = env . FIXED_PORT ?Number ( env . FIXED_PORT ) :await freePort (), base = `http://127.0.0.1: ${ port } ` ; 152const host = spawn ( nodeExe , [ join ( repoHost , 'server' , 'index.mjs' )], { cwd :repoHost , stdio :[ 'ignore' , 'pipe' , 'pipe' ], windowsHide :true , 153env :{ ...baseEnv , STRATA_PORT :String ( port ), STRATA_DIST :join ( repoHost , 'dist' ), STRATA_PACKAGED :'1' , STRATA_REAL_ENGINE :'1' , STRATA_NO_ACQUIRE :'1' , STRATA_CONTROL_DIR :control , STRATA_SHARE_PORT :String ( await freePort ()), STRATA_TUNNEL_PORT :String ( await freePort ()) } }); 154let log = '' ; host . stdout . on ( 'data' , c => { log += c ; }); host . stderr . on ( 'data' , c => { log += c ; }); 155const api = async ( path , init ) => { const r = await fetch ( base + path , init ); return { status :r . status , body :await r . json (). catch (() => null ) }; }; 156const browser = await chromium . launch ({ executablePath :CHROME , headless :true }); 157try { 158let up = false ; 159for ( let i = 0 ; i < 200 && ! up ; i ++ ) { try { up = ( await api ( '/api/health' )). status === 200 ; } catch { await delay ( 150 ); } } 160check ( up , ` ${ name } : the packaged host starts` ); 161await api ( '/api/native?refresh=1' ); 162await body ({ base, api, browser, dirs, shot :( page , n ) => page . screenshot ({ path :join ( shots , ` ${ name } - ${ n } .png` ) }), log :() => log }); 163} catch ( error ) { 164check ( false , ` ${ name } : the flow` , String ( error ?. stack ?? error ). slice ( 0 , 700 ) + '\n' + log . slice ( - 600 )); 165} finally { 166await browser . close (). catch (() => {}); 167host . kill (); await new Promise ( r => host . once ( 'exit' , r )); 168} 169} 170const newPage = async ( browser , base , options = {}) => { 171const context = await browser . newContext ({ viewport :{ width :1400 , height :950 }, ...( process . env . SCHEME ?{ colorScheme :process . env . SCHEME } :{}), ...options }); 172const page = await context . newPage (); 173const problems = []; 174page . on ( 'pageerror' , e => problems . push ( e . message )); 175page . problems = problems ; 176await page . goto ( base , { waitUntil :'domcontentloaded' }); 177return page ; 178}; 179const clickText = async ( page , re , timeout = 30000 ) => { const b = page . getByRole ( 'button' , { name :re }). first (); await b . waitFor ({ timeout}); await b . click (); }; 180const noScroll = async page => page . evaluate (() => { 181const root = document . querySelector ( '.guided-onboarding' ); 182const bad = []; 183for ( let el = document . querySelector ( '.onboard-tune-stage, .onboard-prepare-stage, .onboard-model-stage' ) ?? root ; el && el !== document . body ; el = el . parentElement ) { 184const style = getComputedStyle ( el ); 185if ( / ( auto | scroll ) / . test ( style . overflowY ) && el . scrollHeight > el . clientHeight + 1 ) bad . push ( ` ${ el . className || el . tagName } : ${ el . scrollHeight } > ${ el . clientHeight } ` ); 186} 187return bad ; 188}); 189 190// ------------------------------------------------------------------------------------------------ download 191await scenario ( 'download' , {}, async ({ base, api, browser, shot}) => { 192const page = await newPage ( browser , base ); 193await clickText ( page , / get started / i ); 194await page . getByText ( / Choose a version / i ). waitFor ({ timeout :30000 }); 195await page . locator ( '[role=radio]' ). filter ({ hasText :'IQ3_S' }). first (). click (); 196await clickText ( page , / ^Continue / ); 197await clickText ( page , / Download model / i , 60000 ); 198await page . locator ( '.onboard-progress progress' ). waitFor ({ timeout :30000 }); 199// ONE bar: sample the percent while it runs, it only goes up 200const samples = []; 201let eta = '' ; 202for ( let i = 0 ; i < 40 && ! eta ; i ++ ) { 203const state = ( await api ( '/api/native' )). body ; 204const d = state . jobs . at ( - 1 )?. result ?. install ?. download ; 205if ( d ) samples . push ( d . done_gb ); 206eta = ( await page . locator ( '.onboard-progress-actions span' ). first (). textContent ({ timeout :1000 }). catch (() => '' )) ?? '' ; 207await delay ( 1000 ); 208} 209await shot ( page , '1-wizard-progress' ); 210check ( / About \d + ( min left | h ) / . test ( eta ), 'the wizard shows about how many minutes are left' , eta . trim ()); 211const order = await page . evaluate (() => { const a = document . querySelector ( '.onboard-progress-actions' ); const kids = a ?[ ...a . children ]. map ( k => k . tagName + ':' + Math . round ( k . getBoundingClientRect (). left )) :[]; return kids ; }); 212check ( order . length === 2 && order [ 0 ]. startsWith ( 'SPAN' ) && order [ 1 ]. startsWith ( 'BUTTON' ) && Number ( order [ 0 ]. split ( ':' )[ 1 ]) < Number ( order [ 1 ]. split ( ':' )[ 1 ]), 'the time left sits left of Stop' , order . join ( ' ' )); 213check ( samples . length >= 3 && samples . every (( v , i ) => i === 0 || v >= samples [ i - 1 ]), 'one combined count that only goes up' , samples . map ( v => v . toFixed ( 1 )). join ( ', ' )); 214const meta = await page . locator ( '.onboard-progress-meta span' ). first (). textContent (); 215check ( / GB / . test ( meta ?? '' ) && / 83\.6 / . test ( meta ?? '' ), 'the bar says done / total over the whole model' , meta ); 216// close the pop-up while it downloads 217await clickText ( page , / Finish later / i ); 218await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 219await page . getByText ( / Preparing your model / i ). waitFor ({ timeout :15000 }). catch (() => {}); 220await delay ( 1500 ); 221await shot ( page , '2-models-progress' ); 222await page . locator ( '.native-progress' ). first (). screenshot ({ path :join ( shots , 'download-3-models-progress-card.png' ) }). catch (() => {}); 223check ( await page . locator ( '.guided-onboarding' ). count () === 0 , 'the setup pop-up closed' ); 224check ( await page . getByText ( / Preparing your model / i ). count () > 0 , 'the Models screen shows the running download' ); 225const still = ( await api ( '/api/native' )). body . jobs . at ( - 1 ); 226check ( still ?. state === 'running' , 'the download keeps running in the background' , still ?. state ); 227const modelsEta = await page . locator ( '.native-progress .onboard-progress-actions span' ). first (). textContent ({ timeout :15000 }). catch (() => '' ); 228check ( / About \d + ( min left | h ) / . test ( modelsEta ?? '' ), 'the Models screen shows the time left too' , ( modelsEta ?? '' ). trim ()); 229await clickText ( page , / ^Stop$ / ); 230await delay ( 2500 ); 231check (( await api ( '/api/native' )). body . jobs . at ( - 1 )?. state !== 'running' , 'Stop stops it' ); 232check ( page . problems . length === 0 , 'no page error' , page . problems . join ( '; ' )); 233}); 234 235// ------------------------------------------------------------------------------------------------ models 236await scenario ( 'models' , { installed :true }, async ({ base, api, browser, shot}) => { 237const page = await newPage ( browser , base ); 238await clickText ( page , / Go straight to the app / i ); 239await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 240await page . getByText ( / Conversation context / i ). first (). waitFor ({ timeout :30000 }); 241await delay ( 1500 ); 242await shot ( page , '1-models' ); 243await page . locator ( '.version-trigger' ). first (). waitFor ({ timeout :20000 }). catch ( async () => { await shot ( page , '0-models-missing-summary' ); console . log ( 'info page text:' , JSON . stringify (( await page . locator ( 'body' ). innerText ()). slice ( 0 , 500 ))); }); 244const summary = await page . locator ( '.version-trigger' ). first (). textContent ({ timeout :5000 }). catch (() => '' ); 245// the Models tab fits the first view: nothing to scroll while no list is open and Expert mode is closed 246if ( await page . getByRole ( 'button' , { name :/ ^Close expert mode$ / }). count ()) { await page . getByRole ( 'button' , { name :/ ^Close expert mode$ / }). click (); await delay ( 500 ); } 247await shot ( page , '1b-models-one-view' ); 248const overflow = await page . evaluate (() => { const el = document . querySelector ( '.main__body' ); return el ?el . scrollHeight - el . clientHeight :0 ; }); 249check ( overflow <= 2 , 'the Models tab fits the first view without scrolling' , String ( overflow ) + ' px over' ); 250check ( await page . locator ( '.family-switch' ). count () === 1 , 'the model family switch is in the navbar' ); 251check ( await page . locator ( 'h1' ). filter ({ hasText :/ ^Model$ / }). count () === 0 , 'and the navbar does not say "Model"' ); 252check ( / IQ3_S | High quality / . test ( summary ?? '' ), 'Models selects the model that is on this PC, not the recommendation' , ( summary ?? '' ). replace ( / \s +/ g , ' ' ). trim ()); 253check ( ! /IQ3_XXS | Balanced / . test ( summary ?? '' ), 'the recommendation (IQ3_XXS) is not what is selected' ); 254const load = page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (); 255await load . click (); 256await delay ( 1200 ); 257check ( await page . getByRole ( 'dialog' ). filter ({ hasText :/ Download and prepare / i }). count () === 0 , 'loading an installed model opens no download pop-up' ); 258let ready = false ; 259for ( let i = 0 ; i < 90 && ! ready ; i ++ ) { const s = ( await api ( '/api/native' )). body ; ready = s . instances . some ( x => x . status === 'ready' ); const err = s . instances . find ( x => x . status === 'error' ); if ( err ) throw new Error ( 'load failed: ' + err . error ); await delay ( 1000 ); } 260if ( ! ready ) { const st = ( await api ( '/api/native' )). body ; console . log ( 'info jobs' , JSON . stringify ( st . jobs . map ( j => [ j . kind , j . state , j . error ?? j . summary ])), 'instances' , JSON . stringify ( st . instances . map ( i => [ i . status , i . error ]))); await shot ( page , '2-models-after-click' ); } 261check ( ready , 'the model loads (a fake engine under the real Control)' ); 262await page . reload ({ waitUntil :'domcontentloaded' }); 263await page . getByRole ( 'button' , { name :/ ^Unload$ / }). first (). waitFor ({ timeout :30000 }). catch (() => {}); 264await shot ( page , '3-models-loaded' ); 265check ( await page . getByRole ( 'button' , { name :/ ^Unload$ / }). count () > 0 , 'after a reload the Models screen shows the model as loaded, with Unload' ); 266check ( await page . getByRole ( 'button' , { name :/ ^Load model$ / }). count () === 0 , 'and no longer offers Load model' ); 267await page . getByRole ( 'button' , { name :/ ^Unload$ / }). first (). click (); 268let gone = false ; 269for ( let i = 0 ; i < 40 && ! gone ; i ++ ) { gone = ( await api ( '/api/native' )). body . instances . length === 0 ; await delay ( 500 ); } 270check ( gone , 'Unload stops the engine' ); 271await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). waitFor ({ timeout :15000 }). catch (() => {}); 272check ( await page . getByRole ( 'button' , { name :/ ^Load model$ / }). count () > 0 , 'and Load model is back' ); 273check ( page . problems . length === 0 , 'no page error' , page . problems . join ( '; ' )); 274}); 275 276// ------------------------------------------------------------------------------------------------ the profile used, the popover, the pop-up 277await scenario ( 'profile' , { installed :true }, async ({ base, api, browser, shot}) => { 278const page = await newPage ( browser , base ); 279await clickText ( page , / Go straight to the app / i ); 280await page . getByText ( / Conversation context / i ). first (). waitFor ({ timeout :30000 }); 281await delay ( 1500 ); 282const work = () => page . getByRole ( 'button' , { name :/ Leave 20% for my work / }). first (); 283const full = () => page . getByRole ( 'button' , { name :/ Full performance / }). first (); 284await work (). click (); 285check ( await work (). getAttribute ( 'aria-pressed' ) === 'true' , 'Leave 20% is chosen before loading' ); 286await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). click (); 287let ready = false ; 288for ( let i = 0 ; i < 90 && ! ready ; i ++ ) { const s = ( await api ( '/api/native' )). body ; ready = s . instances . some ( x => x . status === 'ready' ); await delay ( 500 ); } 289check ( ready , 'the model loads' ); 290const inst = ( await api ( '/api/native' )). body . instances . find ( x => x . status === 'ready' ); 291check ( inst ?. resourceProfile === 'work' , 'the running model reports the profile it was started with' , String ( inst ?. resourceProfile )); 292await delay ( 1500 ); 293check ( await work (). getAttribute ( 'aria-pressed' ) === 'true' && await full (). getAttribute ( 'aria-pressed' ) === 'false' , 'after the load the page still shows Leave 20%, not Full performance' ); 294await page . reload ({ waitUntil :'domcontentloaded' }); 295await page . getByRole ( 'button' , { name :/ ^Unload$ / }). first (). waitFor ({ timeout :30000 }); 296await delay ( 1000 ); 297check ( await work (). getAttribute ( 'aria-pressed' ) === 'true' , 'and after a reload it is still the profile in use' ); 298await shot ( page , '1-profile-used' ); 299// the reasoning popover names the loaded model 300await page . evaluate (() => { location . hash = '#/chat' ; }); 301const effort = page . getByRole ( 'button' , { name :/ ^Reasoning effort / }). first (); 302await effort . waitFor ({ timeout :30000 }); 303await effort . click (); 304const header = await page . locator ( '.reasoning-menu-model strong' ). first (). textContent ({ timeout :10000 }); 305check ( header && ! /No model loaded / i . test ( header ), 'the Reasoning popover names the loaded model, not "No model loaded"' , String ( header )); 306await shot ( page , '2-reasoning-popover' ); 307await page . keyboard . press ( 'Escape' ); 308// an installed model asked for with other settings: the pop-up never speaks of downloading 309await page . evaluate (() => { location . hash = '#/models' ; }); 310await page . getByRole ( 'button' , { name :/ ^Unload$ / }). first (). waitFor ({ timeout :30000 }); 311await page . getByRole ( 'button' , { name :/ ^Unload$ / }). first (). click (); 312await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). waitFor ({ timeout :30000 }); 313await page . getByRole ( 'combobox' , { name :'Conversation context' }). first (). click (); 314const options = page . getByRole ( 'option' ); 315const pick = ( await options . allTextContents ()). findIndex ( t => / ^8K$ / . test ( t . trim ())); 316if ( pick >= 0 ) await options . nth ( pick ). click (); 317await page . getByRole ( 'button' , { name :/ ^Load model$ | ^Checking / }). first (). click (); 318const dialog = page . getByRole ( 'dialog' ). first (); 319await dialog . waitFor ({ timeout :15000 }). catch (() => {}); 320const text = ( await dialog . textContent (). catch (() => '' )) ?? '' ; 321await shot ( page , '3-apply-dialog' ); 322if ( text ) { 323check ( ! /Download and prepare | Download . load | approximately | [ 0 - 9 ] GB / i . test ( text ), 'for a downloaded model the pop-up has no download wording or size' , text . replace ( / \s +/ g , ' ' ). slice ( 0 , 600 )); 324check ( / Apply / . test ( text ), 'it says what happens: apply settings and load' ); 325} else console . log ( 'info the settings were the saved ones, so loading needed no pop-up at all' ); 326check ( page . problems . length === 0 , 'no page error' , page . problems . join ( '; ' )); 327}); 328 329// ------------------------------------------------------------------------------------------------ version list, This computer, Tune, a task 330for ( const scheme of [ 'light' , 'dark' ]) await scenario ( scheme === 'light' ?'ui2' :'ui2d' , { installed :true , env :{ FAKE_TOKEN_DELAY :'0.02' , FAKE_REPLY :'I am thinking about it. </think> ' + 'Here is the answer, word by word. ' . repeat ( 12 ), STRATA_TUNE_NO_QUIET_CHECK :'1' } }, async ({ base, api, browser, shot}) => { 331const page = await newPage ( browser , base , { colorScheme :scheme }); 332await clickText ( page , / Go straight to the app / i ); 333await page . getByText ( / Conversation context / i ). first (). waitFor ({ timeout :30000 }); 334await delay ( 1500 ); 335// the version list: Recommended (the fixed four), then folded groups, one line per model 336console . log ( 'info triggers' , await page . locator ( '.version-trigger' ). count (), await page . getByRole ( 'button' , { name :'Model version' }). count ()); 337await page . locator ( '.version-trigger' ). first (). click (); 338await delay ( 300 ); 339console . log ( 'info expanded after click' , await page . locator ( '.version-trigger' ). first (). getAttribute ( 'aria-expanded' )); 340await delay ( 800 ); await shot ( page , `0-after-click- ${ scheme } ` ); 341console . log ( 'info menu' , await page . evaluate (() => { const m = document . querySelector ( '.version-menu' ); const t = document . querySelector ( '.version-trigger' ); return JSON . stringify ({ menu :m ?m . getBoundingClientRect () :null , parent :m ?[ m . parentElement . className , getComputedStyle ( m . parentElement ). display , getComputedStyle ( m . parentElement ). visibility , m . parentElement . style . cssText . slice ( 0 , 120 )] :null , expanded :t ?. getAttribute ( 'aria-expanded' ), roles :[ ...document . querySelectorAll ( '[role=menu]' )]. length }); })); 342await page . locator ( '.version-menu' ). waitFor ({ timeout :10000 }); 343const heads = await page . locator ( '.version-head span:first-child, .version-group__head' ). allTextContents (); 344const names = await page . locator ( '.version-menu > .version-row .version-row__name strong' ). allTextContents (); 345console . log ( 'info version list' , JSON . stringify ( heads . map ( t => t . replace ( / \s +/ g , ' ' ). trim ())), JSON . stringify ( names )); 346check ( heads [ 0 ]?. trim () === 'Recommended' , ` ${ scheme } : the list starts with Recommended` ); 347check ( names . length >= 1 && names . length <= 4 , ` ${ scheme } : Recommended shows only the picks this catalog has (at most the fixed four)` , names . join ( ' | ' )); 348check ( heads . some ( t => / Swift models | GSQ-RCO models | Gyro models | NVFP4 models | Unsloth models / . test ( t )), ` ${ scheme } : the other models are in folded groups` ); 349check ( heads . at ( - 1 )?. includes ( 'Use your own GGUF' ), ` ${ scheme } : the last row is Use your own GGUF` ); 350const tall = await page . locator ( '.version-row' ). evaluateAll ( els => els . filter ( e => e . getBoundingClientRect (). height > 44 ). length ); 351check ( tall === 0 , ` ${ scheme } : every model is one line` , String ( tall )); 352await shot ( page , `1-versions- ${ scheme } ` ); 353await page . keyboard . press ( 'Escape' ); 354// This computer 355const pc = page . locator ( '.pc-card' ); 356await pc . waitFor ({ timeout :10000 }); 357const pcText = (( await pc . textContent ()) ?? '' ). replace ( / \s +/ g , ' ' ); 358check ( / This computer / . test ( pcText ) && / ( Fits fully in memory | read from the SSD ) / . test ( pcText ), ` ${ scheme } : This computer says in one line whether it fits` , pcText . slice ( 0 , 200 )); 359check ( await pc . locator ( '.pc-meter' ). count () >= 1 , ` ${ scheme } : it shows the memory bars` ); 360check ( await pc . locator ( '.chip, .st-pill, [class*="badge"]' ). count () === 0 , ` ${ scheme } : no chips or badges in it` ); 361await shot ( page , `2-computer- ${ scheme } ` ); 362// Tune: five steps, a live speed, a result card 363await page . getByRole ( 'button' , { name :/ ^Tune model$ / }). first (). click ({ timeout :10000 }); 364await delay ( 1500 ); await shot ( page , `2b-tune-dialog- ${ scheme } ` ); 365// The fake engine has no other setting worth trying, so its tune passes through "trying" too fast to be seen. The page is shown the progress a 366// real tune reports (Control's status file: stage, speeds) for the running view; the start, the result and every other call are real. 367let fakePhase = 'run' ; 368await page . route ( '**/api/native*' , async route => { 369const response = await route . fetch (); let json = null ; 370try { json = await response . json (); } catch { return route . fulfill ({ response}); } 371for ( const job of json ?. jobs ?? []) if ( job . kind === 'autotune' && fakePhase === 'done' ) { job . state = 'done' ; job . progress = null ; job . result = { outcome :'improved' , gain_pct :18 , base :{ decode_tok_s :41.2 }, chosen :{ decode_tok_s :48.6 }, preset :{ id :'fast' , name :'Fast · 64K' }, answers :{ class :'exact' , fields :[] } }; } else if ( job . kind === 'autotune' && job . state === 'running' ) job . progress = { stage :'rounds' , text :null , minutesLeft :9 , runsDone :3 , runsPlanned :6 , elapsedS :300 , step :'Trying: more experts kept in memory (round 1 of 2)' , speeds :[{ label :'base' , tok_s :41.2 }, { label :'Fewer helper threads' , tok_s :40.1 }, { label :'More experts kept in memory' , tok_s :46.8 }] }; 372return route . fulfill ({ response, json}); 373}); 374await page . getByRole ( 'button' , { name :/ Start tuning | Tune again / }). first (). click ({ timeout :15000 }); 375await page . locator ( '.tune-step' ). first (). waitFor ({ timeout :60000 }); 376check ( await page . locator ( '.tune-step' ). count () === 5 , ` ${ scheme } : the tuner shows its five steps` ); 377let sawRun = false , sawSpeed = false ; 378for ( let i = 0 ; i < 400 ; i ++ ) { 379const done = await page . locator ( '.tune-result, .tune-progress' ). count (); 380if ( i % 4 === 0 ) { const jobs = ( await api ( '/api/native' )). body ?. jobs ?? []; const j = jobs . find ( x => x . kind === 'autotune' ); if ( j ) console . log ( 'info tune job' , j . state , JSON . stringify ( j . progress ?? null ). slice ( 0 , 300 )); } 381if ( await page . locator ( '.tune-step[data-s=run]' ). count ()) sawRun = true ; 382const big = await page . locator ( '.tune-live__big' ). first (). textContent (). catch (() => '' ); 383if ( / [ 0 - 9 ] / . test ( big ?? '' )) sawSpeed = true ; 384if ( sawRun && sawSpeed ) { await delay ( 700 ); await shot ( page , `3-tune-running- ${ scheme } ` ); break ; } 385if ( done ) break ; 386await delay ( 600 ); 387} 388check ( sawRun , ` ${ scheme } : a step is shown as running` ); 389check ( sawSpeed , ` ${ scheme } : the live speed shows a number while it runs` ); 390if ( sawSpeed ) { fakePhase = 'done' ; await page . locator ( '.tune-outcome' ). waitFor ({ timeout :15000 }). catch (() => {}); check ( / 18% faster / . test (( await page . locator ( '.tune-outcome__body h3' ). textContent (). catch (() => '' )) ?? '' ), ` ${ scheme } : the result card shows the gain as its headline` ); check ( / Fast / . test (( await page . locator ( '.tune-outcome__facts' ). textContent (). catch (() => '' )) ?? '' ), ` ${ scheme } : and what it was saved as` ); } 391await shot ( page , `4-tune-result- ${ scheme } ` ); 392await page . getByRole ( 'button' , { name :/ ^Close$ / }). first (). click ({ timeout :10000 }). catch (() => {}); 393// a task: the opened task is skimmable, with pause / delete / Edit / Run now 394const made = await api ( '/api/tasks' , { method :'POST' , headers :{ 'content-type' :'application/json' }, body :JSON . stringify ({ title :'Open Downloads folder' , prompt :'Open my Downloads folder and tell me what is new.' , frequency :'weekdays' , at :'08:00' , weekday :1 , timeZone :'Europe/Ljubljana' , mode :'manual' , enabled :true }) }); 395const id = made . body ?. id ?? made . body ?. task ?. id ; 396check ( !! id , ` ${ scheme } : a task is created` , JSON . stringify ( made . body ). slice ( 0 , 120 )); 397await page . evaluate ( i => { location . hash = '#/tasks/' + i ; }, id ); 398await page . getByRole ( 'button' , { name :/ ^Edit$ / }). first (). waitFor ({ timeout :15000 }); 399console . log ( 'info header buttons' , await page . getByRole ( 'button' , { name :/ ^Pause / }). count (), await page . getByRole ( 'button' , { name :/ ^Delete / }). count (), await page . getByRole ( 'button' , { name :/ Run now / }). count (), JSON . stringify ( await page . locator ( '.task-header-actions button' ). evaluateAll ( b => b . map ( x => ( x . getAttribute ( 'aria-label' ) ?? x . textContent ?? '' ). trim ())))); 400check ( await page . getByRole ( 'button' , { name :/ ^Pause / }). count () === 1 && await page . getByRole ( 'button' , { name :/ ^Delete / }). count () >= 1 && await page . getByRole ( 'button' , { name :/ Run now / }). count () >= 1 , ` ${ scheme } : pause, delete, Edit and Run now are in the header` ); 401check ( await page . locator ( '.main__back' ). count () === 0 && await page . locator ( '.main__title-line .task-state' ). count () === 0 , ` ${ scheme } : nothing sits on the left of an opened task's navbar` ); 402const factsText = (( await page . locator ( '.task-facts' ). textContent ()) ?? '' ). replace ( / \s +/ g , ' ' ); 403check ( / Weekdays / . test ( factsText ) && / Schedule / i . test ( factsText ) && / Last result / i . test ( factsText ), ` ${ scheme } : schedule, what it may do and the last result are at the top` , factsText . slice ( 0 , 160 )); 404await shot ( page , `5-task- ${ scheme } ` ); 405await page . getByRole ( 'button' , { name :/ ^Pause / }). first (). click (); 406await page . getByRole ( 'button' , { name :/ ^Resume / }). first (). waitFor ({ timeout :10000 }); 407check ( true , ` ${ scheme } : Pause becomes Resume` ); 408check ( page . problems . length === 0 , ` ${ scheme } : no page error` , page . problems . join ( '; ' )); 409}); 410 411// ------------------------------------------------------------------------------------------------ tune + reading size 412await scenario ( 'tune' , { installed :true , env :{ FAKE_TOKEN_DELAY :'0.02' , FAKE_REPLY :[ 'I am thinking about it.' , '</think>' , '' , 'Here is a list:' , '' , '- one' , '- two' , '' , '## Heading' , '' , 'Some `code` and **bold** text.' , '' , '| a | b |' , '|---|---|' , '| 1 | 2 |' , '' , '```' , 'code line' , '```' , '' ]. join ( String . fromCharCode ( 10 )) } }, async ({ base, api, browser, dirs, shot}) => { 413const page = await newPage ( browser , base ); 414await clickText ( page , / get started / i ); 415await page . getByText ( / Choose a version / i ). waitFor ({ timeout :30000 }); 416await page . locator ( '[role=radio]' ). filter ({ hasText :'IQ3_S' }). first (). click (); 417await clickText ( page , / ^Continue / ); 418await page . getByText ( / Leave 20% for my work / i ). waitFor ({ timeout :30000 }); 419await delay ( 800 ); 420await shot ( page , '1-tune-step' ); 421check ( await page . getByText ( / Read pictures when this model loads / i ). count () === 0 , 'the tuning step offers no picture reading for an app install' ); 422await clickText ( page , / Tune & start chatting / i ); 423let done = false , job = null ; 424for ( let i = 0 ; i < 120 && ! done ; i ++ ) { job = ( await api ( '/api/native' )). body . jobs . findLast ?.( j => j . kind === 'tune' ) ?? null ; done = !! job && job . state !== 'running' ; await delay ( 1000 ); } 425check ( job ?. state === 'done' , 'tuning finishes without a vision error' , job ?. error ?? job ?. state ); 426const cfg = JSON . parse ( readFileSync ( join ( dirs . install , 'strata-iq3_s.json' ), 'utf8' )); 427check ( cfg . args . includes ( '--resident-budget-gib' ), '"leave 20%" wrote a RAM budget for the experts' , cfg . args . join ( ' ' )); 428const gib = Number ( cfg . args [ cfg . args . indexOf ( '--resident-budget-gib' ) + 1 ]); 429check ( gib + 10 <= 63.1 * 0.8 , 'the budget keeps the model within 80% of the PC RAM' , ` ${ gib } GiB` ); 430// chat + reading size 431await page . getByRole ( 'textbox' , { name :/ Message Strata / i }). waitFor ({ timeout :60000 }); 432await page . getByRole ( 'textbox' , { name :/ Message Strata / i }). fill ( 'hello' ); 433await page . keyboard . press ( 'Enter' ); 434await page . locator ( '.st-msg--assistant .st-bubble' ). first (). waitFor ({ timeout :60000 }); 435await page . locator ( '.st-msg--assistant .st-bubble p' ). first (). waitFor ({ timeout :60000 }). catch ( async () => console . log ( 'info reply so far:' , JSON . stringify ( await page . locator ( '.st-msg--assistant' ). first (). innerText ()). slice ( 0 , 300 ))); 436await page . waitForFunction (() => ! document . querySelector ( '.st-msg--assistant .caret' ), null , { timeout :90000 }). catch (() => {}); 437// the chat's telemetry chips: speed and context 438const chips = page . locator ( '.telemetry__chip' ); 439const chipTexts = await chips . allInnerTexts (); 440console . log ( 'info chips' , JSON . stringify ( chipTexts )); 441let speedText = '' , contextText = '' ; 442for ( let i = 0 ; i < await chips . count (); i ++ ) { 443await chips . nth ( i ). click (); 444await delay ( 400 ); 445const pop = await page . locator ( '.telepop' ). last (). innerText (). catch (() => '' ); 446if ( / tok\/s | speed / i . test ( pop ) && ! speedText ) speedText = pop ; 447if ( / context / i . test ( pop ) && ! contextText ) contextText = pop ; 448await page . keyboard . press ( 'Escape' ); 449} 450const tps = Number ( speedText . match ( / ([ \d . ] + ) \s * tok (?: ens ) ? \/s / )?.[ 1 ] ?? NaN ); 451check ( tps > 15 && tps < 120 , 'the speed shown is the decode speed (the engine paced at ~50 tokens a second)' , speedText . replace ( / \s +/ g , ' ' ). slice ( 0 , 160 )); 452check ( / 32\.8K | 32K | 32,768 | 32768 / . test ( contextText ) && ! /128K / . test ( contextText ), 'the context shown is the one the model runs with (32K), not 128K' , contextText . replace ( / \s +/ g , ' ' ). slice ( 0 , 160 )); 453const sizes = []; 454for ( const px of [ 12 , 14 , 16 , 22 ]) { 455await page . evaluate ( v => { const k = 'strata.prefs.v2' ; const cur = JSON . parse ( localStorage . getItem ( k ) || '{}' ); localStorage . setItem ( k , JSON . stringify ({ ...cur , contentFontSize :v })); }, px ); 456await page . reload ({ waitUntil :'domcontentloaded' }); 457await page . locator ( '.st-msg--assistant .st-bubble' ). first (). waitFor ({ timeout :30000 }); 458await page . screenshot ({ path :join ( shots , `tune-3-chat- ${ px } px.png` ) }); 459sizes . push ( await page . evaluate (() => { const b = document . querySelector ( '.st-msg--assistant .st-bubble' ); const t = b . querySelector ( 'p, .md-li, span' ) ?? b ; const u = document . querySelector ( '.st-msg--user .st-bubble' ); const all = {}; for ( const el of b . querySelectorAll ( '*' )) { if ( ! el . childNodes . length || ! [ ...el . childNodes ]. some ( n => n . nodeType === 3 && n . textContent . trim ())) continue ; all [ el . tagName . toLowerCase () + ( el . className ?'.' + String ( el . className ). split ( ' ' )[ 0 ] :'' )] = parseFloat ( getComputedStyle ( el ). fontSize ); } const extra = {}; for ( const [ k , q ] of Object . entries ({ reasoning :'.st-msg--assistant .st-collapse__body' , codeblock :'.st-msg--assistant .st-code pre' , codehead :'.st-msg--assistant .st-code__head' })) { const e = document . querySelector ( q ); if ( e ) extra [ k ] = parseFloat ( getComputedStyle ( e ). fontSize ); } Object . assign ( all , extra ); const chain = []; for ( let e = b . querySelector ( 'p' ); e && e !== b ; e = e . parentElement ) chain . push ( e . tagName + '.' + String ( e . className ). split ( ' ' )[ 0 ] + '=' + getComputedStyle ( e ). fontSize ); all . chain = chain ; globalThis . __all = all ; return [ parseFloat ( getComputedStyle ( b ). fontSize ), parseFloat ( getComputedStyle ( t ). fontSize ), parseFloat ( getComputedStyle ( u ). fontSize ), all ]; })); 460} 461console . log ( 'info chain' , JSON . stringify ( await page . evaluate (() => { const el = document . querySelector ( '.st-msg--assistant .st-bubble p' ); const out = []; for ( let e = el ; e && ! e . classList . contains ( 'st-msg' ); e = e . parentElement ) out . push ( e . tagName + '.' + String ( e . className ). split ( ' ' )[ 0 ] + '=' + getComputedStyle ( e ). fontSize ); return out ; }))); 462// which visible text does NOT follow the reading size? (same elements at 12 and 22) 463const survey = async px => { await page . evaluate ( v => { const k = 'strata.prefs.v2' ; const cur = JSON . parse ( localStorage . getItem ( k ) || '{}' ); localStorage . setItem ( k , JSON . stringify ({ ...cur , contentFontSize :v })); }, px ); await page . reload ({ waitUntil :'domcontentloaded' }); await page . locator ( '.st-msg--assistant .st-bubble' ). first (). waitFor ({ timeout :30000 }); await delay ( 600 ); 464return page . evaluate (() => { const out = {}; for ( const el of document . querySelectorAll ( 'main *, .chat *, textarea' )) { if ( ! [ ...el . childNodes ]. some ( n => n . nodeType === 3 && n . textContent . trim ()) && el . tagName !== 'TEXTAREA' ) continue ; const r = el . getBoundingClientRect (); if ( ! r . width || ! r . height ) continue ; const key = el . tagName . toLowerCase () + '.' + String ( el . className ). split ( ' ' )[ 0 ] + ' <' + ( el . parentElement ?. className ?? '' ). toString (). split ( ' ' )[ 0 ] + '>' ; out [ key ] = parseFloat ( getComputedStyle ( el ). fontSize ); } return out ; }); }; 465const a = await survey ( 12 ), b = await survey ( 22 ); 466// a fresh app (nothing saved) uses 14 px 467await page . evaluate (() => localStorage . removeItem ( 'strata.prefs.v2' )); 468await page . reload ({ waitUntil :'domcontentloaded' }); 469await page . locator ( '.st-msg--assistant .st-bubble' ). first (). waitFor ({ timeout :30000 }); 470check ( await page . evaluate (() => getComputedStyle ( document . querySelector ( '.st-msg--assistant .st-bubble' )). fontSize ) === '14px' , 'the default reading size is 14 px' ); 471const fixed = Object . keys ( a ). filter ( k => k in b && a [ k ] === b [ k ]); 472console . log ( 'info text that does not follow the reading size:' , JSON . stringify ( fixed . map ( k => k + '=' + a [ k ]))); 473await shot ( page , '2-chat-22px' ); 474console . log ( 'info sizes' , JSON . stringify ( sizes ), JSON . stringify ( await page . locator ( '.st-msg--assistant .st-bubble' ). first (). innerHTML ()). slice ( 0 , 400 )); 475check ( sizes [ 0 ][ 1 ] === 12 && sizes [ 1 ][ 1 ] === 14 && sizes [ 2 ][ 1 ] === 16 && sizes [ 3 ][ 1 ] === 22 && sizes [ 0 ][ 2 ] === 12 && sizes [ 3 ][ 2 ] === 22 , 'the reading size changes the text size of the conversation' , JSON . stringify ( sizes )); 476// the slider itself 477await page . evaluate (() => { location . hash = '#/chat?settings=1' ; }); 478const slider = page . getByLabel ( 'Reading text size' ); 479if ( await slider . count ()) { 480await slider . first (). focus (); 481for ( let i = 0 ; i < 4 ; i ++ ) await page . keyboard . press ( 'ArrowRight' ); 482await delay ( 500 ); 483const now = await page . evaluate (() => getComputedStyle ( document . querySelector ( '.st-msg--assistant .st-bubble' ) ?? document . body ). fontSize ); 484check ( parseFloat ( now ) === 18 , 'moving the slider changes the conversation text at once' , now ); 485const box = await slider . first (). boundingBox (); 486await page . mouse . click ( box . x + box . width * 0.9 , box . y + box . height / 2 ); 487await delay ( 400 ); 488const dragged = await page . evaluate (() => [ getComputedStyle ( document . querySelector ( '.st-msg--assistant .st-bubble' ) ?? document . body ). fontSize , getComputedStyle ( document . documentElement ). getPropertyValue ( '--st-content-fs' ), JSON . parse ( localStorage . getItem ( 'strata.prefs.v2' ) || '{}' ). contentFontSize ]); 489check ( parseFloat ( dragged [ 0 ]) >= 20 && parseFloat ( dragged [ 2 ]) >= 20 , 'clicking the slider with the mouse changes it too, and it is saved' , dragged . join ( ' ' )); 490} else console . log ( 'info the settings slider was not reachable by hash here; the stored size was checked above' ); 491check ( page . problems . length === 0 , 'no page error' , page . problems . join ( '; ' )); 492}); 493 494// ------------------------------------------------------------------------------------------------ delete 495await scenario ( 'delete' , { installed :true }, async ({ base, api, browser, dirs, shot}) => { 496const page = await newPage ( browser , base ); 497await clickText ( page , / Go straight to the app / i ); 498await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 499await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). click (); 500let ready = false ; 501for ( let i = 0 ; i < 90 && ! ready ; i ++ ) { ready = ( await api ( '/api/native' )). body . instances . some ( x => x . status === 'ready' ); await delay ( 1000 ); } 502check ( ready , 'a model is loaded' ); 503await clickText ( page , / Manage models / i ); 504await page . getByRole ( 'button' , { name :/ ^Delete$ / }). first (). click (); 505await delay ( 600 ); 506await shot ( page , '1-delete-confirm' ); 507const dialog = await page . getByRole ( 'dialog' ). last (). innerText (); 508check ( / Delete this version\? / . test ( dialog ) && / Remove 83\.6 GB of downloaded files\. You can download this version again\. / . test ( dialog ), 'the confirm dialog uses the existing words and the real size' , dialog . replace ( / \s +/ g , ' ' ). slice ( 0 , 600 )); 509check ( / running model will be unloaded / i . test ( dialog ), 'and says the loaded model is unloaded first' ); 510await page . getByRole ( 'button' , { name :/ ^Delete version$ / }). click (); 511let state = null ; 512for ( let i = 0 ; i < 40 ; i ++ ) { state = ( await api ( '/api/native' )). body ; if ( state . instances . length === 0 && ! state . installed ?. models ?. some ( m => m . model === 'iq3_s' )) break ; await delay ( 500 ); } 513check ( state . instances . length === 0 , 'the loaded model was unloaded' ); 514check ( ! existsSync ( join ( dirs . install , 'strata-iq3_s.json' )), 'the installer removed the run config of the model' ); 515check ( ! state . installed ?. models ?. some ( m => m . model === 'iq3_s' ), 'the model is no longer listed as downloaded' ); 516await shot ( page , '2-after-delete' ); 517}); 518 519// ------------------------------------------------------------------------------------------------ perf 520await scenario ( 'perf' , { installed :true }, async ({ base, api, browser, shot}) => { 521const page = await newPage ( browser , base ); 522await clickText ( page , / Go straight to the app / i ); 523await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 524await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). click (); 525let ready = false ; 526for ( let i = 0 ; i < 90 && ! ready ; i ++ ) { ready = ( await api ( '/api/native' )). body . instances . some ( x => x . status === 'ready' ); await delay ( 1000 ); } 527check ( ready , 'a model is loaded' ); 528await delay ( 2500 ); 529const requests = []; 530const started = new Map (); 531page . on ( 'request' , r => started . set ( r , Date . now ())); 532page . on ( 'requestfinished' , r => requests . push ([ r . url (). replace ( base , '' ). slice ( 0 , 60 ), Date . now () - ( started . get ( r ) ?? Date . now ())])); 533await page . evaluate (() => { window . __long = []; new PerformanceObserver ( l => { for ( const e of l . getEntries ()) window . __long . push ( Math . round ( e . duration )); }). observe ({ entryTypes :[ 'longtask' ] }); }); 534const t0 = Date . now (); 535await page . evaluate (() => { location . hash = '#/chat' ; }); 536await page . getByRole ( 'textbox' , { name :/ Message Strata / i }). waitFor ({ timeout :30000 }); 537const open = Date . now () - t0 ; 538await delay ( 1500 ); 539const long = await page . evaluate (() => window . __long ); 540console . log ( 'info chat opened in' , open , 'ms; long tasks' , JSON . stringify ( long ), 'requests' , JSON . stringify ( requests . filter ( r => r [ 1 ] > 100 )), 'all' , requests . length ); 541check ( open < 1500 && Math . max ( 0 , ...long ) < 300 , 'Models to Chat opens at once, with no long block' , open + ' ms, longest task ' + Math . max ( 0 , ...long ) + ' ms' ); 542}); 543 544// ------------------------------------------------------------------------------------------------ polish 545await scenario ( 'polish' , { installed :true }, async ({ base, api, browser, dirs, shot}) => { 546const page = await newPage ( browser , base ); 547await clickText ( page , / Go straight to the app / i ); 548await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 549await page . getByText ( / Conversation context / i ). first (). waitFor ({ timeout :30000 }); 550check ( await page . getByRole ( 'button' , { name :/ ^Tune model$ / }). count () === 1 , 'the Models tab has the Tune model button (the real tuner, not the old short benchmark)' ); 551await clickText ( page , / Manage models / i ); 552await delay ( 500 ); 553const rows = await page . locator ( '.native-manage-row' ). count (); 554check ( rows === 1 , 'Manage models lists only the downloaded model, not the catalog' , rows + ' row(s)' ); 555await shot ( page , '1-manage-models' ); 556await page . getByRole ( 'button' , { name :/ ^Done$ / }). click (); 557await page . getByRole ( 'button' , { name :/ Other local models / i }). click (). catch ( async () => { await clickText ( page , / Manage models / i ); await clickText ( page , / Use a local GGUF / i ); }); 558await page . getByText ( / Folder with the GGUF files / i ). first (). waitFor ({ timeout :15000 }). catch (() => {}); 559await shot ( page , '2-local-gguf' ); 560check ( await page . getByText ( / Folder with the GGUF files / i ). count () > 0 , 'the local GGUF page opens in the same design as Models' ); 561await page . getByPlaceholder ( / Full path to the folder / i ). fill ( join ( dirs . install , 'does-not-exist' )); 562await page . getByRole ( 'button' , { name :/ ^Check files$ / }). click (); 563await delay ( 3000 ); 564check ( await page . locator ( '.error-notice' ). count () > 0 , 'a folder that cannot be used says so in words' ); 565await shot ( page , '2b-local-gguf-problem' ); 566await page . evaluate (() => { location . hash = '#/chat?settings=1' ; }); 567await delay ( 1500 ); 568const text = await page . locator ( 'body' ). innerText (); 569check ( ! /Contrast / . test ( text ), 'Settings has no Contrast option' ); 570check ( ! /View request log / . test ( text ), 'and no "View request log" button' ); 571await page . getByText ( / ^Engine$ / ). first (). click (). catch (() => {}); 572await delay ( 1500 ); 573await shot ( page , '3-settings-engine' ); 574const engine = await page . locator ( 'body' ). innerText (); 575check ( / Update component / . test ( engine ) && / Diagnostics / . test ( engine ), 'Settings > Engine has Update component and Diagnostics' ); 576check ( ! /Performance | Model settings | Calibrate | Engine installation / . test ( engine ), 'and nothing else' ); 577await page . getByRole ( 'button' , { name :/ ^View logs$ / }). click (); // the logs open in a pop-up that holds Save logs 578await page . getByRole ( 'button' , { name :/ ^Save logs$ / }). click (); 579await page . getByText ( / Saved to / ). first (). waitFor ({ timeout :15000 }). catch (() => {}); 580const savedText = await page . getByText ( / Saved to / ). first (). innerText (). catch (() => '' ); 581const savedPath = savedText . replace ( / ^Saved to\s */ , '' ). trim (); 582check ( !! savedPath && existsSync ( savedPath ), 'Save logs writes a file to Downloads and says where' , savedPath ); 583await shot ( page , '4-logs-saved' ); 584await page . evaluate (() => { location . hash = '#/monitor' ; }); 585await delay ( 6000 ); 586await shot ( page , '5-monitor' ); 587const mon = await page . locator ( 'body' ). innerText (); 588check ( / °C / . test ( mon ), 'the Monitor shows GPU data with no model loaded' , ( mon . match ( / . { 0 , 30 } °C. { 0 , 20 } / )?.[ 0 ] ?? 'no temperature text' ). replace ( / \s +/ g , ' ' )); 589}); 590 591// ------------------------------------------------------------------------------------------------ stop 592await scenario ( 'stop' , { installed :true , env :{ FAKE_TOKEN_DELAY :'0.1' , FAKE_REPLY :'thinking ' . repeat ( 30 ) } }, async ({ base, api, browser, shot}) => { 593const page = await newPage ( browser , base ); 594await clickText ( page , / Go straight to the app / i ); 595await page . waitForURL ( / #\/models / , { timeout :15000 }). catch (() => {}); 596await page . getByRole ( 'button' , { name :/ ^Load model$ / }). first (). click (); 597let ready = false ; 598for ( let i = 0 ; i < 90 && ! ready ; i ++ ) { ready = ( await api ( '/api/native' )). body . instances . some ( x => x . status === 'ready' ); await delay ( 1000 ); } 599if ( ! ready ) { const st = ( await api ( '/api/native' )). body ; console . log ( 'info jobs' , JSON . stringify ( st . jobs . map ( j => [ j . kind , j . state , j . error ?? j . summary ])), JSON . stringify ( st . instances . map ( i => [ i . status , i . error ]))); await shot ( page , '0-stop-notloaded' ); } 600check ( ready , 'a model is loaded' ); 601await page . evaluate (() => { location . hash = '#/chat' ; }); 602const box = page . getByRole ( 'textbox' , { name :/ Message Strata / i }); 603await box . waitFor ({ timeout :30000 }); 604await box . fill ( 'hello' ); 605await page . keyboard . press ( 'Enter' ); 606await page . locator ( '.typing' ). first (). waitFor ({ timeout :30000 }); 607await delay ( 1500 ); 608await page . getByRole ( 'button' , { name :/ ^Stop / i }). first (). click (). catch ( async () => { await page . keyboard . press ( 'Escape' ); }); 609await delay ( 4000 ); 610const dots = await page . locator ( '.typing' ). count (); 611await shot ( page , '1-after-stop' ); 612check ( dots === 0 , 'after Stop in the middle of thinking the three dots are gone' , dots + ' left' ); 613}); 614 615// ------------------------------------------------------------------------------------------------ latest 616await scenario ( 'latest' , {}, async ({ base, browser, shot}) => { 617const page = await newPage ( browser , base ); 618const now = Date . now (); 619await page . evaluate ( async now => { 620const messages = []; 621for ( let i = 0 ; i < 40 ; i ++ ) { messages . push ({ id :'u' + i , role :'user' , content :'question ' + i , at :now }, { id :'a' + i , role :'assistant' , content :'answer number ' + i + ' with some text to fill the line and more of it.' , at :now , tokens :20 , inputTokens :5 }); } 622await fetch ( '/api/chats/s_latest' , { method :'PUT' , headers :{ 'x-strata-client' :'ui' }, body :JSON . stringify ({ id :'s_latest' , title :'long' , updatedAt :now , createdAt :now , messages}) }); 623localStorage . setItem ( 'strata.active-session.v1' , 's_latest' ); 624}, now ); 625await page . reload ({ waitUntil :'domcontentloaded' }); 626await delay ( 1500 ); 627if ( await page . getByRole ( 'button' , { name :/ Go straight to the app / i }). count ()) { await clickText ( page , / Go straight to the app / i ); await delay ( 1500 ); } 628await page . goto ( base + '/#/chat' , { waitUntil :'domcontentloaded' }); 629await page . getByRole ( 'textbox' , { name :/ Message Strata / i }). waitFor ({ timeout :30000 }); 630await delay ( 800 ); 631await page . locator ( '.main__body.chat' ). first (). waitFor ({ timeout :15000 }). catch ( async () => { await shot ( page , '0-latest-missing' ); console . log ( 'info body' , JSON . stringify (( await page . locator ( 'body' ). innerText ()). slice ( 0 , 300 ))); }); 632await page . locator ( '.main__body.chat' ). first (). evaluate ( el => { el . scrollTop = 3000 ; }); 633await delay ( 600 ); 634await page . mouse . wheel ( 0 , - 400 ); 635await delay ( 600 ); 636await page . locator ( '.main__body.chat' ). first (). evaluate ( el => { el . scrollTop = 0 ; }); 637await delay ( 800 ); 638const gaps = await page . evaluate (() => { const b = document . querySelector ( '.jumplatest' ), c = document . querySelector ( '.main__body.chat' ); if ( ! b || ! c ) return null ; const r = b . getBoundingClientRect (), cr = c . getBoundingClientRect (); return { top :Math . round ( r . top - cr . top ), bottom :Math . round ( cr . bottom - r . bottom ) }; }); 639console . log ( 'info chat dom' , JSON . stringify ( await page . evaluate (() => { const c = document . querySelector ( '.main__body.chat' ); return { msgs :document . querySelectorAll ( '.st-msg' ). length , scrollH :c ?. scrollHeight , clientH :c ?. clientHeight , top :c ?. scrollTop , jump :document . querySelectorAll ( '.jumplatest' ). length }; }))); 640await shot ( page , '1-latest-button' ); 641check ( !! gaps && gaps . top >= 12 && gaps . bottom >= 12 , 'the Latest button keeps a gap from the top navigation and from the bottom' , JSON . stringify ( gaps )); 642}); 643 644// ------------------------------------------------------------------------------------------------ fail 645await scenario ( 'fail' , { installed :true , env :{ FAKE_ENGINE_FAIL :'1' } }, async ({ base, api, browser, shot}) => { 646const page = await newPage ( browser , base ); 647await clickText ( page , / get started / i ); 648await page . getByText ( / Choose a version / i ). waitFor ({ timeout :30000 }); 649await page . locator ( '[role=radio]' ). filter ({ hasText :'IQ3_S' }). first (). click (); 650await clickText ( page , / ^Continue / ); 651await clickText ( page , / Tune & start chatting / i , 30000 ); 652await page . getByText ( / ran low on memory / i ). first (). waitFor ({ timeout :120000 }); 653await delay ( 1000 ); 654await shot ( page , '1-tune-error' ); 655const text = await page . locator ( '.guided-onboarding' ). innerText (); 656check ( / ran low on memory / . test ( text ), 'the error says in words that the PC ran low on memory' ); 657check ( / Leave 20% for my work / . test ( text ) && / low-RAM / . test ( text ), 'and what to try' ); 658check ( ! /server_exited | memory guard / . test ( text ), 'no code or log line in the main text' ); 659check ( ! /vision files / i . test ( text ), 'no picture-reading error' ); 660const bad = await noScroll ( page ); 661check ( bad . length === 0 , 'the tuning pop-up does not scroll when an error shows' , bad . join ( '; ' )); 662await page . locator ( '.error-notice summary' ). first (). click (); 663await delay ( 500 ); 664await shot ( page , '2-tune-error-details' ); 665const details = await page . locator ( '.error-notice pre' ). first (). innerText (); 666check ( / server_exited / . test ( details ) && / exited before / . test ( details ), 'Details holds the code and the reason the server logged' , details . replace ( / \s +/ g , ' ' ). slice ( 0 , 120 )); 667const badOpen = await noScroll ( page ); 668check ( badOpen . length === 0 , 'and the pop-up still does not scroll with Details open' , badOpen . join ( '; ' )); 669await page . setViewportSize ({ width :1280 , height :700 }); 670await delay ( 600 ); 671const small = await noScroll ( page ); 672check ( small . length === 0 , 'nor in a small window (1280x700), Details open' , small . join ( '; ' )); 673await shot ( page , '3-tune-error-small-window' ); 674void api ; 675}); 676 677// ------------------------------------------------------------------------------------------------ restart 678// The app keeps its theme, text size, language and chat list in the browser's storage, which belongs to the window's origin 679// (127.0.0.1:<port>). The shell now uses the same port every launch: stop the host, start it again on that port, reopen the 680// window with the same browser profile, and everything is still there. 681if ( only . has ( 'restart' )) { 682console . log ( '--- restart' ); 683const fixed = await freePort (); 684const profile = join ( work , 'browser-profile' ); 685const run = async ( body ) => scenario ( 'restart' , { env :{ FIXED_PORT :String ( fixed ) } }, async ctx => { 686const context = await chromium . launchPersistentContext ( profile , { executablePath :CHROME , headless :true , viewport :{ width :1200 , height :800 } }); 687try { await body ( context , ctx ); } finally { await context . close (); } 688}); 689only . add ( 'restart' ); 690await run ( async ( context , { base}) => { 691const page = context . pages ()[ 0 ] ?? await context . newPage (); 692await page . goto ( base , { waitUntil :'domcontentloaded' }); 693await page . evaluate (() => { localStorage . setItem ( 'strata.prefs.v2' , JSON . stringify ({ theme :'dark' , contentFontSize :19 , language :'de' })); return fetch ( '/api/chats/chat-1' , { method :'PUT' , headers :{ 'x-strata-client' :'ui' }, body :JSON . stringify ({ id :'chat-1' , title :'My chat' , messages :[], createdAt :new Date (). toISOString (), updatedAt :new Date (). toISOString () }) }); }); 694}); 695await run ( async ( context , { base}) => { 696const page = context . pages ()[ 0 ] ?? await context . newPage (); 697await page . goto ( base , { waitUntil :'domcontentloaded' }); 698const saved = await page . evaluate ( async () => ({ prefs :JSON . parse ( localStorage . getItem ( 'strata.prefs.v2' ) || '{}' ), chats :JSON . stringify ( await ( await fetch ( '/api/chats' , { headers :{ 'x-strata-client' :'ui' } })). json ()), theme :document . documentElement . dataset . theme })); 699check ( saved . prefs . contentFontSize === 19 && saved . prefs . language === 'de' , 'text size and language survive a restart on the same port' , JSON . stringify ( saved . prefs )); 700check ( saved . theme === 'dark' , 'the theme survives too' , saved . theme ); 701check ( / My chat / . test ( saved . chats ?? '' ), 'and the chat list' , saved . chats ); 702}); 703} 704 705// ------------------------------------------------------------------------------------------------ theme 706await scenario ( 'theme' , {}, async ({ base, browser, shot}) => { 707for ( const scheme of [ 'dark' , 'light' ]) { 708const page = await newPage ( browser , base , { colorScheme :scheme }); 709await delay ( 1500 ); 710const theme = await page . evaluate (() => document . documentElement . dataset . theme ); 711check ( theme === scheme , `a fresh app follows the system ( ${ scheme } )` , theme ); 712await shot ( page , `1- ${ scheme } ` ); 713await page . context (). close (); 714} 715}); 716 717// the junctions into the staged Control go first (rmdir on a junction removes only the link) 718for ( const name of [ 'python' , 'strata_control' , 'strata_cli' , 'serve' ]) { try { rmdirSync ( join ( control , name )); } catch { /* already gone */ } } 719try { rmSync ( work , { recursive :true , force :true , maxRetries :3 }); } catch ( e ) { console . log ( 'info scratch folder left behind:' , work ); } 720console . log ( `shots in ${ shots } ` ); 721process . exit ( failed ?1 :0 );