import {localeTag} from '../lib/i18n'; import { tr } from '../lib/i18n'; import { scopedMonitor, instanceLabel, deviceLabel } from '../lib/runtime-models'; /** The original Strata dashboard, adapted to the current shell and device inventory. */ import { useEffect, useRef, useState, type ReactNode } from 'react'; import { flushSync } from 'react-dom'; import { SnapshotDialog } from '../components/SnapshotDialog'; import { requestSummary } from '../lib/monitor-summary'; import { monitorPng } from '../lib/snapshot'; import { Gauge, ReferenceSpark } from '../components/charts'; import { Brand } from '../components/Brand'; import { Bar, Btn, Icon, IconBtn, Select, type IconName } from '../components/ui'; import { Screen } from '../components/layout'; import { contextLabel, duration, tokens, tps } from '../lib/format'; import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware'; import { useStore } from '../lib/store'; import { api } from '../lib/client'; import { useMoney } from '../lib/money'; import { useKept } from '../lib/kept-state'; import type { Hardware, MonitorState, ServeRequest } from '../lib/types'; import { useNative, nativeRouting, type NativeState } from '../lib/native'; import { nativeMonitorData, withHostSensors } from '../lib/native-monitor'; const number = (value: number | null | undefined, digits = 0) => hasReading(value) ? value.toLocaleString(localeTag(), { maximumFractionDigits: digits, minimumFractionDigits: digits }) : '—'; const percent = (used: number | null | undefined, total: number | null | undefined) => hasReading(used) && hasReading(total) && total > 0 ? Math.max(0, Math.min(100, used / total * 100)) : null; const sourceLabel = (source: string | undefined) => source === 'demo' ? 'Illustrative' : source === 'sensor' || source === 'engine' || source === 'reported' ? 'Measured' : source === 'estimated' ? 'Estimated' : 'Unavailable'; function ReadingBar({ label, value, tone = 'accent' }: { label: string; value: number | null; tone?: 'accent' | 'info' | 'warn' | 'danger'; }) { return hasReading(value) ? :
; } function MonitorMetric({ label, icon, value, unit, sub, chart, source, secondary }: { label: string; icon: IconName; value: ReactNode; unit?: string; sub: ReactNode; chart: ReactNode; source: string; secondary?: ReactNode; }) { return
{tr(label)}{tr(source)}
{tr(value)}{tr(unit ? {tr(unit)} : null)}
{tr(sub)}
{tr(secondary)}
{tr(chart)}
; } function requestStatus(request: ServeRequest) { if (request.state === 'error') return 'Error'; if (request.state === 'queued') return 'Queued'; if (request.state === 'generating') return 'Generating'; if (request.cancelRequested || ['cancel', 'disconnect'].includes(request.finishReason ?? '')) return 'Stopped'; return ['length', 'max_tokens'].includes(request.finishReason ?? '') ? 'Max tokens' : 'Done'; } export function MonitorScreen() { const native = useNative(); // While this screen is open and visible the host reads the graphics card every 3 s; otherwise it asks only every 30 s (#4066). useEffect(() => { const ask = () => { if (typeof document === 'undefined' || document.visibilityState !== 'hidden') void api.get('/api/monitor?drives=1').catch(() => undefined); }; ask(); const timer = setInterval(ask, 10000); return () => clearInterval(timer); }, []); return ; } function LegacyMonitorScreen({ native }: { native: NativeState | null; }) { const storedLive = useStore(s => s.monitor), inventory = useStore(s => s.hardware); const electricityPrice = useStore(s => s.electricityPrice), money = useMoney(); const storedRuntime = useStore(s => s.runtime), serving = useStore(s => s.serving); const [instanceSelection, setInstanceSelection] = useState('all'); const routing = native ? nativeRouting(native, inventory) : null; const runtime = routing && native ? { ...routing, instances: routing.instances.map(instance => { const raw = native.instances.find(item => item.id === instance.id)?.metrics?.live; return { ...instance, outputTps: raw?.tok_s ?? NaN, promptTps: raw?.prefill_tok_s_mean ?? NaN, active: raw ? (raw.running ?? (['reading', 'generating'].includes(raw.state) ? 1 : 0)) : NaN, queued: raw?.queued ?? NaN }; }) } : storedRuntime; const live = native ? withHostSensors(nativeMonitorData(native, inventory, instanceSelection), storedLive) : storedLive; const multipleModels = (runtime?.instances.length ?? 0) > 1; const selectedInstance = runtime?.instances.find(i => i.id === instanceSelection) ?? (!multipleModels ? runtime?.instances[0] : undefined); const selection = selectedInstance?.id ?? 'all'; const scoped = native ? live : scopedMonitor(live, runtime ?? null, selection, serving?.requests ?? []); const scopeLabel = selectedInstance ? instanceLabel(selectedInstance) : `${runtime?.instances.length ?? 0} loaded models`; // null = the person has not chosen: a model with assigned cards shows those (#3211); a choice is kept while the app stays open. const [gpuSelection, setGpuSelection] = useKept('monitor.gpu', null), [cpuSelection, setCpuSelection] = useState('all'), [showAll, setShowAll] = useState(false); const [frozen, setFrozen] = useState<{ data: MonitorState; hardware: Hardware | null; time: string; modelLabel: string; } | null>(null); const snapshotRef = useRef(null); const [saving, setSaving] = useState(false), [saveError, setSaveError] = useState(''); const [snapshotOpen, setSnapshotOpen] = useState(false), [screenshot, setScreenshot] = useState(''); async function saveScreenshot() { if (!live || !snapshotRef.current || saving) return; setSnapshotOpen(true); setScreenshot(''); setSaving(true); setSaveError(''); flushSync(() => setFrozen({ data: structuredClone(scoped ?? live), hardware: structuredClone(inventory), time: new Date().toLocaleString(localeTag()), modelLabel: scopeLabel })); try { setScreenshot(await monitorPng(snapshotRef.current)); } catch (error) { setSaveError(error instanceof Error ? error.message : 'Screenshot could not be saved.'); } finally { setFrozen(null); setSaving(false); } } const data = frozen?.data ?? scoped, hardware = frozen?.hardware ?? inventory; if (!data) return

{tr("Waiting for engine telemetry\u2026")}

; // A display adapter that has no sensors and no memory of its own (an integrated one) cannot be measured; counting it would blank every total. const devices = (hardware?.gpus ?? []).filter(g => g.backend !== 'vulkan' || g.vramGb > 0), defaultDevices = defaultGpuSet(devices), processors = hardware?.processors?.length ? hardware.processors : hardware ? [{ ...hardware.cpu, id: 'cpu', socket: '' }] : []; const assignedDevices = selectedInstance ? devices.filter(g => selectedInstance.gpuIds.includes(gpuId(g))) : []; const gpuChoice = gpuSelection === 'assigned' && selectedInstance ? 'assigned' : devices.some(g => gpuId(g) === gpuSelection) ? gpuSelection! : gpuSelection === 'all' || !assignedDevices.length ? 'all' : 'assigned'; const cpuChoice = processors.some(p => p.id === cpuSelection) ? cpuSelection : 'all'; const selectedGpus = gpuChoice === 'assigned' ? devices.filter(g => selectedInstance?.gpuIds.includes(gpuId(g))) : gpuChoice === 'all' ? defaultDevices : devices.filter(g => gpuId(g) === gpuChoice); const selectedCpus = cpuChoice === 'all' ? processors : processors.filter(p => p.id === cpuChoice); const multipleGpus = selectedGpus.length > 1, shared = selectedGpus.length > 0 && selectedGpus.every(g => g.unified); const readings = data.hardware.gpus; // A card that cannot report a value (an integrated one with no temperature sensor) is left out of that value, and the card the figure is from is named. const report = (key: Parameters[2], mode: Parameters[3] = 'sum') => gpuReported(selectedGpus, readings, key, mode); const gpuValue = (key: Parameters[2], mode: Parameters[3] = 'sum') => report(key, mode).value; const whose = (key: Parameters[2], mode: Parameters[3] = 'sum') => { const r = report(key, mode); return r.partial ? r.devices.map(d => shortGpuName(d.name)).join(' + ') : null; }; const gpuSource = (key: Parameters[2], mode: Parameters[3] = 'sum') => hasReading(gpuValue(key, mode)) ? sourceLabel(readings?.find(r => r.id === gpuId(report(key, mode).devices[0] ?? selectedGpus[0]))?.source) : 'Unavailable'; const gpuLoad = gpuValue('utilizationPct', 'mean'), vram = gpuValue('memoryUsedGb'), temperature = gpuValue('temperatureC', 'max'), power = gpuValue('powerW'), powerLimit = gpuValue('powerLimitW'), pcieRx = gpuValue('pcieRxMbs'); const vramTotal = gpuCapacity(report('memoryUsedGb').partial ? report('memoryUsedGb').devices : selectedGpus); const singleReading = selectedGpus.length === 1 ? readings?.find(r => r.id === gpuId(selectedGpus[0])) : undefined; const gen = singleReading?.pcieGenMax ?? singleReading?.pcieGen, width = singleReading?.pcieWidth; const cpu = cpuChoice === 'all' ? data.hardware.cpuLoad : data.hardware.cpus?.find(p => p.id === cpuChoice)?.utilizationPct; const requests = data.requests ?? [], last = requests.find(r => r.state === 'done'), visibleRequests = showAll ? requests : requests.slice(0, 12); const throughput = sourceLabel(data.telemetry?.throughput), throughputKnown = throughput !== 'Unavailable'; const writing = ['generating', 'thinking'].includes(data.phase); const decode = throughputKnown ? (writing ? data.outputTps : last?.tps) : null; const prefill = throughputKnown ? (data.phase === 'reading' || writing ? data.promptTps : last?.promptTps) : null; const contextKnown = ['reported', 'demo'].includes(data.telemetry?.context ?? '') || data.phase === 'reading' && data.prompt.total > 0; const contextUsed = data.phase === 'reading' ? data.prompt.total : data.context.usedTokens; const contextPct = contextKnown ? percent(contextUsed, data.context.maxTokens) : null; const cacheKnown = ['engine', 'demo'].includes(data.expertCache.source ?? ''); const cacheMemory = cacheKnown ? data.expertCache.memoryGb : null; const cachePercent = hasReading(cacheMemory) ? percent(cacheMemory, gpuCapacity(defaultDevices)) : cacheKnown ? percent(data.expertCache.used, data.expertCache.total) : null; const ramPct = percent(data.hardware.ramUsedGb, data.hardware.ramTotalGb); // The readings strip under the cards: what the GPU used and cost since Strata started, the fan and clock, and the temperatures this PC can give. const energyWh = data.hardware.energyWh, fan = gpuValue('fanPct', 'max'), clock = gpuValue('clockMhz', 'max'); const readingsStrip = [ hasReading(energyWh) ? { label: 'Energy since start', value: energyWh >= 1000 ? `${number(energyWh / 1000, 2)} kWh` : `${number(energyWh, 1)} Wh` } : null, hasReading(energyWh) && electricityPrice > 0 ? { label: 'Cost since start', value: money.format(energyWh / 1000 * electricityPrice) } : null, hasReading(fan) ? { label: 'GPU fan', value: `${number(fan)} %` } : null, hasReading(clock) ? { label: 'GPU clock', value: `${number(clock)} MHz` } : null, hasReading(data.hardware.cpuTempC) ? { label: 'CPU temperature', value: `${number(data.hardware.cpuTempC)} °C` } : null, hasReading(data.hardware.ssdTempC) ? { label: 'SSD temperature', value: `${number(data.hardware.ssdTempC)} °C` } : null, ].filter((line): line is { label: string; value: string } => line !== null); const history = data.history, timestamps = history.map(s => s.t); const historyGpu = (key: Parameters[2], fallback: 'gpuLoad' | 'vramUsedGb' | 'gpuTempC' | 'powerW' | 'pcieRxMbs', mode: Parameters[3] = 'sum') => history.map(sample => sample.gpus ? gpuMetric(selectedGpus, sample.gpus, key, mode) : (sample.gpuIds ? selectedGpus.length === sample.gpuIds.length && selectedGpus.every(gpu => sample.gpuIds!.includes(gpuId(gpu))) : gpuChoice === 'all') ? sample[fallback] : null); const historyCpu = history.map(sample => cpuChoice === 'all' ? sample.cpuLoad : sample.cpus?.find(p => p.id === cpuChoice)?.utilizationPct); const chart = (label: string, values: (number | null | undefined)[], unit: string, maximum?: number, tone?: string) => ; const gpuName = multipleGpus ? `${selectedGpus.length} GPUs · mean utilization` : selectedGpus[0]?.name ?? (selectedInstance && !selectedInstance.gpuIds.length ? native ? 'Automatic GPU placement' : 'CPU only · no GPU assigned' : 'No GPU detected'); const cpuName = !selectedCpus.length ? 'Processor information unavailable' : selectedCpus.length > 1 ? `${selectedCpus.length} processors · ${selectedCpus.reduce((n, p) => n + p.cores, 0)} cores · ${selectedCpus.reduce((n, p) => n + p.threads, 0)} threads` : `${selectedCpus[0]?.model ?? 'CPU'} · ${hardware?.cpu.topologyKnown === false ? '' : `${selectedCpus[0]?.cores ?? 0} cores · `}${selectedCpus[0]?.threads ?? 0} threads`; const phase = writing ? 'generating' : data.queue.waiting > 0 && data.phase === 'idle' ? 'queued' : data.phase; const progress = data.phase === 'reading' ? data.prompt.pct : writing ? percent(data.generation?.done, data.generation?.total) : 0; const statusDetail = data.phase === 'reading' && data.prompt.total ? `${tokens(data.prompt.done)} / ${tokens(data.prompt.total)} tokens · ${Math.round(data.prompt.pct)}%` : writing && hasReading(data.generation?.done) ? `${tokens(data.generation.done)} tokens · ${tps(data.outputTps)} tok/s` : last ? `Last: ${tokens(last.tokensOut)} tokens${hasReading(last.tps) ? ` at ${tps(last.tps)} tok/s` : ''}` : ''; const cache = data.conversationCache; const reused = requests.filter(r => hasReading(r.cachedTokens)); const lastRequest = requests.find(r => r.state === 'done'); const lastReused = hasReading(lastRequest?.cachedTokens) ? lastRequest : null; const reusedTotal = reused.length ? reused.reduce((n, r) => n + (r.cachedTokens ?? 0), 0) : null; const lastCacheText = hasReading(cache?.lastReused) && hasReading(cache?.lastPrompt) ? `${tokens(cache.lastReused)} of ${tokens(cache.lastPrompt)} prompt tokens reused` : lastReused ? `${tokens(lastReused.cachedTokens)} of ${tokens(lastReused.tokensIn)} prompt tokens reused` : 'Reuse not reported'; const promptSpeed = data.totals.promptMs ? data.totals.uncachedTokens / (data.totals.promptMs / 1000) : null; const outputSpeed = data.totals.decodeMs ? data.totals.tokensOut / (data.totals.decodeMs / 1000) : null; const multipleScope = selection === 'all' && (runtime?.instances.length ?? 0) > 1; const chooseInstance = (id: string) => { setInstanceSelection(id); setGpuSelection(null); }; const overview =
{tr(frozen ?

{tr(frozen.modelLabel)} · {tr(frozen.time)}

: null)} {tr(multipleModels ?

{tr("Model performance")}

{tr(runtime?.instances.map(i => { const recent = (data.requests ?? []).find(r => r.instanceId === i.id); const writing = i.phase === 'generating' || i.phase === 'thinking', reading = i.phase === 'reading'; return ; }))}
{tr("Model / device")}{tr("Generating tok/s")}{tr("Reading tok/s")}{tr("State")}{tr("Active / queued")}
{tr(deviceLabel(i.gpuIds, inventory))}{tr(number(writing ? i.outputTps : recent?.tps, 1))}{tr(writing ? 'Now' : recent ? 'Last request' : 'No request yet')}{tr(number(reading ? i.promptTps : recent?.promptTps, 0))}{tr(reading ? 'Now' : recent ? 'Last request' : 'No request yet')}{tr(i.phase)}{tr(runtime.mode === 'simulated' ? {tr("Illustrative")} : null)}{tr(number(i.active))} / {tr(number(i.queued))}
: null)} {tr(multipleModels ?

{tr(selectedInstance ? selectedInstance.gpuIds.length ? 'Requests, context and speed are scoped to this model. GPU readings include all work on the selected devices.' : 'CPU-only model. Requests and context are scoped to this model; system metrics are shared host measurements.' : 'Select a model for its context and speed. GPU readings and system RAM are shared host measurements.')}

: null)}

{tr(multipleScope ? 'Model activity' : 'Model state')}

{tr({tr(phase === 'reading' ? 'Reading' : writing ? 'Generating' : phase === 'queued' ? 'Queued' : phase === 'error' ? 'Error' : phase === 'loading' ? 'Loading' : 'Idle')}{tr(phase === 'queued' && data.queue.waiting > 0 ? ` (${data.queue.waiting})` : '')})}
{tr(devices.length > 1 ? ({ value: p.id, label: `CPU ${i + 1} · ${p.model}` }))]} onChange={setCpuSelection}/> : null)}
{tr(multipleScope ? `${number(data.queue.running)} active · ${number(data.queue.waiting)} queued` : data.phase === 'idle' ? 'Waiting for a request' : data.phaseLabel)}{tr(statusDetail)}
{tr(!multipleScope ? : null)}
{tr(!multipleScope ?
{tr(number(prefill))}{tr(hasReading(prefill) ? {tr("tok/s")} : null)}
{tr(data.phase === 'reading' ? 'Prefill now' : writing ? 'Prefill this request' : last ? 'Prefill last request' : 'Prefill')}
} chart={ throughputKnown ? s.outputTps : null)} secondary={{ data: history.map(s => throughputKnown ? s.promptTps : null), label: 'Prefill', tone: 'var(--st-chart-prefill)' }} tone="var(--st-chart-decode)" unit="tok/s" timestamps={timestamps}/>}/> : null)} = 1 ? data.hardware.diskReadGbs : data.hardware.diskReadGbs * 1024 : null, 1)} unit={hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? 'GB/s' : 'MB/s' : ''} source={hasReading(data.hardware.diskReadGbs) ? 'Measured' : 'Unavailable'} sub={hasReading(data.hardware.diskWriteMbs) ? `Write ${number(data.hardware.diskWriteMbs, 1)} MB/s` : 'Read throughput'} chart={chart('Disk read', history.map(s => hasReading(s.diskReadGbs) ? s.diskReadGbs * 1024 : null), 'MB/s', undefined, 'var(--st-info)')}/>
{tr(readingsStrip.length ?
{readingsStrip.map(item =>
{tr(item.label)}
{item.value}
)}
: null)}

