host: Settings update check, Update engine/Strata and rollback through Control's explicit update step; shell bridge client; updated Control is found
This commit is contained in:
1 parent
13cd63567e
commit
d3c4bba4ca
10 files changed
+492
-30
No files matched your search
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The App Host's client of the desktop shell's update bridge.
|
||||
*
|
||||
* The desktop app updates itself with Tauri's signed updater, which lives in the Rust shell (apps/desktop/src-tauri). The
|
||||
* UI is served by this host, so it cannot call the shell directly; the shell opens a loopback listener, protected by a
|
||||
* random token it hands only to this host (STRATA_SHELL_BRIDGE, STRATA_SHELL_TOKEN), and this module is its client.
|
||||
* Outside the desktop app (a browser, a test, a source checkout) there is no bridge and `createAppUpdater` returns null.
|
||||
*
|
||||
* The shell does the checking against the signed feed (its own minisign key) and the installing; nothing here downloads
|
||||
* anything. These calls happen only for an explicit "Update" or "Check for updates", never when the host starts.
|
||||
*/
|
||||
|
||||
export function createAppUpdater({ env = process.env, fetcher = fetch, sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) {
|
||||
const base = env.STRATA_SHELL_BRIDGE;
|
||||
const token = env.STRATA_SHELL_TOKEN;
|
||||
if (!base || !token || !/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) return null;
|
||||
async function call(path, method = 'GET', timeoutMs = 120_000) {
|
||||
const response = await fetcher(`${base}${path}`, { method, headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(timeoutMs) });
|
||||
let body = null;
|
||||
try { body = await response.json(); } catch { /* no body */ }
|
||||
if (!response.ok) throw new Error(body?.error ?? `The Strata app could not check for updates (${response.status}).`);
|
||||
return body;
|
||||
}
|
||||
return {
|
||||
/** { available, version, current, notes } from the shell's updater (signature-verified metadata). */
|
||||
check: () => call('/app-update/check'),
|
||||
/**
|
||||
* Download, verify and install the app update. Resolves when the shell reports it finished; on Windows the installer ends
|
||||
* the app first, so the host may be stopped before this returns.
|
||||
*/
|
||||
async install({ onProgress = () => {}, signal = null, pollMs = 500 } = {}) {
|
||||
await call('/app-update/install', 'POST');
|
||||
for (;;) {
|
||||
if (signal?.aborted) throw new Error('The app update was stopped.');
|
||||
const status = await call('/app-update/status', 'GET', 15_000);
|
||||
onProgress(status);
|
||||
if (status.state === 'error') throw new Error(status.error ?? 'The app update failed.');
|
||||
if (status.state === 'done') return status;
|
||||
await sleep(pollMs);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -31,32 +31,62 @@ export function componentsDirectory({ env = process.env, platform = process.plat
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there a Control component to use? STRATA_CONTROL_DIR names it; otherwise it is the `control` folder beside
|
||||
* `host` in an installed app. Returns null in a source checkout (the host then keeps its older paths).
|
||||
* A Control that the component updater installed (`strata update` writes `<components>/control/active.json` after the new
|
||||
* bundle ran once). Null when there is none.
|
||||
*/
|
||||
export function findControl({ env = process.env, platform = process.platform, exists = existsSync, hostDir = resolve(HERE, '..') } = {}) {
|
||||
const candidates = [env.STRATA_CONTROL_DIR, join(hostDir, '..', 'control')].filter(Boolean).map(p => resolve(p));
|
||||
for (const dir of candidates) {
|
||||
const python = bundledPython(dir, platform);
|
||||
if (exists(python) && exists(join(dir, 'strata.py')) && exists(join(dir, 'strata_control'))) {
|
||||
let bundle = null;
|
||||
try { bundle = JSON.parse(readFileSync(join(dir, 'BUNDLE.json'), 'utf8').replace(/^/, '')); } catch { /* optional */ }
|
||||
return { dir, python, cli: join(dir, 'strata.py'), bundle };
|
||||
}
|
||||
export function updatedControlDirectory({ env = process.env, platform = process.platform, components = null } = {}) {
|
||||
try {
|
||||
const base = components ?? componentsDirectory({ env, platform });
|
||||
const pointer = JSON.parse(readFileSync(join(base, 'control', 'active.json'), 'utf8').replace(/^/, ''));
|
||||
if (typeof pointer?.folder !== 'string' || !/^[\w.+-]+$/.test(pointer.folder)) return null;
|
||||
return { dir: join(base, 'control', pointer.folder), version: typeof pointer.version === 'string' ? pointer.version : null };
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
const versionKey = value => String(value ?? '').split('.').map(part => Number.parseInt(part, 10) || 0);
|
||||
function newer(a, b) {
|
||||
for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) > (b[i] ?? 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is there a Control component to use? STRATA_CONTROL_DIR names one (the Tauri shell sets it to the bundled one), the
|
||||
* `control` folder beside `host` is the installed app's, and `<components>/control/active.json` is one the component
|
||||
* updater installed. Each must be whole; the newest version wins, so an app update that ships a newer Control is never
|
||||
* held back by an older updated one, and an updated Control is never lost to an older bundled one. A tie goes to the first
|
||||
* in that order. Returns null in a source checkout (the host then keeps its older paths).
|
||||
*/
|
||||
export function findControl({ env = process.env, platform = process.platform, exists = existsSync, hostDir = resolve(HERE, '..'), components = null } = {}) {
|
||||
const updated = updatedControlDirectory({ env, platform, components });
|
||||
const candidates = [{ dir: env.STRATA_CONTROL_DIR }, { dir: join(hostDir, '..', 'control') }, ...(updated ? [updated] : [])]
|
||||
.filter(c => c.dir).map(c => ({ ...c, dir: resolve(c.dir) }));
|
||||
let best = null;
|
||||
for (const candidate of candidates) {
|
||||
const python = bundledPython(candidate.dir, platform);
|
||||
if (!(exists(python) && exists(join(candidate.dir, 'strata.py')) && exists(join(candidate.dir, 'strata_control')))) continue;
|
||||
let bundle = null;
|
||||
try { bundle = JSON.parse(readFileSync(join(candidate.dir, 'BUNDLE.json'), 'utf8').replace(/^/, '')); } catch { /* optional */ }
|
||||
const found = { dir: candidate.dir, python, cli: join(candidate.dir, 'strata.py'), bundle, key: versionKey(bundle?.version ?? candidate.version) };
|
||||
if (!best || newer(found.key, best.key)) best = found;
|
||||
}
|
||||
return null;
|
||||
if (!best) return null;
|
||||
const { key, ...control } = best;
|
||||
return control;
|
||||
}
|
||||
|
||||
/** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */
|
||||
export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }) } = {}) {
|
||||
export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }), acquire = false } = {}) {
|
||||
const next = { ...env };
|
||||
for (const key of ['PYTHONHOME', 'PYTHONPATH', 'PYTHONSTARTUP', 'VIRTUAL_ENV', 'STRATA_PYTHON', 'STRATA_NATIVE_PYTHON', 'STRATA_API_KEY']) delete next[key];
|
||||
return {
|
||||
const result = {
|
||||
...next,
|
||||
PYTHONNOUSERSITE: '1', PYTHONUTF8: '1', PYTHONUNBUFFERED: '1', PYTHONIOENCODING: 'utf-8',
|
||||
STRATA_NO_ACQUIRE: '1', STRATA_COMPONENTS_DIR: components,
|
||||
...(control?.dir ? { STRATA_CONTROL_DIR: control.dir } : {}),
|
||||
};
|
||||
// Only the explicit update step (`strata update`) may acquire; every other Control process keeps the switch on.
|
||||
if (acquire) delete result.STRATA_NO_ACQUIRE;
|
||||
return result;
|
||||
}
|
||||
|
||||
export class ControlError extends Error {
|
||||
@@ -70,25 +100,43 @@ export class ControlError extends Error {
|
||||
}
|
||||
|
||||
/** Run one CLI command of Control. Resolves { code, json, text, stderr }; rejects only if it cannot start or times out. */
|
||||
export function runCli(control, args, { env = process.env, timeoutMs = 60_000, spawnProcess = spawn, components } = {}) {
|
||||
export function runCli(control, args, { env = process.env, timeoutMs = 60_000, spawnProcess = spawn, components, acquire = false, onLine = null, signal = null } = {}) {
|
||||
return new Promise((resolveRun, reject) => {
|
||||
const child = spawnProcess(control.python, [control.cli, ...args], {
|
||||
cwd: control.dir, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: controlEnvironment(control, { env, ...(components ? { components } : {}) }),
|
||||
env: controlEnvironment(control, { env, acquire, ...(components ? { components } : {}) }),
|
||||
});
|
||||
let out = '', err = '', done = false;
|
||||
if (signal) {
|
||||
if (signal.aborted) { try { child.kill(); } catch { /* gone */ } }
|
||||
else signal.addEventListener('abort', () => { try { child.kill(); } catch { /* gone */ } }, { once: true });
|
||||
}
|
||||
let out = '', err = '', done = false, pending = '';
|
||||
const finish = (fn, value) => { if (done) return; done = true; clearTimeout(alarm); fn(value); };
|
||||
const alarm = setTimeout(() => {
|
||||
try { child.kill(); } catch { /* already gone */ }
|
||||
finish(reject, new ControlError(`Strata Control did not answer within ${Math.round(timeoutMs / 1000)} s (${args.slice(0, 2).join(' ')}).`, { code: 'control_timeout' }));
|
||||
}, timeoutMs);
|
||||
child.stdout.on('data', c => { out += c; if (out.length > 4_000_000) child.kill(); });
|
||||
child.stdout.on('data', c => {
|
||||
out += c; if (out.length > 4_000_000) child.kill();
|
||||
if (onLine) { // JSON lines (--output jsonl): each complete line is one event
|
||||
pending += c;
|
||||
let at;
|
||||
while ((at = pending.indexOf('\n')) >= 0) {
|
||||
const line = pending.slice(0, at).trim(); pending = pending.slice(at + 1);
|
||||
if (!line.startsWith('{')) continue;
|
||||
try { onLine(JSON.parse(line)); } catch { /* not an event */ }
|
||||
}
|
||||
}
|
||||
});
|
||||
child.stderr.on('data', c => { err += c; if (err.length > 200_000) err = err.slice(-100_000); });
|
||||
child.on('error', e => finish(reject, new ControlError(`Strata Control could not start: ${e.message}`, { code: 'control_missing' })));
|
||||
child.on('close', code => {
|
||||
let json = null;
|
||||
const text = out.trim();
|
||||
if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON: caller reads text */ } }
|
||||
if (onLine) { // the last line is the result record
|
||||
const last = text.split(/\r?\n/).filter(line => line.startsWith('{')).pop();
|
||||
if (last) { try { json = JSON.parse(last); } catch { /* not JSON */ } }
|
||||
} else if (text) { try { json = JSON.parse(text.slice(text.indexOf('{'))); } catch { /* not JSON: caller reads text */ } }
|
||||
finish(resolveRun, { code, json, text, stderr: err.trim() });
|
||||
});
|
||||
});
|
||||
@@ -102,9 +150,33 @@ const failure = (result, fallback) => new ControlError(
|
||||
export function createControl({ control = findControl(), env = process.env, run = null } = {}) {
|
||||
if (!control) return null;
|
||||
const call = run ?? ((args, options) => runCli(control, args, { env, ...options }));
|
||||
const feedArgs = feed => (feed ? ['--feed', feed] : []);
|
||||
return {
|
||||
control,
|
||||
version: control.bundle?.version ?? null,
|
||||
/**
|
||||
* The explicit update step. These are the only calls that let Control reach the network: `acquire` removes
|
||||
* STRATA_NO_ACQUIRE for that one process. Starting, serving, listing and rolling back never do.
|
||||
*/
|
||||
async updateCheck({ feed = env.STRATA_UPDATE_FEED ?? null, appVersion = env.STRATA_APP_VERSION ?? null } = {}) {
|
||||
const result = await call(['update', '--check', '--output', 'json', ...feedArgs(feed), ...(appVersion ? ['--app-version', appVersion] : [])], { timeoutMs: 90_000, acquire: true });
|
||||
if (result.json?.ok) return result.json;
|
||||
throw failure(result, 'The update check failed.');
|
||||
},
|
||||
async update({ feed = env.STRATA_UPDATE_FEED ?? null, engine = true, control: withControl = true, appVersion = env.STRATA_APP_VERSION ?? null, force = false, onEvent = null, signal = null } = {}) {
|
||||
const args = ['update', '--output', 'jsonl', ...feedArgs(feed), ...(engine ? [] : ['--no-engine']), ...(withControl ? [] : ['--no-control']),
|
||||
...(appVersion ? ['--app-version', appVersion] : []), ...(force ? ['--force'] : [])];
|
||||
const result = await call(args, { timeoutMs: 3 * 3600_000, acquire: true, onLine: onEvent ?? (() => {}), signal });
|
||||
if (result.json?.ok) return result.json;
|
||||
const failed = result.json?.results?.find?.(r => r.status === 'failed');
|
||||
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.');
|
||||
},
|
||||
async rollbackEngine() {
|
||||
const result = await call(['components', 'rollback', '--output', 'json'], { timeoutMs: 120_000 });
|
||||
if (result.json?.ok) return result.json;
|
||||
throw failure(result, 'The engine could not be rolled back.');
|
||||
},
|
||||
async engine({ backend = null } = {}) {
|
||||
const result = await call(['components', 'engine', '--output', 'json', ...(backend ? ['--backend', backend] : [])], { timeoutMs: 30_000 });
|
||||
if (result.json) return result.json; // exit 5 still carries the report and the notice
|
||||
|
||||
@@ -44,7 +44,8 @@ import { EventHub, error, json, readBody, uid } from './util.mjs';
|
||||
import { RequestQueue } from './request-queue.mjs';
|
||||
import { selectSkills, skillInstructions } from './skill-selection.mjs';
|
||||
import { createModelProviders } from './model-providers.mjs';
|
||||
import { checkUpdates } from './updates.mjs';
|
||||
import { checkUpdates, checkComponentUpdates } from './updates.mjs';
|
||||
import { createAppUpdater } from './app-updater.mjs';
|
||||
import { createImageModels } from './image-models.mjs';
|
||||
import { createRuntimeModels } from './runtime-models.mjs';
|
||||
import { createNativeControl } from './native-control.mjs';
|
||||
@@ -80,7 +81,8 @@ const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () =
|
||||
/* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */
|
||||
const CONTROL = findControl();
|
||||
const control = createControl({ control: CONTROL });
|
||||
const native=createNativeControl({control,directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});
|
||||
const appUpdater = createAppUpdater();
|
||||
const native=createNativeControl({control,appUpdater,directory:store.DATA_DIR,modelsDirectory:()=>store.MODELS_DIR,nativeDataDirectory:store.nativeDataDirectory,beforeLoad:async()=>{if(models.REAL&&models.library().loaded){if(serving.state().requests.some(r=>runtimeModels.state().instances.some(i=>i.id===r.instanceId)&&["queued","generating"].includes(r.state)))throw new Error("Finish requests before switching engines.");await models.unload();runtimeState();}},requests:()=>serving.state().requests,changed:value=>hub.send('native',value)});
|
||||
/* The agent: chats become DeepSeek Harness sessions when that component is installed. It is a separate
|
||||
pinned component (STRATA_HARNESS_DIR), not part of this host, so its absence is a visible capability
|
||||
state and the chat falls back to the direct path with a notice, never silently to another model. */
|
||||
@@ -948,6 +950,7 @@ async function api(req, res, path, method, url) {
|
||||
}
|
||||
|
||||
if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState());
|
||||
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:native.state().version??setupState().app.version, engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version }));
|
||||
|
||||
if (path === '/api/setup/step' && method === 'POST') {
|
||||
|
||||
@@ -16,7 +16,7 @@ const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value);
|
||||
const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state));
|
||||
function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}}
|
||||
|
||||
export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){
|
||||
export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},control=null,appUpdater=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){
|
||||
mkdirSync(directory,{recursive:true});
|
||||
const settingsPath=join(directory,'native-host.json');
|
||||
let preferences=readJson(settingsPath,{repo:defaultRepo});
|
||||
@@ -32,7 +32,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
let defaultId=null,timer=null,closing=false,polling=false;
|
||||
const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);};
|
||||
const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();};
|
||||
function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
|
||||
function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
|
||||
function sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}
|
||||
function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}
|
||||
function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,dataFolder,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
|
||||
@@ -59,7 +59,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({model:m.id,config:basename(m.source_config),configPath:m.source_config,model_name:m.name,context:m.context_tokens??0,backend:m.backend,ready:m.component_status==='present',images:'off',port:undefined,last_used:null}));
|
||||
const cores=os.cpus().length;
|
||||
return {summary:engine.usable?`Strata Control is ready; engine ${engine.engine.version} (${engine.engine.platform}-${engine.engine.backend}).`:(engine.notice??'No engine for this PC was found.'),
|
||||
installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir},
|
||||
installDir:list.install_dir,engine:{usable:engine.usable,notice:engine.notice,version:engine.engine?.version??null,backend:engine.backend,componentsDir:engine.components_dir,previous:engine.previous??null,pinned:engine.pinned??null,updateNotice:engine.update_notice??null},
|
||||
installed:{strata_folder:list.install_dir,data_folder:null,engine:engine.engine?{version:engine.engine.version,backend:engine.engine.backend,folder:engine.engine.root}:{folder:null,version:null},models},
|
||||
hardware:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},install:null,running:null};
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
function record(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path,config:readJson(path)};}
|
||||
function settings(model){const {config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true};}
|
||||
function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}
|
||||
function previousEngine(){try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}
|
||||
function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}
|
||||
async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}
|
||||
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);const data=nativeDataDirectory(args.data_dir??existing?.dataFolder??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),confirm};}
|
||||
|
||||
@@ -141,7 +141,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
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)throw new Error(NO_INSTALL);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);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'];}
|
||||
@@ -149,6 +149,31 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
else throw new Error('Unsupported native operation.');
|
||||
return new Promise((resolve,reject)=>{const proc=spawnProcess(command,[...prefix,...argv],{cwd:folder,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1'}});job.process=proc;for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{chunk.toString().split('\n').filter(Boolean).forEach(line=>append(job.id,line));job.summary=chunk.toString().trim().slice(-500);emit();});proc.on('error',reject);proc.on('exit',code=>{delete job.process;code===0?resolve({summary:job.kind==='calibrate'?'Calibration complete. Native settings were saved.':'Native installation updated.'}):reject(new Error(`Operation stopped (exit ${code}). Open diagnostics for details.`));});});
|
||||
}
|
||||
/* 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);
|
||||
if(instances.size)throw new Error('Unload native models before changing engine files.');
|
||||
job.abort=new AbortController();
|
||||
const onEvent=event=>{
|
||||
if(event.event==='progress'){job.summary=`Downloading ${event.label}: ${event.percent}%`;job.result={install:{step:job.summary,download:{file:event.label,percent:event.percent}}};}
|
||||
else if(event.event==='phase'&&event.message)job.summary=event.message;
|
||||
else if(event.event==='waiting')job.summary=event.message;
|
||||
emit();
|
||||
};
|
||||
if(job.kind==='rollback'){const done=await control.rollbackEngine();return {summary:`Engine ${done.to} restored. Model files and settings are kept.`,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});
|
||||
const notes=[updateSummary(done)];
|
||||
if(appUpdater){
|
||||
job.summary='Checking the Strata app for updates…';emit();
|
||||
const verdict=await appUpdater.check();
|
||||
if(verdict.available){await appUpdater.install({signal:job.abort.signal,onProgress:p=>{if(p.total){job.summary=`Downloading Strata ${verdict.version}: ${Math.round(100*p.downloaded/p.total)}%`;job.result={install:{step:job.summary,download:{file:`Strata ${verdict.version}`,percent:Math.round(100*p.downloaded/p.total)}}};emit();}}});notes.push(`Strata ${verdict.version} installed; the app restarts.`);}
|
||||
}
|
||||
return {summary:notes.filter(Boolean).join(' '),result:done};
|
||||
}
|
||||
function updateSummary(done){const r=(done.results??[]).filter(x=>x.status==='updated').map(x=>x.component==='engine'?`Engine ${x.installed_after?.version??''} installed and tested.`:`Control ${x.installed_after??''} installed (takes effect on the next start).`);return r.length?r.join(' '):'Already up to date.';}
|
||||
function execute(cmd,args,cwd){return new Promise((resolve,reject)=>{let output='';const process=spawnProcess(cmd,args,{cwd,stdio:['ignore','pipe','pipe']});process.stdout.on('data',c=>{output+=c;if(output.length>100000)process.kill();});process.stderr.on('data',c=>append('update',c.toString()));process.on('error',reject);process.on('exit',code=>code===0?resolve(output):reject(new Error('Git could not update this installation. Open diagnostics.')));});}
|
||||
function writeModelConfig(path,next){copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);}
|
||||
async function tune(job,args){
|
||||
|
||||
@@ -41,3 +41,44 @@ export async function checkUpdates({ appVersion, engineVersion }, fetcher = fetc
|
||||
engine: { installedVersion: engineVersion, status: 'unavailable', canInstall: false, message: 'Engine update checks are not available in this build.' },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The packaged app's update check: the signed feed, read by Control (`strata update --check`), plus the shell's own verdict
|
||||
* on the app. Same result shape as `checkUpdates`, so the Settings screen needs no change. This is the only place the host
|
||||
* reaches the feed, and only when the user presses "Check for updates".
|
||||
*/
|
||||
export async function checkComponentUpdates({ control, appUpdater = null, appVersion = null }) {
|
||||
const checkedAt = new Date().toISOString();
|
||||
let report;
|
||||
try {
|
||||
report = await control.updateCheck({ appVersion });
|
||||
} catch (error) {
|
||||
const message = error?.message ?? 'Could not check for updates.';
|
||||
return { checkedAt, strata: { installedVersion: appVersion ?? control.version ?? null, status: 'error', message, canInstall: false }, engine: { installedVersion: null, status: 'error', message, canInstall: false } };
|
||||
}
|
||||
const mib = bytes => `${Math.round((bytes ?? 0) / (1 << 20))} MB`;
|
||||
const engine = report.engine ?? {};
|
||||
const installedEngine = engine.installed?.version ?? null;
|
||||
const offered = engine.offered?.version ?? null;
|
||||
const engineView = { installedVersion: installedEngine, latestVersion: offered ?? undefined, canInstall: engine.status === 'available' || engine.status === 'install' };
|
||||
if (engine.status === 'available') Object.assign(engineView, { status: 'available', message: `Engine ${offered} is available (${mib(engine.download_bytes)}).` });
|
||||
else if (engine.status === 'install') Object.assign(engineView, { status: 'available', message: `No engine is installed yet. The right one for this PC, ${offered} (${mib(engine.download_bytes)}), can be downloaded now.` });
|
||||
else if (engine.status === 'current' || engine.status === 'failed-before' || engine.status === 'skipped') Object.assign(engineView, { status: 'current', message: engine.note ?? 'The engine is up to date.' });
|
||||
else Object.assign(engineView, { status: 'unavailable', message: engine.reasons?.[0] ?? 'The update feed has no engine for this PC.' });
|
||||
const control_ = report.control ?? {};
|
||||
const app = report.app ?? {};
|
||||
let appNew = app.status === 'available' ? app.offered : null;
|
||||
let appNotes = app.notes ?? '';
|
||||
if (appUpdater) {
|
||||
try {
|
||||
const verdict = await appUpdater.check();
|
||||
appNew = verdict.available ? verdict.version : null;
|
||||
appNotes = verdict.notes ?? appNotes;
|
||||
} catch { /* the feed's own view stands */ }
|
||||
}
|
||||
const controlNew = control_.status === 'available' ? control_.offered : null;
|
||||
const strata = { installedVersion: appVersion ?? control_.installed ?? control.version ?? null, canInstall: !!(appNew || controlNew) };
|
||||
if (appNew || controlNew) Object.assign(strata, { status: 'available', latestVersion: appNew ?? controlNew, message: `Strata ${appNew ?? controlNew} is available.${appNotes ? ` ${appNotes}` : ''}` });
|
||||
else Object.assign(strata, { status: 'current', message: 'Strata is up to date.' });
|
||||
return { checkedAt, feed: report.feed, strata, engine: engineView, serving: report.serving ?? [] };
|
||||
}
|
||||
@@ -70,7 +70,7 @@ export function SettingsUpdates() {
|
||||
<div className="settings-versions" aria-busy={checking}>
|
||||
{tr(versionRow('Strata', native?.version ?? appVersion, result?.strata))}
|
||||
{tr(versionRow('Engine', native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion, result?.engine))}
|
||||
{tr(native?.available ? <div className="settings-update-actions"><Btn size="sm" disabled={!!active} onClick={() => setConfirm('update-strata')}>{tr("Update Strata")}</Btn><Btn size="sm" disabled={!!active || !native.installed?.models.length} onClick={() => setConfirm('update-engine')}>{tr("Update engine")}</Btn></div> : null)}
|
||||
{tr(native?.available ? <div className="settings-update-actions"><Btn size="sm" disabled={!!active} onClick={() => setConfirm('update-strata')}>{tr("Update Strata")}</Btn><Btn size="sm" disabled={!!active || (!native.installed?.models.length && !native.capabilities.componentUpdates)} onClick={() => setConfirm('update-engine')}>{tr("Update engine")}</Btn></div> : null)}
|
||||
<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(new Date(result.checkedAt).toLocaleTimeString(localeTag(), { hour: '2-digit', minute: '2-digit' }))}</> : null)}</div>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface NativeFamily {family:string;title:string;about:string;experimen
|
||||
export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean}
|
||||
export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;result:Record<string,any>|null}
|
||||
export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record<string,any>|null}
|
||||
export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean}}
|
||||
export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}}
|
||||
let state:NativeState|null=null,timer:ReturnType<typeof setInterval>|null=null,reading:Promise<void>|null=null;
|
||||
const listeners=new Set<()=>void>();
|
||||
export function refreshNative(force=false){if(reading)return reading;reading=api.get<NativeState>(`/api/native${force?'?refresh=1':''}`).then(value=>{state=value;listeners.forEach(fn=>fn());}).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{reading=null;});return reading;}
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } 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 { createAppUpdater } from '../server/app-updater.mjs';
|
||||
import { createNativeControl } from '../server/native-control.mjs';
|
||||
|
||||
const isWin = process.platform === 'win32';
|
||||
|
||||
function controlDir(parent, name, version) {
|
||||
const dir = join(parent, name);
|
||||
mkdirSync(join(dir, 'python', ...(isWin ? [] : ['bin'])), { recursive: true });
|
||||
mkdirSync(join(dir, 'strata_control'), { recursive: true });
|
||||
writeFileSync(bundledPython(dir), 'x');
|
||||
writeFileSync(join(dir, 'strata.py'), '# cli');
|
||||
if (version) writeFileSync(join(dir, 'BUNDLE.json'), JSON.stringify({ version }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
test('only the update step may acquire: Control keeps STRATA_NO_ACQUIRE unless `acquire` is asked for', () => {
|
||||
const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
|
||||
assert.equal(controlEnvironment(control, { env: {}, components: '/k' }).STRATA_NO_ACQUIRE, '1');
|
||||
const env = controlEnvironment(control, { env: { STRATA_NO_ACQUIRE: '1' }, components: '/k', acquire: true });
|
||||
assert.equal('STRATA_NO_ACQUIRE' in env, false);
|
||||
assert.equal(env.STRATA_COMPONENTS_DIR, '/k');
|
||||
assert.equal(env.PYTHONNOUSERSITE, '1');
|
||||
});
|
||||
|
||||
test('an updated Control wins only when it is newer than the bundled one, and only when whole', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'strata-update-control-'));
|
||||
try {
|
||||
const install = join(root, 'install');
|
||||
mkdirSync(join(install, 'host'), { recursive: true });
|
||||
const bundled = controlDir(install, 'control', '0.1.45');
|
||||
const components = join(root, 'components');
|
||||
const updated = controlDir(join(components, 'control'), '0.1.46', '0.1.46');
|
||||
writeFileSync(join(components, 'control', 'active.json'), JSON.stringify({ version: '0.1.46', folder: '0.1.46' }));
|
||||
const find = (extra = {}) => findControl({ env: {}, hostDir: join(install, 'host'), components, ...extra });
|
||||
assert.equal(find().dir, updated, 'the updated 0.1.46 beats the bundled 0.1.45');
|
||||
writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.47' }));
|
||||
assert.equal(find().dir, bundled, 'an app update that ships a newer Control is not held back by an older updated one');
|
||||
writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.46' }));
|
||||
assert.equal(find().dir, bundled, 'a tie keeps the bundled one');
|
||||
rmSync(join(updated, 'strata.py'));
|
||||
writeFileSync(join(bundled, 'BUNDLE.json'), JSON.stringify({ version: '0.1.45' }));
|
||||
assert.equal(find().dir, bundled, 'a half-installed updated Control is not used');
|
||||
writeFileSync(join(components, 'control', 'active.json'), JSON.stringify({ version: '0.1.46', folder: '../../etc' }));
|
||||
assert.equal(updatedControlDirectory({ env: {}, components }), null, 'a pointer cannot leave the control folder');
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
function fakeSpawn(lines, code = 0, seen = []) {
|
||||
return (command, args, options) => {
|
||||
seen.push({ command, args, options });
|
||||
const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = () => { child.killed = true; };
|
||||
queueMicrotask(() => {
|
||||
// split a line in two chunks: the reader must wait for the newline
|
||||
const text = lines.map(l => JSON.stringify(l)).join('\n') + '\n';
|
||||
child.stdout.emit('data', text.slice(0, 20)); child.stdout.emit('data', text.slice(20));
|
||||
child.emit('close', code);
|
||||
});
|
||||
return child;
|
||||
};
|
||||
}
|
||||
|
||||
test('runCli streams JSON lines as events and returns the last record; `acquire` reaches the environment', async () => {
|
||||
const seen = [];
|
||||
const events = [];
|
||||
const control = { dir: '/c', python: '/c/python/python3', cli: '/c/strata.py' };
|
||||
const spawnProcess = fakeSpawn([{ event: 'phase', phase: 'feed', message: 'Reading' }, { event: 'progress', percent: 50, label: 'engine 0.1.46' }, { ok: true, results: [] }], 0, seen);
|
||||
const result = await runCli(control, ['update', '--output', 'jsonl'], { spawnProcess, env: { STRATA_NO_ACQUIRE: '1' }, acquire: true, onLine: e => events.push(e) });
|
||||
assert.equal(events.length, 3);
|
||||
assert.equal(events[1].percent, 50);
|
||||
assert.deepEqual(result.json, { ok: true, results: [] });
|
||||
assert.equal('STRATA_NO_ACQUIRE' in seen[0].options.env, false);
|
||||
await runCli(control, ['models', 'list'], { spawnProcess: fakeSpawn([{ ok: true }], 0, seen), env: {} });
|
||||
assert.equal(seen[1].options.env.STRATA_NO_ACQUIRE, '1', 'everything else keeps the switch on');
|
||||
});
|
||||
|
||||
test('createControl: the update calls ask the explicit commands; a failed step carries its message and exit code', async () => {
|
||||
const seen = [];
|
||||
const reply = { ok: true, results: [{ component: 'engine', status: 'updated' }] };
|
||||
const control = createControl({
|
||||
control: { dir: '/c', python: '/p', cli: '/c/strata.py' }, env: { STRATA_UPDATE_FEED: 'http://127.0.0.1:1/strata-feed.json', STRATA_APP_VERSION: '0.1.0' },
|
||||
run: async (args, options) => { seen.push([args.join(' '), !!options.acquire]); return { code: 0, json: args.includes('--check') ? { ok: true, engine: {} } : args[0] === 'components' ? { ok: true, to: '0.1.45' } : reply, text: '', stderr: '' }; },
|
||||
});
|
||||
await control.updateCheck();
|
||||
await control.update({ engine: true, control: false });
|
||||
await control.rollbackEngine();
|
||||
assert.deepEqual(seen, [
|
||||
['update --check --output json --feed http://127.0.0.1:1/strata-feed.json --app-version 0.1.0', true],
|
||||
['update --output jsonl --feed http://127.0.0.1:1/strata-feed.json --no-control --app-version 0.1.0', true],
|
||||
['components rollback --output json', false],
|
||||
], 'only the check and the update acquire; the rollback downloads nothing');
|
||||
const failing = createControl({
|
||||
control: { dir: '/c', python: '/p', cli: '/c/strata.py' }, env: {},
|
||||
run: async () => ({ code: 7, json: { ok: false, results: [{ component: 'engine', status: 'failed', error: 'app-1 is serving.', exit_code: 7 }] }, text: '', stderr: '' }),
|
||||
});
|
||||
await assert.rejects(failing.update({}), err => err.code === 'engine_serving' && /serving/.test(err.message) && err.exitCode === 7);
|
||||
});
|
||||
|
||||
test('the Settings update check maps the feed to the existing result shape', async () => {
|
||||
const report = overrides => ({ ok: true, feed: { sequence: 3 }, engine: { installed: { version: '0.1.45' }, offered: { version: '0.1.46' }, status: 'available', download_bytes: 505 * (1 << 20) }, control: { installed: '0.1.45', offered: '0.1.45', status: 'current' }, app: { status: 'not-in-feed' }, ...overrides });
|
||||
const make = value => ({ version: '0.1.45', async updateCheck() { if (value instanceof Error) throw value; return value; } });
|
||||
let result = await checkComponentUpdates({ control: make(report()), appVersion: '0.1.0' });
|
||||
assert.equal(result.engine.status, 'available');
|
||||
assert.equal(result.engine.latestVersion, '0.1.46');
|
||||
assert.match(result.engine.message, /0\.1\.46 is available \(505 MB\)/);
|
||||
assert.equal(result.engine.canInstall, true);
|
||||
assert.equal(result.strata.status, 'current');
|
||||
result = await checkComponentUpdates({ control: make(report({ engine: { installed: null, offered: { version: '0.1.46' }, status: 'install', download_bytes: 505 * (1 << 20) } })) });
|
||||
assert.equal(result.engine.status, 'available');
|
||||
assert.match(result.engine.message, /No engine is installed yet/);
|
||||
result = await checkComponentUpdates({ control: make(report({ engine: { installed: { version: '0.1.46' }, offered: { version: '0.1.46' }, status: 'current' } })) });
|
||||
assert.equal(result.engine.status, 'current');
|
||||
result = await checkComponentUpdates({ control: make(report({ engine: { installed: null, offered: null, status: 'none-for-this-pc', reasons: ['0.1.46 is for linux-x86_64, this PC is windows-x86_64'] } })) });
|
||||
assert.equal(result.engine.status, 'unavailable');
|
||||
assert.match(result.engine.message, /windows-x86_64/);
|
||||
result = await checkComponentUpdates({ control: make(new Error('this build trusts no update key')) });
|
||||
assert.equal(result.strata.status, 'error');
|
||||
assert.equal(result.engine.status, 'error');
|
||||
assert.match(result.engine.message, /no update key/);
|
||||
// the app's verdict comes from the shell's updater when the bridge exists
|
||||
const appUpdater = { check: async () => ({ available: true, version: '0.2.0', notes: 'Faster starts.' }) };
|
||||
result = await checkComponentUpdates({ control: make(report()), appUpdater, appVersion: '0.1.0' });
|
||||
assert.equal(result.strata.status, 'available');
|
||||
assert.equal(result.strata.latestVersion, '0.2.0');
|
||||
assert.match(result.strata.message, /Faster starts/);
|
||||
});
|
||||
|
||||
test('the shell bridge client exists only inside the desktop app, speaks to loopback with the token, and polls to the end', async () => {
|
||||
assert.equal(createAppUpdater({ env: {} }), null);
|
||||
assert.equal(createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://example.com:80', STRATA_SHELL_TOKEN: 'x' } }), null, 'not a loopback address');
|
||||
const calls = [];
|
||||
const states = [{ state: 'downloading', downloaded: 10, total: 100 }, { state: 'downloading', downloaded: 100, total: 100 }, { state: 'done' }];
|
||||
const fetcher = async (url, init) => {
|
||||
calls.push([init.method, url.replace(/:\d+/, ':P'), init.headers.authorization]);
|
||||
if (url.endsWith('/app-update/status')) return Response.json(states.shift());
|
||||
return Response.json(url.endsWith('/check') ? { available: true, version: '0.2.0' } : { state: 'downloading' });
|
||||
};
|
||||
const updater = createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:4000', STRATA_SHELL_TOKEN: 'tok' }, fetcher, sleep: async () => {} });
|
||||
assert.equal((await updater.check()).version, '0.2.0');
|
||||
const progress = [];
|
||||
await updater.install({ onProgress: p => progress.push(p.downloaded ?? null) });
|
||||
assert.deepEqual(progress, [10, 100, null]);
|
||||
assert.ok(calls.every(c => c[2] === 'Bearer tok'));
|
||||
assert.deepEqual(calls.map(c => c[0] + ' ' + c[1].split('/').pop()), ['GET check', 'POST install', 'GET status', 'GET status', 'GET status']);
|
||||
const failing = createAppUpdater({ env: { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:4000', STRATA_SHELL_TOKEN: 'tok' }, sleep: async () => {},
|
||||
fetcher: async url => Response.json(url.endsWith('/status') ? { state: 'error', error: 'signature mismatch' } : {}) });
|
||||
await assert.rejects(failing.install(), /signature mismatch/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------- the Settings buttons in the packaged app
|
||||
|
||||
function fixture({ withApp = false, update } = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'strata-update-ops-'));
|
||||
const install = join(root, 'install'), data = join(root, 'data');
|
||||
mkdirSync(install, { recursive: true });
|
||||
const config = join(install, 'strata-iq2_xs.json');
|
||||
writeFileSync(config, JSON.stringify({ exe: 'component:strata-engine', tokenizer: join(install, 'tok'), args: ['--max-context', '32768'], model_name: 'Qwen', port: 8080 }));
|
||||
const calls = [];
|
||||
let previous = null;
|
||||
const control = {
|
||||
control: { dir: join(root, 'control') }, version: '0.1.45',
|
||||
async installedModels() { return { install_dir: install, models: [{ id: 'iq2_xs', name: 'Qwen', source_config: config, component_status: 'present', context_tokens: 32768, backend: 'cuda' }] }; },
|
||||
async engine() { return { usable: true, backend: 'cuda', components_dir: 'E:\\c', previous, engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'e', root: 'r' } }; },
|
||||
async saveProfile() { return {}; }, async start() { return { ok: true, state: 'ready' }; }, async stop() { return { ok: true }; },
|
||||
async update(options) {
|
||||
calls.push(['update', options.engine, options.control]);
|
||||
options.onEvent?.({ event: 'phase', phase: 'download', message: 'Downloading engine 0.1.46 (505 MiB)' });
|
||||
options.onEvent?.({ event: 'progress', phase: 'download', label: 'engine 0.1.46', percent: 42, done: 1, total: 2 });
|
||||
await update?.(options);
|
||||
previous = '0.1.45-windows-x86_64-cuda';
|
||||
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 = [];
|
||||
const appUpdater = withApp ? {
|
||||
check: async () => ({ available: true, version: '0.2.0' }),
|
||||
install: async ({ onProgress }) => { calls.push(['app-install']); onProgress({ downloaded: 50, total: 100 }); return { state: 'done' }; },
|
||||
} : null;
|
||||
const native = createNativeControl({ control, appUpdater, directory: data, spawnProcess: (...args) => { spawned.push(args); throw new Error('no process may be started by the host in packaged mode'); }, fetcher: async () => Response.json({}), requests: () => [] });
|
||||
return { native, calls, spawned, cleanup: () => rmSync(root, { recursive: true, force: true }) };
|
||||
}
|
||||
const finish = async (native, id) => { for (let i = 0; i < 400; i++) { const job = native.state().jobs.find(j => j.id === id); if (job.state !== 'running') return job; await new Promise(r => setTimeout(r, 10)); } throw new Error('job did not finish'); };
|
||||
|
||||
test('packaged: "Update engine" runs the explicit component update, shows its progress, and then offers the rollback', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
assert.equal(f.native.state().capabilities.componentUpdates, true);
|
||||
assert.equal(f.native.state().capabilities.rollback, false, 'nothing to roll back before the first update');
|
||||
const started = f.native.operation('update-engine', {});
|
||||
await new Promise(r => setTimeout(r, 5));
|
||||
const job = await finish(f.native, started.id);
|
||||
assert.equal(job.state, 'done', job.error);
|
||||
assert.match(job.summary, /Engine 0\.1\.46 installed and tested/);
|
||||
assert.deepEqual(f.calls[0], ['update', true, false], 'the engine only: Control and the app are not touched by "Update engine"');
|
||||
assert.equal(f.spawned.length, 0);
|
||||
await f.native.refresh(true);
|
||||
assert.equal(f.native.state().capabilities.rollback, true, 'the previous engine the update kept is offered for rollback');
|
||||
const back = await finish(f.native, f.native.operation('rollback', {}).id);
|
||||
assert.equal(back.state, 'done', back.error);
|
||||
assert.match(back.summary, /Engine 0\.1\.45 restored/);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: progress events become the existing job summary and download bar', async () => {
|
||||
const seen = [];
|
||||
const f = fixture({ update: async () => { await new Promise(r => setTimeout(r, 30)); } });
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
const started = f.native.operation('update-engine', {});
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const job = f.native.state().jobs.find(j => j.id === started.id);
|
||||
if (job.result?.install?.download) { seen.push(job.result.install.download, job.summary); break; }
|
||||
await new Promise(r => setTimeout(r, 5));
|
||||
}
|
||||
await finish(f.native, started.id);
|
||||
assert.deepEqual(seen[0], { file: 'engine 0.1.46', percent: 42 });
|
||||
assert.equal(seen[1], 'Downloading engine 0.1.46: 42%');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: no update while a model is loaded; calibration is still refused', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
const load = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
|
||||
assert.equal(load.state, 'done', load.error);
|
||||
const job = await finish(f.native, f.native.operation('update-engine', {}).id);
|
||||
assert.equal(job.state, 'error');
|
||||
assert.match(job.error, /Unload native models/);
|
||||
assert.equal(f.calls.filter(c => c[0] === 'update').length, 0);
|
||||
const calibrate = await finish(f.native, f.native.operation('calibrate', { model: 'iq2_xs' }).id);
|
||||
assert.match(calibrate.error, /Terminal|calibrates NVIDIA/);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: "Update Strata" updates Control through the feed, then the app through the shell', async () => {
|
||||
const f = fixture({ withApp: true });
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
const job = await finish(f.native, f.native.operation('update-strata', {}).id);
|
||||
assert.equal(job.state, 'done', job.error);
|
||||
assert.deepEqual(f.calls.map(c => c[0]), ['update', 'app-install']);
|
||||
assert.deepEqual(f.calls[0], ['update', false, true]);
|
||||
assert.match(job.summary, /Strata 0\.2\.0 installed/);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('without the shell bridge "Update Strata" still updates Control and says nothing false about the app', async () => {
|
||||
const f = fixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
const job = await finish(f.native, f.native.operation('update-strata', {}).id);
|
||||
assert.equal(job.state, 'done', job.error);
|
||||
assert.doesNotMatch(job.summary, /Strata 0\.2\.0/);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
@@ -175,6 +175,18 @@ def cached_notice(root: Path | None = None) -> str | None:
|
||||
return f"update available ({', '.join(parts)}): run `strata update`" if parts else None
|
||||
|
||||
|
||||
def previous_folder(root: Path | None = None) -> str | None:
|
||||
"""The package folder the last update kept as the version to roll back to, if it is still installed."""
|
||||
base = root or components_dir()
|
||||
try:
|
||||
value = json.loads((base / UPDATE_STATE).read_text(encoding="utf-8-sig"))["engine"]["previous"]
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
if isinstance(value, str) and value and "/" not in value and "\\" not in value and (engine_dir(base) / value / MANIFEST).is_file():
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def pinned_folder(root: Path | None = None) -> str | None:
|
||||
"""The package folder a manual rollback pinned, or None. Read-only; a missing or damaged state file means no pin."""
|
||||
try:
|
||||
@@ -566,7 +578,7 @@ def status(root: Path | None = None, *, backend: str | None = None, full: bool =
|
||||
"backend": backend or detected, "backend_source": "requested" if backend else how,
|
||||
"installed": [item.to_dict() for item in found], "problems": problems,
|
||||
"engine": None, "usable": False, "notice": None, "acquires": False,
|
||||
"pinned": pinned_folder(base)}
|
||||
"pinned": pinned_folder(base), "previous": previous_folder(base), "update_notice": cached_notice(base)}
|
||||
try:
|
||||
chosen = resolve(base, backend=backend, full=full)
|
||||
report["engine"] = chosen.to_dict()
|
||||
|
||||
@@ -399,7 +399,8 @@ class EngineUpdate(UpdaterCase):
|
||||
"""The start path (engine_component, runtime) must not reach the update machinery or the network code."""
|
||||
import subprocess
|
||||
code = ("import sys; import strata_control.engine_component, strata_control.runtime, strata_control.acquisition; "
|
||||
"print(sorted(m for m in sys.modules if m in ('strata_control.updater','strata_control.transfer','strata_control.feed','urllib.request')))")
|
||||
"import strata_cli.cli as c; c.parser(); "
|
||||
"print(sorted(m for m in sys.modules if m in ('strata_control.updater','strata_control.transfer','strata_control.feed')))")
|
||||
done = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, cwd=str(fx.ROOT))
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertEqual(done.stdout.strip(), "[]")
|
||||
|
||||
Reference in new issue
Block a user