okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9caf39495
main
1import { tr } from '../lib/i18n' ; 2import { useEffect , useMemo , useRef , useState , useSyncExternalStore } from 'react' ; 3import { ActionError , Btn , Dialog , ErrorNotice , Icon , Select } from '../components/ui' ; 4import { Screen } from '../components/layout' ; 5import { DemoTest } from '../components/EngineExperience' ; 6import { RunExpertEditor } from '../components/RunExpertEditor' ; 7import { RunPreview } from '../components/RunPreview' ; 8import { api } from '../lib/client' ; 9import { RunningModels } from '../components/RunningModels' ; 10import { LocalModelImport } from '../components/LocalModelImport' ; 11import { gpuId } from '../lib/monitor-hardware' ; 12import { GpuRoles } from '../components/GpuRoles' ; 13import { normalize as normalizeRoles , order as roleOrder , recommend as recommendRoles , sameRoles , type RoleCard , type Roles } from '../lib/gpu-roles' ; 14import { RunImageModel } from '../components/RunImageModel' ; 15import { IMAGE_GENERATION_VISIBLE } from '../lib/features' ; 16import { FloatingMenu } from '../components/FloatingMenu' ; 17import { ModelsScreen } from './Models' ; 18import { configDocument , configPatch , readConfig , type ConfigDocument } from '../lib/config' ; 19import { contextTokens , estimate , execution } from '../lib/experience' ; 20import { demoRunExperience , planMemory } from '../lib/run-memory' ; 21import { computerIdentity , configIdentity , defaultProfileKey , emptyProfiles , readProfiles , recommendedConfig , resourceConfig , RUN_PROFILES_KEY , saveProfile , type ComputerUse , type RunProfiles } from '../lib/run-profiles' ; 22import { modelFamilyIcon } from '../lib/model-icons' ; 23import { familyVersion , modelFamilies } from '../lib/model-versions' ; 24import { sizeGb } from '../lib/format' ; 25import { applyImageModel , getState , useLifecycle , loadRuntimeModel , loadVariant , pushToast , restartEngine , saveEngine , selectImageModel , setConfigDraft , useStore , validateEngine } from '../lib/store' ; 26import type { ImageModelChoice , RuntimeModels , RuntimeModel } from '../lib/types' ; 27import { useNative , nativeSettled , subscribeNative } from '../lib/native' ; 28import { NativeModels } from '../components/NativeModels' ; 29import { NativeLocalModel } from '../components/NativeLocalModel' ; 30import { parseLocation } from '../lib/router' ; 31type Issue = { 32level :'error' | 'warn' ; 33message :string ; 34}; 35type RunStage = 'idle' | 'checking' | 'loading' | 'ready' ; 36export function ModelRunScreen () { 37const native = useNative (); 38const settled = useSyncExternalStore ( subscribeNative , nativeSettled ); 39const location = parseLocation ( window . location . hash ), entry = location . param ; 40const [ other , setOther ] = useState ( entry === 'local' || entry === 'local-import' ), [ importFirst , setImportFirst ] = useState ( entry === 'local-import' ); 41// Before the engine's answer arrives the page would show the bundled Starter and then jump to the installed model (#3740): show a neutral placeholder instead. 42if ( ! native && ! settled ) 43return < div className = "main__body" >< div className = "wrap stack" role = "status" aria-label = { tr ( "Loading…" )}>< div className = "skel" style = {{ height :20 , width :'60%' }}/>< div className = "skel" style = {{ height :20 , width :'80%' }}/>< div className = "skel" style = {{ height :20 , width :'70%' }}/></ div ></ div >; 44if ( native && other ) 45return < NativeLocalModel onBack = {() => { setOther ( false ); setImportFirst ( false ); }}/>; 46if ( native && ! other ) 47return < NativeModels onOtherModels = {() => setOther ( true )} onImport = {() => { setImportFirst ( true ); setOther ( true ); }}/>; 48return <>< LegacyModelRunScreen importFirst = { importFirst } initialVariant = { location . query . get ( 'variant' ) ?? undefined }/>{ tr ( other ?< button className = "st-btn native-return" onClick = {() => setOther ( false )}>{ tr ( "Back" )}</ button > :null )}</>; 49} 50function LegacyModelRunScreen ({ importFirst= false , initialVariant} :{ 51importFirst ?:boolean ; 52initialVariant ?:string ; 53}) { 54const engine = useStore ( s => s . engine ), hardware = useStore ( s => s . hardware ), library = useStore ( s => s . library ); 55const runtime = useStore ( s => s . runtime ); 56const [ deviceChoice , setDeviceChoice ] = useState ( 'auto' ); 57const [ customGpus , setCustomGpus ] = useState < string []>([]); 58// Two or more cards (Expert settings): a role for each card instead of the "Run on" list. null = the recommended roles. 59const [ runRoles , setRunRoles ] = useState < Roles | null >( null ); 60const placementInitialized = useRef ( '' ); 61const imageModels = useStore ( s => s . imageModels ), imagePending = useStore ( s => !! s . busy [ 'image:select' ]); 62const imageChoice = imageModels ?. selected ?? 'off' ; 63const imageVersion = imageModels ?. variants . find ( v => v . id === imageChoice ); 64const imageNeedsDownload = imageChoice !== 'off' && imageVersion ?. state !== 'installed' ; 65const imageUnavailable = imageChoice !== 'off' && ! imageModels ?. generationAvailable ; 66const rawDraft = useStore ( s => s . configDraft ), connected = useStore ( s => s . connection === 'live' ); 67const lifecycle = useLifecycle (); 68const [ selected , setSelected ] = useState (() => { 69if ( initialVariant ) 70return initialVariant ; 71try { 72return sessionStorage . getItem ( 'strata.run-variant.v1' ) ?? '' ; 73} 74catch { 75return '' ; 76} 77}); 78const [ expert , setExpert ] = useState ( false ); 79const [ allowMultiple , setAllowMultiple ] = useState ( false ); 80const executionMode = expert && allowMultiple ?'multiple' :'single' ; 81const [ basicsOpen , setBasicsOpen ] = useState ( false ); 82const [ libraryOpen , setLibraryOpen ] = useState ( false ); 83const [ localModelOpen , setLocalModelOpen ] = useState ( importFirst ); 84const [ testOpen , setTestOpen ] = useState ( false ); 85const [ profileOpen , setProfileOpen ] = useState ( false ); 86const [ profileMenu , setProfileMenu ] = useState ( false ); 87const profileTrigger = useRef < HTMLButtonElement >( null ); 88const familySelections = useRef ( new Map < string , string >()); 89const familyDrafts = useRef ( new Map < string , { 90variantId :string ; 91draft :string | null ; 92profile :string ; 93image :ImageModelChoice ; 94}>()); 95const [ profileName , setProfileName ] = useState ( 'Everyday' ); 96const [ makeDefault , setMakeDefault ] = useState ( false ); 97const [ updateExisting , setUpdateExisting ] = useState ( false ); 98const [ activeProfile , setActiveProfile ] = useState ( 'current' ); 99const [ profiles , setProfiles ] = useState < RunProfiles >( emptyProfiles ); 100const [ profileError , setProfileError ] = useState ( '' ); 101const [ issues , setIssues ] = useState < Issue []>([]); 102const [ pending , setPending ] = useState ( false ); 103const [ placementError , setPlacementError ] = useState ( '' ); 104const [ placementPlan , setPlacementPlan ] = useState <{ 105memory :RuntimeModel [ 'memory' ]; 106budget :RuntimeModels [ 'memory' ]; 107allowed :boolean ; 108alreadyLoaded :boolean ; 109reloads :boolean ; 110} | null >( null ); 111const [ stage , setStage ] = useState < RunStage >( 'idle' ); 112const [ discardOpen , setDiscardOpen ] = useState ( false ); 113const initialized = useRef ( false ); 114const saved = useMemo (() => engine ?configDocument ( engine ) :null , [ engine ]); 115const text = rawDraft ?? ( saved ?JSON . stringify ( saved , null , 2 ) :'' ); 116const parsed = useMemo (() => { 117try { 118return { config :readConfig ( text ), error :'' }; 119} 120catch ( error ) { 121return { config :null , error :error instanceof Error ?error . message :String ( error ) }; 122} 123}, [ text ]); 124const config = parsed . config ; 125const running = library ?. variants . find ( v => v . id === library . loaded ); 126const model = library ?. variants . find ( v => v . id === selected ) ?? running ?? library ?. variants . find ( v => v . state === 'installed' ) ?? library ?. variants [ 0 ]; 127const computer = hardware ?computerIdentity ( hardware ) :'' ; 128const localProfiles = profiles . profiles . filter ( p => p . variantId === model ?. id && p . hardware === computer ); 129const selectedProfile = localProfiles . find ( p => p . id === activeProfile ); 130const personalDefault = model ?profiles . defaults [ defaultProfileKey ( computer , model . id )] :undefined ; 131const profileChanged = !! selectedProfile && !! config && ( configIdentity ( config ) !== configIdentity ( selectedProfile . config ) || imageChoice !== ( selectedProfile . imageModel ?? 'off' )); 132const use = config ?. headroom === 'full' ?'full' :'shared' ; 133const ctx = contextTokens ( config ?. beginner . contextLength ?? 'recommended' ); 134const roleCards :RoleCard [] = ( hardware ?. gpus ?? []). map (( g , i ) => ({ index :i , name :g . name , vram_gb :g . vramGb ?? 0 , integrated :!! g . unified , vendor :g . vendor })); 135const rolesMode = expert && roleCards . length > 1 ; 136const recommendedRoles = recommendRoles ( roleCards ). roles , effectiveRoles :Roles = runRoles ?normalizeRoles ( runRoles , roleCards ) :recommendedRoles ; 137const effectiveDevice = expert ?deviceChoice :'auto' ; 138const gpuIds = hardware ?( rolesMode ?roleOrder ( effectiveRoles , roleCards ). map ( i => gpuId ( hardware . gpus [ i ])) :effectiveDevice === 'auto' ?hardware . gpus . map ( gpuId ) :effectiveDevice === 'cpu' ?[] :effectiveDevice === 'custom' ?customGpus :[ effectiveDevice ]) :[]; 139const executionHardware = hardware ?{ ...hardware , gpus :hardware . gpus . filter ( g => gpuIds . includes ( gpuId ( g ))), accelerator :{ ...hardware . accelerator , backend :gpuIds . length ?hardware . accelerator . backend :'cpu' , unified :gpuIds . length ?hardware . accelerator . unified :false , usableVramGb :hardware . gpus . filter ( g => gpuIds . includes ( gpuId ( g ))). reduce (( n , g ) => n + g . vramGb , 0 ) } } :null ; 140const cfg = execution ({ ...config ?. expert , ...( ! expert ?{ 'gpu.layers' :gpuIds . length ?'Automatic' :'CPU only' } :! gpuIds . length ?{ 'gpu.layers' :'CPU only' } :{}) }, ctx ); 141const baseExperience = estimate ( model , executionHardware , cfg , 'document' , library ?. mode === 'simulated' && ! model ?. local ); 142const baseMemory = planMemory ( baseExperience , executionHardware , use , Number ( config ?. expert [ 'server.parallel' ] ?? 1 ), config ?. expert [ 'mem.mmap' ] !== false && config ?. expert [ 'mem.lock' ] !== true ); 143const memory = baseMemory && placementPlan ?{ ...baseMemory , total :placementPlan . memory . totalGb , ram :placementPlan . memory . ramGb , gpu :placementPlan . memory . gpuGb , ssd :placementPlan . memory . spillGb } :baseMemory ; 144const experience = demoRunExperience ( baseExperience , memory , use ); 145const contextMax = Math . floor (( model ?. contextMax ?? 1048576 ) / 1024 ); 146const unsupportedContext = !! model && ctx > model . contextMax ; 147const invalid = expert && deviceChoice === 'custom' && ! gpuIds . length || !! parsed . error || issues . some ( i => i . level === 'error' ) || unsupportedContext ; 148useEffect (() => { 149if ( ! hardware || ! model || ! engine || initialized . current ) 150return ; 151initialized . current = true ; 152try { 153const stored = readProfiles ( localStorage . getItem ( RUN_PROFILES_KEY )); 154setProfiles ( stored ); 155const id = stored . defaults [ defaultProfileKey ( computer , model . id )]; 156const profile = stored . profiles . find ( p => p . id === id ); 157if ( profile && ( rawDraft === null || parsed . config && configIdentity ( parsed . config ) === configIdentity ( profile . config ))) { 158setActiveProfile ( profile . id ); 159if ( rawDraft === null ) 160setConfigDraft ( JSON . stringify ( profile . config , null , 2 )); 161// Retain an image selection that has not yet been applied. 162if ( imageModels ?. selected === imageModels ?. applied && ( profile . imageModel ?? 'off' ) !== imageChoice ) 163void chooseImage ( profile . imageModel ?? 'off' ); 164} 165} 166catch ( error ) { 167setProfileError ( error instanceof Error ?error . message :'Run profiles could not be loaded.' ); 168} 169}, [ hardware , model ?. id , engine , computer , rawDraft ]); 170useEffect (() => { 171if ( model && ( ! selected || ! library ?. variants . some ( v => v . id === selected ))) 172setSelected ( model . id ); 173}, [ model ?. id , selected , library ]); 174useEffect (() => { 175if ( selected ) 176try { 177sessionStorage . setItem ( 'strata.run-variant.v1' , selected ); 178} 179catch { /* Selection remains available for this session. */ } 180}, [ selected ]); 181useEffect (() => { 182if ( ! model || ! runtime || placementInitialized . current === model . id ) 183return ; 184placementInitialized . current = model . id ; 185const existing = runtime . instances . find ( i => i . variantId === model . id ); 186const ids = existing ?. gpuIds ; 187setDeviceChoice ( runtime . mode === 'real' || ! ids ?'auto' :! ids . length ?'cpu' :ids . length === 1 ?ids [ 0 ] :'custom' ); 188setCustomGpus ( ids ?? []); 189}, [ model ?. id , runtime ?. mode ]); 190useEffect (() => { 191if ( model ) 192familySelections . current . set ( model . family , model . id ); 193}, [ model ?. id ]); 194useEffect (() => { 195if ( ! config || ! model || ! connected ) 196return ; 197let active = true ; 198const timer = setTimeout (() => void validateEngine ({ ...configPatch ( config ), variantId :model . id }). then ( result => { 199if ( active ) 200setIssues ( result . issues . filter ( i => ! i . message . startsWith ( 'Estimated working memory (' ) && ! i . message . includes ( 'is fast memory. Actual fit' ))); 201}). catch ( error => { 202if ( active ) 203setIssues ([{ level :'error' , message :error . message }]); 204}), 180 ); 205return () => { active = false ; clearTimeout ( timer ); }; 206}, [ text , model ?. id , connected ]); 207useEffect (() => { 208setPlacementPlan ( null ); 209setPlacementError ( '' ); 210if ( ! config || ! model || ! hardware || ! connected ) 211return ; 212let active = true ; 213const timer = setTimeout (() => { 214const patch = loadPatch ( config ); 215void api . post < NonNullable < typeof placementPlan >>( '/api/runtime/plan' , { variantId :model . id , gpuIds, config :patch , executionMode}). then ( plan => { 216if ( active ) 217setPlacementPlan ( plan ); 218}). catch ( error => { 219if ( active ) { 220setPlacementPlan ( null ); 221if ( library ?. mode === 'simulated' ) 222setPlacementError ( error instanceof Error ?error . message :String ( error )); 223} 224}); 225}, 180 ); 226return () => { active = false ; clearTimeout ( timer ); }; 227}, [ text , model ?. id , deviceChoice , customGpus . join ( ',' ), JSON . stringify ( runRoles ), runtime ?. revision , connected , expert , executionMode ]); 228function loadPatch ( doc :ConfigDocument ) { 229const patch = configPatch ( doc ); 230if ( ! expert || ! gpuIds . length ) 231patch . expert = patch . expert . map ( p => p . id === 'gpu.layers' ?{ ...p , value :gpuIds . length ?'Automatic' :'CPU only' } :p ); 232return patch ; 233} 234function update ( next :ConfigDocument ) { setIssues ([]); setStage ( 'idle' ); setConfigDraft ( JSON . stringify ( next , null , 2 )); } 235async function chooseImage ( choice :ImageModelChoice ) { 236setStage ( 'idle' ); 237try { 238await selectImageModel ( choice ); 239} 240catch ( error ) { 241setProfileError ( error instanceof Error ?error . message :String ( error )); 242} 243} 244function setContext ( k :number ) { 245if ( config ) 246update ({ ...config , beginner :{ ...config . beginner , contextLength :` ${ k } k` }, expert :{ ...config . expert , 'ctx.length' :` ${ k } K` } }); 247} 248function chooseProfile ( id :string ) { 249if ( ! engine || ! hardware ) 250return ; 251setActiveProfile ( id ); 252setStage ( 'idle' ); 253const profile = profiles . profiles . find ( p => p . id === id ); 254if ( profile ) { 255update ( structuredClone ( profile . config )); 256void chooseImage ( profile . imageModel ?? 'off' ); 257} 258else if ( id === 'current' ) { 259setConfigDraft ( null ); 260void chooseImage ( imageModels ?. applied ?? 'off' ); 261} 262else { 263update ( recommendedConfig ( engine , hardware , 'recommended' , id === 'maximum' ?'full' :'shared' )); 264void chooseImage ( 'off' ); 265} 266} 267function chooseModel ( id :string ) { 268if ( id === model ?. id ) 269return ; 270const next = getState (). library ?. variants . find ( v => v . id === id ); 271if ( model && next && next . family !== model . family ) { 272familyDrafts . current . set ( model . family , { variantId :model . id , draft :rawDraft , profile :activeProfile , image :imageChoice }); 273const previous = familyDrafts . current . get ( next . family ); 274if ( previous ?. variantId === id ) { 275setSelected ( id ); 276setStage ( 'idle' ); 277setIssues ([]); 278setActiveProfile ( previous . profile ); 279setConfigDraft ( previous . draft ); 280void chooseImage ( previous . image ); 281return ; 282} 283} 284setSelected ( id ); 285setStage ( 'idle' ); 286setIssues ([]); 287const profileId = profiles . defaults [ defaultProfileKey ( computer , id )]; 288if ( profileId ) 289chooseProfile ( profileId ); 290else { 291setActiveProfile ( 'current' ); 292if ( engine && hardware ) { 293const nextConfig = recommendedConfig ( engine , hardware ); 294if ( next ?. local ) { 295const k = [ 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 ]. filter ( k => k * 1024 <= next . contextMax ). at ( - 1 ) ?? 4 ; 296const context = Math . min ( 32 , k ); 297nextConfig . beginner . contextLength = ` ${ context } k` ; 298nextConfig . expert [ 'ctx.length' ] = ` ${ context } K` ; 299} 300update ( nextConfig ); 301} 302} 303} 304function chooseFamily ( family :string ) { 305if ( ! library || family === model ?. family ) 306return ; 307const version = familyVersion ( library , family , model ?. quant , familySelections . current . get ( family )); 308if ( version ) 309chooseModel ( version . id ); 310} 311function chooseComputerUse ( value :ComputerUse ) { 312if ( config && hardware ) 313update ( resourceConfig ( config , value , hardware )); 314} 315function persist ( next :RunProfiles ) { 316localStorage . setItem ( RUN_PROFILES_KEY , JSON . stringify ( next )); 317setProfiles ( next ); 318setProfileError ( '' ); 319} 320function openSave ( asNew = false ) { 321setUpdateExisting ( ! asNew && !! selectedProfile ); 322setProfileName ( ! asNew && selectedProfile ?selectedProfile . name :use === 'full' ?'Maximum performance' :'Everyday' ); 323setMakeDefault ( ! asNew && !! selectedProfile && selectedProfile . id === personalDefault ); 324setProfileOpen ( true ); 325} 326async function storeProfile () { 327if ( ! model || ! config || ! hardware || ! engine ) 328return ; 329setPending ( true ); 330try { 331const checked = await validateEngine ({ ...configPatch ( config ), variantId :model . id }); 332if ( ! checked . ok ) { 333setIssues ( checked . issues ); 334throw new Error ( 'Correct the configuration before saving a profile.' ); 335} 336const profile = { id :updateExisting && selectedProfile ?selectedProfile . id :crypto . randomUUID (), name :profileName . trim (), variantId :model . id , hardware :computer , engineVersion :engine . engine . version , config :structuredClone ( config ), imageModel :imageChoice , updatedAt :new Date (). toISOString () }; 337persist ( saveProfile ( profiles , profile , makeDefault )); 338setActiveProfile ( profile . id ); 339setProfileOpen ( false ); 340pushToast ( 'success' , 'Settings saved' , makeDefault ?'Selected automatically for this model on this computer.' :'Ready to restore from Saved settings.' ); 341} 342catch ( error ) { 343setProfileError ( error instanceof Error ?error . message :String ( error )); 344} 345finally { 346setPending ( false ); 347} 348} 349async function tune () { 350if ( ! engine || ! hardware || ! config || ! model || pending ) 351return ; 352setPending ( true ); 353setStage ( 'checking' ); 354setIssues ([]); 355try { 356const tuned = recommendedConfig ( engine , executionHardware ?? hardware , config . beginner . contextLength , use ); 357const checked = await validateEngine ({ ...configPatch ( tuned ), variantId :model . id }); 358if ( ! checked . ok ) { 359setIssues ( checked . issues ); 360throw new Error ( 'Review the highlighted settings before loading.' ); 361} 362update ( tuned ); 363setStage ( 'ready' ); 364pushToast ( 'success' , 'Model tuned' , 'Settings are ready. Load model when you’re ready.' ); 365} 366catch ( error ) { 367setStage ( 'idle' ); 368setIssues ([{ level :'error' , message :error instanceof Error ?error . message :String ( error ) }]); 369} 370finally { 371setPending ( false ); 372} 373} 374async function run () { 375if ( ! config || ! model || pending || imagePending || imageNeedsDownload || imageUnavailable ) 376return ; 377setPending ( true ); 378setStage ( 'loading' ); 379setIssues ([]); 380try { 381const patch = loadPatch ( config ); 382const checked = await validateEngine ({ ...patch , variantId :model . id }); 383if ( ! checked . ok ) { 384setIssues ( checked . issues ); 385throw new Error ( 'Review the highlighted settings before loading.' ); 386} 387if ( library ?. mode === 'simulated' ) 388await loadRuntimeModel ({ variantId :model . id , gpuIds, config :patch , executionMode}); 389else { 390if ( ! lifecycle . allowed ) 391throw new Error ( lifecycle . reason ); 392if ( expert && ( rolesMode ?!! runRoles :deviceChoice !== 'auto' )) 393throw new Error ( 'GPU assignment requires a native engine adapter. Use Automatic with this host.' ); 394await saveEngine ( patch , true , true ); 395const ok = getState (). library ?. loaded === model . id ?await restartEngine () :await loadVariant ( model . id ); 396if ( ! ok ) 397throw new Error ( getState (). actionError ?. message ?? 'The model could not be loaded.' ); 398} 399await applyImageModel (); 400setStage ( 'ready' ); 401pushToast ( 'success' , 'Model loaded' , executionMode === 'multiple' ?'Other loaded models stay available.' :'Ready for requests.' ); 402} 403catch ( error ) { 404setStage ( 'idle' ); 405setIssues ([{ level :'error' , message :error instanceof Error ?error . message :String ( error ) }]); 406} 407finally { 408setPending ( false ); 409} 410} 411if ( ! engine || ! library || ! model || ! saved ) 412return < Screen title = { tr ( "Model" )}>< p className = "small muted" >{ tr ( connected ?'Loading your models and settings…' :'Connect the engine to configure a model.' )}</ p ></ Screen >; 413const versions = library . variants . filter ( v => v . family === model . family || !! v . local ); 414const installed = [ 'loaded' , 'installed' , 'loading' , 'unloading' ]. includes ( model . state ) || !! model . installedAt ; 415const working = [ 'downloading' , 'loading' , 'unloading' ]. includes ( model . state ); 416const modelSummary = <>< Icon name = { model . local ?'model-file' :modelFamilyIcon ( model . family )} size = { 21 }/>< span >< strong >{ tr ( model . local ?model . name :model . family )}</ strong >< small >{ tr ( model . local ?model . quant :model . name )} · { tr ( ctx / 1024 )}{ tr ( "K \u00B7 " )}{ tr ( use === 'full' ?'Maximum performance' :'Room for other apps' )}{ tr ( imageChoice !== 'off' ?` · Image ${ imageChoice . toUpperCase ()} ` :'' )}</ small ></ span ></>; 417return < Screen plainHeader title = { tr ( "Model" )} titleDetail = {< span className = "run-family-switcher" >< Select ariaLabel = { tr ( "Model family" )} value = { model . family } disabled = { pending || imagePending } menuWidth = { 340 } menuClassName = "model-family-menu" optionIcon = { modelFamilyIcon } options = { modelFamilies ( library ). map ( family => ({ value :family , label :family }))} onChange = { chooseFamily }/></ span >} actions = {<>{ tr ( expert ?<>< Btn size = "sm" disabled = { ! config || invalid || pending } onClick = {() => setTestOpen ( true )}>< span className = "run-header-full" >{ tr ( "Benchmark" )}</ span >< span className = "run-header-short" >{ tr ( "Benchmark" )}</ span ></ Btn >< Btn size = "sm" disabled = { ! hardware || pending } onClick = {() => { 418if ( hardware ) { 419setActiveProfile ( 'recommended' ); 420update ( recommendedConfig ( engine , hardware )); 421void chooseImage ( 'off' ); 422} 423}}>< span className = "run-header-full" >{ tr ( "Reset to recommended" )}</ span >< span className = "run-header-short" >{ tr ( "Reset defaults" )}</ span ></ Btn ></> :null )}< button className = "st-btn st-btn--secondary" aria-pressed = { expert } disabled = { pending } onClick = {() => setExpert ( ! expert )}>< Icon name = "sliders" size = { 16 }/>{ tr ( expert ?<>< span className = "run-header-full" >{ tr ( "Close expert mode" )}</ span >< span className = "run-header-short" >{ tr ( "Easy mode" )}</ span ></> :'Expert mode' )}</ button ></>}> 424< div className = "model-run" > 425< ActionError /> 426< div className = "run-toolbar" > 427{ tr ( expert ?< button className = "run-basics-summary run-toolbar-summary" aria-expanded = { basicsOpen } aria-controls = "run-basic-settings" onClick = {() => setBasicsOpen ( ! basicsOpen )}>{ tr ( modelSummary )}< Icon name = "chevron" size = { 15 }/></ button > :< div className = "run-basics-summary run-toolbar-summary run-model-summary" >{ tr ( modelSummary )}</ div >)} 428< button ref = { profileTrigger } className = "st-btn st-btn--secondary run-saved-settings" aria-label = { tr ( "Saved settings{0}{1}" , [ selectedProfile ?`: ${ selectedProfile . name } ` :tr ( '' ), profileChanged ?tr ( ' — unsaved changes' ) :tr ( '' )])} aria-haspopup = "menu" aria-expanded = { profileMenu } disabled = { pending } onClick = {() => setProfileMenu ( ! profileMenu )}>< Icon name = "layers" size = { 17 }/>< span >{ tr ( selectedProfile ?. name ?? 'Saved settings' )}</ span >{ tr ( profileChanged ?< i title = { tr ( "Unsaved changes" )}/> :null )}< Icon name = "chevron" size = { 14 }/></ button > 429< Btn icon = "models" size = "sm" onClick = {() => setLibraryOpen ( true )}>{ tr ( "Manage models" )}</ Btn > 430</ div > 431{ tr ( expert ?< RunningModels controls /> :null )} 432{ tr ( profileError && ! profileOpen ?< ErrorNotice message = { profileError }/> :null )} 433< div className = "run-layout" > 434< div className = "run-setup" data-expert = { expert || undefined }> 435< div className = "run-basics" id = "run-basic-settings" hidden = { expert && ! basicsOpen }> 436< section className = "run-card run-model-choice" > 437< div className = "run-version-choice" >< span >{ tr ( "Version" )}</ span >< Select ariaLabel = { tr ( "Model version" )} value = { model . id } disabled = { pending } menuClassName = "run-version-menu" options = {[ ...versions . map ( v => ({ value :v . id , label :` ${ v . name } · ${ v . quant } · ${ sizeGb ( v . diskGb )} ${ v . local ? ' · Local' : '' } ` })), { value :'use-local-model' , label :'Use a local model…' }]} onChange = { id => id === 'use-local-model' ?setLocalModelOpen ( true ) :chooseModel ( id )}/></ div > 438{ tr ( model . local ?< div className = "run-local-model-note" >< Icon name = "model-file" size = { 15 }/>< span >{ tr ( "Local model \u00B7 " )}{ tr ( model . local . architecture )}{ tr ( " \u00B7 Compatibility checked on load." )}</ span >< button className = "text-btn" onClick = {() => setLocalModelOpen ( true )}>{ tr ( "Change file" )}</ button ></ div > :null )} 439{ IMAGE_GENERATION_VISIBLE ?< RunImageModel library = { imageModels } disabled = { pending || imagePending || ! connected } onChange = {() => setStage ( 'idle' )}/> :null } 440</ section > 441< section className = "run-card run-context" >< div className = "run-card__head" >< span >< Icon name = "chat" size = { 19 }/>< h2 >{ tr ( "Conversation context" )}</ h2 ></ span >< strong >{ tr ( ctx / 1024 )}{ tr ( "K " )}< small >{ tr ( "tokens" )}</ small ></ strong ></ div >< p >{ tr ( "How much your model can keep in mind." )}</ p > 442< div className = "run-context-presets" role = "group" aria-label = { tr ( "Context presets" )}>{ tr ([ 32 , 64 , 128 , 256 ]. map ( k => < button key = { k } disabled = { k > contextMax } aria-pressed = { ctx === k * 1024 } onClick = {() => setContext ( k )}>< span >{ tr ( k )}{ tr ( "K" )}</ span ></ button >))}</ div > 443< div className = "run-context-bottom" >< label className = "run-context-exact" >{ tr ( "Custom " )}< input className = "st-input" aria-label = { tr ( "Custom context in K tokens" )} type = "number" min = "4" max = { contextMax } step = "1" value = { Number . isFinite ( ctx ) ?ctx / 1024 :'' } onChange = { e => { 444if ( e . target . value ) 445setContext ( Number ( e . target . value )); 446}}/>< span >{ tr ( "K" )}</ span ></ label ></ div > 447{ tr ( unsupportedContext ?< p className = "inline-error xs" >{ tr ( "This model supports up to " )}{ tr ( contextMax )}{ tr ( "K. Choose a supported context to run it." )}</ p > :null )} 448</ section > 449< section className = "run-card run-resources" >< div className = "run-card__head" >< span >< Icon name = "computer" size = { 19 }/>< h2 >{ tr ( "Computer use" )}</ h2 ></ span ></ div > 450< div className = "run-resource-options" >{ tr ([{ id :'shared' as const , icon :'computer' as const , title :'Leave room for other apps' , hint :'Work alongside your model' }, { id :'full' as const , icon :'bolt' as const , title :'Maximum performance' , hint :'Give your model more resources' }]. map ( option => < button key = { option . id } aria-pressed = { use === option . id } disabled = { ! hardware } onClick = {() => chooseComputerUse ( option . id )}>< span >< Icon name = { option . icon } size = { 20 }/>< i >{ tr ( use === option . id ?< Icon name = "check" size = { 12 }/> :null )}</ i ></ span >< strong >{ tr ( option . title )}</ strong >< small >{ tr ( option . hint )}</ small ></ button >))}</ div > 451< p className = "run-resources__hint" >< Icon name = "cpu" size = { 14 }/>{ tr ( cfg . threads )}{ tr ( " CPU threads" )}{ tr ( memory ?` · ${ memory . reserve . toFixed ( 0 )} GB RAM headroom in the estimate` :'' )}</ p > 452</ section > 453</ div > 454{ tr ( expert ?< section className = "run-card run-placement" > 455< div className = "run-card__head" >< span >< Icon name = "gpu" size = { 19 }/>< h2 >{ tr ( "Model execution" )}</ h2 ></ span ></ div > 456< label className = "run-multiple-choice" >< span >< strong >{ tr ( "Run multiple models" )}</ strong >< small >{ tr ( "Keep models loaded when you add another." )}</ small ></ span >< input type = "checkbox" role = "switch" aria-label = { tr ( "Run multiple models" )} checked = { allowMultiple } disabled = { pending || runtime ?. capabilities . multipleModels === false } onChange = { e => { setAllowMultiple ( e . target . checked ); setIssues ([]); setStage ( 'idle' ); }}/></ label > 457{ rolesMode ?< GpuRoles cards = { roleCards } roles = { effectiveRoles } custom = { !! runRoles && ! sameRoles ( effectiveRoles , recommendedRoles )} disabled = { pending || runtime ?. capabilities . deviceAssignment === false } onChange = { next => { setRunRoles ( sameRoles ( next , recommendedRoles ) ?null :next ); setStage ( 'idle' ); setIssues ([]); }} onBack = {() => { setRunRoles ( null ); setStage ( 'idle' ); setIssues ([]); }}/> :<> 458< span className = "run-device-label" >{ tr ( "Run on" )}</ span > 459< Select ariaLabel = { tr ( "Execution device" )} value = { deviceChoice } disabled = { pending || runtime ?. capabilities . deviceAssignment === false } options = {[{ value :'auto' , label :hardware ?. gpus . length ?hardware . gpus . length > 1 ?'Automatic · all GPUs' :'Automatic · GPU 1' :'CPU only' }, { value :'cpu' , label :'CPU only' }, ...( hardware ?. gpus ?? []). map (( g , i ) => ({ value :gpuId ( g ), label :`GPU ${ i + 1 } · ${ g . name } ` })), ...(( hardware ?. gpus . length ?? 0 ) > 1 ?[{ value :'custom' , label :'Choose GPUs…' }] :[])]} onChange = { id => { setDeviceChoice ( id ); setStage ( 'idle' ); setIssues ([]); }}/> 460{ tr ( deviceChoice === 'custom' ?< div className = "run-gpu-options" >{ tr ( hardware ?. gpus . map (( g , i ) => < label key = { gpuId ( g )}>< input type = "checkbox" checked = { customGpus . includes ( gpuId ( g ))} onChange = { e => { setCustomGpus ( ids => e . target . checked ?[ ...ids , gpuId ( g )] :ids . filter ( id => id !== gpuId ( g ))); setStage ( 'idle' ); }}/>< span >{ tr ( "GPU " )}{ tr ( i + 1 )} · { tr ( g . name )}< small >{ tr ( g . unified ?'Shared system memory' :` ${ sizeGb ( g . vramGb )} VRAM` )}</ small ></ span ></ label >))}</ div > :null )} 461</>} 462< p className = "xs muted" >{ tr ( runtime ?. capabilities . multipleModels === false ?'This native host currently supports one model with automatic GPU placement.' :! allowMultiple ?'One model at a time. Loading switches to the selected model.' :placementPlan ?. reloads ?'Loading applies these settings to this instance. Other models stay loaded.' :'Loading adds a model. Existing models keep their settings and GPU assignments.' )}</ p > 463{ tr ( runtime ?. instances . length ?< div className = "run-memory-reservations" >< span >{ tr ( placementPlan && ! placementPlan . alreadyLoaded ?'Shared RAM after load' :'Shared RAM reserved' )} < strong >{ tr (( placementPlan ?. budget . ramGb ?? runtime . memory . ramGb ). toFixed ( 1 ))} / { tr (( placementPlan ?. budget . budgetGb ?? runtime . memory . budgetGb ). toFixed ( 1 ))}{ tr ( " GB" )}</ strong ></ span >< small >{ tr ( runtime . memory . reserveGb . toFixed ( 0 ))}{ tr ( " GB RAM headroom \u00B7 estimates include all loaded models" )}</ small >{ tr (( placementPlan ?. budget . devices ?? runtime . memory . devices ). map ( d => < span key = { d . id }>{ tr ( d . name )}< strong >{ tr ( d . usedGb . toFixed ( 1 ))} / { tr ( d . budgetGb . toFixed ( 1 ))}{ tr ( " GB" )}</ strong ></ span >))}</ div > :null )} 464</ section > :null )} 465{ tr ( expert ?< RunExpertEditor engine = { engine } config = { config } text = { text } onChange = { update } onText = { value => { setStage ( 'idle' ); setConfigDraft ( value ); }} onRestore = {() => setDiscardOpen ( true )} onError = { message => setIssues ([{ level :'error' , message}])}/> :null )} 466{ tr ( parsed . error ?< ErrorNotice message = { parsed . error }/> :null )} 467{ tr ( issues . length ?< div className = "run-issues" role = "status" >{ tr ( issues . map (( issue , i ) => < p key = { i } data-tone = { issue . level }>< Icon name = { issue . level === 'error' ?'error' :'info' } size = { 16 }/>{ tr ( issue . message )}</ p >))}</ div > :null )} 468{ tr (( executionMode === 'single' || library . mode === 'real' ) && ! lifecycle . allowed ?< p className = "small muted" >{ tr ( lifecycle . reason )}</ p > :null )} 469{ tr ( placementError ?< p className = "small inline-error" role = "status" >{ tr ( placementError )}</ p > :null )} 470{ tr ( placementPlan && ! placementPlan . allowed ?< p className = "small inline-error" role = "status" >{ tr ( executionMode === 'multiple' ?'Other loaded models have reserved this memory. Choose another GPU, reduce context, or unload a model.' :'Reduce context or choose a smaller version to fit this model.' )}</ p > :null )} 471< section className = "run-actions" aria-label = { tr ( "Run model" )}> 472< Btn icon = "sliders" disabled = { invalid || pending || ! connected } onClick = {() => void tune ()}>{ tr ( pending && stage === 'checking' ?'Tuning…' :'Tune model' )}</ Btn > 473< Btn variant = "primary" icon = "models" disabled = { ! installed || invalid || !! placementError || placementPlan ?. allowed === false || pending || imagePending || imageNeedsDownload || imageUnavailable || ! connected || (( executionMode === 'single' || library . mode === 'real' ) && ! lifecycle . allowed ) || working } onClick = {() => void run ()}>{ tr ( pending && stage === 'loading' ?'Loading…' :'Load model' )}</ Btn > 474</ section > 475{ tr ( imageUnavailable ?< p className = "small muted" >{ tr ( "This engine cannot run image models yet. Choose Off to run the chat model." )}</ p > :null )} 476{ tr ( ! installed ?< Btn icon = { model . local ?'folder' :'download' } onClick = {() => model . local ?setLocalModelOpen ( true ) :setLibraryOpen ( true )}>{ tr ( model . local ?'Reconnect local file' :'Download model version' )}</ Btn > :null )} 477</ div > 478< RunPreview experience = { experience } memory = { memory } hardware = { hardware } imageEnabled = { imageChoice !== 'off' }/> 479</ div > 480</ div > 481{ tr ( profileMenu ?< FloatingMenu anchor = { profileTrigger . current } title = { tr ( "Saved settings" )} width = { 320 } onClose = {() => setProfileMenu ( false )}> 482< div className = "run-settings-menu-label" >{ tr ( "Saved settings" )}</ div > 483< button role = "menuitemradio" aria-checked = { ! selectedProfile } className = "menu__item run-settings-option" onClick = {() => { chooseProfile ( 'current' ); setProfileMenu ( false ); }}>< span className = "run-settings-icon" >< Icon name = "sliders" size = { 18 }/></ span >< span >{ tr ( "Current settings" )}</ span >{ tr ( ! selectedProfile ?< Icon name = "check" size = { 15 } className = "run-settings-selected" /> :null )}</ button > 484{ tr ( localProfiles . map ( profile => < button key = { profile . id } role = "menuitemradio" aria-checked = { profile . id === activeProfile } className = "menu__item run-settings-option" onClick = {() => { chooseProfile ( profile . id ); setProfileMenu ( false ); }}>< span className = "run-settings-icon" >< Icon name = "layers" size = { 18 }/></ span >< span >{ profile . name }{ tr ( profile . id === personalDefault ?< small >{ tr ( "Default for this model" )}</ small > :null )}{ tr ( profile . engineVersion !== engine . engine . version ?< small >{ tr ( "Engine changed \u00B7 tune again before running" )}</ small > :null )}</ span >{ tr ( profile . id === activeProfile ?< Icon name = "check" size = { 15 } className = "run-settings-selected" /> :null )}</ button >))} 485< div className = "run-settings-menu-divider" role = "separator" /> 486{ tr ( selectedProfile ?< button role = "menuitem" className = "menu__item run-settings-action" disabled = { ! config } onClick = {() => { setProfileMenu ( false ); openSave (); }}>< span className = "run-settings-icon" >< Icon name = "pencil" size = { 18 }/></ span >{ tr ( "Edit saved settings\u2026" )}</ button > :null )} 487< button role = "menuitem" className = "menu__item run-settings-action" disabled = { ! config } onClick = {() => { setProfileMenu ( false ); openSave ( true ); }}>< span className = "run-settings-icon" >< Icon name = { selectedProfile ?'copy' :'plus' } size = { 18 }/></ span >{ tr ( selectedProfile ?'Save as new…' :'Save current settings…' )}</ button > 488{ tr ( selectedProfile && profileChanged ?< button role = "menuitem" className = "menu__item run-settings-action" onClick = {() => { setProfileMenu ( false ); chooseProfile ( selectedProfile . id ); }}>< span className = "run-settings-icon" >< Icon name = "refresh" size = { 18 }/></ span >{ tr ( "Restore saved settings" )}</ button > :null )} 489</ FloatingMenu > :null )} 490< Dialog open = { libraryOpen } className = "run-library-dialog" title = { tr ( "Manage models" )} onClose = {() => setLibraryOpen ( false )}>< ModelsScreen embedded familyOverride = { model . family } selectedVariant = { model . id } contextOverride = { ctx } onChoose = { id => { chooseModel ( id ); setLibraryOpen ( false ); }}/></ Dialog > 491< LocalModelImport open = { localModelOpen } directory = { library . disk . modelsDir } onClose = {() => setLocalModelOpen ( false )} onChoose = { id => chooseModel ( id )}/> 492< Dialog open = { profileOpen } compact title = { tr ( updateExisting ?'Update saved settings' :'Save settings' )} onClose = {() => ! pending && setProfileOpen ( false )} actions = {<>< Btn disabled = { pending } onClick = {() => setProfileOpen ( false )}>{ tr ( "Cancel" )}</ Btn >< Btn variant = "primary" disabled = { ! profileName . trim () || pending || imagePending || invalid } onClick = {() => void storeProfile ()}>{ tr ( pending ?'Saving…' :updateExisting ?'Update settings' :'Save settings' )}</ Btn ></>}>< div className = "run-save-profile" >< label className = "input-field" >< span >{ tr ( "Name" )}</ span >< input className = "st-input" aria-label = { tr ( "Settings name" )} maxLength = { 64 } value = { profileName } onChange = { e => setProfileName ( e . target . value )}/></ label >< p className = "small muted" >{ tr ( model . name )} · { tr ( ctx / 1024 )}{ tr ( "K \u00B7 " )}{ tr ( use === 'full' ?'Maximum performance' :'Room for other apps' )}</ p >< label className = "run-default-choice" >< input type = "checkbox" checked = { makeDefault } onChange = { e => setMakeDefault ( e . target . checked )}/>< span >{ tr ( "Use by default for this model" )}< small >{ tr ( "On this computer. Restore it whenever you open Models." )}</ small ></ span ></ label >{ tr ( profileError ?< ErrorNotice message = { profileError }/> :null )}</ div ></ Dialog > 493< DemoTest open = { testOpen } onClose = {() => setTestOpen ( false )} experience = { experience }/> 494< Dialog open = { discardOpen } compact title = { tr ( "Restore saved settings?" )} onClose = {() => setDiscardOpen ( false )} actions = {<>< Btn onClick = {() => setDiscardOpen ( false )}>{ tr ( "Keep editing" )}</ Btn >< Btn onClick = {() => { setConfigDraft ( null ); void chooseImage ( imageModels ?. applied ?? 'off' ); setActiveProfile ( 'current' ); setIssues ([]); setDiscardOpen ( false ); }}>{ tr ( "Restore settings" )}</ Btn ></>}>< p >{ tr ( "Replace this draft with the settings last saved to the engine." )}</ p ></ Dialog > 495</ Screen >; 496}