{tr("Context fill")}

1 ? 'Select a model to see context' : 'No recorded request usage'}/>
{tr("Experts in VRAM")}{tr(cacheKnown ? `${number(data.expertCache.used)}${hasReading(cacheMemory) ? ` · ${number(cacheMemory, 1)} GB` : ''}` : '—')}
{tr("System RAM")}{tr(hasReading(data.hardware.ramUsedGb) ? `${number(data.hardware.ramUsedGb, 1)} / ${number(data.hardware.ramTotalGb)} GB` : '—')}
92 ? 'danger' : 'accent'}/>
{tr("GPU temperature")}{tr(number(temperature))}{tr(hasReading(temperature) ? ' °C' : '')}

{tr("Recent requests")}

{tr(requests.length > 12 ? setShowAll(!showAll)}>{tr(showAll ? 'Show fewer' : `Show all (${requests.length})`)} : null)}
{tr(multipleModels ? : null)}{tr(visibleRequests.length ? visibleRequests.map(r => {tr(multipleModels ? : null)}) : )}
{tr("Time")}{tr("Status")}{tr("Model")}{tr("Prompt")}{tr("Reused")}{tr("Output")}{tr("Tok/s")}{tr("VRAM hit rate")}{tr("Duration")}
{tr(new Date(r.at).toLocaleTimeString(localeTag(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }))}{tr(requestStatus(r))}{tr(r.usageSource === 'demo' ? {tr("Illustrative")} : null)}{tr(r.model)}{tr(number(r.tokensIn))}{tr(number(r.cachedTokens))}{tr(number(r.tokensOut))}{tr(number(r.tps, 1))}{tr(hasReading(r.hitRate) ? `${number(r.hitRate * 100, 1)}%` : '—')}{tr(hasReading(r.pcieShare) && r.pcieShare > 0 ? +{tr(number(r.pcieShare * 100, 1))}{tr("% PCIe")} : null)}{tr(r.durationMs ? duration(r.durationMs) : '—')}
{tr("No requests yet")}
{/* One request is already the row above: the aggregate sentence would only restate it, and in English it also read “In 1 requests”. Show it from two requests on, where it carries information the table cannot. */} {tr(data.totals.requests > 1 ?

{requestSummary({ requests: data.totals.requests, output: outputSpeed, reading: promptSpeed, reused: data.totals.cachedTokens }, { number, tokens })}

: null)}

