Merge f-025-fix (6 owner-QA fixes) into f-026-rel

This commit is contained in:
Niko1221 committed 2026-10-25 11:10:13 +01:00
commit d51d71e7c0
17 files changed
+89 -77

No files matched your search

+1 -1
View File
@@ -137,7 +137,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
if(closing)return state();
/* A read that is not forced never makes the window wait for the (slow) status of Control: it gets the last state at once, and a stale one
is refreshed in the background. Only the first read, and a forced one after an operation, waits. */
if(refreshing)return !force&&snapshot.available?state():refreshing;if(!force&&Date.now()-lastRead<45000)return state();
if(refreshing)return !force&&snapshot.available?state():force?refreshing.then(()=>refresh(true)):refreshing; /* a forced read that meets one already running (started before an engine update finished) waits for it and reads again, so it never settles on the old answer */if(!force&&Date.now()-lastRead<45000)return state();
probeDrafting();
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
}
+6 -3
View File
@@ -104,7 +104,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
// Drafting (which drafter guesses ahead): DFlash2 is for Qwen3.8-Flash-Next only (the qwen and gyro families), so no other model is offered it.
const draftingChoices = selectedSize ? draftingOptions(selectedSize.sourceFamily ?? selectedFamily?.family, native?.capabilities?.dflash2) : null;
const draftingWords: Record<string, string> = { auto: 'Auto (recommended)', mtp: 'MTP', dflash2: 'DFlash2', off: 'Off' };
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), expert, multiple]);
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context: selectedSize?.multi_file ? 8192 : context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), expert, multiple]);
const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' };
useEffect(() => { if (!native?.catalog || family)
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
@@ -138,8 +138,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
if (installed.resourceProfile && !loadedSelected?.resourceProfile)
setResourceProfile(installed.resourceProfile);
}
else
else {
setVision('yes');
if (selectedSize.multi_file)
setContext(8192); // DeepSeek runs at the one context its engine was checked at (as in the guided setup)
}
}, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]);
useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) {
setToastedJob(job.id);
@@ -210,7 +213,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
<Dialog open={!!plan} title={tr(installed?.ready ? "Apply settings and load" : "Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</>)}</p>{tr(plan?.drafting?.needed ? <p className="small muted">{tr("Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.", [plan.drafting.gb])}</p> : null)}{tr(installed?.ready ? <p className="small muted">{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}</p> : null)}{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}{tr(installed?.ready ? <p className="small muted">{tr("Any currently loaded native models will be unloaded first.")}</p> : <><p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p></>)}{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog>
<NativeDeleteDialog id={deleting} onClose={() => setDeleting(null)}/>
<Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="native-manage">
{tr(downloaded.length ? <div className="native-manage-list" role="list">{tr(downloaded.map(m => { const v = allSizes.find(x => x.id === m.model), loaded = native?.instances.some(i => i.model === m.model && i.status === 'ready'); return <div className="native-manage-row" role="listitem" key={m.model} data-selected={selectedSize?.id === m.model || undefined}>
{tr(downloaded.some(m => m.ready || m.diskGb) ? <div className="native-manage-list" role="list">{tr(downloaded.filter(m => m.ready || m.diskGb).map(m => { const v = allSizes.find(x => x.id === m.model), loaded = native?.instances.some(i => i.model === m.model && i.status === 'ready'); return <div className="native-manage-row" role="listitem" key={m.model} data-selected={selectedSize?.id === m.model || undefined}>
<span className="native-manage-name"><strong>{tr(v ? `${catalogVersionLabel(v)}` : m.model_name ?? m.model)}</strong><small>{tr(v ? v.model : m.model)}{tr(m.diskGb ? ` · ${sizeGb(m.diskGb)}` : '')}</small></span>
<span className={loaded ? 'st-pill st-pill--accent' : 'st-pill'}>{tr(loaded ? 'Loaded' : 'Downloaded')}</span>
<span className="native-manage-actions"><Btn size="sm" disabled={!!active || !v} onClick={() => { if (v) setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === m.model ? 'Selected' : 'Use version')}</Btn><Btn size="sm" variant="danger" disabled={!!active} onClick={() => setDeleting(m.model)}>{tr("Delete")}</Btn></span>
+1 -1
View File
@@ -19,7 +19,7 @@ export function SettingsStorage() {
const library = state.library;
const versions = library ? pickerGroups(library).flatMap(group => group.versions) : [];
// ONE list and ONE total: the optimized models (sizes from their real files, shared files counted once) and the other local models together.
const nativeModels = native?.installed?.models ?? [];
const nativeModels = (native?.installed?.models ?? []).filter(m => m.ready || (m.diskGb ?? 0) > 0); // a model whose files are all gone (an old config) is not a 0.0 GB download
const sharedGb = (native?.installed?.usage?.shared_bytes ?? 0) / 1e9;
const nativeGb = native?.installed?.usage ? native.installed.usage.total_gb : nativeModels.reduce((n, m) => n + (m.diskGb ?? 0), 0);
const totalGb = nativeGb + versions.reduce((n, v) => n + (v.diskGb ?? 0), 0);
+4 -3
View File
@@ -9,6 +9,7 @@ import { NativeProgress } from './NativeModels';
import { jobErrorText } from '../lib/native-job-diagnostics';
import { appVersionLabel } from '../lib/app-version';
import { fetchUpdateCheck, publishUpdateCheck, useInstalledVersions, useLastUpdateCheck } from '../lib/update-check';
import { shownEngineVersion } from '../lib/engine-version';
/** A check from an earlier day shows its date too, because the result is kept between visits. */
function checkedLabel(at: string) {
const when = new Date(at), sameDay = when.toDateString() === new Date().toDateString();
@@ -30,7 +31,7 @@ export function SettingsUpdates() {
const [error, setError] = useState('');
const request = useRef<AbortController | null>(null);
useEffect(() => () => request.current?.abort(), []);
const installed = component === 'strata' ? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion;
const installed = component === 'strata' ? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : shownEngineVersion(native, engineVersion);
const active = native?.jobs.find(j => j.state === 'running');
const result = checking || error ? null : (fresh ?? last);
async function operate(kind: string) {
@@ -78,7 +79,7 @@ export function SettingsUpdates() {
return <>
<div className="settings-versions" aria-busy={checking}>
{tr(versionRow('Strata', appVersion, result?.strata))}
{tr(versionRow('Engine', native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion, result?.engine))}
{tr(versionRow('Engine', native?.available ? (native.installed?.engine?.version ?? 'Not installed') : shownEngineVersion(native, engineVersion), result?.engine))}
<div className="settings-update-actions"><Btn size="sm" icon="refresh" disabled={checking} className={checking ? 'settings-update-checking' : undefined} onClick={() => void check()}>{tr(checking ? 'Checking…' : error || result?.strata.status === 'error' ? 'Try again' : result ? 'Check again' : 'Check for updates')}</Btn><Btn size="sm" variant="ghost" onClick={() => setRollback(true)}>{tr("Roll back\u2026")}</Btn></div>
<div className="settings-update-inline" role="status" aria-live="polite">{tr(checking ? 'Checking for new versions…' : error ? <span className="inline-error">{tr(error)}</span> : result ? <><span className="sr-only">{tr(result.strata.message)} {tr(result.engine.message)} </span>{tr("Checked at ")}{tr(checkedLabel(result.checkedAt))}</> : null)}</div>
</div>
@@ -100,6 +101,6 @@ export function AboutVersions() {
const native = useNative();
const app = appVersionLabel(useStore(s => s.setup?.app.version), native?.version);
const engineVersion = useStore(s => s.engine?.engine.version);
const engine = native?.available ? native.installed?.engine?.version : engineVersion;
const engine = shownEngineVersion(native, engineVersion);
return <p className="settings-about-version"><strong>{tr("Strata")} {app ?? ''}</strong>{engine ? <span className="muted"> · {tr("Engine")} {engine}</span> : null}</p>;
}
+8
View File
@@ -0,0 +1,8 @@
/** The host's design-mode placeholder for the engine version; it is not an engine anyone installed. */
const PLACEHOLDER_ENGINE = /^strata-engine 0\.1\.0$/;
/** The engine version the app shows: the installed engine's once the host has read it; until then nothing (never the placeholder). */
export function shownEngineVersion(native: { available?: boolean; installed?: { engine?: { version?: string | null } | null } | null } | null | undefined, storeVersion: string | undefined): string | undefined {
if (native?.available) return native.installed?.engine?.version ?? undefined;
return storeVersion && !PLACEHOLDER_ENGINE.test(storeVersion) ? storeVersion : undefined;
}
+13
View File
@@ -29,3 +29,16 @@ export function gpuCapacity(devices:GpuInfo[]) {
const shared=devices.filter(g=>g.unified).map(g=>g.vramGb);
return devices.filter(g=>!g.unified).reduce((n,g)=>n+g.vramGb,0)+(shared.length?Math.max(...shared):0);
}
/**
* The cards "All GPUs" covers by default. A small integrated chip (an AMD or Intel adapter on the Windows/Vulkan list with a carve-out under
* 2 GB) beside a real card is left out: Strata cannot run a model on it (the native engine report marks it unusable), and counting it adds a
* second "GPU" and half a gigabyte to every total. It stays in the picker. Alone (a Strix Halo, an iGPU-only PC) it stays the default.
*/
export function defaultGpuSet(devices:GpuInfo[]):GpuInfo[] {
const real=(g:GpuInfo)=>g.vramGb>=4||g.vendor==='nvidia'||g.backend==='cuda';
const small=(g:GpuInfo)=>g.backend==='vulkan'&&(g.vendor==='amd'||g.vendor==='intel')&&g.vramGb<2&&!g.unified;
if(!devices.some(real))return devices;
const kept=devices.filter(g=>!small(g));
return kept.length?kept:devices;
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { useEffect, useState } from 'react';
import { useStore } from './store';
import { useNative } from './native';
import { appVersionLabel } from './app-version';
import { shownEngineVersion } from './engine-version';
import { readUpdateCache, saveUpdateCache, type InstalledVersions } from './update-cache';
import type { UpdateCheckResult } from './types';
@@ -10,7 +11,7 @@ export function useInstalledVersions(): InstalledVersions {
const native = useNative();
const engineVersion = useStore(s => s.engine?.engine.version);
const appVersion = appVersionLabel(useStore(s => s.setup?.app.version), native?.version);
return { appVersion: appVersion ?? null, engineVersion: (native?.available ? native.installed?.engine?.version : engineVersion) ?? null, controlVersion: native?.version ?? null };
return { appVersion: appVersion ?? null, engineVersion: shownEngineVersion(native, engineVersion) ?? null, controlVersion: native?.version ?? null };
}
/** The one place the app asks the host to check for updates. Called only from a button press. */
+5 -5
View File
@@ -12,7 +12,7 @@ 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 { gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware';
import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware';
import { useStore } from '../lib/store';
import { useKept } from '../lib/kept-state';
import type { Hardware, MonitorState, ServeRequest } from '../lib/types';
@@ -107,11 +107,11 @@ function LegacyMonitorScreen({ native }: {
if (!data)
return <Screen title={tr("Monitor")}><p className="muted">{tr("Waiting for engine telemetry\u2026")}</p></Screen>;
// 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), processors = hardware?.processors?.length ? hardware.processors : hardware ? [{ ...hardware.cpu, id: 'cpu', socket: '' }] : [];
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' ? devices : devices.filter(g => gpuId(g) === gpuChoice);
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;
@@ -135,7 +135,7 @@ function LegacyMonitorScreen({ native }: {
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(devices)) : cacheKnown ? percent(data.expertCache.used, data.expertCache.total) : 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);
const history = data.history, timestamps = history.map(s => s.t);
const historyGpu = (key: Parameters<typeof gpuMetric>[2], fallback: 'gpuLoad' | 'vramUsedGb' | 'gpuTempC' | 'powerW' | 'pcieRxMbs', mode: Parameters<typeof gpuMetric>[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);
@@ -161,7 +161,7 @@ function LegacyMonitorScreen({ native }: {
{tr(multipleModels ? <section className="st-card"><h2 className="h4">{tr("Model performance")}</h2><div className="st-tablewrap"><table className="st-table native-performance-table"><thead><tr><th>{tr("Model / device")}</th><th>{tr("Generating tok/s")}</th><th>{tr("Reading tok/s")}</th><th>{tr("State")}</th><th>{tr("Active / queued")}</th></tr></thead><tbody>{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 key={i.id}><td><button className="text-btn strong" onClick={() => chooseInstance(i.id)}>{tr(instanceLabel(i))}</button><small>{tr(deviceLabel(i.gpuIds, inventory))}</small></td><td>{tr(number(writing ? i.outputTps : recent?.tps, 1))}<small>{tr(writing ? 'Now' : recent ? 'Last request' : 'No request yet')}</small></td><td>{tr(number(reading ? i.promptTps : recent?.promptTps, 0))}<small>{tr(reading ? 'Now' : recent ? 'Last request' : 'No request yet')}</small></td><td>{tr(i.phase)}{tr(runtime.mode === 'simulated' ? <small>{tr("Illustrative")}</small> : null)}</td><td>{tr(number(i.active))} / {tr(number(i.queued))}</td></tr>; }))}</tbody></table></div></section> : null)}
{tr(multipleModels ? <p className="xs muted monitor-scope-note">{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.')}</p> : null)}
<section className="st-card monitor-state" aria-label={tr("Model state")} data-snapshot-skip>
<div className="monitor-state__head"><h2 className="h4">{tr(multipleScope ? 'Model activity' : 'Model state')}</h2><div className="monitor-state__badges">{tr([{ id: 'idle', label: 'Idle' }, { id: 'reading', label: 'Reading' }, { id: 'generating', label: 'Generating' }, { id: 'queued', label: 'Queued' }, { id: 'error', label: 'Error' }].map(s => <span key={s.id} className="st-badge" data-phase={s.id} data-active={phase === s.id || s.id === 'queued' && data.queue.waiting > 0}>{tr(s.label)}{tr(s.id === 'queued' && data.queue.waiting > 0 ? ` (${data.queue.waiting})` : '')}</span>))}</div><div className="monitor-device-selectors">{tr(devices.length > 1 ? <Select ariaLabel={tr("Monitor GPU")} value={gpuChoice} options={[...(selectedInstance ? [{ value: 'assigned', label: 'Assigned GPUs' }] : []), { value: 'all', label: `All GPUs (${devices.length})` }, ...devices.map((gpu, i) => ({ value: gpuId(gpu), label: `GPU ${i + 1} · ${gpu.name}` }))]} menuMinWidth={340} onChange={setGpuSelection}/> : null)}{tr(processors.length > 1 ? <Select ariaLabel={tr("Monitor processor")} value={cpuChoice} options={[{ value: 'all', label: `All processors (${processors.length})` }, ...processors.map((p, i) => ({ value: p.id, label: `CPU ${i + 1} · ${p.model}` }))]} onChange={setCpuSelection}/> : null)}</div></div>
<div className="monitor-state__head"><h2 className="h4">{tr(multipleScope ? 'Model activity' : 'Model state')}</h2><div className="monitor-state__badges">{tr([{ id: 'idle', label: 'Idle' }, { id: 'reading', label: 'Reading' }, { id: 'generating', label: 'Generating' }, { id: 'queued', label: 'Queued' }, { id: 'error', label: 'Error' }].map(s => <span key={s.id} className="st-badge" data-phase={s.id} data-active={phase === s.id || s.id === 'queued' && data.queue.waiting > 0}>{tr(s.label)}{tr(s.id === 'queued' && data.queue.waiting > 0 ? ` (${data.queue.waiting})` : '')}</span>))}</div><div className="monitor-device-selectors">{tr(devices.length > 1 ? <Select ariaLabel={tr("Monitor GPU")} value={gpuChoice} options={[...(selectedInstance ? [{ value: 'assigned', label: 'Assigned GPUs' }] : []), { value: 'all', label: `All GPUs (${defaultDevices.length})` }, ...devices.map((gpu, i) => ({ value: gpuId(gpu), label: `GPU ${i + 1} · ${gpu.name}` }))]} menuMinWidth={340} onChange={setGpuSelection}/> : null)}{tr(processors.length > 1 ? <Select ariaLabel={tr("Monitor processor")} value={cpuChoice} options={[{ value: 'all', label: `All processors (${processors.length})` }, ...processors.map((p, i) => ({ value: p.id, label: `CPU ${i + 1} · ${p.model}` }))]} onChange={setCpuSelection}/> : null)}</div></div>
<div className="monitor-state__reading small"><span>{tr(multipleScope ? `${number(data.queue.running)} active · ${number(data.queue.waiting)} queued` : data.phase === 'idle' ? 'Waiting for a request' : data.phaseLabel)}</span><span className="muted num">{tr(statusDetail)}</span></div>
{tr(!multipleScope ? <Bar label={tr("Model progress")} value={progress ?? 0} indeterminate={writing && !hasReading(progress)} tone={data.phase === 'reading' ? 'info' : 'accent'}/> : null)}
</section>
+7 -57
View File
@@ -1,61 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { engineRefusal, engineTooOld, markEngine, parseEngineVersion } from '../server/engine-version.mjs';
import { nativeFixture } from './helpers/native-fixture.mjs';
import { shownEngineVersion } from '../src/lib/engine-version.ts';
test('engine versions compare as numbers, a missing part counting as zero', () => {
assert.deepEqual(parseEngineVersion('0.1.45.3'), [0, 1, 45, 3]);
assert.deepEqual(parseEngineVersion('v0.1.45'), [0, 1, 45]);
assert.equal(parseEngineVersion('dev'), null);
assert.equal(engineTooOld('0.1.45', '0.1.45.1'), true, 'the released 0.1.45 stops at v4 files: too old for Gyro');
assert.equal(engineTooOld('0.1.45.1', '0.1.45.1'), false);
assert.equal(engineTooOld('0.1.45.3', '0.1.45.1'), false);
assert.equal(engineTooOld('0.1.46', '0.1.45.1'), false);
assert.equal(engineTooOld('0.1.44.1', '0.1.45.1'), true);
assert.equal(engineTooOld('0.1.45', null), false, 'no minimum: never too old');
assert.equal(engineTooOld(null, '0.1.45.1'), false, 'an unreadable version is not called too old');
assert.equal(engineTooOld('0.1.40', '0.1.45.1', 'local'), false, 'an engine built from this checkout has it whatever its number says');
});
const catalog = () => ({ families: [{ family: 'qwen', sizes: [{ id: 'q2_0', model: 'Q2_0', engine_min: null }] }, { family: 'gyro', sizes: [{ id: 'gyro-gyro-s', model: 'Gyro-S', engine_min: '0.1.45.1' }, { id: 'gyro-gyro-m', model: 'Gyro-M', engine_min: '0.1.45.1' }] }] });
test('the catalog marks the sizes an older engine cannot read; the refusal says what to do', () => {
const marked = markEngine(catalog(), { version: '0.1.45' });
assert.deepEqual(marked.families.flatMap(f => f.sizes.map(s => [s.id, s.needsNewerEngine])), [['q2_0', false], ['gyro-gyro-s', true], ['gyro-gyro-m', true]]);
const text = engineRefusal(marked, 'gyro-gyro-s', { version: '0.1.45' });
assert.match(text, /^This model needs a newer engine: Gyro-S needs engine 0\.1\.45\.1 or newer, and this one is 0\.1\.45\. Update the engine in Settings, then try again\.$/);
assert.equal(engineRefusal(marked, 'q2_0', { version: '0.1.45' }), null);
const fresh = markEngine(catalog(), { version: '0.1.45.3' });
assert.ok(fresh.families.every(f => f.sizes.every(s => !s.needsNewerEngine)));
assert.equal(markEngine(null, {}), null);
});
test('with an older engine installed the app refuses to download or load Gyro, with the plain sentence; a new enough engine goes on', async () => {
const old = nativeFixture({ engineStatus: { version: '0.1.45', backend: 'cuda' } });
try {
old.catalog.families.push({ family: 'gyro', title: 'Qwen3.8-Flash-Next (Gyro)', about: '', images: false, sizes: [{ id: 'iq2_xs', model: 'Gyro-S', download_gb: 58, ram_needed_gb: 28, about: '', on_this_pc: 'fits', installed: true, engine_min: '0.1.45.1' }] });
old.catalog.families[0].sizes[0].engine_min = '0.1.45.1';
const state = await old.control.refresh(true);
const sizes = state.catalog.families.flatMap(f => f.sizes);
assert.ok(sizes.find(s => s.engine_min).needsNewerEngine);
const id = sizes.find(s => s.engine_min).id;
assert.throws(() => old.control.operation('load', { model: id }), /This model needs a newer engine: .* needs engine 0\.1\.45\.1 or newer, and this one is 0\.1\.45\./);
assert.throws(() => old.control.operation('install', { model: id }), /needs a newer engine/);
assert.equal(old.control.state().jobs.length, 0, 'nothing was started');
} finally { await old.cleanup(); }
const ok = nativeFixture({ engineStatus: { version: '0.1.45.3', backend: 'cuda' } });
try {
ok.catalog.families[0].sizes[0].engine_min = '0.1.45.1';
const state = await ok.control.refresh(true);
assert.ok(state.catalog.families[0].sizes.every(s => !s.needsNewerEngine));
} finally { await ok.cleanup(); }
});
test('the screens use the existing "needs a newer engine" notice for a size, and the buttons are held back', async () => {
const models = await readFile(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8');
assert.match(models, /selectedFamily && \(!selectedSize \|\| selectedSize\.needsNewerEngine\) \? <><h2 className="h3">\{tr\("This model needs a newer engine\."\)\}/);
assert.match(models, /!!selectedSize\.needsNewerEngine\}/);
const guided = await readFile(new URL('../src/components/GuidedSetup.tsx', import.meta.url), 'utf8');
assert.equal((guided.match(/needsNewerEngine/g) ?? []).length, 3);
test('About never shows the host placeholder engine version while the real one is still being read', () => {
assert.equal(shownEngineVersion({ available: false }, 'strata-engine 0.1.0'), undefined);
assert.equal(shownEngineVersion(null, 'strata-engine 0.1.0'), undefined);
assert.equal(shownEngineVersion({ available: true, installed: { engine: { version: '0.1.48' } } }, 'strata-engine 0.1.0'), '0.1.48');
assert.equal(shownEngineVersion({ available: true, installed: { engine: null } }, 'strata-engine 0.1.0'), undefined);
assert.equal(shownEngineVersion({ available: false }, 'strata-engine 0.1.51'), 'strata-engine 0.1.51');
});
+14 -1
View File
@@ -4,7 +4,7 @@ import { parseCpuTopology, parseNvidiaReadings, parsePcieThroughput, gpuMemoryTo
import { cpuUtilization, diskRate, parseLinuxDiskCounters, parseMacDiskCounters } from '../server/system-telemetry.mjs';
import { parseEngineMetrics } from '../server/supervisor.mjs';
import { originalDashboard } from '../server/monitor-dashboard.mjs';
import { gpuMetric, gpuCapacity, gpuReported, shortGpuName } from '../src/lib/monitor-hardware.ts';
import { gpuMetric, gpuCapacity, gpuReported, shortGpuName, defaultGpuSet, gpuId } from '../src/lib/monitor-hardware.ts';
import { referencePaths } from '../src/lib/monitor-chart.ts';
const gpu=(id,index=0,unified=false)=>({id,index,unified,vramGb:24,name:id,vendor:'nvidia',backend:'cuda'});
@@ -104,3 +104,16 @@ test('All GPUs: a card with no temperature sensor is left out and the card that
assert.equal(shortGpuName('AMD Radeon RX 9070 XT'),'RX 9070 XT');
assert.equal(shortGpuName('Intel(R) Arc(TM) A750 Graphics'),'A750 Graphics');
});
test('an RTX 5070 beside the unsupported Radeon iGPU: All GPUs is the RTX alone, the iGPU stays pickable',()=>{
const rtx={id:'GPU-5070',index:0,vendor:'nvidia',name:'NVIDIA GeForce RTX 5070',vramGb:11.9,unified:false,backend:'cuda'};
const igpu={id:'PCI\VEN_1002&DEV_164E',index:1,vendor:'amd',name:'AMD Radeon(TM) Graphics',vramGb:0.5,unified:false,backend:'vulkan'};
const set=defaultGpuSet([rtx,igpu]);
assert.deepEqual(set.map(g=>g.id),['GPU-5070']);
assert.equal(gpuCapacity(set),11.9);
// the native engine report numbers each make from 0, so both cards say index 0: the ids stay different
assert.notEqual(gpuId({...rtx,id:undefined}),gpuId({...igpu,id:undefined,index:0}));
// alone, or a real AMD card beside it, nothing is dropped
assert.deepEqual(defaultGpuSet([igpu]).map(g=>g.id),[igpu.id]);
assert.equal(defaultGpuSet([{...igpu,vramGb:96,unified:true},rtx]).length,2);
});
+7
View File
@@ -539,6 +539,13 @@ def tool_arguments(raw) -> dict:
return {"arguments": json.dumps(raw, ensure_ascii=False)}
def require_messages(messages: list) -> None:
"""A chat request with no message at all is a 400 (OpenAI: "empty array. Expected an array with minimum length 1"); the
template would otherwise render just the assistant turn and the model would answer nothing."""
if not messages:
raise ValueError("messages must be a non-empty list: send at least one message")
def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]:
"""OpenAI Chat Completions -> (template messages, template tools, template kwargs)."""
messages = []
+4 -3
View File
@@ -61,7 +61,7 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
sys.path.insert(0, str(ROOT)) # run as a script (run-<model>.bat) as well as a module
from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthropic_to_messages, # noqa: E402
forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages,
forced_call, images_of, literal_tags, mark_think_literals, openai_to_messages, require_messages,
tool_choice_of, unmark_think_literals)
from serve.mcp import McpCancelled, hub_from_config # noqa: E402
from serve import runconfig # noqa: E402
@@ -5516,7 +5516,7 @@ class Service:
"engine_generated": last.get("generated"),
"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),
"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)
if n and last.get("generated") and last.get("decode_ms") else None,
if n and (last.get("generated") or 0) >= 2 and last.get("decode_ms") else None,
"hit_rate": hit_rate, "pcie_share": pcie_share, "ram_blobs": last.get("ram_blobs"),
"file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb"),
# #457: the speculative drafts from the DONE line (None: the engine did not say)
@@ -5650,7 +5650,7 @@ def answer_speed(last: dict, generated: int, wall_s: float | None = None) -> flo
Only an engine that sent no DONE falls back to the server's own clock from the first token, and a clock younger than
RATE_MIN_SPAN_S says nothing (it printed 1000000 tok/s for a one-token reply). Prompt reading is never in it."""
produced, decode_ms = last.get("generated"), last.get("decode_ms")
if produced and decode_ms and decode_ms > 0:
if produced and produced >= 2 and decode_ms and decode_ms > 0: # one token has no first-to-last span (a 1-token probe printed 1,250 tok/s)
return round(produced / (decode_ms / 1000), 1)
if generated and wall_s is not None and wall_s >= RATE_MIN_SPAN_S:
return round(generated / wall_s, 1)
@@ -7136,6 +7136,7 @@ def make_handler(svc: Service):
req = svc.with_shared(req, "openai")
bias_api.normalize(req.get("logit_bias"), len(getattr(svc.tok, "tokens", ())) or None)
messages, tools, kw = openai_to_messages(req)
require_messages(messages) # an empty conversation is a 400, as OpenAI answers it, not a reply to nothing
self._no_local_images(messages)
if tool_choice_of(req.get("tool_choice"))[0] == "none": # as the Responses route: no tools are offered
tools = None
+1
View File
@@ -28,6 +28,7 @@ class AnswerSpeed(unittest.TestCase):
self.assertEqual(answer_speed({**self.REAL, "drafts_offered": 500}, 73), 65.9)
def test_a_one_token_reply_has_no_absurd_rate(self):
self.assertIsNone(answer_speed({"generated": 1, "decode_ms": 0.8}, 1, None)) # a 1-token probe: 1 / 0.8 ms was 1,250 tok/s
self.assertIsNone(answer_speed({}, 1, 1e-6))
self.assertIsNone(answer_speed({}, 1, None))
+10 -1
View File
@@ -3,7 +3,7 @@ import copy
from pathlib import Path
import unittest
from serve.frontend import ChatTemplate, anthropic_to_messages, openai_to_messages
from serve.frontend import ChatTemplate, anthropic_to_messages, openai_to_messages, require_messages
from serve.server import ByteTokenizer, MockEngine, Service
@@ -340,3 +340,12 @@ class FencedJsonCallInWrapper(unittest.TestCase):
other = [{"name": "other", "parameters": {}}]
calls, text = self.run_parser(raw, len(raw), False, tools=other)
self.assertEqual((calls, text), ([], raw))
class EmptyConversation(unittest.TestCase):
def test_no_message_is_an_error_a_message_is_not(self):
with self.assertRaises(ValueError):
require_messages(openai_to_messages({"messages": []})[0])
with self.assertRaises(ValueError):
require_messages(openai_to_messages({})[0])
require_messages(openai_to_messages({"messages": [{"role": "user", "content": "hi"}]})[0])
+1 -1
View File
@@ -58,7 +58,7 @@ def request_speed(r: dict) -> float | None:
out, ms = _num(r.get("output_tokens")), _num(r.get("decode_ms"))
if r.get("decode_tok_s") is not None and _num(r.get("decode_tok_s")) is not None:
return _num(r.get("decode_tok_s"))
return round(out / (ms / 1000.0), 1) if out and ms and ms > 0 else None
return round(out / (ms / 1000.0), 1) if out and out >= 2 and ms and ms > 0 else None # one token has no decode span (a probe showed 1,250 tok/s)
def _cards(hw: dict, static: dict) -> list[dict]:
+2
View File
@@ -975,6 +975,8 @@ class Strata:
except Exception: # noqa: BLE001 - unknown stays unknown: the app then keeps its safety default
pass
hw["gpus"] = nv + amd
for g in hw["gpus"]: # each make numbers its cards from 0 (the engine drives one make): a stable id tells two cards apart
g.setdefault("id", f"{g.get('vendor') or 'gpu'}:{g.get('index')}")
try: # how fast each card is (SMs x clock): the app and the Terminal pick the Main card by it
from strata_control import gpu_roles
gpu_roles.add_speeds(hw["gpus"])
+3
View File
@@ -811,6 +811,9 @@ class MixedGraphics(unittest.TestCase):
self.assertTrue(by["nvidia"]["usable"])
self.assertFalse(by["amd"]["usable"])
self.assertIn("NVIDIA card", by["amd"]["problem"])
# the RTX and the Ryzen iGPU both say index 0 (each make counts from 0), so the report gives each a stable id of its own
self.assertEqual((by["nvidia"]["index"], by["amd"]["index"]), (0, 0))
self.assertEqual(sorted(g["id"] for g in hw["gpus"]), ["amd:0", "nvidia:0"])
rec = s.recommend({**hw, "ram_gb": 92.0})
self.assertEqual((rec["backend"], rec["gpu"]["name"]), ("cuda", "NVIDIA GeForce RTX 5090"))
# with no NVIDIA card the integrated GPU stays what it was