Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

First-run engine card: GPU, engine size, one Download button, progress with resume, 'I already have the file' (offline), plain states; host routes /api/engine/first-run, /job and /from-file; install-engine-file job

Niko1221ec03ae010633
diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs
index 022af1142..f0f64dba4 100644
--- a/apps/host/server/control-runtime.mjs
+++ b/apps/host/server/control-runtime.mjs
@@ -183,6 +183,12 @@ export function createControl({ control = findControl(), env = process.env, run
if (failed) throw Object.assign(new ControlError(failed.error, { exitCode: failed.exit_code ?? result.code, output: result.json }), { code: result.code === 7 ? 'engine_serving' : 'update_failed' });
throw failure(result, 'The update failed.');
},
+ /** Install an engine package the person downloaded and chose (the offline path): no network; Control checks the package's own signature. */
+ async installEngineFile(path, { onEvent = null, signal = null } = {}) {
+ const result = await call(['components', 'install-file', path, '--output', 'jsonl'], { timeoutMs: 3600_000, onLine: onEvent ?? (() => {}), signal });
+ if (result.json?.ok) return { ok: true, results: [result.json] };
+ throw failure(result, 'This file could not be installed.');
+ },
async rollbackEngine() {
const result = await call(['components', 'rollback', '--output', 'json'], { timeoutMs: 120_000 });
if (result.json?.ok) return result.json;
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index b033c6bbe..f8438dbee 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -32,7 +32,8 @@ import { findBrowser, findPlaywrightMcp } from './agent/browser-probe.mjs';
*/
import http from 'node:http';
import { homedir } from 'node:os';
-import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { pipeline } from 'node:stream/promises';
import { spawn } from 'node:child_process';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
@@ -61,7 +62,7 @@ import { createForkTimeskip } from './timeskip-fork.mjs';
import { prepareOversized } from './oversize.mjs';
import { createChatFolders, chatRootOf, openFile, resolveChatFile, previewFile, rawFile, createAttachments, withAttachments } from './chat-files.mjs';
import { createLlmProxy, samplingFromExpert } from './agent/llm-shape.mjs';
-import { checkUpdates, checkComponentUpdates } from './updates.mjs';
+import { checkUpdates, checkComponentUpdates, engineFirstRun } from './updates.mjs';
import { plainNoModel } from './no-model-text.mjs';
import { createAppUi } from './app-ui.mjs';
import { appVersionFrom, appVersionToShow } from './app-version.mjs';
@@ -1327,6 +1328,25 @@ async function api(req, res, path, method, url) {
}
if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState());
+ if (path === '/api/engine/first-run' && method === 'GET') {
+ if (!control?.updateCheck) return json(res, 200, { status: 'unavailable', gpus: [] });
+ return json(res, 200, await engineFirstRun({ control, gpus: hardware.cachedHardware()?.gpus ?? [] }));
+ }
+ if (path === '/api/engine/job' && method === 'GET') {
+ // The newest engine download / file install, read without waiting for the native snapshot to connect (the first-run card needs it before that).
+ const kinds = ['update-engine', 'install-engine-file'];
+ return json(res, 200, { job: native.state().jobs.filter(j => kinds.includes(j.kind)).slice(-1)[0] ?? null });
+ }
+ if (path === '/api/engine/from-file' && method === 'POST') {
+ // The person chose an engine package in the page (the offline path). The bytes come here; Control checks and installs them.
+ const name = String(req.headers['x-file-name'] ?? 'engine.tar.gz').replace(/[^A-Za-z0-9._-]/g, '_').slice(-120);
+ if (!/\.(tar\.gz|tgz|tar\.xz|zip)$/i.test(name)) return error(res, 400, 'This is not a Strata engine package. Choose the .tar.gz or .zip file from the release page.');
+ const folder = join(store.DATA_DIR, 'incoming-engine');
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
+ const target = join(folder, name);
+ await pipeline(req, createWriteStream(target, { mode: 0o600 }));
+ return json(res, 202, native.operation('install-engine-file', { path: target }));
+ }
if (path === '/api/updates/check' && method === 'GET' && control?.updateCheck) return json(res, 200, await checkComponentUpdates({ control, appUpdater, appVersion: process.env.STRATA_APP_VERSION || null }));
if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:appVersionToShow(setupState().app.version,native.state().version), engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version }));
diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs
index d2235ded8..291388e0f 100644
--- a/apps/host/server/native-control.mjs
+++ b/apps/host/server/native-control.mjs
@@ -55,7 +55,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
const defaultInstall=()=>process.env.STRATA_INSTALL_DIR?resolve(process.env.STRATA_INSTALL_DIR):join(dirname(componentsDirectory()),'install');
let packagedInstall=null;
/* The component updates and the rollback go through Control, not through the native snapshot, so they work in the first seconds after the app starts and on a PC that has no engine yet. */
- const COMPONENT_KINDS=['update-engine','update-strata','rollback'];
+ const COMPONENT_KINDS=['update-engine','update-strata','rollback','install-engine-file'];
const updateLog=line=>{try{console.log(`update · ${line}`);}catch{/* no console */}};
const NO_INSTALL='Installing, updating, tuning with calibration or rolling back model files and engines happens from the Terminal (strata install), never while the app runs.';
let defaultId=null,timer=null,closing=false,polling=false;
@@ -338,7 +338,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
function ensurePoll(){if(!timer){timer=setInterval(()=>void poll(),2000);timer.unref?.();}void poll();}
async function benchmark(job,args){const instance=resolveInstance(args.instanceId);job.instanceId=instance.id;if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Wait for this model to finish before benchmarking.');const started=Date.now();job.abort=new AbortController();const response=await fetcher(`http://127.0.0.1:${instance.port}/v1/chat/completions`,{method:'POST',headers:{'content-type':'application/json',authorization:`Bearer ${instance.key}`},signal:AbortSignal.any([job.abort.signal,AbortSignal.timeout(180000)]),body:JSON.stringify({model:instance.apiModelId,messages:[{role:'user',content:'Explain how a rainbow forms in clear, simple language.'}],temperature:0,reasoning_effort:'none',max_tokens:200,stream:false})});const body=await response.json();if(!response.ok)throw new Error(body.error?.message??'Benchmark failed.');if(job.state!=='running')return;const result={summary:'Measured benchmark complete.',at:new Date().toISOString(),model:instance.apiModelId,durationMs:Date.now()-started,tokensIn:body.usage?.prompt_tokens??null,tokensOut:body.usage?.completion_tokens??null,outputTps:body.timings?.predicted_per_second??null,promptTps:body.timings?.prompt_per_second??null,source:'engine',settings:'Greedy · thinking off · up to 200 output tokens'};writeFileSync(join(directory,'native-benchmark.json'),JSON.stringify(result,null,2),{mode:0o600});return result;}
function resolveInstance(id){const aliases=[...instances.values()].filter(i=>i.aliases?.includes(id));if(aliases.length>1&&!instances.has(id)&&![...instances.values()].some(i=>i.apiModelId===id))throw new Error('This alias matches more than one instance. Choose its exact model ID.');const i=instances.get(id)??[...instances.values()].find(i=>i.apiModelId===id)??aliases[0]??(!id&&instances.size===1?[...instances.values()][0]:undefined);if(!i)throw new Error('Choose a loaded model ID.');if(i.status!=='ready')throw new Error('This model is not ready.');return i;}
- async function program(job,args){if(packaged)return componentProgram(job);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;
+ async function program(job,args){if(packaged)return componentProgram(job,args);if(externalRunning().length)throw new Error('Stop the native server running outside this UI before changing engine files.');if(instances.size)throw new Error('Unload native models before changing engine files.');const folder=repo();let {command,args:prefix}=python(),argv;
if(job.kind==='calibrate'||job.kind==='tune'){if(!state().capabilities.calibration)throw new Error('This installation calibrates NVIDIA GPUs only. Use the short benchmark on other devices.');const model=args.model??snapshot.installed?.models?.[0]?.model;const chosen=record(model);if(!chosen.entry.ready)throw new Error('Prepare this model before calibrating.');command=venvPython(folder);prefix=[];if(!existsSync(command))throw new Error('Prepare the Python environment first.');argv=['-c','import sys; from pathlib import Path; import setup; sys.exit(0 if setup.calibrate_config(Path(sys.argv[1])) else 1)',chosen.path];}
else if(job.kind==='rollback'){if(!previousEngine())throw new Error('No saved previous engine is available.');argv=[join(folder,'setup.py'),'--rollback-engine'];}
else if(job.kind==='update-engine'){if(!snapshot.installed?.models?.length)throw new Error('Prepare a model first. Its installer downloads the matching engine.');argv=[join(folder,'setup.py'),'--update'];}
@@ -349,14 +349,14 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
/* Packaged app: engine and Control updates and the engine rollback go through Control's explicit update step (`strata update`,
`strata components rollback`), never through git, setup.py or a download in this process. The app itself is updated by the
shell's signed Tauri updater. Models are not part of any of it. */
- async function componentProgram(job){
- if(!['update-engine','update-strata','rollback'].includes(job.kind)||typeof control.update!=='function')throw new Error(NO_INSTALL);
+ async function componentProgram(job,args={}){
+ if(!COMPONENT_KINDS.includes(job.kind)||typeof control.update!=='function')throw new Error(NO_INSTALL);
if(instances.size)throw new Error('Unload native models before changing engine files.');
job.abort=new AbortController();
const subject=job.kind==='update-strata'?'Strata':'engine';
- try{return await componentSteps(job,subject);}catch(error){updateLog(`${job.kind} failed: ${String(error?.message??error).slice(0,400)}`);throw error?.details!==undefined&&error.message?error:plainError(error,subject);}
+ try{return await componentSteps(job,subject,args);}catch(error){updateLog(`${job.kind} failed: ${String(error?.message??error).slice(0,400)}`);throw error?.details!==undefined&&error.message?error:plainError(error,subject);}
}
- async function componentSteps(job,subject){
+ async function componentSteps(job,subject,args={}){
const onEvent=event=>{
if(event.event==='progress'){job.summary=`Downloading: ${event.percent}%`;job.result={install:{step:job.summary,download:{file:event.label,percent:event.percent}}};}
else if(event.event==='phase'&&PHASE_TEXT[event.phase])job.summary=PHASE_TEXT[event.phase];
@@ -364,6 +364,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
emit();
};
updateLog(`${job.kind} started (app ${thisAppVersion()??'unknown'})`);
+ if(job.kind==='install-engine-file'){if(typeof args.path!=='string'||!args.path)throw new Error('Choose the engine file first.');let done;try{done=await control.installEngineFile(args.path,{onEvent,signal:job.abort.signal});}finally{try{const own=resolve(directory,'incoming-engine')+sep;if(resolve(args.path).startsWith(own))rmSync(args.path,{force:true});}catch{/* the copy in the host's own folder; a leftover is harmless */}}return {summary:updateSummary(done)==='Everything is already up to date.'?(done.results?.[0]?.note??'Nothing was changed.'):updateSummary(done),result:done};}
if(job.kind==='rollback'){const done=await control.rollbackEngine();return {summary:'The previous engine is back. Your models and settings are unchanged.',result:done};}
if(job.kind==='update-engine'){const done=await control.update({engine:true,control:false,onEvent,signal:job.abort.signal});return {summary:updateSummary(done),result:done};}
const done=await control.update({engine:false,control:true,onEvent,signal:job.abort.signal});
@@ -420,7 +421,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
const room=args.resourceProfile==='work';
return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}});
}
- function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available&&!(packaged&&COMPONENT_KINDS.includes(kind)))throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});}
+ function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','install-engine-file','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available&&!(packaged&&COMPONENT_KINDS.includes(kind)))throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});}
/* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */
const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null;
const moveFile=()=>join(directory,'models-move.cancel');
diff --git a/apps/host/server/updates.mjs b/apps/host/server/updates.mjs
index 36ac65425..3b0c6704a 100644
--- a/apps/host/server/updates.mjs
+++ b/apps/host/server/updates.mjs
@@ -90,3 +90,28 @@ export async function checkComponentUpdates({ control, appUpdater = null, appVer
else Object.assign(strata, { status: 'current', message: 'Strata is up to date.' });
return { checkedAt, feed: report.feed, strata, engine: engineView, serving: report.serving ?? [] };
}
+
+/**
+ * What the first-run card shows: this PC's graphics card(s), the engine package the signed feed offers for it and how big it is.
+ * One feed read, nothing downloaded. `status`: offer (a package fits), none (nothing fits; `reasons` say why), offline (the feed could not be
+ * read), installed (an engine is already here), wrong-make (an engine for another make of card is installed).
+ */
+export async function engineFirstRun({ control, gpus = [] }) {
+ const cards = gpus.map(g => ({ name: g.name ?? 'Graphics card', vramGb: g.vramGb ?? null }));
+ let report;
+ try {
+ report = await control.updateCheck({});
+ } catch (error) {
+ const plain = plainUpdateError(error, 'Strata');
+ return { status: looksOffline(error) || /update server|No internet/.test(plain.headline ?? '') ? 'offline' : 'error', gpus: cards, message: plain.message, details: plain.details };
+ }
+ const engine = report.engine ?? {};
+ const hardware = report.hardware ?? {};
+ const base = { gpus: cards, driver: hardware.nvidia_driver ?? null, backend: hardware.backend ?? null };
+ if (engine.installed) return { ...base, status: 'installed', installedVersion: engine.installed.version ?? null };
+ if (engine.status === 'wrong-make') return { ...base, status: 'wrong-make', message: engine.note ?? null, reasons: engine.reasons ?? [] };
+ if (engine.offered && (engine.status === 'install' || engine.status === 'available')) {
+ return { ...base, status: 'offer', offer: { version: engine.offered.version, bytes: engine.download_bytes || engine.offered.size || 0, variant: engine.offered.variant ?? '', backend: engine.offered.backend ?? null } };
+ }
+ return { ...base, status: 'none', message: engine.note ?? null, reasons: engine.reasons ?? [] };
+}
diff --git a/apps/host/src/components/EngineFirstRun.tsx b/apps/host/src/components/EngineFirstRun.tsx
new file mode 100644
index 000000000..c4678323a
--- /dev/null
+++ b/apps/host/src/components/EngineFirstRun.tsx
@@ -0,0 +1,170 @@
+import { tr } from '../lib/i18n';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Brand } from './Brand';
+import { Bar, Btn, Icon } from './ui';
+import { api } from '../lib/client';
+import { useDownloadEta } from '../lib/download-eta';
+import type { NativeJob } from '../lib/native';
+
+/** What the host says about this PC's engine (GET /api/engine/first-run). */
+export interface FirstRunInfo {
+ status: 'offer' | 'none' | 'offline' | 'error' | 'installed' | 'wrong-make' | 'unavailable';
+ gpus: { name: string; vramGb: number | null }[];
+ driver?: string | null;
+ offer?: { version: string; bytes: number; variant: string; backend: string | null };
+ message?: string | null;
+ reasons?: string[];
+ details?: string;
+}
+
+const MB = 1024 * 1024;
+export const mb = (bytes: number) => Math.max(1, Math.round(bytes / MB));
+
+/**
+ * Whether this PC still needs its engine. Reads only Control's local answer (no network): the engine is missing and the engine that came
+ * with the app is not being unpacked. `null` while that is not known yet.
+ */
+export function useEngineNeeded(): boolean | null {
+ const [needed, setNeeded] = useState<boolean | null>(null);
+ useEffect(() => {
+ let live = true;
+ const ask = () => api.get<{ engine?: { usable?: boolean } | null; engineSetup?: boolean }>('/api/control/status').then(s => {
+ if (!live) return;
+ if (s.engineSetup) return setNeeded(null);
+ setNeeded(!!s.engine && s.engine.usable === false);
+ }, () => { if (live) setNeeded(false); });
+ void ask();
+ const timer = setInterval(() => void ask(), 3000);
+ return () => { live = false; clearInterval(timer); };
+ }, []);
+ return needed;
+}
+
+function gpuLine(info: FirstRunInfo) {
+ const first = info.gpus[0];
+ if (!first) return '';
+ const vram = first.vramGb ? `, ${Math.round(first.vramGb)} GB` : '';
+ const driver = info.driver ? `, driver ${info.driver}` : '';
+ return `${first.name}${vram}${driver}`;
+}
+
+/**
+ * The first-run card: the engine this PC needs, one button to download it, progress, and the offline way (choose a downloaded file).
+ * Nothing is downloaded before a button is pressed.
+ */
+export function EngineFirstRun({ onDone }: { onDone: () => void }) {
+ const [info, setInfo] = useState<FirstRunInfo | null>(null);
+ const [job, setJob] = useState<NativeJob | null>(null);
+ const [busy, setBusy] = useState(false), [problem, setProblem] = useState('');
+ const [finished, setFinished] = useState(false);
+ const file = useRef<HTMLInputElement>(null);
+ const started = useRef(false);
+
+ const look = useCallback(() => {
+ setInfo(null);
+ setProblem('');
+ api.get<FirstRunInfo>('/api/engine/first-run').then(setInfo, e => setInfo({ status: 'error', gpus: [], message: e instanceof Error ? e.message : String(e) }));
+ }, []);
+ useEffect(() => { look(); }, [look]);
+
+ // follow the download / install job
+ useEffect(() => {
+ const timer = setInterval(() => {
+ if (!started.current) return;
+ api.get<{ job: NativeJob | null }>('/api/engine/job').then(r => {
+ setJob(r.job);
+ if (r.job?.state === 'done') setFinished(true);
+ if (r.job && r.job.state !== 'running') started.current = false;
+ }, () => { });
+ }, 700);
+ return () => clearInterval(timer);
+ }, []);
+
+ async function start() {
+ setBusy(true);
+ setProblem('');
+ try {
+ started.current = true;
+ setJob(await api.post<NativeJob>('/api/native/operations', { kind: 'update-engine', args: {} }));
+ }
+ catch (e) {
+ started.current = false;
+ setProblem(e instanceof Error ? e.message : String(e));
+ }
+ finally {
+ setBusy(false);
+ }
+ }
+ async function chosen(files: FileList | null) {
+ const picked = files?.[0];
+ if (!picked) return;
+ setBusy(true);
+ setProblem('');
+ try {
+ const response = await fetch('/api/engine/from-file', { method: 'POST', headers: { 'x-file-name': picked.name }, body: picked });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(body?.error ?? `The file could not be used (${response.status}).`);
+ started.current = true;
+ setJob(body as NativeJob);
+ }
+ catch (e) {
+ setProblem(e instanceof Error ? e.message : String(e));
+ }
+ finally {
+ setBusy(false);
+ if (file.current) file.current.value = '';
+ }
+ }
+
+ const running = job?.state === 'running';
+ const failed = !!job && (job.state === 'error' || job.state === 'cancelled');
+ const percent = Number(job?.result?.install?.download?.percent ?? 0);
+ const bytes = info?.offer?.bytes ?? 0;
+ const doneMb = Math.round(mb(bytes) * percent / 100);
+ const eta = useDownloadEta(running && bytes ? { done_gb: bytes * percent / 100 / 1e9, remaining_gb: bytes * (100 - percent) / 100 / 1e9 } : undefined, job?.id);
+ const cards = info?.gpus.length ?? 0;
+ const hidden = <input ref={file} type="file" accept=".gz,.tgz,.xz,.zip" hidden onChange={e => void chosen(e.target.files)}/>;
+ const pick = (label: string) => <button type="button" className="onboard-continue-anyway" disabled={busy || running} onClick={() => file.current?.click()}>{tr(label)}</button>;
+
+ let body;
+ if (finished) {
+ body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("The engine is ready.")}</h1><p>{tr("Next: pick a model.")}</p></div>
+ <footer className="onboard-footer onboard-footer--welcome"><Btn variant="primary" onClick={onDone}>{tr("Continue")}<Icon name="chevron" size={16}/></Btn></footer></>;
+ }
+ else if (running) {
+ body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Downloading the engine")}</h1>
+ <p>{bytes && job?.result?.install?.download ? `${doneMb} of ${mb(bytes)} MB${eta ? ' · ' + eta : ''}` : tr(job?.summary ?? 'Starting…')}</p></div>
+ <div className="onboard-error" style={{ maxWidth: 520, margin: '0 auto', width: '100%' }}><Bar value={percent} label="Downloading the engine"/><p className="small muted" style={{ textAlign: 'center' }}>{tr("You can close Strata; it continues where it stopped.")}</p></div></>;
+ }
+ else if (!info) {
+ body = <div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Welcome to Strata")}</h1><p role="status">{tr("Looking at your graphics card…")}</p></div>;
+ }
+ else {
+ const card = gpuLine(info);
+ const found = card ? <p>{tr("Strata found your graphics card:")}<br/><strong>{card}</strong>{cards > 1 ? <><br/><span className="small muted">{tr("{0} cards found. Strata uses the first one for the engine; change it later in Settings.", [cards])}</span></> : null}</p>
+ : <p>{tr("Strata did not recognise a supported graphics card.")}</p>;
+ let main, actions;
+ if (info.status === 'offer' && info.offer) {
+ main = <>{found}<p>{tr("To run models on it, Strata needs one download:")}<br/><strong>{tr("The engine for this card")} {'—'} {mb(info.offer.bytes)} MB</strong></p>
+ <p className="small muted">{tr("It comes from Strata’s own update server and is checked before it is used. Your models and chats are never touched by it.")}</p></>;
+ actions = <><Btn variant="primary" disabled={busy} onClick={() => void start()}>{tr(failed ? 'Continue' : 'Download the engine')}</Btn>{pick("I already have the file…")}</>;
+ }
+ else if (info.status === 'offline') {
+ main = <>{found}<p>{tr("Strata could not reach github.com. Check your connection and try again, or download the engine file on another PC and choose it here.")}</p></>;
+ actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}</>;
+ }
+ else if (info.status === 'wrong-make') {
+ main = <>{found}<p>{info.message ?? tr("The engine installed here is for another make of graphics card.")}</p></>;
+ actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}</>;
+ }
+ else {
+ main = <>{found}<p>{tr("Strata can’t pick an engine for this PC from its update list.")}</p>{info.message ? <p className="small muted">{info.message}</p> : null}{(info.reasons ?? []).length ? <ul className="small muted" style={{ textAlign: 'left', display: 'inline-block' }}>{(info.reasons ?? []).map(r => <li key={r}>{r}</li>)}</ul> : null}</>;
+ actions = <><Btn variant="primary" disabled={busy} onClick={look}>{tr("Try again")}</Btn>{pick("Choose a downloaded file…")}<button type="button" className="onboard-continue-anyway" onClick={onDone}>{tr("Continue without an engine")}</button></>;
+ }
+ body = <><div className="onboard-welcome-copy"><h1 tabIndex={-1} data-initial-focus>{tr("Welcome to Strata")}</h1>{main}</div>
+ {failed ? <div className="onboard-error" style={{ maxWidth: 560, margin: '0 auto' }}><p role="alert" className="small inline-error">{job?.error ?? job?.summary}</p><p className="small muted">{tr("The download stopped. Continue picks it up where it stopped.")}</p></div> : null}
+ {problem ? <div className="onboard-error" style={{ maxWidth: 560, margin: '0 auto' }}><p role="alert" className="small inline-error">{problem}</p></div> : null}
+ <footer className="onboard-footer onboard-footer--welcome">{actions}</footer></>;
+ }
+ return <div className="setup guided-onboarding" data-step="engine">{hidden}<header className="onboard-header"><Brand variant="lockup" height={22}/></header>{body}</div>;
+}
diff --git a/apps/host/src/screens/Setup.tsx b/apps/host/src/screens/Setup.tsx
index 9ecbf62a1..3b5f2282f 100644
--- a/apps/host/src/screens/Setup.tsx
+++ b/apps/host/src/screens/Setup.tsx
@@ -3,10 +3,16 @@ import { GuidedSetup } from '../components/GuidedSetup';
import { useNative } from '../lib/native';
import { useStore } from '../lib/store';
import { useEngineUnpacking } from '../lib/engine-setup';
+import { EngineFirstRun, useEngineNeeded } from '../components/EngineFirstRun';
+import { useState } from 'react';
/** Every setup entry uses the same guided onboarding. */
export function SetupScreen() {
const native = useNative(), setup = useStore(s => s.setup);
+ const needsEngine = useEngineNeeded(), [engineStepDone, setEngineStepDone] = useState(false);
const unpacking = useEngineUnpacking(!native || !setup);
+ // No engine on this PC yet: the first-run card comes before the model steps (it works before the native snapshot has connected).
+ if (!engineStepDone && !setup?.complete && needsEngine)
+ return <EngineFirstRun onDone={() => setEngineStepDone(true)}/>;
if (!native || !setup)
return <div className="setup guided-onboarding"><p className="onboard-loading" role="status">{tr("Getting your setup ready\u2026")}</p>{unpacking ? <p className="onboard-loading small" role="status">{tr("Unpacking the engine that came with the app. This takes about a minute the first time.")}</p> : null}</div>;
return <GuidedSetup />;
diff --git a/apps/host/tests/component-updates.test.mjs b/apps/host/tests/component-updates.test.mjs
index fa6cca319..c5a3d556d 100644
--- a/apps/host/tests/component-updates.test.mjs
+++ b/apps/host/tests/component-updates.test.mjs
@@ -1,11 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from 'node:fs';
import { join, basename } from 'node:path';
import { tmpdir } from 'node:os';
import { bundledPython, controlEnvironment, createControl, findControl, runCli, updatedControlDirectory } from '../server/control-runtime.mjs';
-import { checkComponentUpdates } from '../server/updates.mjs';
+import { checkComponentUpdates, engineFirstRun } from '../server/updates.mjs';
import { createAppUpdater } from '../server/app-updater.mjs';
import { createNativeControl } from '../server/native-control.mjs';
@@ -187,6 +187,7 @@ function fixture({ withApp = false, update, appInstall } = {}) {
previous = '0.1.45-windows-x86_64-cuda';
return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] };
},
+ async installEngineFile(path, options) { calls.push(['install-file', path]); options.onEvent?.({ event: 'phase', phase: 'verify', message: 'Checking' }); return { ok: true, results: [{ component: 'engine', status: 'updated', installed_after: { version: '0.1.46' } }] }; },
async rollbackEngine() { calls.push(['rollback']); previous = null; return { ok: true, to: '0.1.45' }; },
};
const spawned = [];
@@ -303,6 +304,40 @@ test('packaged: "Update engine" works in the first seconds, before the native sn
} finally { await f.native.close(); f.cleanup(); }
});
+test('packaged: a chosen engine file goes to Control; only a file in the own incoming folder is deleted afterwards', async () => {
+ const f = fixture();
+ try {
+ const incoming = join(f.data, 'incoming-engine');
+ mkdirSync(incoming, { recursive: true });
+ const mine = join(incoming, 'strata-engine-x.tar.gz'), theirs = join(f.data, 'keep-me.tar.gz');
+ writeFileSync(mine, 'x'); writeFileSync(theirs, 'y');
+ const job = await finish(f.native, f.native.operation('install-engine-file', { path: mine }).id);
+ assert.equal(job.state, 'done', job.error);
+ assert.deepEqual(f.calls.at(-1), ['install-file', mine]);
+ assert.equal(existsSync(mine), false, 'the copy the page uploaded is removed');
+ const other = await finish(f.native, f.native.operation('install-engine-file', { path: theirs }).id);
+ assert.equal(other.state, 'done', other.error);
+ assert.equal(existsSync(theirs), true, 'a file anywhere else is never deleted');
+ const none = await finish(f.native, f.native.operation('install-engine-file', {}).id);
+ assert.equal(none.state, 'error');
+ assert.equal(f.calls.filter(c => c[0] === 'install-file').length, 2, 'no file, no install');
+ } finally { await f.native.close(); f.cleanup(); }
+});
+
+test('first-run card data: an offer with its size, nothing-fits with reasons, offline, and an engine already there', async () => {
+ const gpus = [{ name: 'NVIDIA GeForce RTX 5070', vramGb: 12 }];
+ const report = engine => ({ ok: true, hardware: { nvidia_driver: '581.15', backend: 'cuda' }, engine });
+ const offer = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'install', installed: null, offered: { version: '0.1.48', variant: 'cuda13', backend: 'cuda' }, download_bytes: 581299508 }) }, gpus });
+ assert.deepEqual([offer.status, offer.offer.bytes, offer.driver, offer.gpus[0].name], ['offer', 581299508, '581.15', 'NVIDIA GeForce RTX 5070']);
+ const none = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'none-for-this-pc', installed: null, offered: null, reasons: ['needs NVIDIA driver 580.65 or newer, this PC has 560.1'] }) }, gpus });
+ assert.equal(none.status, 'none');
+ assert.match(none.reasons[0], /driver 580/);
+ const installed = await engineFirstRun({ control: { updateCheck: async () => report({ status: 'current', installed: { version: '0.1.48' }, offered: null }) }, gpus });
+ assert.equal(installed.status, 'installed');
+ const offline = await engineFirstRun({ control: { updateCheck: async () => { throw new Error('the update feed could not be read: could not read https://github.com/x (URLError: [WinError 10060] timed out)'); } }, gpus });
+ assert.equal(offline.status, 'offline');
+});
+
test('without the shell bridge "Update Strata" still updates Control and says nothing false about the app', async () => {
const f = fixture();
try {