{tr("Conversation cache")}

{tr(lastReused ? {tr("{0} of {1} requests reused prompt tokens", [number(cache?.requestsReused ?? reused.filter(r => (r.cachedTokens ?? 0) > 0).length),number(cache?.requests ?? requests.length)])} : null)}
{tr(cache?.enabled ?
{tr("Parked conversations")}{tr(number(cache.parked))} / {tr(number(cache.slots))}
{tr("Their memory (RAM)")}{tr(number(cache.memoryGb, 1))} / {tr(number(cache.budgetGb, 1))}{tr(" GB")}
: null)}
{tr("Last request")}
{tr(lastCacheText)}
{tr("Reused since start")}
{tr(hasReading(reusedTotal) ? `${tokens(data.totals.cachedTokens)} tokens` : '—')}
{tr(cache?.enabled ? <>
{tr("Parked / restored")}
{tr(number(cache.parks))} / {tr(number(cache.restores))}{tr(cache.evictions ? ` · ${number(cache.evictions)} evicted` : '')}
{tr(cache.lastEvent ?
{tr("Last switch")}
{tr(cache.lastEvent === 'parked' ? 'Parked' : 'Restored')} {tr(tokens(cache.lastTokens))}{tr(" tokens")}{tr(cache.lastAt ? ` · ${new Date(cache.lastAt * 1000).toLocaleTimeString(localeTag())}` : '')}
: null)} : null)}

