okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d8124515a
main
1// serve/web/app.js - the Strata web app: Chat, Monitor, About. No framework, no network beyond this server. 2// The Monitor tab rebuilds PR #22's dashboard idea (code-martin) on the server's own /metrics. 3"use strict" ; 4 5const $ = ( id ) => document . getElementById ( id ); 6const SPRITE = "web/sprite.svg" ; 7const icon = ( name , cls = "st-icon" ) => `<svg class=" ${ cls } " aria-hidden="true"><use href=" ${ SPRITE } #i- ${ name } "/></svg>` ; 8const esc = ( s ) => String ( s ). replace ( / [ &<>"' ] / g , ( c ) => ({ "&" :"&" , "<" :"<" , ">" :">" , '"' :""" , "'" :"'" }[ c ])); 9const fmt = ( n , d = 0 ) => ( n == null || Number . isNaN ( n ) ?"–" :Number ( n ). toLocaleString ( undefined , { maximumFractionDigits :d , minimumFractionDigits :d })); 10const kfmt = ( n ) => ( n == null ?"–" :n >= 1000 ?` ${ fmt ( n / 1000 , n >= 10000 ? 0 : 1 )} k` :fmt ( n )); 11// a context size: 32768 -> "32K" (powers of two), else like kfmt 12const ctxfmt = ( n ) => ( n && n % 1024 === 0 ?` ${ fmt ( n / 1024 )} K` :kfmt ( n )); 13const gb = ( b , d = 1 ) => ( b == null ?"–" :fmt ( b / 1073741824 , d )); // memory: binary GB, as Windows shows it 14 15const store = { 16get ( k , d ) { try { const v = localStorage . getItem ( "strata." + k ); return v === null ?d :JSON . parse ( v ); } catch ( e ) { return d ; } }, 17set ( k , v ) { try { localStorage . setItem ( "strata." + k , JSON . stringify ( v )); return true ; } catch ( e ) { return false ; } }, 18}; 19 20// ------------------------------------------------------------------ toasts 21function toast ( kind , title , text = "" , ms = 3500 , action = null ) { 22const names = { info :"info" , success :"check" , warn :"warning" , error :"error" }; 23const el = document . createElement ( "div" ); 24el . className = `st-toast st-toast-- ${ kind } ` ; 25el . innerHTML = ` ${ icon ( names [ kind ] || "info" )} <div><div class="st-toast__title"></div><div class="t-text"></div></div>` ; 26el . querySelector ( ".st-toast__title" ). textContent = title ; 27el . querySelector ( ".t-text" ). textContent = text ; 28if ( action ) { 29const b = document . createElement ( "button" ); 30b . className = "st-btn st-btn--secondary" ; 31b . style . height = "32px" ; 32b . style . marginLeft = "auto" ; 33b . textContent = action . label ; 34b . onclick = () => { action . run (); el . remove (); }; 35el . appendChild ( b ); 36} 37$ ( "toasts" ). appendChild ( el ); 38setTimeout (() => el . remove (), ms ); 39} 40 41async function copyText ( text , btn ) { 42try { 43await navigator . clipboard . writeText ( text ); 44} catch ( e ) { // http on another host: no async clipboard 45const ta = document . createElement ( "textarea" ); 46ta . value = text ; document . body . appendChild ( ta ); ta . select (); document . execCommand ( "copy" ); ta . remove (); 47} 48if ( btn ) { 49const use = btn . querySelector ( "use" ); 50use . setAttribute ( "href" , ` ${ SPRITE } #i-check` ); 51setTimeout (() => use . setAttribute ( "href" , ` ${ SPRITE } #i-copy` ), 1500 ); 52} 53toast ( "success" , tr ( "toast.copied" , "Copied to clipboard" ), "" , 1800 ); 54} 55 56// ------------------------------------------------------------------ theme and tabs 57// the system's theme until the user picks one (only a click is saved) 58function setTheme ( t , save ) { 59document . documentElement . dataset . theme = t ; 60if ( save ) try { localStorage . setItem ( "strata.theme" , t ); } catch ( e ) { /* ignore */ } 61$ ( "theme-icon" ). setAttribute ( "href" , ` ${ SPRITE } #i- ${ t === "dark" ? "sun" : "moon" } ` ); 62$ ( "dark-toggle" ). setAttribute ( "aria-checked" , String ( t === "dark" )); 63refreshPreviews (); // the preview frames carry the page's colours 64} 65const flipTheme = () => setTheme ( document . documentElement . dataset . theme === "dark" ?"light" :"dark" , true ); 66$ ( "theme-btn" ). onclick = flipTheme ; 67$ ( "dark-toggle" ). onclick = flipTheme ; 68setTheme ( document . documentElement . dataset . theme || "light" , false ); 69matchMedia ( "(prefers-color-scheme: dark)" ). addEventListener ( "change" , ( e ) => { 70let saved = null ; 71try { saved = localStorage . getItem ( "strata.theme" ); } catch ( err ) { /* ignore */ } 72if ( ! saved ) setTheme ( e . matches ?"dark" :"light" , false ); 73}); 74 75let tab = "chat" ; 76function showTab ( name ) { 77tab = [ "chat" , "images" , "monitor" , "about" ]. includes ( name ) ?name :"chat" ; 78for ( const b of document . querySelectorAll ( ".st-tab" )) b . setAttribute ( "aria-selected" , String ( b . dataset . tab === tab )); 79for ( const v of [ "chat" , "images" , "monitor" , "about" ]) $ ( `view- ${ v } ` ). hidden = v !== tab ; 80if ( tab === "images" ) $ ( "img-prompt" ). focus (); 81if ( location . hash . slice ( 1 ) !== tab ) history . replaceState ( null , "" , tab === "chat" ?location . pathname :`# ${ tab } ` ); 82if ( tab === "chat" ) $ ( "input" ). focus (); 83if ( tab === "monitor" ) loadMcp (); 84if ( tab === "about" ) loadConfig (); 85if ( lastMetrics ) render ( lastMetrics ); 86} 87for ( const b of document . querySelectorAll ( ".st-tab" )) b . onclick = () => showTab ( b . dataset . tab ); 88window . addEventListener ( "hashchange" , () => showTab ( location . hash . slice ( 1 ))); 89 90// ------------------------------------------------------------------ server access 91let apiKey = store . get ( "apikey" , "" ); 92function headers ( json = false ) { 93const h = {}; 94if ( apiKey ) h . Authorization = "Bearer " + apiKey ; 95if ( json ) h [ "Content-Type" ] = "application/json" ; 96return h ; 97} 98$ ( "api-key" ). value = apiKey ; 99function saveApiKey ( notify = false ) { 100apiKey = $ ( "api-key" ). value . trim (); // usable even when browser storage is blocked or full 101const saved = store . set ( "apikey" , apiKey ); 102if ( notify ) { 103if ( saved ) toast ( "success" , "API key saved" , "Kept in this browser only." ); 104else toast ( "warn" , "API key used for this page only" , "Browser storage is unavailable. Enter it again after reloading." ); 105} 106} 107$ ( "api-key" ). oninput = () => saveApiKey (); 108$ ( "api-key" ). onchange = () => saveApiKey ( true ); 109 110let health = { model :"strata" , images :false , max_context :0 }; 111// the texts that depend on what this server offers: the empty chat's line and the attach button's hint 112function renderEmptyChat () { 113$ ( "attach-btn" ). title = health . images ?tr ( "composer.attachPictures" , "Attach a text file or a picture (or drop it here)" ) 114 :tr ( "composer.attach" , "Attach a text file (or drop it here)" ); 115$ ( "chat-empty-sub" ). textContent = tr ( "chat.emptyModel" , "{model} runs on this PC. Nothing leaves it." , { model :health . model }); 116} 117async function loadHealth () { 118try { 119health = await ( await fetch ( "health" )). json (); 120renderEmptyChat (); 121$ ( "tab-btn-images" ). hidden = ! health . image_generation ; 122if ( location . hash === "#images" && health . image_generation ) showTab ( "images" ); 123} catch ( e ) { 124setTimeout ( loadHealth , 2000 ); 125} 126} 127 128// ------------------------------------------------------------------ Monitor 129const METRICS = [ 130{ key :"speed" , label :"Speed" , icon :"gauge" , unit :"t/s" , series :"tok_s" }, 131{ key :"gpu" , label :"GPU load" , icon :"gpu" , unit :"%" , series :"gpu_util" , max :100 }, 132{ key :"vram" , label :"VRAM" , icon :"layers" , unit :"GB" , series :"gpu_mem_used" }, 133{ key :"temp" , label :"GPU temp" , icon :"thermometer" , unit :"°C" , series :"gpu_temp" , tone :"warn" }, 134{ key :"power" , label :"Power" , icon :"bolt" , unit :"W" , series :"gpu_power" }, 135{ key :"pcie" , label :"PCIe" , icon :"link" , unit :"" , series :"gpu_pcie_rx_mb" , tone :"info" }, 136{ key :"cpu" , label :"CPU" , icon :"cpu" , unit :"%" , series :"cpu" , max :100 }, 137{ key :"disk" , label :"Disk read" , icon :"disk" , unit :"MB/s" , series :"disk_read_mb" , tone :"info" }, 138]; 139$ ( "metrics" ). innerHTML = METRICS . map (( m ) => ` 140<div class="st-card metric-card"><div class="st-metric"> 141<span class="st-metric__label"> ${ icon ( m . icon , "st-icon st-icon--sm" )} ${ esc ( m . label )} </span> 142${ m . key === "speed" ? `<div class="speed-values"> 143<div><span class="st-metric__value" id="mv-speed">-</span><span class="st-metric__sub" id="ms-speed">Decode</span></div> 144<div class="speed-prefill"><span class="st-metric__value" id="mv-prefill">-</span><span class="st-metric__sub" id="ms-prefill">Prefill</span></div> 145</div>` : `<span class="st-metric__value" id="mv- ${ m . key } ">–</span> 146<span class="st-metric__sub" id="ms- ${ m . key } "></span>` } 147<svg class="st-metric__spark" id="sp- ${ m . key } " viewBox="0 0 100 32" preserveAspectRatio="none" ${ m . tone ? ` data-tone=" ${ m . tone } "` : "" } > 148<path class="area" fill="currentColor" opacity=".12"/><path class="line" fill="none" stroke="currentColor" 149stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/> 150${ m . key === "speed" ? `<g id="sp-prefill" class="speed-prefill"><path class="area" fill="currentColor" opacity=".12"/> 151<path class="line" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" 152stroke-linecap="round" vector-effect="non-scaling-stroke"/></g>` : "" } </svg> 153</div></div>` ). join ( "" ); 154 155function spark ( id , values , max ) { 156const svg = $ ( id ); 157const v = ( values || []). map (( x ) => ( x == null ?0 :x )); 158if ( v . length < 2 ) { svg . querySelector ( ".line" ). setAttribute ( "d" , "" ); svg . querySelector ( ".area" ). setAttribute ( "d" , "" ); return ; } 159const top = Math . max ( max || 0 , ...v , 1 ); 160const pts = v . map (( x , i ) => [( i / ( v . length - 1 )) * 100 , 30 - ( x / top ) * 26 ]); 161const line = pts . map (( p , i ) => ` ${ i ? "L" : "M" } ${ p [ 0 ]. toFixed ( 2 )} , ${ p [ 1 ]. toFixed ( 2 )} ` ). join ( "" ); 162svg . querySelector ( ".line" ). setAttribute ( "d" , line ); 163svg . querySelector ( ".area" ). setAttribute ( "d" , ` ${ line } L100,32L0,32Z` ); 164} 165function setMetric ( key , value , unit , sub ) { 166$ ( `mv- ${ key } ` ). innerHTML = value == null ?"–" :` ${ esc ( value )} ${ unit ? `<small> ${ esc ( unit )} </small>` : "" } ` ; 167$ ( `ms- ${ key } ` ). textContent = sub || "" ; 168} 169 170let lastMetrics = null , metricsFailures = 0 , keyWarned = false , mcpTick = 0 ; 171let metricsEpoch = 0 ; 172// After Load or Unload returns, a poll that started earlier can still say the opposite. Hold the POST's state until a later 173// poll agrees, or until the first poll that started after the POST arrives. (PR #3550 by sakuumomo) 174let metricsHold = null ; 175let reqShowAll = false ; // the Monitor's request table: the last 12, or every one the server keeps (issue #35) 176function metricsAgree ( live , state ) { 177const s = ( live && live . state ) || "" ; 178if ( state === "unloaded" ) return s === "unloaded" ; 179return s !== "" && s !== "unloaded" ; 180} 181async function poll () { 182const epoch = ++ metricsEpoch ; 183try { 184const r = await fetch ( reqShowAll ?"metrics?requests=all" :"metrics" , { headers :headers ()}); 185if ( r . status === 401 ) { 186setPill ( "error" , tr ( "pill.keyNeeded" , "API key needed" )); 187if ( ! keyWarned ) { keyWarned = true ; toast ( "warn" , tr ( "pill.keyNeeded" , "API key needed" ), tr ( "toast.keyAbout" , "This server needs a key: add it under About > Settings." ), 6000 ); } 188} else if ( r . ok ) { 189const m = await r . json (); 190if ( metricsHold && epoch <= metricsHold . after && ! metricsAgree ( m . live , metricsHold . state )) { 191setTimeout ( poll , 1000 ); 192return ; 193} 194if ( metricsHold && ( metricsAgree ( m . live , metricsHold . state ) || epoch > metricsHold . after )) metricsHold = null ; 195lastMetrics = m ; 196metricsFailures = 0 ; 197render ( lastMetrics ); 198} else { 199throw new Error ( `HTTP ${ r . status } ` ); 200} 201} catch ( e ) { 202if ( ++ metricsFailures === 3 ) setPill ( "error" , tr ( "pill.unreachable" , "Server not reachable" )); 203} 204if ( tab === "monitor" && ++ mcpTick % 10 === 0 ) loadMcp (); // server states change rarely: every 10 s 205setTimeout ( poll , 1000 ); 206} 207 208function setPill ( state , text ) { 209$ ( "pill" ). dataset . state = state === "error" ?"queued" :state ; 210$ ( "pill-text" ). textContent = text ; 211// a poll re-sets the sentence every second; refit only when its text changed 212if ( text !== lastPillText ) { lastPillText = text ; fitHeader (); } 213} 214let lastPillText = null ; 215// The pill's sentence is the first thing the header row can spare when it runs out of room. 216function fitHeader () { 217const header = document . querySelector ( ".st-header" ); 218if ( ! header ) return ; 219header . classList . remove ( "st-header--clip" ); 220if ( header . scrollWidth > header . clientWidth ) header . classList . add ( "st-header--clip" ); 221} 222window . addEventListener ( "resize" , fitHeader ); 223 224// ------------------------------------------------------------------ Load / Unload (POST /load, /unload: the header button) 225// Metrics stay "unloaded" until the engine is READY, so a turn or an image job on this page has to paint Loading itself. 226// modelOp covers the button's own POST, which returns before the next poll can agree. 227let modelOp = null ; 228let imageBusy = false ; 229function pageBusy () { return busy != null || imageBusy ; } 230// "generating an image" is the job a refresh can see. imageBusy is this page's POST before that phase is published. A chat 231// phase already on the metrics wins, because Stop still stops that reply. 232function imageLive ( live ) { 233if ( live && live . phase === "generating an image" ) return true ; 234const state = live && live . state ; 235if ( state === "reading" || state === "generating" ) return false ; 236return imageBusy ; 237} 238function paintLive () { if ( lastMetrics ) render ( lastMetrics ); } 239function turnBlocksUnload ( live ) { 240const state = ( live && live . state ) || "" ; 241return pageBusy () || state === "reading" || state === "generating" || ( live && live . queued > 0 ); 242} 243function setModelButton ( text , title , disabled ) { 244const btn = $ ( "unload-btn" ); 245btn . textContent = text ; btn . title = title ; btn . disabled = disabled ; 246fitHeader (); 247} 248function modelButton ( live ) { 249if ( modelOp === "load" ) return setModelButton ( tr ( "model.loading" , "Loading…" ), tr ( "model.loadingTitle" , "The model is loading" ), true ); 250if ( modelOp === "unload" ) return setModelButton ( tr ( "model.unloading" , "Unloading…" ), tr ( "model.unloadingTitle" , "The model is unloading" ), true ); 251const state = ( live && live . state ) || "" ; 252const metricsBusy = state === "reading" || state === "generating" || ( live && live . queued > 0 ); 253const imageNow = imageLive ( live ); 254const unload = tr ( "model.unload" , "Unload" ); 255if ( state === "unloaded" ) { 256if ( imageNow ) return setModelButton ( tr ( "model.loading" , "Loading…" ), tr ( "model.imageLoading" , "An image is already loading the model" ), true ); 257if ( pageBusy ()) return setModelButton ( tr ( "model.loading" , "Loading…" ), tr ( "model.replyLoading" , "A reply is already loading the model" ), true ); 258return setModelButton ( tr ( "model.load" , "Load" ), tr ( "model.loadTitle" , "Load the model now. A message also loads it." ), false ); 259} 260if ( imageNow ) return setModelButton ( unload , tr ( "model.imageBusy" , "An image is generating. It finishes on its own." ), true ); 261if ( ! state ) return setModelButton ( "…" , tr ( "model.waiting" , "Waiting for the server" ), true ); 262if ( metricsBusy || pageBusy ()) return setModelButton ( unload , tr ( "model.stopFirst" , "Stop the reply, then unload" ), true ); 263return setModelButton ( unload , tr ( "model.unloadTitle" , "Unload the model and free the GPU" ), false ); 264} 265$ ( "unload-btn" ). onclick = async () => { 266if ( modelOp ) return ; 267const live = ( lastMetrics && lastMetrics . live ) || {}; 268const loading = live . state === "unloaded" ; 269const busyCopy = ( sample , stillLoading ) => stillLoading 270 ?( imageLive ( sample ) ?tr ( "model.imageLoadingDot" , "An image is already loading the model." ) :tr ( "model.replyLoadingDot" , "A reply is already loading the model." )) 271 :( imageLive ( sample ) ?tr ( "model.imageBusy" , "An image is generating. It finishes on its own." ) :tr ( "model.stopFirstDot" , "Stop the reply, then unload." )); 272if ( loading ?pageBusy () :turnBlocksUnload ( live )) { 273toast ( "warn" , tr ( "model.busy" , "Model is busy" ), busyCopy ( live , loading )); 274return ; 275} 276if ( ! loading && ! confirm ( tr ( "model.confirmUnload" , "Unload the model and free the GPU? Load, or the next message, brings it back." ))) return ; 277// confirm() blocks the poll. Yield so a sample that arrived during the dialog is applied. A confirmed Unload stays an unload. 278if ( ! loading ) { 279modelOp = "unload" ; 280modelButton ( live ); 281await new Promise (( resolve ) => setTimeout ( resolve , 0 )); 282} 283const now = ( lastMetrics && lastMetrics . live ) || {}; 284const loadingNow = loading ; 285if ( loadingNow ?pageBusy () :turnBlocksUnload ( now )) { 286modelOp = null ; 287if ( lastMetrics ) render ( lastMetrics ); else modelButton ( now ); 288toast ( "warn" , tr ( "model.busy" , "Model is busy" ), busyCopy ( now , loadingNow )); 289return ; 290} 291modelOp = loadingNow ?"load" :"unload" ; 292modelButton ( now ); 293if ( loadingNow ) toast ( "info" , tr ( "model.loadingToast" , "Loading the model" ), tr ( "model.fewMinutes" , "This can take a few minutes." )); 294const remember = ( state ) => { 295if ( ! lastMetrics ) lastMetrics = {}; 296lastMetrics . live = Object . assign ({}, lastMetrics . live , { state, queued :0 }); 297metricsHold = { state, after :metricsEpoch }; 298}; 299try { 300const r = await fetch ( loadingNow ?"load" :"unload" , { method :"POST" , headers :headers ( true ), body :"{}" }); 301let body = {}; 302try { body = await r . json (); } catch ( e ) { /* the connection dropped */ } 303const status = body . status || "" ; 304const msg = ( body . error && body . error . message ) || 305( r . status === 401 ?tr ( "toast.keyAbout2" , "API key needed: add it under About > Settings." ) :tr ( "toast.httpAnswer" , "The server answered HTTP {code}." , { code :r . status })); 306const failTitle = loadingNow ?tr ( "model.loadFailed" , "Load failed" ) :tr ( "model.unloadFailed" , "Unload failed" ); 307if ( loadingNow ) { 308if ( r . ok && status === "loaded" ) { 309remember ( "idle" ); 310toast ( "success" , tr ( "model.loaded" , "Model loaded" ), tr ( "model.gpuInUse" , "The GPU is in use." )); 311} else { 312toast ( "error" , failTitle , msg ); 313} 314} else if ( status === "unloaded" || status === "not loaded" ) { 315remember ( "unloaded" ); 316toast ( status === "unloaded" ?"success" :"info" , 317status === "unloaded" ?tr ( "model.unloaded" , "Model unloaded" ) :tr ( "model.alreadyUnloaded" , "Already unloaded" ), 318tr ( "model.gpuFree" , "The GPU is free. Load, or the next message, brings it back." )); 319} else if ( r . status === 409 || status === "busy" ) { 320let sample = ( lastMetrics && lastMetrics . live ) || {}; 321try { 322const mr = await fetch ( "metrics" , { headers :headers ()}); 323if ( mr . ok ) { 324const m = await mr . json (); 325if ( m && m . live ) { sample = m . live ; lastMetrics = m ; } 326} 327} catch ( e ) { /* the 409 body has no phase */ } 328toast ( "warn" , tr ( "model.busy" , "Model is busy" ), imageLive ( sample ) 329 ?tr ( "model.imageBusy" , "An image is generating. It finishes on its own." ) :tr ( "model.stopFirstDot" , "Stop the reply, then unload." )); 330} else if ( status === "unsupported" ) { 331toast ( "error" , tr ( "model.unsupported" , "Unload is not available" ), "" ); 332} else { 333toast ( "error" , failTitle , msg ); 334} 335} catch ( e ) { 336toast ( "error" , loadingNow ?tr ( "model.loadFailed" , "Load failed" ) :tr ( "model.unloadFailed" , "Unload failed" ), tr ( "model.noAnswer" , "The server did not answer." )); 337} finally { 338modelOp = null ; 339if ( lastMetrics ) render ( lastMetrics ); else modelButton ({}); 340} 341}; 342 343function render ( m ) { 344const live = m . live || {}, hw = m . hardware || {}, st = m . hardware_static || {}, eng = m . engine || {}, h = m . history || {}; 345const last = ( m . requests || [])[ 0 ]; 346// the header pill. modelOp and a local load win over "N queued": with parallel requests, queued stays up through 347// ensure_loaded(), and metrics stay "unloaded" until the engine is READY. An image POST in that window is still a load. 348const localLoad = live . state === "unloaded" && ( busy != null || imageBusy ); 349if ( modelOp === "load" ) { 350setPill ( "idle" , tr ( "model.loading" , "Loading…" )); 351} else if ( modelOp === "unload" ) { 352setPill ( "idle" , tr ( "model.unloading" , "Unloading…" )); 353} else if ( localLoad ) { 354setPill ( "idle" , tr ( "model.loading" , "Loading…" )); 355} else if ( imageLive ( live )) { 356setPill ( "reading" , tr ( "pill.image" , "Generating image…" )); 357} else if ( live . state === "reading" ) { 358const pct = live . prompt_total ?Math . round (( 100 * live . prompt_read ) / live . prompt_total ) :null ; 359setPill ( "reading" , pct != null ?tr ( "pill.readingPct" , "Reading prompt · {pct}%" , { pct}) :tr ( "pill.reading" , "Reading prompt" )); 360} else if ( live . state === "generating" ) { 361setPill ( "generating" , tr ( "pill.generating" , "Generating · {rate} tok/s" , { rate :fmt ( live . tok_s , 1 )})); 362} else if ( live . state === "unloaded" ) { 363setPill ( "idle" , tr ( "pill.unloaded" , "Unloaded" )); 364} else { 365setPill ( "idle" , tr ( "pill.idle" , "Idle" )); 366} 367modelButton ( live ); 368if ( ! modelOp && ! localLoad && live . queued > 0 ) setPill ( "queued" , tr ( "pill.queued" , "{n} queued" , { n :live . queued })); 369if ( tab === "monitor" ) renderMonitor ( live , hw , st , eng , h , last , m . requests || [], m . totals , m . requests_kept ); 370if ( tab === "monitor" ) renderConvCache ( m . conversation_cache ); 371if ( tab === "about" ) renderAbout ( eng , hw , st ); 372} 373 374// #596: the conversation cache - the prompt's state the engine keeps between requests (always), and the whole 375// conversations it parks in RAM when "--conversation-cache-mib N" is in the run config's args (opt-in) 376function since ( t ) { 377if ( ! t ) return "" ; 378const s = Math . max ( 0 , Date . now () / 1000 - t ); 379return s < 60 ?"just now" :s < 3600 ?` ${ fmt ( s / 60 )} min ago` :` ${ fmt ( s / 3600 , 1 )} h ago` ; 380} 381function renderConvCache ( c ) { 382$ ( "cc-card" ). hidden = ! c ; 383if ( ! c ) return ; // an older server 384const pct = ( a , b ) => ( b ?` ${ Math . min ( 100 , ( 100 * a ) / b )} %` :"0%" ); 385$ ( "cc-bars" ). hidden = ! c . enabled ; 386if ( c . enabled ) { 387$ ( "cc-slots-text" ). textContent = ` ${ fmt ( c . parked )} / ${ fmt ( c . slots )} ` ; 388$ ( "cc-slots-bar" ). style . width = pct ( c . parked , c . slots ); 389const budget = c . budget_mib * 1048576 ; 390$ ( "cc-mem-text" ). textContent = ` ${ gb ( c . bytes )} / ${ gb ( budget )} GB` ; 391$ ( "cc-mem-bar" ). style . width = pct ( c . bytes , budget ); 392} 393$ ( "cc-sum" ). textContent = c . requests ?` ${ fmt ( c . requests_reused )} of ${ fmt ( c . requests )} requests reused part of their prompt` :"" ; 394const share = c . prompt_tokens ?` ( ${ fmt (( 100 * c . reused_tokens ) / c . prompt_tokens )} % of all prompt tokens)` :"" ; 395const event = c . last_event ?` ${ c . last_event === "parked" ? "Parked" : "Restored" } ${ fmt ( c . last_tokens )} tokens, ${ since ( c . last_at )} ` :null ; 396facts ( $ ( "cc-facts" ), [ 397[ "Last request" , c . last_prompt != null ?` ${ fmt ( c . last_reused || 0 )} of ${ fmt ( c . last_prompt )} prompt tokens reused` :null ], 398[ "Reused since start" , c . requests ?` ${ fmt ( c . reused_tokens )} tokens ${ share } ` :null ], 399[ "Parked / restored" , c . enabled ?` ${ fmt ( c . parks )} / ${ fmt ( c . restores )} ${ c . evictions ? ` · ${ fmt ( c . evictions )} evicted` : "" } ` :null ], 400[ "Last switch" , c . enabled ?event :null ], 401]); 402$ ( "cc-note" ). textContent = c . enabled 403 ?"A request that continues a parked conversation gets its state back instead of reading it again; the oldest goes when the slots or the memory are full." 404 :"The engine keeps the last conversation's state, so a follow-up reads only what is new. To keep several conversations (agents taking turns), add \"--conversation-cache-mib\", \"8192\" to the run config's args (docs/DETAILS.md)." ; 405} 406 407function renderTotals ( t ) { 408if ( ! t || ! t . requests ) return "" ; 409const since = new Date ( t . since * 1000 ). toLocaleString ([], { weekday :"short" , hour :"2-digit" , minute :"2-digit" }); 410const read = t . prompt_tokens - t . reused ; 411const pSpeed = t . prompt_ms > 0 && read > 0 ?` at ${ fmt ( read / ( t . prompt_ms / 1000 ))} tok/s` :"" ; 412const oSpeed = t . decode_ms > 0 && t . output_tokens > 0 ?` at ${ fmt ( t . output_tokens / ( t . decode_ms / 1000 ), 1 )} tok/s` :"" ; 413return `Since ${ since } : ${ fmt ( t . requests )} requests · ${ fmt ( read )} prompt tokens read ${ pSpeed } ( ${ fmt ( t . reused )} reused) · ` + 414` ${ fmt ( t . output_tokens )} written ${ oSpeed } ` ; 415} 416function renderMonitor ( live , hw , st , eng , h , last , requests , totals , kept ) { 417// model state 418// A local turn keeps metrics on "unloaded" for the whole engine start. 419const imageNow = imageLive ( live ); 420const starting = modelOp === "load" || imageNow || ( busy != null && live . state === "unloaded" ); 421const on = ! modelOp && live . queued > 0 ?"queued" :live . state ; 422for ( const b of document . querySelectorAll ( "#state-badges .st-badge" )) { 423const lit = ( b . dataset . s === on || b . dataset . s === live . state ) && ! ( starting && b . dataset . s === "unloaded" ); 424b . classList . toggle ( "on" , lit ); 425} 426const prog = $ ( "state-progress" ); 427let label = "Waiting for a request" , detail = "" , pct = 0 ; 428if ( modelOp === "load" || ( busy != null && live . state === "unloaded" && ! imageNow )) { 429label = "Loading" ; 430delete prog . dataset . tone ; 431detail = "The model is loading." ; 432} else if ( imageNow && ( live . state === "unloaded" || live . state === "reading" || live . state === "generating" || live . state === "idle" )) { 433label = live . state === "unloaded" ?"Loading" :"Generating image" ; 434delete prog . dataset . tone ; 435detail = live . state === "unloaded" ?"The model is loading." :"An image is generating. It finishes on its own." ; 436} else if ( modelOp === "unload" ) { 437label = "Unloading" ; 438delete prog . dataset . tone ; 439detail = "Freeing the GPU." ; 440} else if ( live . state === "reading" ) { 441label = "Reading prompt" ; 442prog . dataset . tone = "info" ; 443if ( live . prompt_total ) { 444pct = ( 100 * live . prompt_read ) / live . prompt_total ; 445detail = ` ${ fmt ( live . prompt_read )} / ${ fmt ( live . prompt_total )} tokens · ${ fmt ( pct )} %` ; 446} else { 447detail = ` ${ fmt ( live . prompt_tokens )} tokens` ; 448} 449} else if ( live . state === "generating" ) { 450label = live . phase ?live . phase [ 0 ]. toUpperCase () + live . phase . slice ( 1 ) :"Generating" ; 451delete prog . dataset . tone ; 452pct = live . max_tokens ?Math . min ( 100 , ( 100 * live . generated ) / live . max_tokens ) :0 ; 453detail = ` ${ fmt ( live . generated )} tokens · ${ fmt ( live . tok_s , 1 )} tok/s` ; 454} else if ( live . state === "unloaded" ) { 455label = "Unloaded" ; 456delete prog . dataset . tone ; 457detail = "Load brings it back. A message does too." ; 458} else if ( last ) { 459delete prog . dataset . tone ; 460detail = `last: ${ fmt ( last . output_tokens )} tokens ${ last . decode_tok_s ? ` at ${ fmt ( last . decode_tok_s , 1 )} tok/s` : "" } ` ; 461} 462$ ( "state-label" ). textContent = label ; 463$ ( "state-detail" ). textContent = detail ; 464$ ( "state-bar" ). style . width = ` ${ pct } %` ; 465 466// the eight cards 467// Idle: not the last request's speed (one request is noisy) but the run's average from the server's totals 468// (token-weighted, the same figure the engine's DONE lines and Prometheus report). Live stays live. 469const avgDecode = totals && totals . decode_ms > 0 && totals . output_tokens > 0 ?totals . output_tokens / ( totals . decode_ms / 1000 ) :null ; 470const readTokens = totals ?totals . prompt_tokens - ( totals . reused || 0 ) :0 ; 471const avgPrefill = totals && totals . prompt_ms > 0 && readTokens > 0 ?readTokens / ( totals . prompt_ms / 1000 ) :null ; 472const speed = live . state === "generating" ?live . tok_s :avgDecode != null ?avgDecode :last ?last . decode_tok_s :null ; 473setMetric ( "speed" , speed == null ?null :fmt ( speed , 1 ), "t/s" , 474live . state === "generating" ?"Decode now" :avgDecode != null ?"Decode · run average" :last ?"Decode last request" :"Decode" ); 475const prefill = live . state !== "idle" ?live . prefill_tok_s_mean 476 :avgPrefill != null ?avgPrefill :last && last . prompt_ms > 0 ?Math . max ( 0 , last . prompt_tokens - ( last . reused || 0 )) / ( last . prompt_ms / 1000 ) :null ; 477setMetric ( "prefill" , prefill == null ?null :fmt ( prefill ), "t/s" , 478live . state === "reading" ?"Prefill now" :live . state === "generating" ?"Prefill this request" :avgPrefill != null ?"Prefill · run average" :last ?"Prefill last request" :"Prefill" ); 479spark ( "sp-speed" , h . tok_s ); 480spark ( "sp-prefill" , h . prefill_tok_s_mean ); 481// a model split across several cards (issue #112): the cards show their total / mean / hottest, and each card's own 482const per = ( f ) => ( hw . gpus || []). map (( g ) => `GPU ${ g . index } ${ f ( g )} ` ). join ( " · " ); 483const multi = ( hw . gpus || []). length > 1 ; 484setMetric ( "gpu" , hw . gpu_util == null ?null :fmt ( hw . gpu_util ), "%" , 485multi ?per (( g ) => ( g . util == null ?"–" :` ${ fmt ( g . util )} %` )) :st . gpu_name || ( st . gpu_note ?"not available" :"" )); 486spark ( "sp-gpu" , h . gpu_util , 100 ); 487setMetric ( "vram" , hw . gpu_mem_used == null ?null :gb ( hw . gpu_mem_used ), hw . gpu_mem_total ?`/ ${ gb ( hw . gpu_mem_total , 0 )} GB` :"GB" , 488multi ?per (( g ) => ( g . mem_used == null ?"–" :` ${ gb ( g . mem_used )} GB` )) 489 :eng . expert_slots ?` ${ fmt ( eng . expert_slots )} experts cached` :( st . gpu_note ?"not available on Windows AMD yet" :"" )); 490spark ( "sp-vram" , h . gpu_mem_used , hw . gpu_mem_total ); 491setMetric ( "temp" , hw . gpu_temp == null ?null :fmt ( hw . gpu_temp ), "°C" , 492multi ?per (( g ) => ( g . temp == null ?"–" :` ${ fmt ( g . temp )} °` )) :"" ); 493spark ( "sp-temp" , h . gpu_temp , 90 ); 494setMetric ( "power" , hw . gpu_power == null ?null :fmt ( hw . gpu_power ), "W" , hw . gpu_power_limit ?`of ${ fmt ( hw . gpu_power_limit )} W limit` :"" ); 495spark ( "sp-power" , h . gpu_power , hw . gpu_power_limit ); 496const gen = hw . gpu_pcie_gen_max || hw . gpu_pcie_gen ; 497setMetric ( "pcie" , gen ?`Gen ${ gen } ` :null , hw . gpu_pcie_width ?`x ${ hw . gpu_pcie_width } ` :"" , 498hw . gpu_pcie_rx_mb == null ?"" :`to GPU ${ fmt ( hw . gpu_pcie_rx_mb , hw . gpu_pcie_rx_mb < 10 ? 1 : 0 )} MB/s` + 499( hw . gpu_pcie_gen && gen && hw . gpu_pcie_gen < gen ?` · idle Gen ${ hw . gpu_pcie_gen } ` :"" )); 500spark ( "sp-pcie" , h . gpu_pcie_rx_mb ); 501setMetric ( "cpu" , hw . cpu == null ?null :fmt ( hw . cpu ), "%" , st . threads ?` ${ st . cores ? ` ${ st . cores } cores · ` : "" } ${ st . threads } threads` :"" ); 502spark ( "sp-cpu" , h . cpu , 100 ); 503if ( hw . disk_read_mb == null ) { 504setMetric ( "disk" , null , "" , st . psutil ?"" :"needs psutil (setup installs it)" ); 505} else { 506const big = hw . disk_read_mb >= 1000 ; 507setMetric ( "disk" , big ?fmt ( hw . disk_read_mb / 1024 , 2 ) :fmt ( hw . disk_read_mb , hw . disk_read_mb < 10 ?1 :0 ), big ?"GB/s" :"MB/s" , 508hw . disk_write_mb == null ?"" :`write ${ fmt ( hw . disk_write_mb , 1 )} MB/s` ); 509} 510spark ( "sp-disk" , h . disk_read_mb ); 511 512// context fill: the running request, else the last one 513const ctx = eng . max_context || 0 ; 514let used = 0 ; 515if ( live . state !== "idle" ) used = ( live . prompt_tokens || 0 ) + ( live . generated || 0 ); 516else if ( last ) used = ( last . prompt_tokens || 0 ) + ( last . output_tokens || 0 ); 517const frac = ctx ?Math . min ( 1 , used / ctx ) :0 ; 518$ ( "ctx-fill" ). setAttribute ( "stroke-dasharray" , ` ${( 235.6 * frac ). toFixed ( 1 )} 314.2` ); 519$ ( "ctx-fill" ). style . opacity = 235.6 * frac >= 3 ?"1" :"0" ; // a near-zero arc would draw just its round cap 520$ ( "ctx-pct" ). textContent = ` ${ Math . round ( frac * 100 )} %` ; 521$ ( "ctx-sub" ). textContent = ctx ?` ${ kfmt ( used )} / ${ ctxfmt ( ctx )} ` :"–" ; 522const cacheBytes = ( eng . expert_cache_mib || 0 ) * 1048576 ; 523$ ( "slots-text" ). textContent = eng . expert_slots ?` ${ fmt ( eng . expert_slots )} · ${ gb ( cacheBytes )} GB` :"–" ; 524$ ( "slots-bar" ). style . width = hw . gpu_mem_total ?` ${ Math . min ( 100 , ( 100 * cacheBytes ) / hw . gpu_mem_total )} %` :"0%" ; 525$ ( "ram-text" ). textContent = hw . ram_total ?` ${ gb ( hw . ram_used )} / ${ gb ( hw . ram_total , 0 )} GB` :"–" ; 526const ramPct = hw . ram_total ?( 100 * hw . ram_used ) / hw . ram_total :0 ; 527$ ( "ram-bar" ). style . width = ` ${ ramPct } %` ; 528if ( ramPct > 92 ) $ ( "ram-progress" ). dataset . tone = "danger" ; else delete $ ( "ram-progress" ). dataset . tone ; 529$ ( "temp-text" ). textContent = hw . gpu_temp == null ?"–" :` ${ fmt ( hw . gpu_temp )} °C` ; 530$ ( "temp-bar" ). style . width = hw . gpu_temp == null ?"0%" :` ${ Math . min ( 100 , hw . gpu_temp )} %` ; 531 532// recent requests 533const body = $ ( "req-body" ); 534if ( ! requests . length ) { 535body . innerHTML = `<tr><td colspan="9" class="muted">No requests yet</td></tr>` ; 536} else { 537const badge = { stop :[ "" , "Done" ], length :[ "" , "Max tokens" ], cancel :[ "st-badge--queued" , "Stopped" ], 538disconnect :[ "st-badge--queued" , "Closed" ], error :[ "st-badge--error" , "Error" ], 539timeout :[ "st-badge--queued" , "Timeout" ]}; 540body . innerHTML = requests . slice ( 0 , reqShowAll ?requests . length :12 ). map (( r ) => { 541const [ cls , text ] = badge [ r . finish ] || [ "" , r . finish || "–" ]; 542const t = new Date ( r . time * 1000 ). toLocaleTimeString ([], { hour :"2-digit" , minute :"2-digit" , second :"2-digit" }); 543const proj = r . projection == null ?"" :` <span class="st-badge ${ r . projection ? " st-badge--reading" : "" } " title="experimental speed projection ${ r . projection ? "on" : "off" } "> ${ r . projection ? "ESP" : "stock" } </span>` ; 544// #588: the VRAM share; the PCIe share (--pcie-frac) beside it when there is one 545const hit = r . hit_rate == null ?"–" :` ${( r . hit_rate * 100 ). toFixed ( 1 )} %` + 546( r . pcie_share ?` <span class="muted" title="routed experts the GPU read over PCIe (--pcie-frac) or another GPU computed">+ ${( r . pcie_share * 100 ). toFixed ( 1 )} % PCIe</span>` :"" ); 547// Reused tokens are not prefetched again. Match the Monitor's existing Prefill metric. 548const fresh = r . prompt_tokens == null ?null :Math . max ( 0 , r . prompt_tokens - ( r . reused || 0 )); 549const prefillRate = fresh > 0 && r . prompt_ms > 0 ?fresh / ( r . prompt_ms / 1000 ) :null ; 550return `<tr><td> ${ esc ( t )} </td><td><span class="st-badge ${ cls } "> ${ esc ( text )} </span> ${ proj } </td><td class="num"> ${ fmt ( r . prompt_tokens )} </td> 551<td class="num"> ${ fmt ( r . reused )} </td><td class="num"> ${ fmt ( r . output_tokens )} </td><td class="num"> ${ fmt ( prefillRate )} </td><td class="num"> ${ fmt ( r . decode_tok_s , 1 )} </td> 552<td class="num"> ${ hit } </td><td class="num"> ${ fmt ( r . duration_s , 1 )} s</td></tr>` ; 553}). join ( "" ); 554} 555const all = $ ( "req-all" ); 556kept = kept == null ?requests . length :kept ; 557all . hidden = kept <= 12 ; 558all . textContent = reqShowAll ?"Show fewer" :`Show all ( ${ kept } )` ; 559$ ( "req-wrap" ). classList . toggle ( "all" , reqShowAll ); 560$ ( "req-totals" ). textContent = renderTotals ( totals ); 561} 562 563function facts ( el , rows ) { 564el . innerHTML = rows . filter (( r ) => r [ 1 ] != null && r [ 1 ] !== "" ). map (([ k , v , copy ]) => 565`<dt> ${ esc ( k )} </dt><dd> ${ copy ? `<code> ${ esc ( v )} </code><button class="st-btn st-btn--icon" data-copy=" ${ esc ( v )} " aria-label="Copy"> ${ icon ( "copy" )} </button>` : esc ( v )} </dd>` ). join ( "" ); 566} 567// INFO cvec=project:4-44[:singleL] | add:A-B | 0 568function projectionText ( c ) { 569if ( ! c || c === "0" || c === 0 ) return null ; 570const [ mode , range , single ] = String ( c ). split ( ":" ); 571const [ a , b ] = ( range || "" ). split ( "-" ); 572return ` ${ mode === "project" ? "Projection" : "Additive" } control vector on layers ${ a } – ${ b } ` + 573` ${ single ? ` (layer ${ single . replace ( "single" , "" )} 's direction)` : "" } . Per chat in Sampling. Its package ` + 574"describes the vector as a refusal-direction projection; measure the speed yourself" ; 575} 576function renderAbout ( eng , hw , st ) { 577const kv = { int8 :"8-bit" , q4_0 :"4-bit (Hadamard-rotated)" , fp16 :"16-bit" }[ eng . kv ] || eng . kv ; 578facts ( $ ( "facts-engine" ), [ 579[ "Model" , eng . model ], 580[ "Engine" , eng . version ?`v ${ eng . version } ` :"built from source" ], 581[ "Context" , eng . max_context ?` ${ fmt ( eng . max_context )} tokens` :null ], 582[ "KV cache" , kv ?` ${ kv } ${ eng . kv_resident ? `, streamed: ${ fmt ( eng . kv_resident )} positions per layer in VRAM, the rest in RAM` : ", all in VRAM" } ` :null ], 583[ "Experts in VRAM" , eng . expert_slots ?` ${ fmt ( eng . expert_slots )} ( ${ gb (( eng . expert_cache_mib || 0 ) * 1048576 )} GB)` :null ], 584// #5080: the MTP line only when the MTP is the drafter (eng.drafting, strata_control/drafting.py engine_info; an engine too old to say had only the MTP) 585[ "Speculation" , eng . spec && ( eng . drafting == null || eng . drafting === "mtp" ) ?`MTP drafts up to ${ Math . max ( 0 , ( eng . mtp_max || eng . spec ) - 1 )} tokens ${ eng . lookup ? ", prompt lookup on" : "" } ` :null ], 586[ "Images" , eng . images ?"on" :"off" ], 587[ "Experimental speed projection" , projectionText ( eng . cvec )], 588]); 589facts ( $ ( "facts-hw" ), [ 590[ "GPU" , st . gpu_name ?` ${ st . gpu_name } ${ hw . gpu_mem_total ? `, ${ gb ( hw . gpu_mem_total , 0 )} GB` : "" } ` :( st . gpu_note || "not readable (NVML)" )], 591[ "CPU" , st . cpu_name ?` ${ st . cpu_name } ${ st . threads ? `, ${ st . threads } threads` : "" } ` :null ], 592[ "RAM" , hw . ram_total ?` ${ gb ( hw . ram_total , 0 )} GB` :null ], 593]); 594const base = location . origin ; 595facts ( $ ( "facts-api" ), [ 596[ "OpenAI base URL" , ` ${ base } /v1` , true ], 597[ "Anthropic base URL" , base , true ], 598[ "Model name" , eng . model , true ], 599]); 600} 601document . addEventListener ( "click" , ( e ) => { 602const b = e . target . closest ( "[data-copy]" ); 603if ( b ) copyText ( b . dataset . copy , b ); 604}); 605$ ( "req-all" ). addEventListener ( "click" , () => { reqShowAll = ! reqShowAll ; if ( lastMetrics ) render ( lastMetrics ); }); 606 607// ------------------------------------------------------------------ MCP servers (GET /mcp) 608// Tools from the MCP servers in the run config: the chat offers them to the model (opt-in per request, 609// "strata_mcp": true, which only this page sends); the Monitor lists the servers and what they offer. 610let mcpInfo = { servers :[], tools :0 }, mcpRetry = null ; 611async function loadMcp () { 612try { 613const r = await fetch ( "mcp" , { headers :headers ()}); 614if ( ! r . ok ) return ; 615mcpInfo = await r . json (); 616} catch ( e ) { return ; /* an older server: no MCP */ } 617renderMcp (); 618clearTimeout ( mcpRetry ); // right after the start, servers may still be starting (npx downloads) 619if (( mcpInfo . servers || []). some (( s ) => s . status === "starting" )) mcpRetry = setTimeout ( loadMcp , 3000 ); 620} 621const MCP_STATE = { ready :[ "st-badge--generating" , "Connected" ], starting :[ "st-badge--reading" , "Starting" ], 622failed :[ "st-badge--error" , "Failed" ], stopped :[ "st-badge--queued" , "Stopped" ], idle :[ "" , "Waiting" ]}; 623function renderMcp () { 624const servers = mcpInfo . servers || []; 625$ ( "mcp-card" ). hidden = ! servers . length ; 626$ ( "mcp-row" ). hidden = ! servers . length ; 627const ready = servers . filter (( s ) => s . status === "ready" || s . status === "stopped" ); 628$ ( "mcp-sum" ). textContent = servers . length ?` ${ fmt ( mcpInfo . tools )} tools · ${ ready . length } of ${ servers . length } servers connected` :"" ; 629$ ( "mcp-row-sub" ). textContent = mcpInfo . tools ?` ${ fmt ( mcpInfo . tools )} tools from ${ ready . map (( s ) => s . name ). join ( ", " )} ; the model calls them when it decides to` 630 :"no server is connected yet (see the Monitor)" ; 631$ ( "mcp-list" ). innerHTML = servers . map (( s ) => { 632const [ cls , text ] = MCP_STATE [ s . status ] || [ "" , s . status ]; 633const info = s . info && s . info . name ?` · ${ s . info . name } ${ s . info . version ? ` ${ s . info . version } ` : "" } ` :"" ; 634return `<div class="mcp-server"><div class="mcp-server__head"><span class="st-badge ${ cls } "> ${ esc ( text )} </span>` + 635`<strong> ${ esc ( s . name )} </strong><span class="muted small"> ${ esc ( s . transport )} · ${ fmt ( s . tools . length )} tools ${ esc ( info )} </span></div>` + 636( s . error ?`<div class="msg-error"> ${ esc ( s . error )} </div>` :"" ) + 637( s . tools . length ?`<div class="mcp-server__tools"> ${ s . tools . map (( t ) => `<span class="chip" title=" ${ esc ( t . description || "" )} "> ${ esc ( t . tool )} </span>` ). join ( "" )} </div>` :"" ) + 638`</div>` ; 639}). join ( "" ); 640} 641 642// ------------------------------------------------------------------ Model settings (GET / POST /config, #564) 643// A few documented keys of the run config (strata-<model>.json), for every client, from the next start on. The 644// server lists them, checks every value and keeps every other key of the file as it is. 645let cfgKeys = []; 646async function loadConfig () { 647let r ; 648try { r = await fetch ( "config" , { headers :headers ()}); } catch ( e ) { return ; } 649if ( ! r . ok ) { $ ( "cfg-card" ). hidden = true ; return ; } // no run config, an older server, or no key yet 650const c = await r . json (); 651cfgKeys = c . keys || []; 652$ ( "cfg-file" ). textContent = c . file || "" ; 653$ ( "cfg-form" ). innerHTML = cfgKeys . map (( k , i ) => { 654const id = `cfg- ${ i } ` , v = k . value ; 655let input ; 656if ( k . kind === "bool" || k . kind === "enum" ) { 657const opts = k . kind === "bool" ?[[ "true" , "on" ], [ "false" , "off" ]] :k . choices . map (( x ) => [ x , x ]); 658const cur = v == null ?"" :String ( v ); 659input = `<select class="st-input" id=" ${ id } "><option value="" ${ cur === "" ? " selected" : "" } >default</option>` + 660opts . map (([ val , text ]) => `<option value=" ${ esc ( val )} " ${ cur === val ? " selected" : "" } > ${ esc ( text )} </option>` ). join ( "" ) + `</select>` ; 661} else { 662const text = v == null ?"" :Array . isArray ( v ) ?v . join ( ", " ) :String ( v ); 663input = `<input class="st-input" id=" ${ id } " ${ k . kind === "number" ? 'type="number" step="any" min="0"' : 'type="text"' } ` + 664`value=" ${ esc ( text )} " placeholder="default" autocomplete="off">` ; 665} 666return `<label for=" ${ id } " title=" ${ esc ( k . help )} "> ${ esc ( k . help )} <code> ${ esc ( k . key )} </code></label> ${ input } ` ; 667}). join ( "" ); 668$ ( "cfg-card" ). hidden = false ; 669} 670function configValue ( k , el ) { 671const s = el . value . trim (); 672if ( s === "" ) return null ; 673if ( k . kind === "bool" ) return s === "true" ; 674if ( k . kind === "number" ) return Number ( s ); 675return s ; // enum, or names (the server splits them at commas) 676} 677$ ( "cfg-save" ). addEventListener ( "click" , async () => { 678const set = {}; 679cfgKeys . forEach (( k , i ) => { 680const v = configValue ( k , $ ( `cfg- ${ i } ` )); 681const old = Array . isArray ( k . value ) ?k . value . join ( ", " ) :k . value ; 682if ( JSON . stringify ( v ) !== JSON . stringify ( old ?? null )) set [ k . key ] = v ; 683}); 684if ( ! Object . keys ( set ). length ) { $ ( "cfg-msg" ). textContent = "Nothing changed." ; return ; } 685try { 686const r = await fetch ( "config" , { method :"POST" , headers :headers ( true ), body :JSON . stringify ({ set})}); 687const b = await r . json (); 688if ( ! r . ok ) throw new Error (( b . error || {}). message || `HTTP ${ r . status } ` ); 689$ ( "cfg-msg" ). textContent = b . changed . length 690 ?`Saved ( ${ b . changed . join ( ", " )} ); the earlier file is ${ b . file } .bak. Start the model again to use it.` :"Nothing changed." ; 691loadConfig (); 692} catch ( e ) { 693$ ( "cfg-msg" ). textContent = "" ; 694toast ( "error" , "Not saved" , String ( e . message || e ), 6000 ); 695} 696}); 697 698// ------------------------------------------------------------------ Markdown (escaped first, then formatted) 699function inline ( s ) { 700const codes = []; 701s = s . replace ( / ` ([ ^ ` \n ] + ) ` / g , ( _ , c ) => { codes . push ( c ); return `\u0000 ${ codes . length - 1 } \u0000` ; }); 702s = esc ( s ) 703. replace ( / \*\* ([ ^ * \n ] + ) \*\* / g , "<strong>$1</strong>" ) 704. replace ( / ( ^ | [ ^ * \w ]) \* ([ ^ * \n ] + ) \* (? ! [ * \w ]) / g , "$1<em>$2</em>" ) 705. replace ( / \[ ([ ^ \]\n ] + ) \]\( ( https ? :\/\/ [ ^ ) \s ] + ) \) / g , '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>' ); 706return s . replace ( / \u0000 ( \d + ) \u0000 / g , ( _ , i ) => `<code class="inline"> ${ esc ( codes [ + i ])} </code>` ); 707} 708// An ```svg or ```html block that is complete gets a Preview button (serve/web/preview.js): the block's own code in a sandboxed 709// frame, built when it is first opened and again when the theme changes. The state lives on the box (data-preview), so it 710// resets if the answer is rebuilt. A page (html) can also be run WITH scripts, after a warning, one block at a time. 711function pageTheme () { 712const root = document . documentElement ; 713return { dark :root . dataset . theme === "dark" , ink :getComputedStyle ( root ). getPropertyValue ( "--st-ink" ). trim ()}; 714} 715function fillPreview ( fr , scripts , blank ) { 716const box = fr . closest ( ".st-code" ); 717const doc = blank ?null :StrataPreview . previewDoc ( fr . dataset . lang , box . querySelector ( "pre" ). textContent , scripts , pageTheme (), window ); 718const nf = StrataPreview . makeFrame ( doc , { scripts, title :fr . title , lang :fr . dataset . lang }); 719fr . replaceWith ( nf ); 720box . classList . toggle ( "st-code--run" , !! ( doc && scripts )); 721const rb = box . querySelector ( "[data-preview-scripts]" ); 722if ( rb ) { 723rb . setAttribute ( "aria-pressed" , String ( !! ( doc && scripts ))); 724rb . setAttribute ( "aria-label" , doc && scripts ?tr ( "preview.stopScripts" , "Stop scripts" ) :tr ( "preview.runScripts" , "Run scripts" )); 725} 726} 727function refreshPreviews () { for ( const fr of document . querySelectorAll ( "iframe[data-opened]" )) fillPreview ( fr , fr . dataset . scripts === "1" ); } 728function codeBlock ( lang , code , complete ) { 729const ok = complete && StrataPreview . canPreview ( lang || "" , code ); 730const kind = ok ?StrataPreview . kindOf ( lang ) :null ; 731const label = kind === "svg" ?tr ( "preview.showSvg" , "Preview the picture" ) :tr ( "preview.showPage" , "Preview the page" ); 732const head = `<div class="st-code__head"><span> ${ esc ( lang || tr ( "code.label" , "code" ))} </span><span class="st-code__btns">` + 733( kind === "page" ?`<button class="st-btn st-btn--icon" data-preview-scripts aria-label=" ${ esc ( tr ( "preview.runScripts" , "Run scripts" ))} " aria-pressed="false" title=" ${ esc ( tr ( "preview.runScripts" , "Run scripts" ))} "> ${ icon ( "warning" )} </button>` :"" ) + 734( ok ?`<button class="st-btn st-btn--icon" data-preview-toggle data-preview-label=" ${ esc ( label )} " aria-label=" ${ esc ( label )} " title=" ${ esc ( label )} " aria-pressed="false"> ${ icon ( "image" )} </button>` :"" ) + 735`<button class="st-btn st-btn--icon" data-code-copy aria-label=" ${ esc ( tr ( "code.copy" , "Copy code" ))} "> ${ icon ( "copy" )} </button></span></div>` ; 736const prev = ok ?`<div class="st-code__preview"><iframe sandbox="" title=" ${ esc ( kind === "svg" ? tr ( "preview.titleSvg" , "Picture preview" ) : tr ( "preview.titlePage" , "Page preview" ))} " data-lang=" ${ esc ( lang )} "></iframe></div>` :"" ; 737return `<div class="st-code"> ${ head } <pre><code> ${ esc ( code )} </code></pre> ${ prev } </div>` ; 738} 739function blocks ( text ) { 740const out = [], lines = text . split ( "\n" ); 741let para = [], list = null ; 742const flushPara = () => { if ( para . length ) out . push ( `<p> ${ para . map ( inline ). join ( "<br>" )} </p>` ); para = []; }; 743const flushList = () => { if ( list ) out . push ( `< ${ list . tag } > ${ list . items . map (( i ) => `<li> ${ inline ( i )} </li>` ). join ( "" )} </ ${ list . tag } >` ); list = null ; }; 744for ( let i = 0 ; i < lines . length ; i ++ ) { 745const l = lines [ i ]; 746let m ; 747if ( ! l . trim ()) { flushPara (); flushList (); continue ; } 748if (( m = l . match ( / ^ ( # { 1 , 6 }) \s + ( . * ) $ / ))) { flushPara (); flushList (); out . push ( `< ${ m [ 1 ]. length <= 2 ? "h3" : "h4" } > ${ inline ( m [ 2 ])} </ ${ m [ 1 ]. length <= 2 ? "h3" : "h4" } >` ); continue ; } 749if ( / ^\s * ([ -*_ ]) \s * \1\s * \1 [ \s\1 ] * $ / . test ( l )) { flushPara (); flushList (); out . push ( "<hr>" ); continue ; } 750if (( m = l . match ( / ^>\s ? ( . * ) $ / ))) { flushPara (); flushList (); out . push ( `<blockquote> ${ inline ( m [ 1 ])} </blockquote>` ); continue ; } 751if ( / ^\s * \|. * \|\s * $ / . test ( l ) && i + 1 < lines . length && / ^\s * \| ? [ \s :- ] + \| [ \s |:- ] * $ / . test ( lines [ i + 1 ])) { 752flushPara (); flushList (); 753const cells = ( row ) => row . trim (). replace ( / ^\| | \|$ / g , "" ). split ( "|" ). map (( c ) => inline ( c . trim ())); 754let html = `<table><thead><tr> ${ cells ( l ). map (( c ) => `<th> ${ c } </th>` ). join ( "" )} </tr></thead><tbody>` ; 755i += 2 ; 756while ( i < lines . length && / ^\s * \|. * \|\s * $ / . test ( lines [ i ])) html += `<tr> ${ cells ( lines [ i ++ ]). map (( c ) => `<td> ${ c } </td>` ). join ( "" )} </tr>` ; 757i -- ; 758out . push ( html + "</tbody></table>" ); 759continue ; 760} 761if (( m = l . match ( / ^\s * (?:[ -*+ ] | ( \d + )[ .) ]) \s + ( . * ) $ / ))) { 762flushPara (); 763const tag = m [ 1 ] ?"ol" :"ul" ; 764if ( ! list || list . tag !== tag ) { flushList (); list = { tag, items :[]}; } 765list . items . push ( m [ 2 ]); 766continue ; 767} 768if ( list && / ^\s { 2 ,} \S / . test ( l )) { list . items [ list . items . length - 1 ] += " " + l . trim (); continue ; } 769flushList (); 770para . push ( l ); 771} 772flushPara (); flushList (); 773return out . join ( "" ); 774} 775function markdown ( text ) { 776let html = "" , rest = text ; 777for (;;) { 778const m = rest . match ( / ( ^ | \n ) ``` ([ ^ \n ` ] * ) \n / ); 779if ( ! m ) { html += blocks ( rest ); break ; } 780html += blocks ( rest . slice ( 0 , m . index )); 781rest = rest . slice ( m . index + m [ 0 ]. length ); 782const end = rest . match ( / ( ^ | \n ) ``` [ \t ] * ( \n | $ ) / ); 783if ( ! end ) { html += codeBlock ( m [ 2 ]. trim (), rest , false ); break ; } // still streaming: no preview of a half-written block 784html += codeBlock ( m [ 2 ]. trim (), rest . slice ( 0 , end . index ), true ); 785rest = rest . slice ( end . index + end [ 0 ]. length ); 786} 787return html ; 788} 789 790// ------------------------------------------------------------------ Chat 791// The sampling shown until the user changes it is the model card's thinking set. Untouched, the page sends NO sampling 792// fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking 793// 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two 794// values untouched counts as "not set" too. 795const DEFAULTS = { thinking :"high" , temperature :1.0 , top_p :0.95 , top_k :20 , max :"" , seed :"" , show :true , esp :true , mcp :true , math :false , 796chatList :false , chatEdit :false , whileBusy :"wait" }; 797const OLD_DEFAULT_TEMPERATURE = 0.6 ; 798function samplingUntouched ( s ) { 799const t = + s . temperature ; 800return ( t === DEFAULTS . temperature || t === OLD_DEFAULT_TEMPERATURE ) && + s . top_p === DEFAULTS . top_p && + s . top_k === DEFAULTS . top_k ; 801} 802let settings = { ...DEFAULTS , ...store . get ( "sampling" , {})}; 803if ( samplingUntouched ( settings )) settings . temperature = DEFAULTS . temperature ; 804let messages = store . get ( "chat" , []); // the open chat's messages (chats-ui.js: with the saved-chats list on, also that chat's own) 805let attachments = []; // {name, url} 806let busy = null ; // {controller, msg, cut, cutAfterTool} 807let pending = null ; // a message parked while an answer is written: {text, images, files, mode} 808function timeStr ( t ) { return new Date ( t ). toLocaleTimeString ([], { hour :"2-digit" , minute :"2-digit" }); } 809 810function msgEl ( m , i ) { 811const el = document . createElement ( "div" ); 812el . className = `st-msg st-msg-- ${ m . role } ` ; 813el . dataset . i = i ; 814if ( m . role === "user" ) { 815if ( m . files && m . files . length ) { 816const wrap = document . createElement ( "div" ); 817wrap . className = "msg-images" ; 818for ( const f of m . files ) { 819const c = document . createElement ( "span" ); 820c . className = "chip" ; 821c . innerHTML = icon ( "attach" , "st-icon st-icon--sm" ); 822c . append ( f . name ); 823wrap . appendChild ( c ); 824} 825el . appendChild ( wrap ); 826} 827if ( m . images && m . images . length ) { 828const wrap = document . createElement ( "div" ); 829wrap . className = "msg-images" ; 830for ( const im of m . images ) { 831if ( im . url ) { const img = document . createElement ( "img" ); img . src = im . url ; img . alt = im . name || tr ( "chat.image" , "image" ); wrap . appendChild ( img ); } 832else { const c = document . createElement ( "span" ); c . className = "chip" ; c . innerHTML = icon ( "image" , "st-icon st-icon--sm" ); c . append ( im . name || tr ( "chat.image" , "image" )); wrap . appendChild ( c ); } 833} 834el . appendChild ( wrap ); 835} 836const b = document . createElement ( "div" ); 837b . className = "st-bubble" ; 838b . textContent = m . text ; 839el . appendChild ( b ); 840const meta = document . createElement ( "div" ); 841meta . className = "st-msg__meta" ; 842meta . textContent = ` ${ tr ( "chat.you" , "You" )} · ${ timeStr ( m . time )} ` ; 843el . appendChild ( meta ); 844} else { 845el . innerHTML = `<details class="st-collapse think" hidden><summary> ${ icon ( "thinking" , "st-icon st-icon--sm" )} <span class="think-title"></span>` + 846` ${ icon ( "chevron" , "st-icon st-icon--sm st-chev" )} </summary><div class="st-collapse__body thinking"></div></details>` + 847`<div class="st-bubble"></div><div class="st-msg__meta"><span class="meta-text"></span>` + 848`<button class="st-btn st-btn--icon" data-msg-copy aria-label=" ${ esc ( tr ( "chat.copyAnswer" , "Copy the answer" ))} " title=" ${ esc ( tr ( "chat.copy" , "Copy" ))} "> ${ icon ( "copy" )} </button></div>` ; 849updateAssistant ( el , m , false ); 850} 851const actions = msgActions ( m , i ); // edit / regenerate / rewind (chats-ui.js), when switched on 852if ( actions ) el . appendChild ( actions ); 853return el ; 854} 855// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and 856// the result as the model read it. Its body is built only while open: a result can be 20,000 characters. 857const TOOL_STATE = { writing :[ "st-badge--reading" , () => tr ( "tool.writing" , "Writing" )], running :[ "st-badge--generating" , () => tr ( "tool.running" , "Running" )], 858done :[ "" , () => tr ( "tool.done" , "Done" )], error :[ "st-badge--error" , () => tr ( "tool.error" , "Error" )], 859skipped :[ "st-badge--queued" , () => tr ( "tool.skipped" , "Not run" )]}; 860function toolHtml ( t , k ) { 861const [ cls , labelOf ] = TOOL_STATE [ t . state ] || [ "" , () => t . state ]; 862const label = labelOf (); 863const args = t . arguments == null ?"" :JSON . stringify ( t . arguments , null , 2 ); 864const preview = t . result != null ?t . result :args . replace ( / \s +/ g , " " ); 865let body = "" ; 866if ( t . open ) { 867body = `<div class="tool-call__label"> ${ esc ( tr ( "tool.arguments" , "Arguments" ))} </div><pre class="tool-call__pre"> ${ esc ( args || tr ( "tool.beingWritten" , "(being written)" ))} </pre>` ; 868if ( t . result != null ) { 869body += `<div class="tool-call__label"> ${ esc ( t . ok ? tr ( "tool.result" , "Result" ) : tr ( "tool.error" , "Error" ))} ${ t . chars ? ` · ${ esc ( tr ( "tool.chars" , "{n} characters" , { n : fmt ( t . chars )}))} ` : "" } ` + 870` ${ t . truncated ? esc ( tr ( "tool.cut" , ", cut for the model" )) : "" } </div><pre class="tool-call__pre"> ${ esc ( t . result )} </pre>` ; 871} 872} 873return `<details class="st-collapse tool-call" data-tool=" ${ k } " data-state=" ${ esc ( t . state )} " ${ t . open ? " open" : "" } >` + 874`<summary> ${ icon ( "tool" , "st-icon st-icon--sm" )} <span class="tool-call__name" title=" ${ esc ( t . name || "" )} "> ${ esc ( t . tool || t . name || "tool" )} </span>` + 875( t . server ?`<span class="muted small"> ${ esc ( t . server )} </span>` :"" ) + 876`<span class="tool-call__preview muted"> ${ esc ( preview . slice ( 0 , 200 ))} </span>` + 877`<span class="st-badge ${ cls } "> ${ esc ( label )} </span> ${ t . ms != null && t . state !== "skipped" ? `<span class="muted small"> ${ fmt ( t . ms / 1000 , 1 )} s</span>` : "" } ` + 878` ${ icon ( "chevron" , "st-icon st-icon--sm st-chev" )} </summary><div class="st-collapse__body"> ${ body } </div></details>` ; 879} 880// Raster tool results are same-origin cached files; credentials stay in request headers. 881const mediaBlobs = new Map (); 882let mediaEpoch = 0 ; 883function clearToolMedia () { 884mediaEpoch ++ ; 885for ( const pending of mediaBlobs . values ()) pending . then (( url ) => URL . revokeObjectURL ( url ), () => {}); 886mediaBlobs . clear (); 887} 888window . addEventListener ( "pagehide" , clearToolMedia ); 889window . addEventListener ( "pageshow" , ( event ) => { if ( event . persisted ) hydrateToolImages ( document ); }); 890function safeToolMedia ( url ) { return typeof url === "string" && / ^tool-media\/ [ 0 - 9a - f ]{ 64 } \. ( png | jpg | webp ) $ / . test ( url ); } 891function toolImages ( t ) { 892return ( t . images || []). filter (( im ) => safeToolMedia ( im . url )). map (( im ) => 893`<figure class="tool-image"><img data-tool-image=" ${ esc ( im . url )} " alt="Tool image" loading="lazy">` + 894`<figcaption><a class="st-btn" data-tool-download=" ${ esc ( im . url )} " download=" ${ esc ( im . name || "generated-image.png" )} ">Download image</a></figcaption></figure>` ). join ( "" ); 895} 896function hydrateToolImages ( root ) { 897root . querySelectorAll ( "[data-tool-image]" ). forEach (( img ) => { 898const url = img . dataset . toolImage , epoch = mediaEpoch ; 899if ( ! safeToolMedia ( url )) return ; 900if ( ! mediaBlobs . has ( url )) mediaBlobs . set ( url , fetch ( url , { headers :headers ()}). then (( r ) => { 901if ( ! r . ok ) throw new Error ( "Image unavailable" ); 902return r . blob (); 903}). then (( b ) => URL . createObjectURL ( b )). catch (( e ) => { if ( epoch === mediaEpoch ) mediaBlobs . delete ( url ); throw e ;})); 904mediaBlobs . get ( url ). then (( blob ) => { 905if ( epoch !== mediaEpoch || ! img . isConnected ) return ; 906img . src = blob ; 907const a = img . closest ( "figure" ). querySelector ( "[data-tool-download]" ); 908a . href = blob ; 909}). catch (() => { img . alt = "Image unavailable; try refreshing" ; }); 910}); 911} 912// the answer's text with the tool blocks where the model called them 913// math (opt-in, serve/web/math.js): formulas become placeholders before the Markdown runs and are drawn after it 914function answerMarkdown ( text ) { 915return settings . math ?StrataMath . markdown ( text , markdown ) :markdown ( text ); 916} 917function answerHtml ( m ) { 918if ( ! m . tools || ! m . tools . length ) return answerMarkdown ( m . text || "" ); 919let html = "" , pos = 0 ; 920m . tools . forEach (( t , k ) => { 921const at = Math . min ( Math . max ( t . at || 0 , pos ), m . text . length ); 922if ( at > pos ) html += answerMarkdown ( m . text . slice ( pos , at )); 923pos = at ; 924html += toolHtml ( t , k ) + toolImages ( t ); 925}); 926return html + answerMarkdown ( m . text . slice ( pos )); 927} 928// a tool event from the stream (the `strata_mcp` field of a chunk) 929function onTool ( m , x ) { 930if ( x . event === "limit" ) { m . limit = x . max_rounds ; return ; } 931m . tools = m . tools || []; 932let t = m . tools . find (( y ) => y . id === x . id ); 933if ( ! t ) { t = { id :x . id , name :x . name , at :m . text . length , rat :m . reasoning . length , state :"writing" }; m . tools . push ( t ); } 934if ( x . event === "call" ) { 935Object . assign ( t , { name :x . name , server :x . server , tool :x . tool , arguments :x . arguments , round :x . round , state :"running" }); 936} else if ( x . event === "result" ) { 937Object . assign ( t , { result :x . text , ok :x . ok , chars :x . chars , truncated :x . truncated , ms :x . ms , images :x . images || [], vision :x . vision === true , 938state :x . skipped ?"skipped" :x . ok ?"done" :"error" }); 939} 940} 941function updateAssistant ( el , m , streaming ) { 942const det = el . querySelector ( "details.think" ); 943if ( m . reasoning ) { 944det . hidden = false ; 945const thinkingNow = streaming && ! m . text ; 946el . querySelector ( ".think-title" ). textContent = thinkingNow ?tr ( "think.now" , "Thinking…" ) : 947m . thinkSecs != null ?tr ( "think.for" , "Thought for {s} s" , { s :fmt ( m . thinkSecs , 1 )}) :tr ( "think.done" , "Thoughts" ); 948const body = el . querySelector ( ".thinking" ); 949if ( det . open || thinkingNow ) body . textContent = m . reasoning ; 950else body . dataset . pending = "1" ; 951// open while it streams (if wanted), closed once the answer starts - unless the user toggled it themselves 952if ( thinkingNow && settings . show && ! det . dataset . touched && ! det . open ) { det . _auto = true ; det . open = true ; } 953if ( ! thinkingNow && det . open && ! det . dataset . touched ) { det . _auto = true ; det . open = false ; } 954} 955const bubble = el . querySelector ( ".st-bubble" ); 956if ( m . error ) { 957bubble . innerHTML = `<div class="msg-error"></div>` ; 958bubble . firstChild . textContent = m . error ; 959} else if ( ! m . text && streaming && ! ( m . tools && m . tools . length )) { 960bubble . innerHTML = m . reasoning ?`<span class="muted cursor">Writing</span>` :`<span class="cursor"></span>` ; 961} else { 962bubble . innerHTML = answerHtml ( m ); 963hydrateToolImages ( bubble ); 964if ( settings . math ) StrataMath . hydrate ( bubble ); 965if ( streaming ) bubble . classList . add ( "cursor" ); else bubble . classList . remove ( "cursor" ); 966} 967el . querySelector ( ".meta-text" ). textContent = m . meta || ( streaming ?"" :m . stopped ?tr ( "chat.stopped" , "Stopped" ) :"" ); 968el . querySelector ( "[data-msg-copy]" ). hidden = streaming || ! m . text ; 969} 970function renderChat () { 971const chat = $ ( "chat" ); 972chat . querySelectorAll ( ".st-msg" ). forEach (( e ) => e . remove ()); 973$ ( "chat-empty" ). hidden = messages . length > 0 ; 974messages . forEach (( m , i ) => chat . appendChild ( msgEl ( m , i ))); 975renderSidebar (); 976renderParent (); 977renderUndoBar (); 978scrollDown ( true ); 979} 980// Follow the answer while the reader has not left (#4014). Asking "am I within 120 px of the bottom?" on every frame pulled 981// the view back after every wheel notch (a notch is about 100 px), so scrolling up during a long answer only worked by 982// dragging the scrollbar. Now the reader's own input lets go (wheel up, a finger or a key moving up, the scrollbar), and a 983// scroll back to the bottom follows again. 984let stickToBottom = true , lastReaderInput = 0 ; 985const FOLLOW_SLACK = 24 , FAR_AWAY = 400 , INPUT_WINDOW_MS = 400 ; 986function followAfterScroll ( distance , wasFollowing , msSinceInput ) { 987if ( distance <= FOLLOW_SLACK ) return true ; 988if ( msSinceInput <= INPUT_WINDOW_MS || distance > FAR_AWAY ) return false ; 989return wasFollowing ; 990} 991function scrollDown ( force ) { 992const s = $ ( "chat-scroll" ); 993if ( force ) stickToBottom = true ; 994if ( stickToBottom ) s . scrollTop = s . scrollHeight ; 995} 996( function watchReader () { 997const s = $ ( "chat-scroll" ); 998const touch = () => { lastReaderInput = Date . now (); }; 999s . addEventListener ( "wheel" , ( e ) => { touch (); if ( e . deltaY < 0 && s . scrollTop > 0 ) stickToBottom = false ; }, { passive :true }); 1000s . addEventListener ( "touchmove" , touch , { passive :true }); 1001s . addEventListener ( "pointerdown" , touch , { passive :true }); 1002s . addEventListener ( "keydown" , ( e ) => { 1003touch (); 1004if ([ "PageUp" , "ArrowUp" , "Home" ]. includes ( e . key ) && e . target === s && s . scrollTop > 0 ) stickToBottom = false ; 1005}); 1006s . addEventListener ( "scroll" , () => { 1007stickToBottom = followAfterScroll ( s . scrollHeight - s . scrollTop - s . clientHeight , stickToBottom , Date . now () - lastReaderInput ); 1008}, { passive :true }); 1009})(); 1010 1011$ ( "chat" ). addEventListener ( "click" , ( e ) => { 1012const cc = e . target . closest ( "[data-code-copy]" ); 1013if ( cc ) { copyText ( cc . closest ( ".st-code" ). querySelector ( "pre" ). textContent , cc ); return ; } 1014// an svg/html block: flip between its code and its sandboxed preview. Closing the preview also turns scripts off. 1015const pv = e . target . closest ( "[data-preview-toggle]" ); 1016if ( pv ) { 1017const box = pv . closest ( ".st-code" ); 1018const on = box . dataset . preview === "true" ; 1019if ( on ) delete box . dataset . preview ; else box . dataset . preview = "true" ; 1020pv . setAttribute ( "aria-pressed" , String ( ! on )); 1021pv . setAttribute ( "aria-label" , on ?pv . dataset . previewLabel :tr ( "preview.showCode" , "Show the code" )); 1022const fr = box . querySelector ( "iframe" ); 1023if ( on ) fillPreview ( fr , false , true ); 1024else if ( ! fr . dataset . opened ) fillPreview ( fr , false ); 1025return ; 1026} 1027const rs = e . target . closest ( "[data-preview-scripts]" ); 1028if ( rs ) { 1029const fr = rs . closest ( ".st-code" ). querySelector ( "iframe" ); 1030const run = fr . dataset . scripts !== "1" ; 1031if ( run && ! confirm ( tr ( "preview.confirm" , "Run this code with scripts?\n\nIt runs in your browser, cut off from this chat and from the network, but it can still freeze the tab, and it is code the model wrote.\n\nOnly this block, and only until you close the preview." ))) return ; 1032fillPreview ( fr , run ); 1033return ; 1034} 1035const mc = e . target . closest ( "[data-msg-copy]" ); 1036if ( mc ) { const i = + mc . closest ( ".st-msg" ). dataset . i ; copyText ( messages [ i ]. text , mc ); return ; } 1037// a tool block: its open state lives in the message (the answer is rebuilt while it streams), so the click sets it 1038const sum = e . target . closest ( ".tool-call > summary" ); 1039if ( sum ) { 1040e . preventDefault (); 1041const el = sum . closest ( ".st-msg" ), m = messages [ + el . dataset . i ], t = m && m . tools && m . tools [ + sum . parentElement . dataset . tool ]; 1042if ( ! t ) return ; 1043t . open = ! t . open ; 1044updateAssistant ( el , m , !! busy && busy . msg === m ); 1045} 1046}); 1047$ ( "chat" ). addEventListener ( "toggle" , ( e ) => { 1048const d = e . target ; 1049if ( d . tagName !== "DETAILS" || ! d . classList . contains ( "think" )) return ; 1050if ( d . _auto ) { d . _auto = false ; return ; } // our own open/close, not the user's 1051d . dataset . touched = "1" ; 1052const body = d . querySelector ( ".thinking" ); 1053if ( d . open && body . dataset . pending ) { body . textContent = messages [ + d . closest ( ".st-msg" ). dataset . i ]. reasoning ; delete body . dataset . pending ; } 1054}, true ); 1055 1056function apiMessages () { 1057const out = []; 1058for ( const m of messages ) { 1059if ( m . role === "user" ) { 1060const imgs = ( m . images || []). filter (( i ) => i . url ); 1061const text = userText ( m ); 1062out . push ({ role :"user" , content :imgs . length ?[{ type :"text" , text}, 1063 ...imgs . map (( i ) => ({ type :"image_url" , image_url :{ url :i . url }}))] :text }); 1064} else if ( ! ( busy && busy . msg === m )) { // the answer being asked for now is not history yet 1065out . push ( ...assistantMessages ( m )); 1066} 1067} 1068return out ; 1069} 1070// An answer that used MCP tools goes back as the model wrote it: per round the text before the calls, the calls and 1071// their results (as the model read them), then the rest - so the next question can build on what the tools found. 1072function assistantMessages ( m ) { 1073const ran = ( m . tools || []). filter (( t ) => t . round != null && t . result != null && t . state !== "skipped" ); 1074// #1392: a turn with no answer text (only reasoning, a stop before the first content token, or an error) still goes 1075// back as an assistant turn, so the history keeps alternating and a reasoning model sees that it already answered. 1076// The server leaves such a turn out of the prompt itself (serve/frontend.py, #843); reasoning_content rides along. 1077if ( ! ran . length ) { 1078const msg = { role :"assistant" , content :m . text || "" }; 1079if ( ! m . text && m . reasoning ) msg . reasoning_content = m . reasoning ; 1080return [ msg ]; 1081} 1082const out = []; 1083let pos = 0 ; 1084for ( const r of [ ...new Set ( ran . map (( t ) => t . round ))]) { 1085const calls = ran . filter (( t ) => t . round === r ); 1086const at = Math . min ( Math . max ( pos , calls [ 0 ]. at || 0 ), m . text . length ); 1087out . push ({ role :"assistant" , content :m . text . slice ( pos , at ). trim (), 1088tool_calls :calls . map (( t ) => ({ id :t . id , type :"function" , function :{ name :t . name , arguments :JSON . stringify ( t . arguments || {})}}))}); 1089for ( const t of calls ) { 1090const pictures = t . vision ?( t . images || []). filter (( im ) => safeToolMedia ( im . url )) :[]; 1091const content = pictures . length ?[{ type :"text" , text :t . result }, ...pictures . map (( im ) => 1092({ type :"image_url" , image_url :{ url :"strata-tool-media:" + im . url . split ( "/" ). pop ()}}))] :t . result ; 1093out . push ({ role :"tool" , tool_call_id :t . id , content}); 1094} 1095pos = at ; 1096} 1097const rest = m . text . slice ( pos ). trim (); 1098if ( rest ) out . push ({ role :"assistant" , content :rest }); 1099return out ; 1100} 1101 1102function busyHint () { 1103const mode = settings . whileBusy ; 1104return mode === "queue" ?tr ( "composer.hintQueue" , "Enter sends when the answer is done" ) 1105 :mode === "interject" ?tr ( "composer.hintInterject" , "Enter stops the answer here and sends now" ) :"" ; 1106} 1107// While an answer is written, Send is off ("wait", as always) or parks the message ("queue", "interject": Chat settings) 1108const parksWhileBusy = () => settings . whileBusy === "queue" || settings . whileBusy === "interject" ; 1109function setBusy ( on ) { 1110$ ( "stop-btn" ). hidden = ! on ; 1111$ ( "send-btn" ). disabled = ( on && ! parksWhileBusy ()) || !! panel ; 1112$ ( "input" ). disabled = !! panel ; 1113$ ( "composer-hint" ). textContent = panel ?tr ( "composer.finishOpen" , "Save or cancel what is open above to continue" ) 1114 :on ?busyHint () :tr ( "composer.newline" , "Shift+Enter: new line" ); 1115if ( settings . chatEdit ) syncActions (); // the buttons follow the state: none under the answer being written 1116$ ( "s-list" ). disabled = $ ( "s-edit" ). disabled = !! busy || !! panel ; // they change the messages on the screen 1117renderUndoBar (); 1118renderPending (); 1119} 1120 1121// A message sent while an answer is being written (#4004). "queue": it waits and goes when the answer is done. "interject": the 1122// answer stops where it is (what is written stays, marked interrupted) and the message goes at once; if a tool is running, the 1123// tool finishes first. Only one message waits. Off by default: with "wait" the page does nothing, as before. 1124function park ( p , own ) { 1125if ( ! parksWhileBusy ()) return ; 1126if ( pending ) { toast ( "warn" , tr ( "pending.one" , "A message is already waiting" ), tr ( "pending.oneText" , "Take it back or wait until it is sent." )); return ; } 1127pending = { ...p , mode :settings . whileBusy }; 1128if ( own ) { attachments = []; renderAttachments (); $ ( "input" ). value = "" ; autosize (); } 1129if ( pending . mode === "interject" ) requestCut (); 1130setBusy ( !! busy ); 1131} 1132function requestCut () { 1133if ( ! busy || busy . cut ) return ; 1134if (( busy . msg . tools || []). some (( t ) => t . state === "running" )) { busy . cutAfterTool = true ; return ; } // let the tool finish 1135busy . cut = true ; 1136busy . controller . abort (); 1137} 1138function renderPending () { 1139let el = $ ( "pending" ); 1140if ( ! pending ) { if ( el ) el . remove (); return ; } 1141if ( ! el ) { 1142el = node ( "div" , "pending" ); 1143el . id = "pending" ; 1144el . setAttribute ( "role" , "status" ); 1145el . innerHTML = "<span class=\"pending__text\"></span><span class=\"pending__actions\"><button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-now></button>" + 1146"<button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-back></button></span>" ; 1147el . querySelector ( "[data-pending-now]" ). onclick = pendingNow ; 1148el . querySelector ( "[data-pending-back]" ). onclick = releasePending ; 1149$ ( "composer" ). before ( el ); 1150} 1151const quote = ( pending . text || ( pending . files [ 0 ] || pending . images [ 0 ] || {}). name || "" ). replace ( / \s +/ g , " " ). slice ( 0 , 70 ); 1152const text = ! busy ?tr ( "pending.ready" , "Not sent yet: “{text}”" , { text :quote }) 1153 :pending . mode === "queue" ?tr ( "pending.queued" , "Sends when this answer is done: “{text}”" , { text :quote }) 1154 :busy . cutAfterTool ?tr ( "pending.afterTool" , "Waiting for the tool to finish, then sending: “{text}”" , { text :quote }) 1155 :tr ( "pending.cutting" , "Stopping the answer, then sending: “{text}”" , { text :quote }); 1156el . querySelector ( ".pending__text" ). textContent = text ; 1157const now = el . querySelector ( "[data-pending-now]" ); 1158now . textContent = busy ?tr ( "pending.sendNow" , "Send now" ) :tr ( "pending.send" , "Send" ); 1159now . hidden = !! busy && pending . mode === "interject" ; // already on its way 1160el . querySelector ( "[data-pending-back]" ). textContent = tr ( "pending.takeBack" , "Take back" ); 1161} 1162function pendingNow () { 1163if ( ! pending ) return ; 1164if ( busy ) { pending . mode = "interject" ; requestCut (); setBusy ( true ); return ; } 1165const p = pending ; 1166pending = null ; 1167setBusy ( false ); 1168send ( p ); 1169} 1170// the waiting message goes back into the message box (a chat switch or a new chat must not lose it) 1171function releasePending () { 1172if ( ! pending ) return ; 1173const p = pending ; 1174pending = null ; 1175if ( ! $ ( "input" ). value . trim ()) $ ( "input" ). value = p . text ; 1176else $ ( "input" ). value = ` ${ p . text } \n\n ${ $ ( "input" ). value } ` ; 1177attachments = [ ...p . images , ...p . files , ...attachments ]; 1178renderAttachments (); autosize (); 1179setBusy ( !! busy ); 1180} 1181// after an answer: an interrupted one sends an interjection, a finished one sends a queued message 1182function settlePending ( cut , finished ) { 1183if ( ! pending ) return ; 1184if (( pending . mode === "interject" && cut ) || ( pending . mode === "queue" && finished )) { 1185const p = pending ; 1186pending = null ; 1187setBusy ( false ); 1188send ( p ); 1189} 1190} 1191 1192// the message box (or a parked message, `payload`) becomes a user turn and a reply is asked for 1193async function send ( payload ) { 1194const own = ! payload ; 1195const p = payload || { text :$ ( "input" ). value . trim (), images :attachments . filter (( a ) => a . kind !== "file" ), 1196files :attachments . filter (( a ) => a . kind === "file" )}; 1197if ( ! p . text && ! p . images . length && ! p . files . length ) return ; 1198if ( panel ) return ; // something is open above (an edit): finish it first 1199if ( busy ) { park ( p , own ); return ; } 1200clearUndo (); 1201messages . push ({ role :"user" , text :p . text , images :p . images , files :p . files , time :Date . now ()}); 1202if ( own ) { 1203attachments = []; 1204renderAttachments (); 1205$ ( "input" ). value = "" ; 1206autosize (); 1207} 1208return generateReply (); 1209} 1210// an answer for the messages as they are: the last one is a user turn 1211async function generateReply () { 1212const m = { role :"assistant" , text :"" , reasoning :"" , time :Date . now ()}; 1213messages . push ( m ); 1214renderChat (); 1215const el = $ ( "chat" ). lastElementChild ; 1216const controller = new AbortController (); 1217busy = { controller, msg :m , cut :false , cutAfterTool :false }; 1218setBusy ( true ); 1219paintLive (); 1220 1221const body = { model :health . model , messages :apiMessages (), stream :true , 1222reasoning_effort :settings . thinking }; 1223if ( ! ( settings . temperature > 0 )) { 1224body . temperature = 0 ; 1225} else if ( ! samplingUntouched ( settings )) { 1226Object . assign ( body , { temperature :+ settings . temperature , top_p :+ settings . top_p , top_k :+ settings . top_k }); 1227} 1228if ( settings . seed ) body . seed = + settings . seed ; 1229if ( settings . max ) body . max_tokens = + settings . max ; 1230if ( projectionLoaded ()) body . experimental_speed_projection = !! settings . esp ; 1231if ( settings . mcp !== false && mcpInfo . tools > 0 ) body . strata_mcp = true ; // this server may run MCP tools for it 1232 1233let firstAt = null , thinkStart = null , usage = null , frame = 0 ; 1234const paint = () => { frame = 0 ; updateAssistant ( el , m , true ); scrollDown (); }; 1235try { 1236const r = await fetch ( "v1/chat/completions" , { method :"POST" , headers :headers ( true ), body :JSON . stringify ( body ), 1237signal :controller . signal }); 1238if ( ! r . ok ) { 1239let msg = `HTTP ${ r . status } ` ; 1240try { msg = ( await r . json ()). error . message || msg ; } catch ( e ) { /* not json */ } 1241if ( r . status === 401 ) msg = tr ( "toast.keyNeeded" , "This server needs an API key: add it under About > Settings." ); 1242throw new Error ( msg ); 1243} 1244const reader = r . body . getReader (), dec = new TextDecoder (); 1245let buf = "" ; 1246for (;;) { 1247const { value, done} = await reader . read (); 1248if ( done ) break ; 1249buf += dec . decode ( value , { stream :true }); 1250let nl ; 1251while (( nl = buf . indexOf ( "\n" )) >= 0 ) { 1252const line = buf . slice ( 0 , nl ). trim (); 1253buf = buf . slice ( nl + 1 ); 1254if ( ! line . startsWith ( "data:" )) continue ; // ": keep-alive" comments while a long prompt is read 1255const data = line . slice ( 5 ). trim (); 1256if ( data === "[DONE]" ) continue ; 1257let j ; 1258try { j = JSON . parse ( data ); } catch ( e ) { continue ; } 1259if ( j . error ) throw new Error ( j . error . message || tr ( "toast.engineError" , "the engine reported an error" )); 1260if ( j . usage ) usage = j . usage ; 1261if ( j . strata_mcp ) { 1262onTool ( m , j . strata_mcp ); 1263// an interjection waited for a running tool: it has its result now, so the answer can stop 1264if ( busy . cutAfterTool && ! busy . cut && ! ( m . tools || []). some (( t ) => t . state === "running" )) { busy . cut = true ; controller . abort (); } 1265} 1266const d = ( j . choices && j . choices [ 0 ] && j . choices [ 0 ]. delta ) || {}; 1267const lastTool = m . tools && m . tools . length ?m . tools [ m . tools . length - 1 ] :null ; // a new round after a tool 1268if ( d . reasoning_content ) { 1269if ( ! firstAt ) firstAt = performance . now (); 1270if ( ! thinkStart ) thinkStart = performance . now (); 1271if ( lastTool && m . reasoning && lastTool . rat === m . reasoning . length ) m . reasoning += "\n\n" ; 1272m . reasoning += d . reasoning_content ; 1273} 1274if ( d . content ) { 1275if ( ! firstAt ) firstAt = performance . now (); 1276if ( thinkStart && m . thinkSecs == null ) m . thinkSecs = ( performance . now () - thinkStart ) / 1000 ; 1277if ( lastTool && m . text && lastTool . at === m . text . length ) m . text += "\n\n" ; 1278m . text += d . content ; 1279} 1280if ( ! frame ) frame = requestAnimationFrame ( paint ); 1281} 1282} 1283} catch ( e ) { 1284if ( e . name === "AbortError" ) m . stopped = true ; 1285else { m . error = e . message || String ( e ); toast ( "error" , tr ( "toast.requestFailed" , "The request failed" ), m . error , 6000 ); } 1286} 1287const cut = busy . cut ; // an interjection ended it: kept as written, marked interrupted 1288if ( cut ) m . interrupted = true ; 1289if ( thinkStart && m . thinkSecs == null ) m . thinkSecs = ( performance . now () - thinkStart ) / 1000 ; 1290const n = usage ?usage . completion_tokens :null ; 1291const ended = cut ?tr ( "chat.interruptedLower" , "interrupted" ) :tr ( "chat.stoppedLower" , "stopped" ); 1292if ( n && firstAt ) { 1293const secs = ( performance . now () - firstAt ) / 1000 ; 1294m . meta = tr ( "chat.tokens" , "{n} tokens" , { n :fmt ( n )}) + ( secs > 0.25 ?` · ${ fmt ( n / secs , 1 )} tok/s` :"" ) + ( m . stopped ?` · ${ ended } ` :"" ) + 1295( projectionLoaded () ?( settings . esp ?` · ${ tr ( "chat.projectionOn" , "projection on" )} ` :` · ${ tr ( "chat.projectionOff" , "projection off" )} ` ) :"" ); 1296} else if ( m . stopped ) { 1297m . meta = cut ?tr ( "chat.interrupted" , "Interrupted" ) :tr ( "chat.stopped" , "Stopped" ); 1298} 1299for ( const t of m . tools || []) if ( t . state === "writing" || t . state === "running" ) { t . state = "skipped" ; t . ms = null ; } 1300const ran = ( m . tools || []). filter (( t ) => t . state === "done" || t . state === "error" ). length ; 1301if ( ran ) m . meta = ` ${ m . meta ? ` ${ m . meta } · ` : "" } ${ tr ( "chat.toolCalls" , { one : "{n} tool call" , other : "{n} tool calls" }, { n : ran })} ` ; 1302if ( m . limit ) m . meta = ` ${ m . meta || "" } · ${ tr ( "chat.toolLimit" , "stopped at the limit of {n} tool rounds (mcp.max_rounds)" , { n : m . limit })} ` ; 1303busy = null ; 1304setBusy ( false ); 1305paintLive (); 1306if ( frame ) cancelAnimationFrame ( frame ); 1307updateAssistant ( el , m , false ); 1308saveChat (); 1309scrollDown (); 1310settlePending ( cut , ! m . stopped && ! m . error ); 1311} 1312 1313$ ( "composer" ). onsubmit = ( e ) => { e . preventDefault (); send (); }; 1314$ ( "stop-btn" ). onclick = () => { if ( busy ) busy . controller . abort (); }; 1315$ ( "input" ). addEventListener ( "keydown" , ( e ) => { 1316if ( e . key === "Enter" && ! e . shiftKey && ! e . isComposing ) { e . preventDefault (); send (); } 1317}); 1318function autosize () { const t = $ ( "input" ); t . style . height = "auto" ; t . style . height = ` ${ Math . min ( t . scrollHeight , innerHeight * 0.4 )} px` ; } 1319$ ( "input" ). addEventListener ( "input" , autosize ); 1320 1321// one chat, as before: New chat clears it, with an Undo (with the saved-chats list on, its own New chat button does this job) 1322$ ( "new-btn" ). onclick = () => { 1323if ( busy ) { stillWriting (); return ; } 1324if ( panel ) { closePanel (); } 1325clearUndo (); 1326releasePending (); 1327if ( ! messages . length ) return ; 1328const backup = messages ; 1329clearToolMedia (); 1330messages = []; 1331saveChat (); 1332renderChat (); 1333toast ( "info" , tr ( "chat.newToast" , "New chat" ), tr ( "chat.clearedToast" , "The last one was cleared." ), 6000 , { label :tr ( "undo" , "Undo" ), run :() => { 1334if ( busy || messages . length ) return ; // a new question since: the cleared chat is not put back over it 1335messages = backup ; saveChat (); renderChat (); 1336}}); 1337}; 1338$ ( "export-btn" ). onclick = () => { 1339if ( ! messages . length ) { toast ( "info" , tr ( "export.nothing" , "Nothing to save yet" )); return ; } 1340const tools = ( m ) => ( m . tools || []). filter (( t ) => t . result != null ). map (( t ) => 1341`<details><summary>Tool ${ t . server ? ` ${ t . server } / ` : "" } ${ t . tool || t . name } ${ t . ok ? "" : " (error)" } </summary>\n\n` + 1342`\`\`\`json\n ${ JSON . stringify ( t . arguments || {}, null , 2 )} \n\`\`\`\n\n\`\`\`\n ${ t . result } \n\`\`\`\n\n</details>\n\n` ). join ( "" ); 1343const md = messages . map (( m ) => m . role === "user" ?`## You\n\n ${ m . text } \n` : 1344`## ${ health . model } \n\n ${ m . reasoning ? `<details><summary>Thinking</summary>\n\n ${ m . reasoning } \n\n</details>\n\n` : "" } ${ tools ( m )} ${ m . text || m . error || "" } \n` ). join ( "\n" ); 1345const a = document . createElement ( "a" ); 1346a . href = URL . createObjectURL ( new Blob ([ md ], { type :"text/markdown" })); 1347a . download = `strata-chat- ${ new Date (). toISOString (). slice ( 0 , 16 ). replace ( / [: T ] / g , "-" )} .md` ; 1348a . click (); 1349setTimeout (() => URL . revokeObjectURL ( a . href ), 5000 ); 1350}; 1351 1352// pictures and text files: the attach button, dropping them on the chat, or pasting a picture (issue #30) 1353const TEXT_EXT = / \. ( txt | md | markdown | rst | tex | py | pyi | ipynb | js | mjs | cjs | ts | tsx | jsx | vue | svelte | json | jsonl | csv | tsv | log | ya ? ml | toml | ini | cfg | conf | env | xml | html ?| css | scss | less | c | cc | cpp | cxx | h | hh | hpp | cu | cuh | rs | go | java | kt | kts | swift | rb | php | pl | lua | r | jl | scala | sql | sh | bash | zsh | fish | ps1 | psm1 | bat | cmd | diff | patch | gradle | cmake | mk | dockerfile | gitignore | proto | graphql ) $ / i ; 1354const MAX_TEXT_FILE = 512 * 1024 ; 1355function isTextFile ( f ) { 1356return f . type . startsWith ( "text/" ) || / json | xml | javascript | yaml | toml | x-sh | x-python / . test ( f . type ) || 1357TEXT_EXT . test ( f . name ) || / ( ^ | [ \\ / ])( makefile | dockerfile | readme | license ) $ / i . test ( f . name ); 1358} 1359function addFiles ( files ) { 1360for ( const f of files ) { 1361if ( f . type . startsWith ( "image/" )) { 1362if ( ! health . images ) { toast ( "warn" , tr ( "file.picturesOff" , "Pictures are off" ), tr ( "file.picturesOffText" , "This model was set up for text only." )); continue ; } 1363if ( f . size > 20e6 ) { toast ( "warn" , tr ( "file.pictureBig" , "Picture too large" ), tr ( "file.pictureBigText" , "{name} is over 20 MB." , { name :f . name })); continue ; } 1364const r = new FileReader (); 1365r . onload = () => { attachments . push ({ kind :"image" , name :f . name || tr ( "file.pasted" , "pasted image" ), url :r . result }); renderAttachments (); }; 1366r . readAsDataURL ( f ); 1367continue ; 1368} 1369if ( ! isTextFile ( f )) { toast ( "warn" , tr ( "file.notText" , "Not a text file" ), health . images ?tr ( "file.notTextPictures" , "{name}: attach text files (code, notes, logs, data) or pictures." , { name :f . name }) 1370 :tr ( "file.notTextOnly" , "{name}: attach text files (code, notes, logs, data)." , { name :f . name })); continue ; } 1371if ( f . size > MAX_TEXT_FILE ) { toast ( "warn" , tr ( "file.big" , "File too large" ), tr ( "file.bigText" , "{name} is over 512 KB." , { name :f . name })); continue ; } 1372const r = new FileReader (); 1373r . onload = () => { 1374const text = String ( r . result ); 1375if ( text . includes ( "\u0000" )) { toast ( "warn" , tr ( "file.notText" , "Not a text file" ), tr ( "file.binaryText" , "{name} looks like a binary file." , { name :f . name })); return ; } 1376attachments . push ({ kind :"file" , name :f . name , text}); 1377renderAttachments (); 1378}; 1379r . readAsText ( f ); 1380} 1381} 1382// a file's text in the message, fenced with more backticks than it contains itself 1383function fileBlock ( f ) { 1384const longest = Math . max ( 2 , ...( f . text . match ( / ` +/ g ) || []). map (( s ) => s . length )); 1385const fence = "`" . repeat ( longest + 1 ); 1386return `File: ${ f . name } \n ${ fence } \n ${ f . text } \n ${ fence } ` ; 1387} 1388function userText ( m ) { 1389const files = ( m . files || []). filter (( f ) => f . text != null ); 1390return [ m . text , ...files . map ( fileBlock )]. filter (( s ) => s ). join ( "\n\n" ); 1391} 1392function renderAttachments () { 1393const box = $ ( "attachments" ); 1394box . hidden = ! attachments . length ; 1395box . innerHTML = "" ; 1396attachments . forEach (( a , i ) => { 1397const c = document . createElement ( "span" ); 1398c . className = "chip" ; 1399c . innerHTML = icon ( a . kind === "file" ?"attach" :"image" , "st-icon st-icon--sm" ); 1400c . append ( a . name ); 1401const x = document . createElement ( "button" ); 1402x . type = "button" ; x . className = "st-btn st-btn--icon" ; x . setAttribute ( "aria-label" , tr ( "file.remove" , "Remove" )); 1403x . innerHTML = icon ( "trash" ); 1404x . onclick = () => { attachments . splice ( i , 1 ); renderAttachments (); }; 1405c . appendChild ( x ); 1406box . appendChild ( c ); 1407}); 1408} 1409$ ( "attach-btn" ). onclick = () => $ ( "file" ). click (); 1410// drop files on the chat or the message box 1411for ( const id of [ "chat" , "composer" ]) { 1412const el = $ ( id ); 1413el . addEventListener ( "dragover" , ( e ) => { 1414if ( ! [ ...( e . dataTransfer || {}). types || []]. includes ( "Files" )) return ; 1415e . preventDefault (); 1416$ ( "composer" ). classList . add ( "dragging" ); 1417}); 1418el . addEventListener ( "dragleave" , () => $ ( "composer" ). classList . remove ( "dragging" )); 1419el . addEventListener ( "drop" , ( e ) => { 1420$ ( "composer" ). classList . remove ( "dragging" ); 1421if ( ! e . dataTransfer || ! e . dataTransfer . files . length ) return ; 1422e . preventDefault (); 1423addFiles ( e . dataTransfer . files ); 1424$ ( "input" ). focus (); 1425}); 1426} 1427$ ( "file" ). onchange = () => { addFiles ( $ ( "file" ). files ); $ ( "file" ). value = "" ; }; 1428$ ( "input" ). addEventListener ( "paste" , ( e ) => { 1429if ( ! health . images ) return ; 1430const files = [ ...( e . clipboardData || {}). files || []]. filter (( f ) => f . type . startsWith ( "image/" )); 1431if ( files . length ) { e . preventDefault (); addFiles ( files ); } 1432}); 1433 1434// ------------------------------------------------------------------ the chat settings drawer 1435function openDrawer ( open ) { 1436$ ( "drawer" ). dataset . open = String ( open ); 1437$ ( "drawer" ). setAttribute ( "aria-hidden" , String ( ! open )); 1438$ ( "scrim" ). hidden = ! open ; 1439if ( open ) { loadDrawer (); loadShared (); loadMcp (); } 1440} 1441const checked = ( id ) => $ ( id ). getAttribute ( "aria-checked" ) === "true" ; 1442const segValue = ( id ) => { const b = [ ...$ ( id ). children ]. find (( x ) => x . getAttribute ( "aria-checked" ) === "true" ); return b ?b . dataset . v :null ; }; 1443function loadDrawer ( s = settings ) { 1444for ( const b of $ ( "s-thinking" ). children ) b . setAttribute ( "aria-checked" , String ( b . dataset . v === s . thinking )); 1445$ ( "s-temp" ). value = s . temperature ; $ ( "s-topp" ). value = s . top_p ; $ ( "s-topk" ). value = s . top_k ; 1446$ ( "s-max" ). value = s . max ; $ ( "s-seed" ). value = s . seed ; 1447$ ( "s-math" ). setAttribute ( "aria-checked" , String ( !! s . math )); 1448$ ( "s-show" ). setAttribute ( "aria-checked" , String ( !! s . show )); 1449$ ( "s-esp" ). setAttribute ( "aria-checked" , String ( s . esp !== false )); 1450$ ( "esp-row" ). hidden = ! projectionLoaded (); 1451$ ( "s-mcp" ). setAttribute ( "aria-checked" , String ( s . mcp !== false )); 1452$ ( "s-share" ). setAttribute ( "aria-checked" , String ( sharedOn )); 1453$ ( "s-list" ). setAttribute ( "aria-checked" , String ( !! s . chatList )); 1454$ ( "s-edit" ). setAttribute ( "aria-checked" , String ( !! s . chatEdit )); 1455for ( const b of $ ( "s-busy" ). children ) b . setAttribute ( "aria-checked" , String ( b . dataset . v === ( s . whileBusy || "wait" ))); 1456outputs (); 1457} 1458// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings) 1459let sharedOn = false ; 1460async function loadShared () { 1461try { 1462const r = await fetch ( "settings" , { headers :headers ()}); 1463if ( r . ok ) sharedOn = !! ( await r . json ()). shared ; 1464} catch ( e ) { /* an older server: the switch just stays off */ } 1465$ ( "s-share" ). setAttribute ( "aria-checked" , String ( sharedOn )); 1466} 1467function sharedDefaults ( s ) { 1468const d = { reasoning_effort :s . thinking }; 1469if ( ! ( + s . temperature > 0 )) d . temperature = 0 ; 1470else if ( ! samplingUntouched ( s )) Object . assign ( d , { temperature :+ s . temperature , top_p :+ s . top_p , top_k :+ s . top_k }); 1471if ( s . seed ) d . seed = + s . seed ; 1472if ( s . max ) d . max_tokens = + s . max ; 1473if ( projectionLoaded ()) d . experimental_speed_projection = s . esp !== false ; 1474return d ; 1475} 1476async function saveShared ( on , s ) { 1477const r = await fetch ( "settings" , { method :"POST" , headers :headers ( true ), 1478body :JSON . stringify ({ defaults :on ?sharedDefaults ( s ) :null })}); 1479if ( ! r . ok ) { 1480let msg = `HTTP ${ r . status } ` ; 1481try { msg = ( await r . json ()). error . message || msg ; } catch ( e ) { /* not json */ } 1482throw new Error ( msg ); 1483} 1484sharedOn = !! ( await r . json ()). shared ; 1485} 1486// the engine was started with the experimental-speed-projection control vector (INFO cvec=...) 1487function projectionLoaded () { 1488const c = lastMetrics && lastMetrics . engine ?lastMetrics . engine . cvec :0 ; 1489return !! c && c !== "0" ; 1490} 1491function outputs () { 1492const t = + $ ( "s-temp" ). value ; 1493$ ( "o-temp" ). textContent = t === 0 ?tr ( "drawer.greedy" , "0 · greedy" ) :t . toFixed ( 2 ); 1494$ ( "o-topp" ). textContent = ( + $ ( "s-topp" ). value ). toFixed ( 2 ); 1495$ ( "o-topk" ). textContent = $ ( "s-topk" ). value ; 1496const sel = segValue ( "s-thinking" ); 1497$ ( "o-thinking" ). textContent = sel ?{ none :tr ( "drawer.thinkNone" , "answers right away" ), low :tr ( "drawer.thinkLow" , "short" ), 1498medium :tr ( "drawer.thinkMedium" , "medium" ), high :tr ( "drawer.thinkHigh" , "thorough (default)" )}[ sel ] :"" ; 1499const busyMode = segValue ( "s-busy" ); 1500$ ( "o-busy" ). textContent = { wait :tr ( "drawer.busyWaitNote" , "Send is off until the answer is done, as before." ), 1501queue :tr ( "drawer.busyQueueNote" , "Your message waits and goes as soon as the answer is done." ), 1502interject :tr ( "drawer.busyInterjectNote" , "The answer stops where it is (what is written stays) and your message goes at once. A tool that is running finishes first." )}[ busyMode ] || "" ; 1503for ( const id of [ "s-topp" , "s-topk" ]) $ ( id ). disabled = t === 0 ; 1504} 1505for ( const b of $ ( "s-thinking" ). children ) b . onclick = () => { for ( const x of $ ( "s-thinking" ). children ) x . setAttribute ( "aria-checked" , String ( x === b )); outputs (); }; 1506for ( const b of $ ( "s-busy" ). children ) b . onclick = () => { for ( const x of $ ( "s-busy" ). children ) x . setAttribute ( "aria-checked" , String ( x === b )); outputs (); }; 1507for ( const id of [ "s-temp" , "s-topp" , "s-topk" ]) $ ( id ). oninput = outputs ; 1508for ( const id of [ "s-math" , "s-show" , "s-esp" , "s-mcp" , "s-share" , "s-list" , "s-edit" ]) { 1509$ ( id ). onclick = () => $ ( id ). setAttribute ( "aria-checked" , String ( $ ( id ). getAttribute ( "aria-checked" ) !== "true" )); 1510} 1511$ ( "s-reset" ). onclick = () => loadDrawer ( DEFAULTS ); 1512$ ( "s-apply" ). onclick = async () => { 1513const prev = settings ; 1514// the list and the edit controls change the messages on the screen: not while an answer is written or something is open 1515const locked = !! busy || !! panel ; 1516settings = { thinking :segValue ( "s-thinking" ) || "high" , temperature :+ $ ( "s-temp" ). value , top_p :+ $ ( "s-topp" ). value , 1517top_k :+ $ ( "s-topk" ). value , max :$ ( "s-max" ). value . trim (), seed :$ ( "s-seed" ). value . trim (), 1518math :checked ( "s-math" ), show :checked ( "s-show" ), esp :checked ( "s-esp" ), mcp :checked ( "s-mcp" ), 1519chatList :locked ?!! prev . chatList :checked ( "s-list" ), chatEdit :locked ?!! prev . chatEdit :checked ( "s-edit" ), 1520whileBusy :segValue ( "s-busy" ) || "wait" }; 1521store . set ( "sampling" , settings ); 1522StrataMath . reset (); // math on or off: every answer is drawn again 1523if ( settings . chatList !== !! prev . chatList ) await setChatList ( settings . chatList , true ); 1524if ( settings . chatEdit !== !! prev . chatEdit ) { clearUndo (); syncActions (); } 1525if ( settings . whileBusy === "wait" && pending ) releasePending (); // "wait" parks nothing: a waiting message goes back to the box 1526setBusy ( !! busy ); 1527for ( const el of $ ( "chat" ). querySelectorAll ( ".st-msg--assistant" )) { 1528const m = messages [ + el . dataset . i ]; 1529updateAssistant ( el , m , !! busy && busy . msg === m ); // the element send() holds stays the same while an answer streams 1530} 1531const share = checked ( "s-share" ); 1532openDrawer ( false ); 1533if ( share || sharedOn ) { 1534try { 1535await saveShared ( share , settings ); 1536toast ( "success" , tr ( "drawer.saved" , "Chat settings saved" ), share ?tr ( "drawer.savedShared" , "Other apps (omp, API clients) use these settings from their next request." ) 1537 :tr ( "drawer.savedOwn" , "Other apps use their own settings again." )); 1538} catch ( e ) { 1539toast ( "error" , tr ( "drawer.savedHere" , "Saved here, but not for other apps" ), e . message , 6000 ); 1540} 1541return ; 1542} 1543toast ( "success" , tr ( "drawer.saved" , "Chat settings saved" ), settings . temperature === 0 ?tr ( "drawer.savedGreedy" , "Greedy: the same question gives the same answer." ) :"" ); 1544}; 1545$ ( "sampling-btn" ). onclick = () => openDrawer ( true ); 1546$ ( "drawer-close" ). onclick = () => openDrawer ( false ); 1547$ ( "scrim" ). onclick = () => openDrawer ( false ); 1548document . addEventListener ( "keydown" , ( e ) => { if ( e . key === "Escape" && $ ( "drawer" ). dataset . open === "true" ) openDrawer ( false ); }); 1549 1550// ------------------------------------------------------------------ language (serve/web/i18n.js) 1551// The user's own choice, kept in this browser: English until they pick another. /?lang=de shows one for this visit only. 1552const urlLang = new URLSearchParams ( location . search ). get ( "lang" ); 1553$ ( "lang" ). innerHTML = StrataI18n . LANGUAGES . map (([ code , name ]) => `<option value=" ${ esc ( code )} "> ${ esc ( name )} </option>` ). join ( "" ); 1554function showLanguage () { 1555$ ( "lang" ). value = StrataI18n . lang ; 1556renderEmptyChat (); 1557setSidebar ( sidebarOpen , false ); 1558outputs (); 1559renderChat (); 1560setBusy ( !! busy ); 1561if ( lastMetrics ) render ( lastMetrics ); 1562} 1563$ ( "lang" ). onchange = async () => { 1564store . set ( "lang" , $ ( "lang" ). value ); 1565await StrataI18n . setLanguage ( $ ( "lang" ). value ); 1566showLanguage (); 1567}; 1568 1569// ------------------------------------------------------------------ start 1570async function start () { 1571await StrataI18n . setLanguage ( urlLang || store . get ( "lang" , "en" )); 1572$ ( "lang" ). value = StrataI18n . lang ; 1573renderEmptyChat (); 1574initChats (); 1575if ( settings . chatList ) await setChatList ( true , false ); // the saved-chats list is read before the first draw 1576setBusy ( false ); 1577renderChat (); 1578// /?q=... fills the question in and focuses the box; it is never sent from the address (#4221): any page can link here, 1579// and a send would go out with the API key and the MCP tools saved in this browser. The person presses Send. 1580const startQuestion = new URLSearchParams ( location . search ). get ( "q" ); 1581if ( startQuestion ) { 1582history . replaceState ( null , "" , location . pathname + location . hash ); 1583$ ( "input" ). value = startQuestion ; 1584autosize (); 1585} 1586loadHealth (). then ( loadMcp ); 1587showTab ( location . hash . slice ( 1 ) || "chat" ); 1588if ( startQuestion && tab === "chat" ) $ ( "input" ). focus (); 1589poll (); 1590requestAnimationFrame ( fitHeader ); 1591} 1592start (); 1593 1594// ------------------------------------------------------------------ images (POST /v1/images/generations) 1595$ ( "img-form" ). onsubmit = async ( ev ) => { 1596ev . preventDefault (); 1597const prompt = $ ( "img-prompt" ). value . trim (); 1598if ( ! prompt ) return ; 1599const body = { prompt, size :$ ( "img-size" ). value , response_format :"b64_json" }; 1600if ( $ ( "img-seed" ). value !== "" ) body . seed = Number ( $ ( "img-seed" ). value ); 1601imageBusy = true ; 1602$ ( "img-go" ). disabled = true ; 1603paintLive (); 1604const t0 = performance . now (); 1605$ ( "img-hint" ). textContent = "Generating\u2026 (a minute or more on a small GPU)" ; 1606try { 1607const r = await fetch ( "v1/images/generations" , { method :"POST" , headers :headers ( true ), body :JSON . stringify ( body )}); 1608const j = await r . json (); 1609if ( ! r . ok ) throw new Error (( j . error && j . error . message ) || r . statusText ); 1610for ( const d of j . data ) { 1611const fig = document . createElement ( "figure" ); 1612const img = document . createElement ( "img" ); 1613img . src = "data:image/png;base64," + d . b64_json ; 1614img . alt = prompt ; 1615const cap = document . createElement ( "figcaption" ); 1616cap . textContent = ` ${ j . size } , seed ${ d . seed } , ${(( performance . now () - t0 ) / 1000 ). toFixed ( 0 )} s: ${ prompt } ` ; 1617fig . append ( img , cap ); 1618$ ( "img-results" ). prepend ( fig ); 1619} 1620$ ( "img-hint" ). textContent = "Done. Right-click an image to save it." ; 1621} catch ( e ) { 1622$ ( "img-hint" ). textContent = "" ; 1623toast ( "error" , "No image" , String ( e . message || e ), 8000 ); 1624} finally { 1625imageBusy = false ; 1626$ ( "img-go" ). disabled = false ; 1627paintLive (); 1628} 1629};