okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
dc87d45eb
main
1import { localeTag } from '../lib/i18n' ; 2import { tr } from '../lib/i18n' ; 3import { useEffect , useId , useRef , useState } from 'react' ; 4import type { PointerEvent } from 'react' ; 5import { closestStop , dialAngle , dialIndex , unwrapAngle } from '../lib/tuning-controls' ; 6import { Btn , Dialog , Icon , Select } from './ui' ; 7import { DEFAULT_EXECUTION , FIT_TEXT , OUTPUT_TOKENS , PROFILES , WORKLOADS , RECOMMENDED_CONTEXT_TOKENS , durationText , speedText } from '../lib/experience' ; 8import type { Execution , Experience , Profile , Workload } from '../lib/experience' ; 9export function ProfileChoice ({ value, onChange} :{ 10value :Profile ; 11onChange :( profile :Profile ) => void ; 12}) { 13return < div className = "profile-choice" role = "radiogroup" aria-label = { tr ( "Model priority" )}>{ tr ( PROFILES . map (( p , i ) => < button type = "button" className = "profile-option" role = "radio" aria-checked = { value === p . id } tabIndex = { value === p . id ?0 :- 1 } key = { p . id } onClick = {() => onChange ( p . id )} onKeyDown = { e => { 14if ( ! [ 'ArrowRight' , 'ArrowLeft' , 'ArrowDown' , 'ArrowUp' , 'Home' , 'End' ]. includes ( e . key )) 15return ; 16e . preventDefault (); 17const at = e . key === 'Home' ?0 :e . key === 'End' ?2 :( i + ([ 'ArrowRight' , 'ArrowDown' ]. includes ( e . key ) ?1 :- 1 ) + 3 ) % 3 ; 18onChange ( PROFILES [ at ]. id ); 19( e . currentTarget . parentElement ?. children [ at ] as HTMLElement )?. focus (); 20}}>< Icon name = { p . icon } size = { 22 }/>< strong >{ tr ( p . label )}</ strong >< span >{ tr ( p . purpose )}</ span >{ tr ( value === p . id ?< Icon name = "check" size = { 16 }/> :null )}</ button >))}</ div >; 21} 22function point ( angle :number , r = 78 ) { const a = angle * Math . PI / 180 ; return { x :110 + r * Math . sin ( a ), y :110 - r * Math . cos ( a ) }; } 23function angleAt ( index :number , count :number ) { return - 135 + 270 * index / Math . max ( 1 , count - 1 ); } 24export function Dial ({ label, hint, values, value, saved, recommended, onChange, onReset, tone= 'accent' , gestureHint= true , exactEntry= true } :{ 25label :string ; 26hint :string ; 27values :{ 28value :number ; 29label :string ; 30}[]; 31value :number ; 32saved :number ; 33recommended :number ; 34onChange :( v :number ) => void ; 35onReset ?:() => void ; 36tone ?:'accent' | 'info' ; 37gestureHint ?:boolean ; 38exactEntry ?:boolean ; 39}) { 40const id = useId (); 41const drag = useRef <{ 42angle :number ; 43} | null >( null ); 44const index = Math . max ( 0 , values . findIndex ( v => v . value === value )); 45const [ dragIndex , setDragIndex ] = useState < number | null >( null ); 46const [ entry , setEntry ] = useState ( String ( value )); 47const [ entryError , setEntryError ] = useState ( '' ); 48useEffect (() => { setEntry ( String ( value )); setEntryError ( '' ); }, [ value ]); 49const shown = dragIndex ?? index ; 50function select ( i :number ) { onChange ( values [ Math . max ( 0 , Math . min ( values . length - 1 , Math . round ( i )))]. value ); } 51function track ( e :PointerEvent < HTMLDivElement >, initial = false ) { 52const r = e . currentTarget . getBoundingClientRect (); 53const x = e . clientX - r . left - r . width / 2 , y = e . clientY - r . top - r . height / 2 ; 54if ( Math . hypot ( x , y ) < r . width * .12 ) 55return ; 56const raw = dialAngle ( x , y ); 57const angle = initial || ! drag . current ?raw :unwrapAngle ( raw , drag . current . angle ); 58drag . current = { angle}; 59const next = dialIndex ( angle , values . length ); 60setDragIndex ( next ); 61select ( next ); 62} 63function finish ( e :PointerEvent < HTMLDivElement >) { 64if ( ! drag . current ) 65return ; 66track ( e ); 67drag . current = null ; 68setDragIndex ( null ); 69if ( e . currentTarget . hasPointerCapture ( e . pointerId )) 70e . currentTarget . releasePointerCapture ( e . pointerId ); 71} 72function commitEntry () { 73const n = Number ( entry ); 74if ( ! Number . isFinite ( n ) || n <= 0 ) { 75setEntryError ( 'Enter a positive number.' ); 76return ; 77} 78const snapped = closestStop ( n , values . map ( v => v . value )); 79onChange ( snapped ); 80setEntry ( String ( snapped )); 81setEntryError ( '' ); 82} 83const pointer = angleAt ( shown , values . length ); 84const known = values . some ( v => v . value === value ); 85return < section className = "tactile-control" data-tone = { tone }> 86< div className = "row row--between" >< h3 className = "h4" id = { id }>{ tr ( label )}</ h3 >< button type = "button" className = "dial-reset" onClick = {() => onReset ?onReset () :onChange ( recommended )} disabled = { value === recommended }>{ tr ( "Reset" )}</ button ></ div > 87< div className = "dial" role = "slider" aria-labelledby = { id } aria-describedby = { ` ${ id } -hint` } aria-valuemin = { values [ 0 ]?. value } aria-valuemax = { values . at ( - 1 )?. value } aria-valuenow = { known ?value :undefined } aria-valuetext = { values . find ( v => v . value === value )?. label ?? ` ${ value } custom` } tabIndex = { 0 } data-custom = { ! known || undefined } data-dragging = { dragIndex !== null } onPointerDown = { e => { 88if ( e . button !== 0 ) 89return ; 90e . preventDefault (); 91e . currentTarget . focus (); 92e . currentTarget . setPointerCapture ( e . pointerId ); 93drag . current = { angle :angleAt ( index , values . length ) }; 94track ( e , true ); 95}} onPointerMove = { e => { 96if ( drag . current ) 97track ( e ); 98}} onPointerUp = { finish } onPointerCancel = {() => { drag . current = null ; setDragIndex ( null ); }} onKeyDown = { e => { 99if ( ! [ 'ArrowUp' , 'ArrowDown' , 'ArrowLeft' , 'ArrowRight' , 'Home' , 'End' , 'PageUp' , 'PageDown' ]. includes ( e . key )) 100return ; 101e . preventDefault (); 102select ( e . key === 'Home' ?0 :e . key === 'End' ?values . length - 1 :index + ([ 'ArrowUp' , 'ArrowRight' , 'PageUp' ]. includes ( e . key ) ?1 :- 1 )); 103}}> 104< svg viewBox = "0 0 220 220" aria-hidden = "true" > 105< circle className = "dial-track" cx = "110" cy = "110" r = "78" pathLength = "360" strokeDasharray = "270 90" transform = "rotate(135 110 110)" /> 106< circle className = "dial-fill" cx = "110" cy = "110" r = "78" pathLength = "360" strokeDasharray = { ` ${ 270 * shown / Math . max ( 1 , values . length - 1 )} 360` } transform = "rotate(135 110 110)" /> 107{ tr ( values . map (( v , i ) => { const p = point ( angleAt ( i , values . length ), 96 ); const q = point ( angleAt ( i , values . length ), v . value === recommended ?87 :91 ); return < line key = { v . value } x1 = { p . x } y1 = { p . y } x2 = { q . x } y2 = { q . y } className = { v . value === recommended ?'dial-detent dial-detent--recommended' :'dial-detent' }/>; }))} 108{ tr ( values . some ( v => v . value === saved ) ?< circle className = "dial-saved" { ...{ cx :point ( angleAt ( values . findIndex ( v => v . value === saved ), values . length )). x , cy :point ( angleAt ( values . findIndex ( v => v . value === saved ), values . length )). y }} r = "5" /> :null )} 109< circle className = "dial-face" cx = "110" cy = "110" r = "62" /> 110< g className = "dial-pointer" style = {{ transform :`rotate( ${ pointer } deg)` }}>< line x1 = "110" y1 = "53" x2 = "110" y2 = "66" /></ g > 111</ svg > 112< div className = "dial-value" >< strong >{ tr ( dragIndex !== null ?values [ Math . round ( dragIndex )]. label :known ?values [ index ]. label :value . toLocaleString ( localeTag ()))}</ strong >< span >{ tr ( value === recommended ?'Recommended' :known ?'Custom' :'Expert value' )}</ span ></ div > 113</ div > 114< div className = "dial-stops" aria-hidden = "true" >{ tr ( values . map ( v => < span key = { v . value }>{ tr ( v . label )}</ span >))}</ div >{ tr ( gestureHint ?< p className = "dial-caption" >{ tr ( "Turn the dial \u00B7 or use arrow keys" )}</ p > :null )} 115{ tr ( exactEntry ?< label className = "dial-entry" >< span >{ tr ( "Exact value" )}</ span >< input className = "st-input" aria-label = { tr ( "{0} exact value" , [ label ])} aria-invalid = { !! entryError } inputMode = "numeric" value = { entry } onChange = { e => setEntry ( e . target . value )} onBlur = { commitEntry } onKeyDown = { e => { 116if ( e . key === 'Enter' ) { 117e . preventDefault (); 118commitEntry (); 119} 120}}/></ label > :null )} 121{ tr ( entryError ?< p className = "inline-error xs" role = "alert" >{ tr ( entryError )}</ p > :null )}< p className = "small muted" id = { ` ${ id } -hint` }>{ tr ( hint )}</ p > 122</ section >; 123} 124export function TuningDials ({ config, saved= config , contextMax, batchSupported, batchAuto, onBatchAuto, onChange, showContext= true , showBatch= true , exactEntry= true } :{ 125config :Execution ; 126saved ?:Execution ; 127contextMax :number ; 128batchSupported :boolean ; 129batchAuto :boolean ; 130onBatchAuto :( v :boolean ) => void ; 131onChange :( patch :Partial < Execution >) => void ; 132showContext ?:boolean ; 133showBatch ?:boolean ; 134exactEntry ?:boolean ; 135}) { 136const contexts = [ 4096 , 8192 , 16384 , 32768 , 65536 , 131072 , 262144 , 524288 , 1048576 ]. filter ( v => v <= contextMax ). map ( value => ({ value, label :` ${ value / 1024 } K` })); 137const recommended = Math . min ( RECOMMENDED_CONTEXT_TOKENS , contexts . at ( - 1 )?. value ?? 4096 ); 138return < div className = "tuning-dials" > 139{ tr ( showContext ?contexts . length ?< Dial exactEntry = { exactEntry } label = { tr ( "Context" )} hint = { tr ( "More text uses more memory." )} values = { contexts } value = { config . context } saved = { saved . context } recommended = { recommended } onChange = { context => onChange ({ context})}/> :< p >{ tr ( "No supported context length." )}</ p > :null )} 140{ tr ( showBatch ?batchSupported ?< details className = "disclosure batch-disclosure" >< summary >{ tr ( "Prompt batch \u00B7 " )}{ tr ( batchAuto ?'Automatic' :`Custom: ${ config . batch . toLocaleString ( localeTag ())} ` )} < span className = "accent" >{ tr ( "Adjust" )}</ span ></ summary >< div >< Dial gestureHint = { false } label = { tr ( "Prompt batch" )} hint = { tr ( "Larger batches can use more memory; they are not always faster." )} tone = "info" values = {[ 256 , 512 , 1024 , 2048 , 4096 ]. map ( value => ({ value, label :value . toLocaleString ( localeTag ()) }))} value = { config . batch } saved = { saved . batch } recommended = { DEFAULT_EXECUTION . batch } onReset = {() => onBatchAuto ( true )} onChange = { batch => { onBatchAuto ( false ); onChange ({ batch}); }}/>< label className = "check-label batch-auto" >< input type = "checkbox" checked = { batchAuto } onChange = { e => { onBatchAuto ( e . target . checked ); }}/>{ tr ( "Automatic \u00B7 recommended 2,048" )}</ label ></ div ></ details > :< div className = "tactile-control" >< h3 className = "h4" >{ tr ( "Prompt batch" )}</ h3 >< p className = "muted" >{ tr ( "This adapter cannot apply prompt batch settings." )}</ p ></ div > :null )} 141</ div >; 142} 143export function WorkloadChoice ({ value, context, onChange} :{ 144value :Workload ; 145context :number ; 146onChange :( w :Workload ) => void ; 147}) { 148return < Select ariaLabel = { tr ( "Sample workload" )} value = { value } options = { WORKLOADS . map ( w => ({ value :w . id , label :` ${ w . label } · ${ w . tokens / 1024 } K tokens ${ w . tokens + OUTPUT_TOKENS > context ? ' · needs more context' : '' } ` , disabled :w . tokens + OUTPUT_TOKENS > context }))} onChange = { onChange }/>; 149} 150export function SpeedPair ({ experience :e } :{ 151experience :Experience ; 152}) { 153return < div className = "speed-summary" title = { tr ( e . provenance )} aria-label = { tr ( "Reading and answer speeds. {0}." , [ e . source === 'demo' ?tr ( 'Illustrative estimates' ) :e . source ])}>< div className = "speed-pair" >{ tr ([{ label :'Reading' , value :e . reading , tone :'info' }, { label :'Answer' , value :e . answer , tone :'accent' }]. map ( m => < div key = { m . label } data-tone = { m . tone }>< span className = "small muted" >{ tr ( m . label )}</ span >< strong className = "speed-value" >{ tr ( speedText ( m . value ))}{ tr ( m . value ?< small >{ tr ( " tok/s" )}</ small > :null )}</ strong ></ div >))}</ div ></ div >; 154} 155export function MemoryBudget ({ experience :e , detailed= false } :{ 156experience :Experience ; 157detailed ?:boolean ; 158}) { 159const m = e . memory ; 160if ( ! m ) 161return < p className = "small muted" >{ tr ( "Memory \u00B7 Not estimated \u00B7 " )}{ tr ( FIT_TEXT [ e . fit ])}</ p >; 162const max = Math . max ( m . total , m . budget ?? m . total ); 163return < div className = "memory-budget" >< div className = "row row--between" >< strong className = "small" >{ tr ( m . pool )}</ strong >< span className = "xs muted" >{ tr ( "Estimated" )}</ span ></ div >< div className = "memory-summary" >< strong >{ tr ( m . total . toFixed ( 1 ))} < small >{ tr ( "GB required" )}</ small ></ strong >< span >{ tr ( m . remaining === null ?'Room remaining unknown' :m . remaining >= 0 ?` ${ m . remaining . toFixed ( 1 )} GB remaining` :` ${( - m . remaining ). toFixed ( 1 )} GB over budget` )}</ span ></ div > 164< div className = "memory-strip" role = "img" aria-label = { tr ( "Model {0} GB, context {1} GB, runtime {2} GB. {3}" , [ m . weights . toFixed ( 1 ), m . cache . toFixed ( 1 ), m . runtime . toFixed ( 1 ), FIT_TEXT [ e . fit ]])}> 165< span data-part = "weights" style = {{ flex :m . weights / max }}/>< span data-part = "cache" style = {{ flex :m . cache / max }}/>< span data-part = "runtime" style = {{ flex :m . runtime / max }}/>< span data-part = "free" style = {{ flex :Math . max ( 0 , m . remaining ?? 0 ) / max }}/> 166</ div >< p className = "small muted" >{ tr ( FIT_TEXT [ e . fit ])}</ p > 167{ tr ( detailed ?<>< div className = "memory-legend" >{ tr ([ 'Model weights' , 'Context/cache' , 'Runtime' , 'Remaining' ]. map (( l , i ) => < span key = { l }>< i data-part = {[ 'weights' , 'cache' , 'runtime' , 'free' ][ i ]}/>{ tr ( l )}</ span >))}</ div >< p className = "small muted" >{ tr ( m . unified ?'One shared pool; CPU and GPU use the same memory.' :! m . placementKnown ?'Partial offload: allocation between GPU and system memory is not estimated.' :m . systemBudget !== null ?`System budget ${ m . systemBudget . toFixed ( 1 )} GB separately; additional host use is not estimated.` :'System memory budget reserves room for the OS.' )}</ p ></> :null )} 168</ div >; 169} 170export function ExperienceDetails ({ experience :e } :{ 171experience :Experience ; 172}) { 173const tokens = WORKLOADS . find ( w => w . id === e . workload ) ! . tokens ; 174return < div className = "experience-details-content" >< ol className = "experience-path" >< li >< span >{ tr ( "Read prompt" )}< strong >{ tr ( e . fitsWorkload ?durationText ( tokens , e . reading ) :'Context too short' )}</ strong ></ span ></ li >< li >< span >{ tr ( "Start answering" )}< strong >{ tr ( "Not estimated" )}</ strong ></ span ></ li >< li >< span >{ tr ( "Generate" )}< strong >{ tr ( e . fitsWorkload ?durationText ( OUTPUT_TOKENS , e . answer ) :'Unavailable' )}</ strong ></ span ></ li ></ ol > 175< MemoryBudget experience = { e } detailed />< p >{ tr ( e . provenance )}</ p >< p >{ tr ( tokens . toLocaleString ( localeTag ()))}{ tr ( " input \u00B7 256 output \u00B7 " )}{ tr ( e . config . context / 1024 )}{ tr ( "K context \u00B7 batch " )}{ tr ( e . config . batch . toLocaleString ( localeTag ()))} · { tr ( e . config . kv )}{ tr ( " cache \u00B7 " )}{ tr ( e . config . placement )} · { tr ( e . config . threads )}{ tr ( " CPU threads." )}</ p >< p >{ tr ( "Memory is a catalog approximation, not a free-memory measurement. Batch workspace and partial offload are not predicted. Reasoning and scheduling time are not estimated; these durations are not total task time." )}</ p ></ div >; 176} 177export function PerformancePreview ({ experience :e , saved, updating= false } :{ 178experience :Experience ; 179saved ?:Experience ; 180workload :Workload ; 181onWorkload :( v :Workload ) => void ; 182updating ?:boolean ; 183compact ?:boolean ; 184}) { 185const delta = e . memory && saved ?. memory ?e . memory . total - saved . memory . total :0 ; 186return < section className = "performance-preview" aria-label = { tr ( "Expected experience" )}> 187< h2 className = "h4" >{ tr ( "Expected experience" )}</ h2 > 188< SpeedPair experience = { e }/> 189{ tr ( ! e . fitsWorkload ?< p className = "inline-error small" >{ tr ( "Sample exceeds context, including 256 output tokens. Choose shorter text or increase context." )}</ p > :null )} 190< MemoryBudget experience = { e }/> 191{ tr ( updating || Math . abs ( delta ) > .005 ?< p className = "small muted" aria-live = "polite" >{ tr ( updating ?'Checking draft…' :`Draft: ${ delta > 0 ? '+' : '−' } ${ Math . abs ( delta ). toFixed ( 2 )} GB estimated` )}</ p > :null )} 192</ section >; 193} 194export function DemoTest ({ open, onClose, experience} :{ 195open :boolean ; 196onClose :() => void ; 197experience :Experience ; 198}) { 199const status = useRef < HTMLParagraphElement >( null ); 200const [ stage , setStage ] = useState ( 0 ); 201const [ running , setRunning ] = useState ( false ); 202useEffect (() => { 203if ( open ) { 204setStage ( 0 ); 205setRunning ( false ); 206} 207}, [ open ]); 208useEffect (() => { 209if ( ! open || ! running || stage >= 4 ) 210return ; 211const timer = setTimeout (() => setStage ( s => s + 1 ), 900 ); 212return () => clearTimeout ( timer ); 213}, [ open , running , stage ]); 214useEffect (() => { 215if ( open && running && ( stage === 0 || stage === 4 )) 216status . current ?. focus ({ preventScroll :true }); 217}, [ open , running , stage ]); 218const demoOnly = experience . source === 'demo' ; 219return < Dialog open = { open } title = { tr ( "Speed test preview" )} onClose = { onClose } actions = {<>< Btn onClick = {() => { setRunning ( false ); onClose (); }}>{ tr ( running && stage < 4 ?'Cancel preview' :'Close' )}</ Btn >< Btn variant = "primary" disabled = { ! experience . fitsWorkload || running && stage < 4 } onClick = {() => { setStage ( 0 ); setRunning ( true ); }}>{ tr ( stage === 4 ?'Replay preview' :'Start preview' )}</ Btn ></>}> 220< div className = "stack" >< p className = "muted" >{ tr ( "Explore the test flow. Preview values are never stored as measured performance or used as real recommendation evidence." )}</ p > 221< ol className = "test-stages" >{ tr ([ 'Warm up' , 'Read sample prompt' , 'Generate sample answer' , 'Review results' ]. map (( label , i ) => < li key = { label } data-state = { running && stage > i ?'done' :running && stage === i ?'active' :'pending' }>< span >{ tr ( running && stage > i ?< Icon name = "check" size = { 16 }/> :i + 1 )}</ span >{ tr ( label )}</ li >))}</ ol > 222< p ref = { status } tabIndex = { - 1 } role = "status" className = "small" >{ tr ( ! running ?'Ready to preview' :stage === 4 ?'Preview complete. No measurement was taken.' :tr ( 'Preview: {0}…' , [ tr ([ 'warming up' , 'reading' , 'generating' , 'preparing results' ][ stage ])]))}</ p > 223{ tr ( stage === 4 ?demoOnly ?< SpeedPair experience = { experience }/> :< p className = "small muted" >{ tr ( "The flow is ready. Speeds remain unmeasured until a local benchmark adapter is connected." )}</ p > :null )}</ div > 224</ Dialog >; 225}