{tr(cache?.enabled ? 'Parked conversations resume from their saved state. The oldest is removed when the cache fills.' : lastReused ? 'Follow-up requests can reuse the previous prompt’s cached tokens.' : 'Cache details appear when the engine reports prompt reuse.')}

{tr(data.mcp?.servers.length ?

{tr("MCP servers")}

{tr("{0} tools · {1} of {2} servers connected", [number(data.mcp.tools),number(data.mcp.servers.filter(server => ['ready','stopped'].includes(server.state)).length),number(data.mcp.servers.length)])}
{tr(data.mcp.servers.map(server =>
{server.name}{tr({ ready: 'Connected', starting: 'Starting', failed: 'Failed', stopped: 'Stopped', idle: 'Waiting' }[server.state] ?? server.state)}

{server.transport}{tr(server.transport ? ' · ' : '')}{tr(server.tools.length)}{tr(" tools")}{tr(server.info?.name ? ` · ${server.info.name}${server.info.version ? ` ${server.info.version}` : ''}` : '')}

{tr(server.error ?

{tr(server.error)}

: null)}
{tr(server.tools.map(tool => {tool.name}))}
))}
: null)}
; return ({ value: i.id, label: `${instanceLabel(i)} · ${deviceLabel(i.gpuIds, inventory)}` }))]} onChange={chooseInstance}/> : selectedInstance ? instanceLabel(selectedInstance) : 'No model loaded'} actions={ void saveScreenshot()}/>}>{tr(saveError ?

{tr(saveError)}

: null)}{tr(overview)} setSnapshotOpen(false)} onRetry={() => void saveScreenshot()}/>
; }