okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1import { tr } from '../lib/i18n' ; 2import { FloatingMenu } from '../components/FloatingMenu' ; 3import { LifecycleNotice } from '../components/LifecycleNotice' ; 4/** One configuration draft shared by simple choices, parameters and JSON. */ 5import { useEffect , useMemo , useRef , useState } from 'react' ; 6import { DemoTest , PerformancePreview } from '../components/EngineExperience' ; 7import { AutoTune } from '../components/AutoTune' ; 8import { contextTokens , estimate , execution , RECOMMENDED_CONTEXT_TOKENS } from '../lib/experience' ; 9import type { Workload } from '../lib/experience' ; 10import { ActionError , Btn , Dialog , ErrorNotice , Icon , Select } from '../components/ui' ; 11import { Screen , SectionHead } from '../components/layout' ; 12import { configDocument , configPatch , draftParams , readConfig , type ConfigDocument } from '../lib/config' ; 13import { useStore , setConfigDraft , saveEngine , restartEngine , validateEngine , pushToast , lifecycleAvailable , useLifecycle } from '../lib/store' ; 14import type { BeginnerConfig , EngineConfig , ExpertParam } from '../lib/types' ; 15type Issue = { 16level :'warn' | 'error' ; 17key ?:string ; 18message :string ; 19}; 20export function TuningScreen () { 21const engine = useStore ( s => s . engine ); 22const hardware = useStore ( s => s . hardware ); 23const [ workload , setWorkload ] = useState < Workload >( 'document' ); 24const [ testOpen , setTestOpen ] = useState ( false ); 25const [ tuneOpen , setTuneOpen ] = useState ( false ); 26const [ unsupported , setUnsupported ] = useState ( false ); 27const [ updating , setUpdating ] = useState ( false ); 28const library = useStore ( s => s . library ); 29const rawDraft = useStore ( s => s . configDraft ); 30const connected = useStore ( s => s . connection === 'live' ); 31const [ mode , setMode ] = useState < 'beginner' | 'expert' >( 'beginner' ); 32const [ view , setView ] = useState < 'parameters' | 'raw' >( 'parameters' ); 33const [ query , setQuery ] = useState ( '' ); 34const [ group , setGroup ] = useState ( 'all' ); 35const [ changedOnly , setChangedOnly ] = useState ( false ); 36const [ descriptions , setDescriptions ] = useState ( false ); 37const [ moreOpen , setMoreOpen ] = useState ( false ); 38const lifecycle = useLifecycle (); 39const [ issues , setIssues ] = useState < Issue []>([]); 40const [ preview , setPreview ] = useState < EngineConfig [ 'predicted' ] | null >( null ); 41const [ pending , setPending ] = useState ( false ); 42const [ checked , setChecked ] = useState ( false ); 43const [ applyOpen , setApplyOpen ] = useState ( false ); 44const [ discardOpen , setDiscardOpen ] = useState ( false ); 45const importRef = useRef < HTMLInputElement >( null ); 46const moreRef = useRef < HTMLButtonElement >( null ); 47function closeMore () { setMoreOpen ( false ); moreRef . current ?. focus (); } 48const saved = useMemo (() => engine ?configDocument ( engine ) :null , [ engine ]); 49const text = rawDraft ?? ( saved ?JSON . stringify ( saved , null , 2 ) :'' ); 50const parsed = useMemo (() => { 51try { 52return { doc :readConfig ( text ), error :null }; 53} 54catch ( e ) { 55return { doc :null , error :e instanceof Error ?e . message :String ( e ) }; 56} 57}, [ text ]); 58const doc = parsed . doc ; 59const params = useMemo (() => engine && doc ?draftParams ( engine , doc ) :[], [ engine , doc ]); 60const changed = useMemo (() => params . filter ( p => p . value !== saved ?. expert [ p . id ]), [ params , saved ]); 61const dirty = rawDraft !== null && ( ! doc || JSON . stringify ( doc ) !== JSON . stringify ( saved )); 62const groups = [ ...new Set ( params . map ( p => p . group ))]; 63const rows = params . filter ( p => p . id !== 'server.host' && ( unsupported || !! p . applies && ! p . applies . startsWith ( 'Preserved' ))). filter ( p => ( group === 'all' || p . group === group ) && ( ! changedOnly || p . value !== saved ?. expert [ p . id ]) && ` ${ p . id } ${ p . label } ${ p . effect } ${ p . group } ` . toLowerCase (). includes ( query . toLowerCase ())); 64const current = library ?. variants . find ( v => v . id === library ?. loaded ); 65useEffect (() => { 66setChecked ( false ); 67setUpdating ( true ); 68if ( ! doc || ! engine || ! connected ) { 69setPreview ( null ); 70setUpdating ( false ); 71return ; 72} 73let active = true ; 74const timer = setTimeout (() => { 75void validateEngine ( configPatch ( doc )). then ( result => { 76if ( ! active ) 77return ; 78setUpdating ( false ); 79setIssues ( result . issues ); 80setPreview ( result . predicted ?? null ); 81}). catch ( e => { if ( active ) { 82setUpdating ( false ); 83setIssues ([{ level :'error' , message :e . message }]); 84} }); 85}, 180 ); 86return () => { active = false ; clearTimeout ( timer ); }; 87}, [ text , connected , engine ?. variantId ]); 88function update ( next :ConfigDocument ) { setConfigDraft ( JSON . stringify ( next , null , 2 )); } 89function changeParam ( id :string , value :ExpertParam [ 'value' ]) { 90if ( ! doc ) 91return ; 92const next = { ...doc , beginner :{ ...doc . beginner }, expert :{ ...doc . expert , [ id ] :value } }; 93if ( id === 'perf.batch' ) 94Object . assign ( next , { batchAutomatic :false }); 95if ( id === 'ctx.length' ) 96next . beginner . contextLength = String ( value ). toLowerCase () as BeginnerConfig [ 'contextLength' ]; 97update ( next ); 98} 99async function check () { 100if ( ! doc ) { 101setChecked ( true ); 102return false ; 103} 104const result = await validateEngine ( configPatch ( doc )); 105setIssues ( result . issues ); 106setPreview ( result . predicted ?? null ); 107setChecked ( true ); 108return result . ok ; 109} 110async function save ( apply = false ) { 111if ( ! doc || pending ) 112return ; 113setPending ( true ); 114try { 115if ( ! await check ()) 116return ; 117if ( apply && ! lifecycleAvailable ()) 118return ; 119await saveEngine ( configPatch ( doc ), true , apply ); 120setConfigDraft ( null ); 121setApplyOpen ( false ); 122if ( apply ) 123await restartEngine (); 124else 125pushToast ( 'success' , 'Settings saved' , 'Used the next time this model loads. Sampling defaults affect the next request.' ); 126} 127catch ( e ) { 128setIssues ([{ level :'error' , message :e instanceof Error ?e . message :String ( e ) }]); 129} 130finally { 131setPending ( false ); 132} 133} 134function download () { 135if ( ! doc ) 136return ; 137const url = URL . createObjectURL ( new Blob ([ JSON . stringify ( doc , null , 2 )], { type :'application/json' })); 138const a = document . createElement ( 'a' ); 139a . href = url ; 140a . download = 'strata-engine.json' ; 141a . click (); 142URL . revokeObjectURL ( url ); 143} 144function resetDraft () { 145if ( ! engine || ! doc ) 146return ; 147update ({ ...doc , batchAutomatic :true , beginner :{ priority :'balanced' , contextLength :'recommended' , readImages :false , gpuIdle :'never' }, expert :Object . fromEntries ( engine . expert . map ( p => [ p . id , p . recommended ])) }); 148} 149async function importFile ( file :File | undefined ) { 150if ( ! file ) 151return ; 152try { 153update ( readConfig ( await file . text ())); 154setMode ( 'expert' ); 155setView ( 'raw' ); 156} 157catch ( e ) { 158setIssues ([{ level :'error' , message :`Import failed: ${ e instanceof Error ? e . message : String ( e )} ` }]); 159} 160} 161if ( ! engine || ! saved ) 162return < Screen plainHeader title = { tr ( "Engine" )}>< div className = "setup__note" >{ tr ( connected ?'Loading settings…' :'Connect the engine to edit its settings.' )}</ div ></ Screen >; 163const predicted = preview ?? engine . predicted ; 164const cfg = execution ( doc ?. expert , contextTokens ( doc ?. beginner . contextLength ?? engine . beginner . contextLength )); 165const savedCfg = execution ( saved . expert , contextTokens ( saved . beginner . contextLength )); 166const contextMax = Math . max ( 4 , Math . floor (( current ?. contextMax ?? 32768 ) / 1024 )); 167const recommendedContext = RECOMMENDED_CONTEXT_TOKENS / 1024 ; 168const recommendedPosition = contextMax === 4 ?0 :Math . min ( 100 , ( recommendedContext - 4 ) / ( contextMax - 4 ) * 100 ); 169const experience = estimate ( current , hardware , cfg , workload , library ?. mode === 'simulated' ); 170const savedExperience = estimate ( current , hardware , savedCfg , workload , library ?. mode === 'simulated' ); 171const showPreview = < PerformancePreview experience = { experience } saved = { savedExperience } workload = { workload } onWorkload = { setWorkload } updating = { updating }/>; 172const errors = parsed . error ?[{ level :'error' , message :parsed . error } as Issue ] :issues ; 173const visibleIssues = errors . filter ( i => ! i . message . startsWith ( 'Estimated working memory (' ) && ! i . message . includes ( 'is fast memory. Actual fit and offload behavior' )); 174const invalid = !! parsed . error || errors . some ( i => i . level === 'error' ); 175return < Screen plainHeader title = { tr ( "Engine" )} actions = {<>< button className = "st-btn st-btn--secondary" aria-pressed = { mode === 'expert' } onClick = {() => setMode ( mode === 'expert' ?'beginner' :'expert' )}>{ tr ( mode === 'expert' ?'Easy mode' :'Expert mode' )}</ button >< Btn disabled = { ! doc } onClick = { resetDraft }>{ tr ( "Reset to recommended" )}</ Btn >< Btn disabled = { ! doc } onClick = {() => setTestOpen ( true )}>{ tr ( "Run speed test" )}</ Btn ></>}> 176< div className = "stack stack--lg tuning" data-mode = { mode }> 177< ActionError /> 178{ tr ( mode === 'beginner' && doc ?< div className = "instrument-layout" > 179< section className = "instrument-controls simple-engine" >< div className = "auto-tune-card" >< Icon name = "gauge" size = { 28 }/>< h2 className = "h3" >{ tr ( "Make the most of this computer" )}</ h2 >< p className = "small muted" >{ tr ( "Find a starting point for your hardware, then review before saving." )}</ p >< Btn variant = "primary" disabled = { ! hardware || ! current } onClick = {() => setTuneOpen ( true )}>{ tr ( "Auto-tune for my PC" )}</ Btn > 180< label className = "input-field" >< span >{ tr ( "Conversation context \u00B7 " )}{ tr ( cfg . context / 1024 )}{ tr ( "K" )}</ span > 181< div className = "context-slider" >< input type = "range" className = "st-slider" aria-label = { tr ( "Conversation context" )} aria-valuetext = { ` ${ cfg . context / 1024 } K tokens` } aria-describedby = "context-recommendation context-help" min = { 4 } max = { contextMax } step = { 1 } value = { cfg . context / 1024 } onChange = { e => changeParam ( 'ctx.length' , ` ${ e . target . value } K` )}/>< span className = "context-recommendation-mark" aria-hidden = "true" style = {{ left :`calc( ${ recommendedPosition } % + ${ 8 - recommendedPosition * .16 } px)` }}/></ div > 182< div className = "context-guidance" >< div className = "context-scale" aria-hidden = "true" >< span >{ tr ( "4K" )}</ span >< span >{ tr ( contextMax )}{ tr ( "K" )}</ span ></ div >< p className = "context-recommendation" id = "context-recommendation" >< span aria-hidden = "true" />{ tr ( "Recommended: " )}{ tr ( recommendedContext )}{ tr ( "K" )}</ p >< p className = "xs muted" id = "context-help" >{ tr ( "More conversation history uses more memory." )}</ p ></ div > 183</ label ></ div > 184< section >< h2 className = "h4" >{ tr ( "Resources" )}</ h2 >< div className = "workload-cards" >{ tr ([{ id :'shared' , title :'Leave room for other apps' , detail :'Keep this computer responsive' }, { id :'full' , title :'Full speed' , detail :'Give the engine more CPU threads' }]. map ( h => < button key = { h . id } aria-pressed = {( doc . headroom ?? 'shared' ) === h . id } onClick = {() => update ({ ...doc , headroom :h . id , expert :{ ...doc . expert , 'perf.threads' :Math . max ( 1 , ( hardware ?. cpu . cores ?? 4 ) - ( h . id === 'shared' ?2 :0 )) } })}>< strong >{ tr ( h . title )}</ strong >< span >{ tr ( h . detail )}</ span ></ button >))}</ div ></ section > 185</ section >{ tr ( showPreview )} 186</ div > :< div className = "stack expert-engine" > 187< div className = "engine-subtabs" role = "tablist" aria-label = { tr ( "Expert editor" )}>{ tr (([ 'parameters' , 'raw' ] as const ). map ( v => < button role = "tab" aria-selected = { view === v } key = { v } onClick = {() => setView ( v )}>{ tr ( v === 'raw' ?'Raw config' :'Parameters' )}</ button >))}</ div > 188{ tr ( view === 'raw' ?< section className = "stack" > 189< SectionHead title = { tr ( "Configuration draft" )} right = {< div className = "row" >< Btn size = "sm" onClick = {() => setDiscardOpen ( true )}>{ tr ( "Reload saved" )}</ Btn >< Btn size = "sm" onClick = { download } disabled = { ! doc }>{ tr ( "Export" )}</ Btn >< Btn size = "sm" onClick = {() => importRef . current ?. click ()}>{ tr ( "Import" )}</ Btn ></ div >}/> 190{ tr ( parsed . error ?< ErrorNotice message = { parsed . error } next = { tr ( "Correct the JSON before saving or applying." )}/> :null )}< textarea className = "st-input config-editor" aria-label = { tr ( "Configuration draft" )} aria-invalid = { !! parsed . error } aria-describedby = { visibleIssues . length ?'config-errors' :undefined } spellCheck = { false } value = { text } onChange = { e => setConfigDraft ( e . target . value )}/> 191</ section > :<> 192< div className = "row small muted" >< a href = "#/serving" >{ tr ( "Server access is managed in Serving" )}</ a >< label className = "check-label" >< input type = "checkbox" checked = { unsupported } onChange = { e => setUnsupported ( e . target . checked )}/>{ tr ( "Show unsupported" )}</ label ></ div >< div className = "parameter-toolbar" > 193< input className = "st-input" type = "search" aria-label = { tr ( "Search parameters" )} placeholder = { tr ( "Search name or technical key…" )} value = { query } onChange = { e => setQuery ( e . target . value )}/> 194< Select value = { group } ariaLabel = { tr ( "Parameter group" )} options = {[{ value :'all' , label :'All groups' }, ...groups . map ( g => ({ value :g , label :g }))]} onChange = { setGroup }/> 195< label className = "check-label" >< input type = "checkbox" checked = { changedOnly } onChange = { e => setChangedOnly ( e . target . checked )}/>{ tr ( "Changed only (" )}{ tr ( changed . length )} ) </ label >< label className = "check-label" >< input type = "checkbox" checked = { descriptions } onChange = { e => setDescriptions ( e . target . checked )}/>{ tr ( "Show descriptions" )}</ label > 196</ div > 197{ tr ( groups . filter ( g => rows . some ( p => p . group === g )). map ( g => < section className = "parameter-group" key = { g }> 198< h2 className = "h4" >{ tr ( g )}</ h2 > 199{ tr ( rows . filter ( p => p . group === g ). map ( p => < div className = "parameter-row" key = { p . id }> 200< div >< label className = "strong" htmlFor = { `param- ${ p . id } ` }>{ tr ( p . label )}</ label >< code className = "parameter-key" >{ p . id }</ code >{ tr ( descriptions ?< div className = "small muted" >{ tr ( p . effect )}</ div > :null )}< div className = "parameter-support xs muted" data-unsupported = { ! p . applies || p . applies . startsWith ( 'Preserved' ) || undefined }>{ tr ( ! p . applies || p . applies . startsWith ( 'Preserved' ) ?'Not used by this engine' :p . applies )}{ tr ( " \u00B7 recommended " )}{ tr ( String ( p . recommended ))}</ div ></ div > 201< div >< div className = "parameter-control" >< ExpertInput param = { p } disabled = { ! p . applies || p . applies . startsWith ( 'Preserved' )} onChange = { value => changeParam ( p . id , value )}/>< Btn variant = "ghost" size = "sm" disabled = { p . value === saved . expert [ p . id ]} onClick = {() => changeParam ( p . id , saved . expert [ p . id ] ?? p . recommended )}>{ tr ( "Revert" )}</ Btn ></ div >{ tr ( errors . filter ( i => i . message . startsWith ( p . id + ':' )). map ( i => < p className = "small inline-error" role = "alert" key = { i . message }>{ tr ( i . message )}</ p >))}</ div > 202</ div >))} 203</ section >))} 204{ tr ( ! rows . length ?< div className = "empty-inline" >{ tr ( "No parameters match. " )}< Btn variant = "ghost" onClick = {() => { setQuery ( '' ); setGroup ( 'all' ); setChangedOnly ( false ); }}>{ tr ( "Clear filters" )}</ Btn ></ div > :null )} 205</>)} 206</ div >)} 207< input type = "file" accept = ".json,application/json" ref = { importRef } hidden onChange = { e => { void importFile ( e . target . files ?.[ 0 ]); e . target . value = '' ; }}/> 208{ tr ( mode === 'expert' && descriptions && predicted . notes . length ?< p className = "xs muted" >{ tr ( predicted . notes . join ( ' ' ))}</ p > :null )} 209{ tr ( visibleIssues . length ?< div className = "validation-list" id = "config-errors" role = "status" >{ tr ( visibleIssues . map (( issue , i ) => < div key = { i } data-tone = { issue . level }>< Icon name = { issue . level === 'error' ?'error' :'info' } size = { 16 }/>< span >{ tr ( issue . message )}</ span ></ div >))}</ div > :checked ?< p className = "small" role = "status" >{ tr ( "Configuration checked. No validation errors." )}</ p > :null )} 210{ tr ( dirty ?< div className = "config-savebar" >< span className = "small" >{ tr ( changed . length || 'Configuration' )} { tr ( changed . length === 1 ?'change' :'changes' )}</ span >< span className = "spacer" />{ tr ( library ?. loaded && library . mode !== 'simulated' ?< Btn size = "sm" disabled = { invalid || pending || ! connected || ! lifecycle . allowed } onClick = {() => setApplyOpen ( true )}>{ tr ( "Apply now\u2026" )}</ Btn > :null )}< Btn size = "sm" variant = "ghost" disabled = { pending } onClick = {() => setDiscardOpen ( true )}>{ tr ( "Discard" )}</ Btn >< Btn size = "sm" variant = "primary" disabled = { invalid || pending || ! connected } onClick = {() => void save ()}>{ tr ( pending ?'Saving…' :'Save' )}</ Btn ></ div > :null )} 211 212</ div > 213{ tr ( moreOpen ?< FloatingMenu anchor = { moreRef . current } title = { tr ( "More actions" )} onClose = { closeMore }> 214< button role = "menuitem" className = "menu__item" disabled = { pending || ! doc } onClick = {() => { closeMore (); resetDraft (); }}>{ tr ( "Recommended defaults" )}</ button > 215< button role = "menuitem" className = "menu__item" disabled = { ! connected || pending } onClick = {() => { closeMore (); void check (). catch ( e => setIssues ([{ level :'error' , message :e . message }])); }}>{ tr ( "Validate draft" )}</ button > 216< button role = "menuitem" className = "menu__item" disabled = { ! doc || invalid } onClick = {() => { closeMore (); setTestOpen ( true ); }}>{ tr ( "Preview test \u00B7 Example" )}</ button > 217</ FloatingMenu > :null )} 218< DemoTest open = { testOpen } onClose = {() => setTestOpen ( false )} experience = { experience }/> 219< AutoTune open = { tuneOpen } onClose = {() => setTuneOpen ( false )} onDone = {() => { resetDraft (); setTuneOpen ( false ); }}/> 220< Dialog open = { discardOpen } compact title = { tr ( "Discard configuration changes?" )} onClose = {() => setDiscardOpen ( false )} actions = {<>< Btn onClick = {() => setDiscardOpen ( false )}>{ tr ( "Keep editing" )}</ Btn >< Btn variant = "danger" onClick = {() => { setConfigDraft ( null ); setIssues ([]); setDiscardOpen ( false ); }}>{ tr ( "Discard changes" )}</ Btn ></>}>< p >{ tr ( "Discard all unsaved engine changes and return to the saved configuration." )}</ p ></ Dialog > 221< Dialog open = { applyOpen } title = { tr ( "Apply settings now?" )} onClose = {() => setApplyOpen ( false )} actions = {<>< Btn onClick = {() => setApplyOpen ( false )}>{ tr ( "Keep editing" )}</ Btn >< Btn variant = "primary" disabled = { pending || invalid || ! lifecycle . allowed } onClick = {() => void save ( true )}>{ tr ( "Save and restart" )}</ Btn ></>}>< p >{ tr ( "Save the draft and restart " )}{ tr ( current ?. label ?? 'the loaded model' )} . </ p >< LifecycleNotice /></ Dialog > 222</ Screen >; 223} 224function ExpertInput ({ param, onChange, disabled= false } :{ 225param :ExpertParam ; 226disabled ?:boolean ; 227onChange :( value :ExpertParam [ 'value' ]) => void ; 228}) { 229if ( param . type === 'select' && param . options ) 230return < Select disabled = { disabled } value = { String ( param . value )} ariaLabel = { tr ( param . label )} options = { param . options . map ( value => ({ value, label :value }))} onChange = { onChange }/>; 231if ( param . type === 'toggle' ) 232return < button disabled = { disabled } className = "st-toggle" type = "button" role = "switch" aria-checked = { !! param . value } aria-label = { tr ( param . label )} onClick = {() => onChange ( ! param . value )}/>; 233return < input disabled = { disabled } id = { `param- ${ param . id } ` } className = "st-input" aria-label = { tr ( param . label )} inputMode = { param . type === 'number' ?'decimal' :undefined } value = { String ( param . value )} onChange = { e => { const v = e . target . value ; onChange ( param . type === 'number' && v . trim () !== '' && Number . isFinite ( Number ( v )) ?Number ( v ) :v ); }}/>; 234}