merge f-split-fr (owner app UI fixes, rounds 1-5) into f-split-int
native-control.mjs: fr's file kept, S6's engine step, component updates, plain update messages and app updater re-applied on it; native.ts: fr's types plus capabilities.componentUpdates; SettingsUpdates: fr's per-row update buttons, Update engine enabled without a model when component updates exist.
No files matched your search
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1,
|
||||
* the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding.
|
||||
*
|
||||
* node apps/desktop/scripts/first-run-ui.mjs [--control <staged control>] [--node <node.exe>] [--work <scratch>] [--shots <dir>]
|
||||
*
|
||||
* Checks, one line each (exit 1 if any fails):
|
||||
* the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC
|
||||
* (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model
|
||||
* list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a
|
||||
* plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch.
|
||||
* Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work.
|
||||
* No model is downloaded and no engine runs.
|
||||
*/
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), []));
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoHost = resolve(here, '../../host');
|
||||
const staged = resolve(here, '../src-tauri/resources');
|
||||
const control = resolve(args.control ?? join(staged, 'control'));
|
||||
const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node'));
|
||||
const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-')));
|
||||
const shots = resolve(args.shots ?? join(work, 'shots'));
|
||||
mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true });
|
||||
const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href;
|
||||
const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, '');
|
||||
|
||||
const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
|
||||
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync);
|
||||
|
||||
let failed = false;
|
||||
const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; };
|
||||
const delay = ms => new Promise(r => setTimeout(r, ms));
|
||||
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
|
||||
|
||||
for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); }
|
||||
|
||||
const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') };
|
||||
for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true });
|
||||
const port = await freePort();
|
||||
const env = {
|
||||
...process.env,
|
||||
STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1',
|
||||
STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components,
|
||||
APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'),
|
||||
STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog,
|
||||
};
|
||||
delete env.STRATA_INSTALL_DIR;
|
||||
mkdirSync(env.STRATA_MODELS_DIR, { recursive: true });
|
||||
const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let hostLog = '';
|
||||
host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; });
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; };
|
||||
|
||||
let browser;
|
||||
try {
|
||||
let up = false;
|
||||
for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } }
|
||||
check(up, 'the packaged host starts', `port ${port}`);
|
||||
if (!up) throw new Error(hostLog.slice(-2000));
|
||||
|
||||
const native = await api('/api/native?refresh=1');
|
||||
const state = native.body;
|
||||
check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? '');
|
||||
const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0);
|
||||
check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`);
|
||||
check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120));
|
||||
check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC');
|
||||
check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir);
|
||||
const hw = (await api('/api/hardware')).body;
|
||||
console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified }))));
|
||||
check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? '');
|
||||
|
||||
browser = await chromium.launch({ executablePath: CHROME, headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1400, height: 950 } });
|
||||
const problems = [];
|
||||
page.on('pageerror', e => problems.push(`pageerror: ${e.message}`));
|
||||
await page.goto(base, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {});
|
||||
await page.screenshot({ path: join(shots, '1-welcome.png') });
|
||||
const broken = await page.locator('text=/couldn.t show this screen/i').count();
|
||||
check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")');
|
||||
const start = page.getByRole('button', { name: /get started/i });
|
||||
check(await start.count() > 0, 'the welcome step offers "Let\'s get started"');
|
||||
if (await start.count()) await start.first().click();
|
||||
await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {});
|
||||
await delay(1200);
|
||||
await page.screenshot({ path: join(shots, '2-models.png') });
|
||||
check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders');
|
||||
check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions');
|
||||
const labels = await page.locator('[role=radio]').allInnerTexts();
|
||||
check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | '));
|
||||
check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size');
|
||||
check(problems.length === 0, 'no page error', problems.join('; '));
|
||||
|
||||
const recommended = state?.catalog?.recommendation;
|
||||
if (recommended?.model) {
|
||||
const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) });
|
||||
check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150));
|
||||
check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files');
|
||||
}
|
||||
} catch (error) {
|
||||
check(false, 'the run', String(error?.message ?? error).slice(0, 600));
|
||||
} finally {
|
||||
await browser?.close().catch(() => {});
|
||||
host.kill();
|
||||
await new Promise(r => host.once('exit', r)); // only the PID this script started
|
||||
const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean);
|
||||
check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' '));
|
||||
console.log(`shots in ${shots}`);
|
||||
if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 });
|
||||
}
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with
|
||||
* the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what
|
||||
* the owner is shown before an installer is chosen.
|
||||
*
|
||||
* node apps/desktop/scripts/installer-mockups.mjs [--out <folder>]
|
||||
*/
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const host = resolve(here, '../../host');
|
||||
const out = resolve(args.out ?? join(here, '../installer-mockups'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
const dist = join(host, 'dist');
|
||||
const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n');
|
||||
const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8');
|
||||
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
|
||||
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
|
||||
|
||||
const check = '<svg class="st-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>';
|
||||
const folder = '<svg class="st-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
|
||||
|
||||
const screens = {
|
||||
welcome: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
|
||||
<div class="onboard-welcome-copy"><h1>State of the art. At home.</h1><p>Strata runs AI on your own computer.<br>Setting it up takes a few minutes.</p>
|
||||
<div class="onboard-benefits"><span>${check}Private</span><span>${check}Fast</span><span>${check}Easy to use</span></div></div>
|
||||
<footer class="onboard-footer onboard-footer--welcome"><button class="st-btn st-btn--primary">Install Strata</button><small>Installs for you only. No administrator needed.</small></footer>`,
|
||||
where: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
|
||||
<div class="mock-body"><h2 class="mock-title">Where should Strata go?</h2><p class="mock-sub">This is the right place for most people.</p>
|
||||
<div class="onboard-folder">${folder}<div><strong>Your Strata folder</strong><small>C:\\Users\\Alex\\AppData\\Local\\Strata</small></div><button class="st-btn st-btn--sm">Change</button></div>
|
||||
<p class="mock-note">About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.</p></div>
|
||||
<footer class="onboard-footer"><button class="st-btn st-btn--ghost">Back</button><span></span><button class="st-btn st-btn--primary">Install</button></footer>`,
|
||||
installing: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
|
||||
<div class="mock-body"><h2 class="mock-title">Installing Strata…</h2><p class="mock-sub">Copying the app and its engine room. You can keep working meanwhile.</p>
|
||||
<div class="onboard-progress" style="--p:62%"><progress max="100" value="62"></progress></div>
|
||||
<div class="onboard-progress-meta"><span>62% · 190 / 310 MB</span><div class="onboard-progress-actions"><span>About 1 min left</span><button>Cancel</button></div></div></div>
|
||||
<footer class="onboard-footer"><span></span><span class="mock-hint">Next: choose your first model inside Strata.</span><button class="st-btn st-btn--primary" disabled>Installing…</button></footer>`,
|
||||
done: theme => `<header class="onboard-header"><span class="mock-logo">${logo(theme)}</span></header>
|
||||
<div class="onboard-welcome-copy"><h1>Strata is ready.</h1><p>Open it to pick your first model. Strata downloads it for you and gets it ready.</p></div>
|
||||
<footer class="onboard-footer onboard-footer--welcome"><button class="st-btn st-btn--primary">Open Strata</button><small>A shortcut was added to your Start menu and desktop.</small></footer>`,
|
||||
};
|
||||
|
||||
const page = (name, theme) => `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css}
|
||||
body{background:${theme === 'dark' ? '#0b0d0e' : '#e9edef'};margin:0;display:grid;place-items:center;min-height:100vh}
|
||||
.mock-window{width:720px;border-radius:14px;overflow:hidden;background:var(--st-surface,#fff);border:1px solid var(--st-line,#dde);box-shadow:0 30px 80px #0003}
|
||||
.mock-titlebar{height:34px;display:flex;align-items:center;justify-content:space-between;padding:0 14px;font-size:12px;color:var(--st-ink-muted);background:var(--st-surface-2,#f3f5f6);border-bottom:1px solid var(--st-line-soft,#e6e9eb)}
|
||||
.mock-logo svg{height:22px;width:auto;display:block}
|
||||
.mock-body{padding:8px 36px 28px}.mock-title{font-size:28px;margin:16px 0 8px}.mock-sub{color:var(--st-ink-muted);margin:0 0 22px;line-height:1.6}
|
||||
.mock-note{color:var(--st-ink-muted);font-size:12px;margin-top:16px;line-height:1.6}.mock-hint{font-size:12px;color:var(--st-ink-muted)}
|
||||
.onboard-progress progress{width:100%}
|
||||
.guided-onboarding{min-height:430px;display:flex;flex-direction:column}.onboard-footer{margin-top:auto}
|
||||
</style></head><body><div class="mock-window"><div class="mock-titlebar"><span>Strata setup</span><span>– ☐ ✕</span></div>
|
||||
<div class="setup guided-onboarding" data-step="${name === 'welcome' || name === 'done' ? 1 : 2}">${screens[name](theme)}</div></div></body></html>`;
|
||||
|
||||
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
|
||||
const written = [];
|
||||
for (const theme of ['light', 'dark']) {
|
||||
for (const name of Object.keys(screens)) {
|
||||
const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 });
|
||||
await tab.setContent(page(name, theme));
|
||||
await tab.waitForTimeout(250);
|
||||
const file = join(out, `${name}-${theme}.png`);
|
||||
await tab.screenshot({ path: file });
|
||||
written.push(file);
|
||||
await tab.close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
console.log(written.join('\n'));
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current
|
||||
* icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is
|
||||
* how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they
|
||||
* stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions.
|
||||
*
|
||||
* node apps/desktop/scripts/make-icons.mjs [--out <folder>] writes icon-<size>.png for every size and icon.ico
|
||||
*/
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const host = resolve(here, '../../host');
|
||||
const out = resolve(args.out ?? join(here, '../src-tauri/icons'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
|
||||
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
|
||||
|
||||
const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png
|
||||
|
||||
/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */
|
||||
function hinted(size) {
|
||||
const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1;
|
||||
const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2);
|
||||
const even = w => (w % 2 === size % 2 ? w : w + 1);
|
||||
const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76));
|
||||
return [
|
||||
{ x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT },
|
||||
{ x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN },
|
||||
{ x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT },
|
||||
];
|
||||
}
|
||||
/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */
|
||||
function proportional(size) {
|
||||
const k = size / 512;
|
||||
return [
|
||||
{ x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT },
|
||||
{ x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN },
|
||||
{ x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT },
|
||||
];
|
||||
}
|
||||
function svg(size) {
|
||||
const small = size <= 48;
|
||||
const bars = (small ? hinted(size) : proportional(size));
|
||||
const radius = small ? Math.round(size * 0.22) : size * 0.215;
|
||||
const rects = bars.map(b => `<rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" rx="${small ? Math.min(b.h / 2, 1.5 + size / 32) : b.h / 2}" fill="${b.fill}"${small ? ' shape-rendering="crispEdges"' : ''}/>`).join('');
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><rect width="${size}" height="${size}" rx="${radius}" fill="${TILE}"/>${rects}</svg>`;
|
||||
}
|
||||
|
||||
const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024];
|
||||
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
|
||||
const png = {};
|
||||
for (const size of SIZES) {
|
||||
const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 });
|
||||
await page.setContent(`<!doctype html><body style="margin:0;background:transparent">${svg(size)}</body>`);
|
||||
png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } });
|
||||
await page.close();
|
||||
writeFileSync(join(out, `icon-${size}.png`), png[size]);
|
||||
}
|
||||
await browser.close();
|
||||
|
||||
// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling.
|
||||
const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256];
|
||||
const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4);
|
||||
let offset = 6 + 16 * ICO.length;
|
||||
const entries = [], blobs = [];
|
||||
for (const size of ICO) {
|
||||
const data = png[size], e = Buffer.alloc(16);
|
||||
e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3);
|
||||
e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12);
|
||||
offset += data.length; entries.push(e); blobs.push(data);
|
||||
}
|
||||
writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs]));
|
||||
writeFileSync(join(out, 'icon.png'), png[512]);
|
||||
console.log('icons in', out, ICO.join(','));
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the
|
||||
* brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font).
|
||||
*
|
||||
* node apps/desktop/scripts/make-installer-images.mjs [--out <folder>] [--preview <folder>]
|
||||
*
|
||||
* Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with
|
||||
* --preview the same as PNGs at 3x.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const host = resolve(here, '../../host');
|
||||
const out = resolve(args.out ?? join(here, '../src-tauri/nsis'));
|
||||
mkdirSync(out, { recursive: true });
|
||||
const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
|
||||
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
|
||||
const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href;
|
||||
const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href;
|
||||
const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8');
|
||||
const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8');
|
||||
|
||||
// the app's light tokens
|
||||
const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea';
|
||||
const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})}
|
||||
*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`;
|
||||
|
||||
const pages = {
|
||||
sidebar: { w: 164, h: 314, html: `<div style="width:164px;height:314px;padding:22px 18px;display:flex;flex-direction:column;background:linear-gradient(180deg,#f9fafb 0%,#eef6f2 100%);border-right:1px solid ${LINE}">
|
||||
<div style="height:26px">${lockup.replace('<svg', '<svg style="height:26px;width:auto;display:block"')}</div>
|
||||
<div style="margin-top:auto">
|
||||
<div style="font-weight:700;font-size:22px;line-height:1.12;letter-spacing:-.01em">State of<br>the art.<br>At home.</div>
|
||||
<div style="margin-top:10px;font-weight:500;font-size:11px;line-height:1.5;color:${MUTED}">AI on your own computer.<br>Private. Fast. Easy.</div>
|
||||
<div style="margin-top:16px;height:3px;width:34px;border-radius:2px;background:${ACCENT}"></div>
|
||||
</div></div>` },
|
||||
header: { w: 150, h: 57, html: `<div style="width:150px;height:57px;display:flex;align-items:center;justify-content:flex-end;padding-right:12px;background:${SURFACE}">${lockup.replace('<svg', '<svg style="height:22px;width:auto;display:block"')}</div>` },
|
||||
};
|
||||
|
||||
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
|
||||
const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true });
|
||||
for (const [name, page] of Object.entries(pages)) {
|
||||
for (const scale of [1, 3]) {
|
||||
const file = join(work, `${name}.html`);
|
||||
writeFileSync(file, `<!doctype html><meta charset="utf-8"><style>${css}</style><body>${page.html}</body>`);
|
||||
const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale });
|
||||
await tab.goto(pathToFileURL(file).href);
|
||||
await tab.evaluate(() => document.fonts.ready);
|
||||
await tab.waitForTimeout(200);
|
||||
const png = join(work, `${name}@${scale}.png`);
|
||||
await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } });
|
||||
await tab.close();
|
||||
if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); }
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter
|
||||
const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`;
|
||||
const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' });
|
||||
if (done.status !== 0) { console.error(done.stderr); process.exit(1); }
|
||||
console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp'));
|
||||
@@ -73,6 +73,55 @@ def extract(archive: Path, destination: Path) -> Path:
|
||||
return inner
|
||||
|
||||
|
||||
#: What the app's installer needs on top of the Terminal bundle: the model catalog and GPU probe (tools/strata_mcp.py reads
|
||||
#: setup.py's tables), and the install job, which downloads a model the user chose, prepares it with the bundled tools and
|
||||
#: writes a run config naming "component:strata-engine". setup.py runs in its CONTROL mode there (no pip, no engine fetch,
|
||||
#: no compiler). Entry points; their local imports under tools/ come with them.
|
||||
INSTALLER_FILES = ("setup.py", "ref/load.py") # ref/load.py: strata_pack.py (the Q2_0 AVX-512 repack) imports it
|
||||
INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fetch", "mtp_pack", "mtp_rt", "draft_vocab",
|
||||
"strata_tokenizer", "gguf_reader")
|
||||
INSTALLER_DATA = "data" # draft vocabularies, expert profiles: 2 MB
|
||||
|
||||
|
||||
def local_imports(folder: Path, entry: tuple[str, ...]) -> list[str]:
|
||||
"""The tools/ modules `entry` imports, transitively (static: import and from-import statements)."""
|
||||
import ast
|
||||
seen: set[str] = set()
|
||||
todo = list(entry)
|
||||
while todo:
|
||||
name = todo.pop()
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
source = folder / "tools" / f"{name}.py"
|
||||
if not source.exists():
|
||||
raise SystemExit(f"installer tool missing: tools/{name}.py")
|
||||
for node in ast.walk(ast.parse(source.read_text(encoding="utf-8-sig"))):
|
||||
names = [a.name.split(".")[0] for a in node.names] if isinstance(node, ast.Import) else \
|
||||
[node.module.split(".")[0]] if isinstance(node, ast.ImportFrom) and node.module and node.level == 0 else []
|
||||
todo += [m for m in names if (folder / "tools" / f"{m}.py").exists() and m not in seen]
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def add_installer(folder: Path) -> dict:
|
||||
"""Copy the installer's files from the source tree into the staged Control (after the Terminal bundle is in place)."""
|
||||
tools = local_imports(ROOT, INSTALLER_TOOLS)
|
||||
copied = []
|
||||
for name in INSTALLER_FILES:
|
||||
(folder / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(ROOT / name, folder / name)
|
||||
copied.append(name)
|
||||
(folder / "tools").mkdir(exist_ok=True)
|
||||
for name in tools:
|
||||
shutil.copy2(ROOT / "tools" / f"{name}.py", folder / "tools" / f"{name}.py")
|
||||
copied.append(f"tools/{name}.py")
|
||||
if (folder / INSTALLER_DATA).exists():
|
||||
shutil.rmtree(folder / INSTALLER_DATA)
|
||||
shutil.copytree(ROOT / INSTALLER_DATA, folder / INSTALLER_DATA, ignore=shutil.ignore_patterns("__pycache__"))
|
||||
return {"files": copied, "data": INSTALLER_DATA, "setup_sha256": sha256(folder / "setup.py"),
|
||||
"mode": "STRATA_CONTROL_INSTALL=1: downloads the chosen model, prepares it, installs no package and no engine"}
|
||||
|
||||
|
||||
def write_bundle_record(folder: Path, archive: Path) -> dict:
|
||||
manifest_path = archive.with_name(archive.name.rsplit(".", 2 if archive.name.endswith(".tar.gz") else 1)[0] + ".manifest.json")
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {}
|
||||
@@ -86,6 +135,7 @@ def write_bundle_record(folder: Path, archive: Path) -> dict:
|
||||
"installed": manifest.get("installed"),
|
||||
"archive": {"name": archive.name, "sha256": sha256(archive), "bytes": archive.stat().st_size},
|
||||
"acquires_at_runtime": False,
|
||||
"installer": add_installer(folder),
|
||||
}
|
||||
(folder / "BUNDLE.json").write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
|
||||
return record
|
||||
@@ -95,7 +145,8 @@ def check(folder: Path) -> int:
|
||||
target = pt.host_target()
|
||||
python = folder / pt.PYTHON_PINS[target]["python"]
|
||||
problems = []
|
||||
for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json"):
|
||||
for need in (python, folder / "strata.py", folder / "strata_control", folder / "serve" / "server.py", folder / "BUNDLE.json",
|
||||
folder / "setup.py", folder / "tools" / "strata_mcp.py", folder / "tools" / "iq_pack.py", folder / "data" / "draft_vocab.bin"):
|
||||
if not need.exists():
|
||||
problems.append(f"missing {need}")
|
||||
if problems:
|
||||
@@ -105,7 +156,16 @@ def check(folder: Path) -> int:
|
||||
done = subprocess.run([str(python), str(folder / "strata.py"), "--version"], capture_output=True, text=True, env=env,
|
||||
cwd=str(folder), timeout=60)
|
||||
print(done.stdout.strip() or done.stderr.strip())
|
||||
return done.returncode
|
||||
if done.returncode:
|
||||
return done.returncode
|
||||
# the installer: its catalog, a GPU probe and its imports work on the bundled Python alone (nothing is installed or fetched)
|
||||
probe = ("import sys; sys.path.insert(0, %r); import importlib.util as u; s = u.spec_from_file_location('s', %r); m = u.module_from_spec(s); "
|
||||
"s.loader.exec_module(m); import iq_pack, strata_pack, pack_index, mtp_fetch; "
|
||||
"print('installer ok: %%d models, %%d families' %% (len(m.MODELS), len(m.FAMILIES)))") % (str(folder / "tools"), str(folder / "setup.py"))
|
||||
env["STRATA_CONTROL_INSTALL"] = "1"
|
||||
again = subprocess.run([str(python), "-c", probe], capture_output=True, text=True, env=env, cwd=str(folder), timeout=120)
|
||||
print(again.stdout.strip() or again.stderr.strip()[-600:])
|
||||
return again.returncode
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Headless UI flows of the installed app against a packaged host with a FAKE installer and a FAKE engine (nothing is
|
||||
* downloaded, no real engine runs; the real Control starts the fake engine through the owner runtime):
|
||||
*
|
||||
* node apps/desktop/scripts/ui-flows.mjs [--control <staged control>] [--node <node.exe>] [--shots <dir>] [--only download,models,tune,fail,theme]
|
||||
*
|
||||
* download the onboarding download: ONE combined bar over both files, an ETA in minutes left of Stop, Finish later closes the
|
||||
* pop-up with the download still running, the Models screen shows the same progress, Stop stops it
|
||||
* models an installed model is the one Models selects and loads, without a download pop-up
|
||||
* tune the tuning step offers no picture reading, tunes, writes a RAM budget for "leave 20%", opens chat; reading size
|
||||
* fail an engine that stops while loading: the error is in words and the pop-up does not scroll
|
||||
* theme the app follows the system light/dark setting
|
||||
* Per-user folders are all under a scratch folder. Exit 1 if a check fails.
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), []));
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const repoHost = resolve(here, '../../host');
|
||||
const staged = resolve(here, '../src-tauri/resources');
|
||||
const stagedControl = resolve(args.control ?? join(staged, 'control'));
|
||||
const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node'));
|
||||
const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-'));
|
||||
const shots = resolve(args.shots ?? join(work, 'shots'));
|
||||
mkdirSync(shots, { recursive: true });
|
||||
const only = new Set(String(args.only ?? 'download,models,tune,fail,delete,theme,restart,perf,polish,stop,latest').split(','));
|
||||
const isWin = process.platform === 'win32';
|
||||
const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
|
||||
const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
|
||||
const delay = ms => new Promise(r => setTimeout(r, ms));
|
||||
const sha = buf => createHash('sha256').update(buf).digest('hex');
|
||||
const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; };
|
||||
let failed = false;
|
||||
const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; };
|
||||
|
||||
// ------------------------------------------------------------------ the app folder: the real Control with a fake installer
|
||||
const control = join(work, 'control');
|
||||
mkdirSync(control, { recursive: true });
|
||||
for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) symlinkSync(join(stagedControl, name), join(control, name), 'junction');
|
||||
for (const name of ['strata.py', 'VERSION', 'BUNDLE.json', 'requirements.txt']) copyFileSync(join(stagedControl, name), join(control, name));
|
||||
cpSync(join(stagedControl, 'tools'), join(control, 'tools'), { recursive: true });
|
||||
const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'python', 'bin', 'python3');
|
||||
|
||||
const FAKE_INSTALLER = String.raw`
|
||||
import json, os, sys, time
|
||||
from pathlib import Path
|
||||
ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.')
|
||||
STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True)
|
||||
RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5'))
|
||||
def size(model, gb, ram, mid):
|
||||
return {'model': model, 'about': model, 'download_gb': gb, 'ram_needed_gb': ram, 'experts_gb': ram - 8, 'on_this_pc': 'fits', 'installed': False, 'images': True, 'experimental': False, 'id': mid}
|
||||
CATALOG = {'summary': 'fake', 'families': [{'family': 'qwen', 'title': 'Qwen3.8-Flash-Next', 'about': 'x', 'experimental': False, 'images': True, 'sizes': [
|
||||
size('Q2_0', 66.4, 48, 'q2_0'), size('IQ3_XXS', 75.8, 60, 'iq3_xxs'), size('IQ3_S', 83.6, 62, 'iq3_s')]}],
|
||||
'contexts': [8192, 32768, 65536], 'recommendation': {'family': 'qwen', 'model': 'IQ3_XXS', 'title': 'Qwen3.8-Flash-Next IQ3_XXS', 'context': 32768}, 'context_note': ''}
|
||||
HARDWARE = {'ram_gb': 63.1, 'cpu': {'name': 'cpu', 'cores': 12}, 'gpus': [{'index': 0, 'name': 'NVIDIA GeForce RTX 5070', 'vram_gb': 11.9, 'usable': True}]}
|
||||
TOTAL = 83.6
|
||||
def job():
|
||||
f = STATE / 'job.json'
|
||||
if not f.exists(): return None
|
||||
j = json.loads(f.read_text())
|
||||
if j.get('cancelled'):
|
||||
return {'running': False, 'exit_code': 1, 'error': 'stopped', 'result': 'failed'}
|
||||
done = min(TOTAL, RATE * (time.time() - j['start']))
|
||||
return {'running': True, 'step': '5/7: downloading Qwen3.8-Flash-Next IQ3_S', 'model': 'IQ3_S',
|
||||
'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}}
|
||||
def call(name, a):
|
||||
if name == 'strata_models': return CATALOG
|
||||
if name == 'strata_remove':
|
||||
cfg = ROOT / ('strata-%s.json' % a['model'])
|
||||
if a.get('confirm') and cfg.exists(): cfg.unlink()
|
||||
return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []}
|
||||
if name == 'strata_status': return {'summary': 'fake', 'installed': {'models': [{'model': 'iq3_s', 'disk_gb': 83.6, 'disk_bytes': 83600000000}]}, 'hardware': HARDWARE, 'recommendation': CATALOG['recommendation'], 'install': job(), 'running': []}
|
||||
if name == 'strata_install':
|
||||
if a.get('cancel'):
|
||||
f = STATE / 'job.json'
|
||||
if f.exists(): j = json.loads(f.read_text()); j['cancelled'] = True; f.write_text(json.dumps(j))
|
||||
return {'summary': 'stopped', 'install': job()}
|
||||
if a.get('confirm'):
|
||||
(STATE / 'job.json').write_text(json.dumps({'start': time.time()}))
|
||||
return {'summary': 'started', 'plan': {'download_gb': TOTAL}, 'install': job()}
|
||||
if not a: return {'summary': 'progress', 'install': job()}
|
||||
return {'summary': 'Plan', 'plan': {'title': 'Qwen3.8-Flash-Next IQ3_S', 'download_gb': TOTAL, 'disk_short': None}}
|
||||
raise Exception('unknown tool ' + name)
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line: continue
|
||||
m = json.loads(line)
|
||||
if 'id' not in m: continue
|
||||
method = m.get('method')
|
||||
if method == 'initialize': res = {'protocolVersion': '2024-11-05'}
|
||||
elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]}
|
||||
else:
|
||||
p = m['params']
|
||||
res = {'structuredContent': call(p['name'], p.get('arguments') or {})}
|
||||
sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': res}) + '\n'); sys.stdout.flush()
|
||||
`;
|
||||
writeFileSync(join(control, 'tools', 'strata_mcp.py'), FAKE_INSTALLER);
|
||||
|
||||
const FAKE_ENGINE = `import os, sys, json, time
|
||||
from pathlib import Path
|
||||
if os.environ.get('FAKE_ENGINE_FAIL'):
|
||||
print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True)
|
||||
sys.exit(3)
|
||||
ctx = '4096'
|
||||
if '--max-context' in sys.argv: ctx = sys.argv[sys.argv.index('--max-context') + 1]
|
||||
print('READY %s stop' % ctx, flush=True)
|
||||
for line in sys.stdin:
|
||||
if line.strip() == 'QUIT': break
|
||||
if line.startswith(('GEN ', 'BGEN ')):
|
||||
slot = int(line.split()[1]) if line.startswith('BGEN ') else None
|
||||
t0 = time.time(); n = 0
|
||||
for ch in os.environ.get('FAKE_REPLY', 'a'):
|
||||
print('T %d' % ord(ch), flush=True); n += 1
|
||||
if os.environ.get('FAKE_TOKEN_DELAY'): time.sleep(float(os.environ['FAKE_TOKEN_DELAY']))
|
||||
print('DONE %d 12 300.0 %.1f length 0 0 0' % (n, max(1.0, (time.time() - t0) * 1000)), flush=True)
|
||||
if slot is not None: print(f'BADM {slot} 0', flush=True)
|
||||
`;
|
||||
|
||||
// one scenario = one fresh host with its own per-user folders
|
||||
async function scenario(name, { installed = false, env = {} } = {}, body) {
|
||||
if (!only.has(name)) return;
|
||||
console.log(`--- ${name}`);
|
||||
const dir = join(work, name);
|
||||
const dirs = { home: join(dir, 'home'), appdata: join(dir, 'appdata'), local: join(dir, 'local'), components: join(dir, 'local', 'Strata', 'components'), install: join(dir, 'local', 'Strata', 'install'), state: join(dir, 'fake-state'), profiles: join(dir, 'profiles'), runtime: join(dir, 'runtime') };
|
||||
for (const d of [dirs.home, dirs.appdata, dirs.local, dirs.components, dirs.install, dirs.state, join(dir, 'models')]) mkdirSync(d, { recursive: true });
|
||||
const baseEnv = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(dir, 'models'), APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, USERPROFILE: dirs.home, XDG_CONFIG_HOME: join(dir, 'xdg'), XDG_DATA_HOME: join(dir, 'xdgdata'), PYTHONDONTWRITEBYTECODE: '1', STRATA_ENGINE_BACKEND: 'cuda', FAKE_STATE: dirs.state, ...env };
|
||||
delete baseEnv.STRATA_API_KEY; delete baseEnv.STRATA_INSTALL_DIR;
|
||||
if (installed) {
|
||||
const platform = isWin ? 'windows-x86_64' : 'linux-x86_64';
|
||||
const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`);
|
||||
mkdirSync(folder, { recursive: true });
|
||||
writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE);
|
||||
const entry = isWin ? 'engine.cmd' : 'engine';
|
||||
writeFileSync(join(folder, entry), isWin ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`);
|
||||
const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; });
|
||||
writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files }));
|
||||
const tok = join(dirs.install, 'tokenizer');
|
||||
mkdirSync(tok, { recursive: true });
|
||||
const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`;
|
||||
const made = spawnSync(python, ['-c', script, tok], { cwd: control, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' });
|
||||
if (made.status !== 0) throw new Error('tokenizer fixture: ' + made.stderr);
|
||||
writeFileSync(join(dirs.install, 'strata-iq3_s.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: ['--max-context', '32768', '--pool-workers', '12'], cwd: dir, model_name: 'stub', host: '127.0.0.1', port: 0, kv: 'int8' }));
|
||||
}
|
||||
const port = env.FIXED_PORT ? Number(env.FIXED_PORT) : await freePort(), base = `http://127.0.0.1:${port}`;
|
||||
const host = spawn(nodeExe, [join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
||||
env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_CONTROL_DIR: control, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } });
|
||||
let log = ''; host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; });
|
||||
const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; };
|
||||
const browser = await chromium.launch({ executablePath: CHROME, headless: true });
|
||||
try {
|
||||
let up = false;
|
||||
for (let i = 0; i < 200 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(150); } }
|
||||
check(up, `${name}: the packaged host starts`);
|
||||
await api('/api/native?refresh=1');
|
||||
await body({ base, api, browser, dirs, shot: (page, n) => page.screenshot({ path: join(shots, `${name}-${n}.png`) }), log: () => log });
|
||||
} catch (error) {
|
||||
check(false, `${name}: the flow`, String(error?.stack ?? error).slice(0, 700) + '\n' + log.slice(-600));
|
||||
} finally {
|
||||
await browser.close().catch(() => {});
|
||||
host.kill(); await new Promise(r => host.once('exit', r));
|
||||
}
|
||||
}
|
||||
const newPage = async (browser, base, options = {}) => {
|
||||
const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...(process.env.SCHEME ? { colorScheme: process.env.SCHEME } : {}), ...options });
|
||||
const page = await context.newPage();
|
||||
const problems = [];
|
||||
page.on('pageerror', e => problems.push(e.message));
|
||||
page.problems = problems;
|
||||
await page.goto(base, { waitUntil: 'domcontentloaded' });
|
||||
return page;
|
||||
};
|
||||
const clickText = async (page, re, timeout = 30000) => { const b = page.getByRole('button', { name: re }).first(); await b.waitFor({ timeout }); await b.click(); };
|
||||
const noScroll = async page => page.evaluate(() => {
|
||||
const root = document.querySelector('.guided-onboarding');
|
||||
const bad = [];
|
||||
for (let el = document.querySelector('.onboard-tune-stage, .onboard-prepare-stage, .onboard-model-stage') ?? root; el && el !== document.body; el = el.parentElement) {
|
||||
const style = getComputedStyle(el);
|
||||
if (/(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 1) bad.push(`${el.className || el.tagName}: ${el.scrollHeight} > ${el.clientHeight}`);
|
||||
}
|
||||
return bad;
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ download
|
||||
await scenario('download', {}, async ({ base, api, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /get started/i);
|
||||
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
|
||||
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
|
||||
await clickText(page, /^Continue/);
|
||||
await clickText(page, /Download model/i, 60000);
|
||||
await page.locator('.onboard-progress progress').waitFor({ timeout: 30000 });
|
||||
// ONE bar: sample the percent while it runs, it only goes up
|
||||
const samples = [];
|
||||
let eta = '';
|
||||
for (let i = 0; i < 40 && !eta; i++) {
|
||||
const state = (await api('/api/native')).body;
|
||||
const d = state.jobs.at(-1)?.result?.install?.download;
|
||||
if (d) samples.push(d.done_gb);
|
||||
eta = (await page.locator('.onboard-progress-actions span').first().textContent({ timeout: 1000 }).catch(() => '')) ?? '';
|
||||
await delay(1000);
|
||||
}
|
||||
await shot(page, '1-wizard-progress');
|
||||
check(/About \d+ (min left|h)/.test(eta), 'the wizard shows about how many minutes are left', eta.trim());
|
||||
const order = await page.evaluate(() => { const a = document.querySelector('.onboard-progress-actions'); const kids = a ? [...a.children].map(k => k.tagName + ':' + Math.round(k.getBoundingClientRect().left)) : []; return kids; });
|
||||
check(order.length === 2 && order[0].startsWith('SPAN') && order[1].startsWith('BUTTON') && Number(order[0].split(':')[1]) < Number(order[1].split(':')[1]), 'the time left sits left of Stop', order.join(' '));
|
||||
check(samples.length >= 3 && samples.every((v, i) => i === 0 || v >= samples[i - 1]), 'one combined count that only goes up', samples.map(v => v.toFixed(1)).join(', '));
|
||||
const meta = await page.locator('.onboard-progress-meta span').first().textContent();
|
||||
check(/GB/.test(meta ?? '') && /83\.6/.test(meta ?? ''), 'the bar says done / total over the whole model', meta);
|
||||
// close the pop-up while it downloads
|
||||
await clickText(page, /Finish later/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByText(/Preparing your model/i).waitFor({ timeout: 15000 }).catch(() => {});
|
||||
await delay(1500);
|
||||
await shot(page, '2-models-progress');
|
||||
await page.locator('.native-progress').first().screenshot({ path: join(shots, 'download-3-models-progress-card.png') }).catch(() => {});
|
||||
check(await page.locator('.guided-onboarding').count() === 0, 'the setup pop-up closed');
|
||||
check(await page.getByText(/Preparing your model/i).count() > 0, 'the Models screen shows the running download');
|
||||
const still = (await api('/api/native')).body.jobs.at(-1);
|
||||
check(still?.state === 'running', 'the download keeps running in the background', still?.state);
|
||||
const modelsEta = await page.locator('.native-progress .onboard-progress-actions span').first().textContent({ timeout: 15000 }).catch(() => '');
|
||||
check(/About \d+ (min left|h)/.test(modelsEta ?? ''), 'the Models screen shows the time left too', (modelsEta ?? '').trim());
|
||||
await clickText(page, /^Stop$/);
|
||||
await delay(2500);
|
||||
check((await api('/api/native')).body.jobs.at(-1)?.state !== 'running', 'Stop stops it');
|
||||
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ models
|
||||
await scenario('models', { installed: true }, async ({ base, api, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /Go straight to the app/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
|
||||
await delay(1500);
|
||||
await shot(page, '1-models');
|
||||
await page.locator('.native-toolbar-summary').first().waitFor({ timeout: 20000 }).catch(async () => { await shot(page, '0-models-missing-summary'); console.log('info page text:', JSON.stringify((await page.locator('body').innerText()).slice(0, 500))); });
|
||||
const summary = await page.locator('.native-toolbar-summary').first().textContent({ timeout: 5000 }).catch(() => '');
|
||||
check(/IQ3_S|High quality/.test(summary ?? ''), 'Models selects the model that is on this PC, not the recommendation', (summary ?? '').replace(/\s+/g, ' ').trim());
|
||||
check(!/IQ3_XXS|Balanced/.test(summary ?? ''), 'the recommendation (IQ3_XXS) is not what is selected');
|
||||
const load = page.getByRole('button', { name: /^Load model$/ }).first();
|
||||
await load.click();
|
||||
await delay(1200);
|
||||
check(await page.getByRole('dialog').filter({ hasText: /Download and prepare/i }).count() === 0, 'loading an installed model opens no download pop-up');
|
||||
let ready = false;
|
||||
for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); const err = s.instances.find(x => x.status === 'error'); if (err) throw new Error('load failed: ' + err.error); await delay(1000); }
|
||||
if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), 'instances', JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '2-models-after-click'); }
|
||||
check(ready, 'the model loads (a fake engine under the real Control)');
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 }).catch(() => {});
|
||||
await shot(page, '3-models-loaded');
|
||||
check(await page.getByRole('button', { name: /^Unload$/ }).count() > 0, 'after a reload the Models screen shows the model as loaded, with Unload');
|
||||
check(await page.getByRole('button', { name: /^Load model$/ }).count() === 0, 'and no longer offers Load model');
|
||||
await page.getByRole('button', { name: /^Unload$/ }).first().click();
|
||||
let gone = false;
|
||||
for (let i = 0; i < 40 && !gone; i++) { gone = (await api('/api/native')).body.instances.length === 0; await delay(500); }
|
||||
check(gone, 'Unload stops the engine');
|
||||
await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 15000 }).catch(() => {});
|
||||
check(await page.getByRole('button', { name: /^Load model$/ }).count() > 0, 'and Load model is back');
|
||||
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ tune + reading size
|
||||
await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: ['I am thinking about it.', '</think>', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /get started/i);
|
||||
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
|
||||
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
|
||||
await clickText(page, /^Continue/);
|
||||
await page.getByText(/Leave 20% for my work/i).waitFor({ timeout: 30000 });
|
||||
await delay(800);
|
||||
await shot(page, '1-tune-step');
|
||||
check(await page.getByText(/Read pictures when this model loads/i).count() === 0, 'the tuning step offers no picture reading for an app install');
|
||||
await clickText(page, /Tune & start chatting/i);
|
||||
let done = false, job = null;
|
||||
for (let i = 0; i < 120 && !done; i++) { job = (await api('/api/native')).body.jobs.findLast?.(j => j.kind === 'tune') ?? null; done = !!job && job.state !== 'running'; await delay(1000); }
|
||||
check(job?.state === 'done', 'tuning finishes without a vision error', job?.error ?? job?.state);
|
||||
const cfg = JSON.parse(readFileSync(join(dirs.install, 'strata-iq3_s.json'), 'utf8'));
|
||||
check(cfg.args.includes('--resident-budget-gib'), '"leave 20%" wrote a RAM budget for the experts', cfg.args.join(' '));
|
||||
const gib = Number(cfg.args[cfg.args.indexOf('--resident-budget-gib') + 1]);
|
||||
check(gib + 10 <= 63.1 * 0.8, 'the budget keeps the model within 80% of the PC RAM', `${gib} GiB`);
|
||||
// chat + reading size
|
||||
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 60000 });
|
||||
await page.getByRole('textbox', { name: /Message Strata/i }).fill('hello');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 60000 });
|
||||
await page.locator('.st-msg--assistant .st-bubble p').first().waitFor({ timeout: 60000 }).catch(async () => console.log('info reply so far:', JSON.stringify(await page.locator('.st-msg--assistant').first().innerText()).slice(0, 300)));
|
||||
await page.waitForFunction(() => !document.querySelector('.st-msg--assistant .caret'), null, { timeout: 90000 }).catch(() => {});
|
||||
// the chat's telemetry chips: speed and context
|
||||
const chips = page.locator('.telemetry__chip');
|
||||
const chipTexts = await chips.allInnerTexts();
|
||||
console.log('info chips', JSON.stringify(chipTexts));
|
||||
let speedText = '', contextText = '';
|
||||
for (let i = 0; i < await chips.count(); i++) {
|
||||
await chips.nth(i).click();
|
||||
await delay(400);
|
||||
const pop = await page.locator('.telepop').last().innerText().catch(() => '');
|
||||
if (/tok\/s|speed/i.test(pop) && !speedText) speedText = pop;
|
||||
if (/context/i.test(pop) && !contextText) contextText = pop;
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
const tps = Number(speedText.match(/([\d.]+)\s*tok(?:ens)?\/s/)?.[1] ?? NaN);
|
||||
check(tps > 15 && tps < 120, 'the speed shown is the decode speed (the engine paced at ~50 tokens a second)', speedText.replace(/\s+/g, ' ').slice(0, 160));
|
||||
check(/32\.8K|32K|32,768|32768/.test(contextText) && !/128K/.test(contextText), 'the context shown is the one the model runs with (32K), not 128K', contextText.replace(/\s+/g, ' ').slice(0, 160));
|
||||
const sizes = [];
|
||||
for (const px of [12, 14, 16, 22]) {
|
||||
await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px);
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
|
||||
await page.screenshot({ path: join(shots, `tune-3-chat-${px}px.png`) });
|
||||
sizes.push(await page.evaluate(() => { const b = document.querySelector('.st-msg--assistant .st-bubble'); const t = b.querySelector('p, .md-li, span') ?? b; const u = document.querySelector('.st-msg--user .st-bubble'); const all = {}; for (const el of b.querySelectorAll('*')) { if (!el.childNodes.length || ![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) continue; all[el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '')] = parseFloat(getComputedStyle(el).fontSize); } const extra = {}; for (const [k, q] of Object.entries({ reasoning: '.st-msg--assistant .st-collapse__body', codeblock: '.st-msg--assistant .st-code pre', codehead: '.st-msg--assistant .st-code__head' })) { const e = document.querySelector(q); if (e) extra[k] = parseFloat(getComputedStyle(e).fontSize); } Object.assign(all, extra); const chain = []; for (let e = b.querySelector('p'); e && e !== b; e = e.parentElement) chain.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); all.chain = chain; globalThis.__all = all; return [parseFloat(getComputedStyle(b).fontSize), parseFloat(getComputedStyle(t).fontSize), parseFloat(getComputedStyle(u).fontSize), all]; }));
|
||||
}
|
||||
console.log('info chain', JSON.stringify(await page.evaluate(() => { const el = document.querySelector('.st-msg--assistant .st-bubble p'); const out = []; for (let e = el; e && !e.classList.contains('st-msg'); e = e.parentElement) out.push(e.tagName + '.' + String(e.className).split(' ')[0] + '=' + getComputedStyle(e).fontSize); return out; })));
|
||||
// which visible text does NOT follow the reading size? (same elements at 12 and 22)
|
||||
const survey = async px => { await page.evaluate(v => { const k = 'strata.prefs.v2'; const cur = JSON.parse(localStorage.getItem(k) || '{}'); localStorage.setItem(k, JSON.stringify({ ...cur, contentFontSize: v })); }, px); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 }); await delay(600);
|
||||
return page.evaluate(() => { const out = {}; for (const el of document.querySelectorAll('main *, .chat *, textarea')) { if (![...el.childNodes].some(n => n.nodeType === 3 && n.textContent.trim()) && el.tagName !== 'TEXTAREA') continue; const r = el.getBoundingClientRect(); if (!r.width || !r.height) continue; const key = el.tagName.toLowerCase() + '.' + String(el.className).split(' ')[0] + ' <' + (el.parentElement?.className ?? '').toString().split(' ')[0] + '>'; out[key] = parseFloat(getComputedStyle(el).fontSize); } return out; }); };
|
||||
const a = await survey(12), b = await survey(22);
|
||||
// a fresh app (nothing saved) uses 14 px
|
||||
await page.evaluate(() => localStorage.removeItem('strata.prefs.v2'));
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
|
||||
check(await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble')).fontSize) === '14px', 'the default reading size is 14 px');
|
||||
const fixed = Object.keys(a).filter(k => k in b && a[k] === b[k]);
|
||||
console.log('info text that does not follow the reading size:', JSON.stringify(fixed.map(k => k + '=' + a[k])));
|
||||
await shot(page, '2-chat-22px');
|
||||
console.log('info sizes', JSON.stringify(sizes), JSON.stringify(await page.locator('.st-msg--assistant .st-bubble').first().innerHTML()).slice(0, 400));
|
||||
check(sizes[0][1] === 12 && sizes[1][1] === 14 && sizes[2][1] === 16 && sizes[3][1] === 22 && sizes[0][2] === 12 && sizes[3][2] === 22, 'the reading size changes the text size of the conversation', JSON.stringify(sizes));
|
||||
// the slider itself
|
||||
await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
|
||||
const slider = page.getByLabel('Reading text size');
|
||||
if (await slider.count()) {
|
||||
await slider.first().focus();
|
||||
for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowRight');
|
||||
await delay(500);
|
||||
const now = await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize);
|
||||
check(parseFloat(now) === 18, 'moving the slider changes the conversation text at once', now);
|
||||
const box = await slider.first().boundingBox();
|
||||
await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2);
|
||||
await delay(400);
|
||||
const dragged = await page.evaluate(() => [getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize, getComputedStyle(document.documentElement).getPropertyValue('--st-content-fs'), JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}').contentFontSize]);
|
||||
check(parseFloat(dragged[0]) >= 20 && parseFloat(dragged[2]) >= 20, 'clicking the slider with the mouse changes it too, and it is saved', dragged.join(' '));
|
||||
} else console.log('info the settings slider was not reachable by hash here; the stored size was checked above');
|
||||
check(page.problems.length === 0, 'no page error', page.problems.join('; '));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ delete
|
||||
await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /Go straight to the app/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByRole('button', { name: /^Load model$/ }).first().click();
|
||||
let ready = false;
|
||||
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
|
||||
check(ready, 'a model is loaded');
|
||||
await clickText(page, /Manage models/i);
|
||||
await page.getByRole('button', { name: /^Delete$/ }).first().click();
|
||||
await delay(600);
|
||||
await shot(page, '1-delete-confirm');
|
||||
const dialog = await page.getByRole('dialog').last().innerText();
|
||||
check(/Delete this version\?/.test(dialog) && /Remove 83\.6 GB of downloaded files\. You can download this version again\./.test(dialog), 'the confirm dialog uses the existing words and the real size', dialog.replace(/\s+/g, ' ').slice(0, 200));
|
||||
check(/running model will be unloaded/i.test(dialog), 'and says the loaded model is unloaded first');
|
||||
await page.getByRole('button', { name: /^Delete version$/ }).click();
|
||||
let state = null;
|
||||
for (let i = 0; i < 40; i++) { state = (await api('/api/native')).body; if (state.instances.length === 0 && !state.installed?.models?.some(m => m.model === 'iq3_s')) break; await delay(500); }
|
||||
check(state.instances.length === 0, 'the loaded model was unloaded');
|
||||
check(!existsSync(join(dirs.install, 'strata-iq3_s.json')), 'the installer removed the run config of the model');
|
||||
check(!state.installed?.models?.some(m => m.model === 'iq3_s'), 'the model is no longer listed as downloaded');
|
||||
await shot(page, '2-after-delete');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ perf
|
||||
await scenario('perf', { installed: true }, async ({ base, api, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /Go straight to the app/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByRole('button', { name: /^Load model$/ }).first().click();
|
||||
let ready = false;
|
||||
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
|
||||
check(ready, 'a model is loaded');
|
||||
await delay(2500);
|
||||
const requests = [];
|
||||
const started = new Map();
|
||||
page.on('request', r => started.set(r, Date.now()));
|
||||
page.on('requestfinished', r => requests.push([r.url().replace(base, '').slice(0, 60), Date.now() - (started.get(r) ?? Date.now())]));
|
||||
await page.evaluate(() => { window.__long = []; new PerformanceObserver(l => { for (const e of l.getEntries()) window.__long.push(Math.round(e.duration)); }).observe({ entryTypes: ['longtask'] }); });
|
||||
const t0 = Date.now();
|
||||
await page.evaluate(() => { location.hash = '#/chat'; });
|
||||
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
|
||||
const open = Date.now() - t0;
|
||||
await delay(1500);
|
||||
const long = await page.evaluate(() => window.__long);
|
||||
console.log('info chat opened in', open, 'ms; long tasks', JSON.stringify(long), 'requests', JSON.stringify(requests.filter(r => r[1] > 100)), 'all', requests.length);
|
||||
check(open < 1500 && Math.max(0, ...long) < 300, 'Models to Chat opens at once, with no long block', open + ' ms, longest task ' + Math.max(0, ...long) + ' ms');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ polish
|
||||
await scenario('polish', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /Go straight to the app/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
|
||||
check(await page.getByRole('button', { name: /Tune model/i }).count() === 0, 'the Models tab has no "Tune model" button');
|
||||
await clickText(page, /Manage models/i);
|
||||
await delay(500);
|
||||
const rows = await page.locator('.native-manage-row').count();
|
||||
check(rows === 1, 'Manage models lists only the downloaded model, not the catalog', rows + ' row(s)');
|
||||
await shot(page, '1-manage-models');
|
||||
await page.getByRole('button', { name: /^Done$/ }).click();
|
||||
await page.getByRole('button', { name: /Other local models/i }).click().catch(async () => { await clickText(page, /Manage models/i); await clickText(page, /Use a local GGUF/i); });
|
||||
await page.getByText(/Folder with the GGUF files/i).first().waitFor({ timeout: 15000 }).catch(() => {});
|
||||
await shot(page, '2-local-gguf');
|
||||
check(await page.getByText(/Folder with the GGUF files/i).count() > 0, 'the local GGUF page opens in the same design as Models');
|
||||
await page.getByPlaceholder(/Full path to the folder/i).fill(join(dirs.install, 'does-not-exist'));
|
||||
await page.getByRole('button', { name: /^Check files$/ }).click();
|
||||
await delay(3000);
|
||||
check(await page.locator('.error-notice').count() > 0, 'a folder that cannot be used says so in words');
|
||||
await shot(page, '2b-local-gguf-problem');
|
||||
await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
|
||||
await delay(1500);
|
||||
const text = await page.locator('body').innerText();
|
||||
check(!/Contrast/.test(text), 'Settings has no Contrast option');
|
||||
check(!/View request log/.test(text), 'and no "View request log" button');
|
||||
await page.getByText(/^Engine$/).first().click().catch(() => {});
|
||||
await delay(1500);
|
||||
await shot(page, '3-settings-engine');
|
||||
const engine = await page.locator('body').innerText();
|
||||
check(/Update component/.test(engine) && /Diagnostics/.test(engine), 'Settings > Engine has Update component and Diagnostics');
|
||||
check(!/Performance|Model settings|Calibrate|Engine installation/.test(engine), 'and nothing else');
|
||||
await page.getByRole('button', { name: /^Save logs$/ }).click();
|
||||
await page.getByText(/Saved to/).first().waitFor({ timeout: 15000 }).catch(() => {});
|
||||
const savedText = await page.getByText(/Saved to/).first().innerText().catch(() => '');
|
||||
const savedPath = savedText.replace(/^Saved to\s*/, '').trim();
|
||||
check(!!savedPath && existsSync(savedPath), 'Save logs writes a file to Downloads and says where', savedPath);
|
||||
await shot(page, '4-logs-saved');
|
||||
await page.evaluate(() => { location.hash = '#/monitor'; });
|
||||
await delay(6000);
|
||||
await shot(page, '5-monitor');
|
||||
const mon = await page.locator('body').innerText();
|
||||
check(/°C/.test(mon), 'the Monitor shows GPU data with no model loaded', (mon.match(/.{0,30}°C.{0,20}/)?.[0] ?? 'no temperature text').replace(/\s+/g, ' '));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ stop
|
||||
await scenario('stop', { installed: true, env: { FAKE_TOKEN_DELAY: '0.1', FAKE_REPLY: 'thinking '.repeat(30) } }, async ({ base, api, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /Go straight to the app/i);
|
||||
await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
|
||||
await page.getByRole('button', { name: /^Load model$/ }).first().click();
|
||||
let ready = false;
|
||||
for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
|
||||
if (!ready) { const st = (await api('/api/native')).body; console.log('info jobs', JSON.stringify(st.jobs.map(j => [j.kind, j.state, j.error ?? j.summary])), JSON.stringify(st.instances.map(i => [i.status, i.error]))); await shot(page, '0-stop-notloaded'); }
|
||||
check(ready, 'a model is loaded');
|
||||
await page.evaluate(() => { location.hash = '#/chat'; });
|
||||
const box = page.getByRole('textbox', { name: /Message Strata/i });
|
||||
await box.waitFor({ timeout: 30000 });
|
||||
await box.fill('hello');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.locator('.typing').first().waitFor({ timeout: 30000 });
|
||||
await delay(1500);
|
||||
await page.getByRole('button', { name: /^Stop/i }).first().click().catch(async () => { await page.keyboard.press('Escape'); });
|
||||
await delay(4000);
|
||||
const dots = await page.locator('.typing').count();
|
||||
await shot(page, '1-after-stop');
|
||||
check(dots === 0, 'after Stop in the middle of thinking the three dots are gone', dots + ' left');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ latest
|
||||
await scenario('latest', {}, async ({ base, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
const now = Date.now();
|
||||
await page.evaluate(now => {
|
||||
const messages = [];
|
||||
for (let i = 0; i < 40; i++) { messages.push({ id: 'u' + i, role: 'user', content: 'question ' + i, at: now }, { id: 'a' + i, role: 'assistant', content: 'answer number ' + i + ' with some text to fill the line and more of it.', at: now, tokens: 20, inputTokens: 5 }); }
|
||||
localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 's_latest', title: 'long', updatedAt: now, createdAt: now, messages }]));
|
||||
localStorage.setItem('strata.active-session.v1', 's_latest');
|
||||
}, now);
|
||||
await page.reload({ waitUntil: 'domcontentloaded' });
|
||||
await delay(1500);
|
||||
if (await page.getByRole('button', { name: /Go straight to the app/i }).count()) { await clickText(page, /Go straight to the app/i); await delay(1500); }
|
||||
await page.goto(base + '/#/chat', { waitUntil: 'domcontentloaded' });
|
||||
await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
|
||||
await delay(800);
|
||||
await page.locator('.main__body.chat').first().waitFor({ timeout: 15000 }).catch(async () => { await shot(page, '0-latest-missing'); console.log('info body', JSON.stringify((await page.locator('body').innerText()).slice(0, 300))); });
|
||||
await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 3000; });
|
||||
await delay(600);
|
||||
await page.mouse.wheel(0, -400);
|
||||
await delay(600);
|
||||
await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 0; });
|
||||
await delay(800);
|
||||
const gaps = await page.evaluate(() => { const b = document.querySelector('.jumplatest'), c = document.querySelector('.main__body.chat'); if (!b || !c) return null; const r = b.getBoundingClientRect(), cr = c.getBoundingClientRect(); return { top: Math.round(r.top - cr.top), bottom: Math.round(cr.bottom - r.bottom) }; });
|
||||
console.log('info chat dom', JSON.stringify(await page.evaluate(() => { const c = document.querySelector('.main__body.chat'); return { msgs: document.querySelectorAll('.st-msg').length, scrollH: c?.scrollHeight, clientH: c?.clientHeight, top: c?.scrollTop, jump: document.querySelectorAll('.jumplatest').length }; })));
|
||||
await shot(page, '1-latest-button');
|
||||
check(!!gaps && gaps.top >= 12 && gaps.bottom >= 12, 'the Latest button keeps a gap from the top navigation and from the bottom', JSON.stringify(gaps));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fail
|
||||
await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => {
|
||||
const page = await newPage(browser, base);
|
||||
await clickText(page, /get started/i);
|
||||
await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
|
||||
await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
|
||||
await clickText(page, /^Continue/);
|
||||
await clickText(page, /Tune & start chatting/i, 30000);
|
||||
await page.getByText(/ran low on memory/i).first().waitFor({ timeout: 120000 });
|
||||
await delay(1000);
|
||||
await shot(page, '1-tune-error');
|
||||
const text = await page.locator('.guided-onboarding').innerText();
|
||||
check(/ran low on memory/.test(text), 'the error says in words that the PC ran low on memory');
|
||||
check(/Leave 20% for my work/.test(text) && /low-RAM/.test(text), 'and what to try');
|
||||
check(!/server_exited|memory guard/.test(text), 'no code or log line in the main text');
|
||||
check(!/vision files/i.test(text), 'no picture-reading error');
|
||||
const bad = await noScroll(page);
|
||||
check(bad.length === 0, 'the tuning pop-up does not scroll when an error shows', bad.join('; '));
|
||||
await page.locator('.error-notice summary').first().click();
|
||||
await delay(500);
|
||||
await shot(page, '2-tune-error-details');
|
||||
const details = await page.locator('.error-notice pre').first().innerText();
|
||||
check(/server_exited/.test(details) && /exited before/.test(details), 'Details holds the code and the reason the server logged', details.replace(/\s+/g, ' ').slice(0, 120));
|
||||
const badOpen = await noScroll(page);
|
||||
check(badOpen.length === 0, 'and the pop-up still does not scroll with Details open', badOpen.join('; '));
|
||||
await page.setViewportSize({ width: 1280, height: 700 });
|
||||
await delay(600);
|
||||
const small = await noScroll(page);
|
||||
check(small.length === 0, 'nor in a small window (1280x700), Details open', small.join('; '));
|
||||
await shot(page, '3-tune-error-small-window');
|
||||
void api;
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ restart
|
||||
// The app keeps its theme, text size, language and chat list in the browser's storage, which belongs to the window's origin
|
||||
// (127.0.0.1:<port>). The shell now uses the same port every launch: stop the host, start it again on that port, reopen the
|
||||
// window with the same browser profile, and everything is still there.
|
||||
if (only.has('restart')) {
|
||||
console.log('--- restart');
|
||||
const fixed = await freePort();
|
||||
const profile = join(work, 'browser-profile');
|
||||
const run = async (body) => scenario('restart', { env: { FIXED_PORT: String(fixed) } }, async ctx => {
|
||||
const context = await chromium.launchPersistentContext(profile, { executablePath: CHROME, headless: true, viewport: { width: 1200, height: 800 } });
|
||||
try { await body(context, ctx); } finally { await context.close(); }
|
||||
});
|
||||
only.add('restart');
|
||||
await run(async (context, { base }) => {
|
||||
const page = context.pages()[0] ?? await context.newPage();
|
||||
await page.goto(base, { waitUntil: 'domcontentloaded' });
|
||||
await page.evaluate(() => { localStorage.setItem('strata.prefs.v2', JSON.stringify({ theme: 'dark', contentFontSize: 19, language: 'de' })); localStorage.setItem('strata.sessions.v1', JSON.stringify([{ id: 'chat-1', title: 'My chat' }])); });
|
||||
});
|
||||
await run(async (context, { base }) => {
|
||||
const page = context.pages()[0] ?? await context.newPage();
|
||||
await page.goto(base, { waitUntil: 'domcontentloaded' });
|
||||
const saved = await page.evaluate(() => ({ prefs: JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}'), chats: localStorage.getItem('strata.sessions.v1'), theme: document.documentElement.dataset.theme }));
|
||||
check(saved.prefs.contentFontSize === 19 && saved.prefs.language === 'de', 'text size and language survive a restart on the same port', JSON.stringify(saved.prefs));
|
||||
check(saved.theme === 'dark', 'the theme survives too', saved.theme);
|
||||
check(/My chat/.test(saved.chats ?? ''), 'and the chat list', saved.chats);
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ theme
|
||||
await scenario('theme', {}, async ({ base, browser, shot }) => {
|
||||
for (const scheme of ['dark', 'light']) {
|
||||
const page = await newPage(browser, base, { colorScheme: scheme });
|
||||
await delay(1500);
|
||||
const theme = await page.evaluate(() => document.documentElement.dataset.theme);
|
||||
check(theme === scheme, `a fresh app follows the system (${scheme})`, theme);
|
||||
await shot(page, `1-${scheme}`);
|
||||
await page.context().close();
|
||||
}
|
||||
});
|
||||
|
||||
// the junctions into the staged Control go first (rmdir on a junction removes only the link)
|
||||
for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) { try { rmdirSync(join(control, name)); } catch { /* already gone */ } }
|
||||
try { rmSync(work, { recursive: true, force: true, maxRetries: 3 }); } catch (e) { console.log('info scratch folder left behind:', work); }
|
||||
console.log(`shots in ${shots}`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 882 B After Width: | Height: | Size: 433 B |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1004 B |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 151 KiB |
@@ -239,6 +239,22 @@ fn pick_port() -> Result<u16, String> {
|
||||
Ok(port)
|
||||
}
|
||||
|
||||
/// The port the app prefers. The window's origin is `http://127.0.0.1:<port>`, and the browser storage that holds the
|
||||
/// theme, text size, language and the chat list belongs to that origin, so a port that changed on every launch lost all
|
||||
/// of it. The preferred port is fixed; only when something else holds it does the app fall back to a free one (and that
|
||||
/// launch starts with empty storage, as before).
|
||||
const PREFERRED_PORT: u16 = 47831;
|
||||
|
||||
fn pick_stable_port() -> Result<u16, String> {
|
||||
match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)) {
|
||||
Ok(listener) => {
|
||||
drop(listener);
|
||||
Ok(PREFERRED_PORT)
|
||||
}
|
||||
Err(_) => pick_port(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Locate a bundled resource.
|
||||
///
|
||||
/// In a packaged `.app` Tauri places `bundle.resources` under `Contents/Resources`. During
|
||||
@@ -418,7 +434,7 @@ fn start_host(app: &tauri::AppHandle) -> Result<u16, String> {
|
||||
}
|
||||
let node = node_binary(&res)?;
|
||||
|
||||
let port = pick_port()?;
|
||||
let port = pick_stable_port()?;
|
||||
|
||||
let mut cmd = Command::new(&node);
|
||||
cmd.arg(&entry)
|
||||
@@ -815,6 +831,21 @@ fn main() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_window_origin_is_stable_unless_the_port_is_taken() {
|
||||
// free (or already ours from a previous run): the same port every launch, so browser storage survives a restart
|
||||
let first = pick_stable_port().unwrap();
|
||||
let second = pick_stable_port().unwrap();
|
||||
assert_eq!(first, second);
|
||||
// held by another program: a different free port, not a failure
|
||||
if first == PREFERRED_PORT {
|
||||
let held = TcpListener::bind(("127.0.0.1", PREFERRED_PORT)).unwrap();
|
||||
let fallback = pick_stable_port().unwrap();
|
||||
assert_ne!(fallback, PREFERRED_PORT);
|
||||
drop(held);
|
||||
}
|
||||
}
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("strata-desktop-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
"deb"
|
||||
],
|
||||
"icon": [
|
||||
"icons/icon.png"
|
||||
"icons/icon.png",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"category": "DeveloperTool",
|
||||
"shortDescription": "Local AI, tuned to one model.",
|
||||
@@ -44,6 +45,10 @@
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"installMode": "currentUser",
|
||||
"template": "nsis/installer.nsi",
|
||||
"headerImage": "nsis/header.bmp",
|
||||
"sidebarImage": "nsis/sidebar.bmp",
|
||||
"installerIcon": "icons/icon.ico",
|
||||
"compression": "lzma",
|
||||
"languages": [
|
||||
"English"
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
// Set the saved appearance before CSS and logo images are painted.
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem('strata.prefs.v2') || localStorage.getItem('strata.prefs.v1') || '{}');
|
||||
const theme = saved.theme === 'dark' || (saved.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
|
||||
const choice = saved.theme ?? 'system';
|
||||
const theme = choice === 'dark' || (choice === 'system' && matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light';
|
||||
document.documentElement.dataset.theme = theme;
|
||||
document.querySelector('meta[name="theme-color"]').content = theme === 'dark' ? '#0e1113' : '#f9fafb';
|
||||
} catch { document.documentElement.dataset.theme = 'light'; }
|
||||
|
||||
@@ -89,6 +89,14 @@ export function controlEnvironment(control, { env = process.env, components = co
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The environment of the installer process (tools/strata_mcp.py): Control's, with acquiring still forbidden for the process
|
||||
* itself. Only the install job it starts when the user asks to download a model lifts that for its own children.
|
||||
*/
|
||||
export function installerEnvironment(control, { env = process.env, installDir, components = componentsDirectory({ env }) } = {}) {
|
||||
return { ...controlEnvironment(control, { env, components }), STRATA_CONTROL_INSTALL: '1', ...(installDir ? { STRATA_INSTALL_DIR: installDir } : {}) };
|
||||
}
|
||||
|
||||
export class ControlError extends Error {
|
||||
constructor(message, { code = 'control_failed', exitCode = null, output = null } = {}) {
|
||||
super(message);
|
||||
@@ -187,6 +195,12 @@ export function createControl({ control = findControl(), env = process.env, run
|
||||
if (result.code !== 0 || !result.json) throw failure(result, 'The installed models could not be read.');
|
||||
return result.json;
|
||||
},
|
||||
/** What a local GGUF folder or file holds, without touching it: the model it is, and why it cannot be used when it cannot. */
|
||||
async importPlan(path) {
|
||||
const result = await call(['models', 'import', path, '--plan', '--output', 'json'], { timeoutMs: 120_000 });
|
||||
if (result.json && result.code === 0) return result.json.plan ?? result.json;
|
||||
throw failure(result, 'The files could not be checked.');
|
||||
},
|
||||
async saveProfile(name, configPath) {
|
||||
const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 });
|
||||
const known = (listed.json?.profiles ?? []).some(p => p.id === name);
|
||||
|
||||
@@ -22,11 +22,12 @@ import { createAgentBridge } from './agent/agent-bridge.mjs';
|
||||
* live metrics and the local inference API. No runtime dependencies.
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import { homedir } from 'node:os';
|
||||
import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { basename, extname, isAbsolute, join, normalize, resolve } from 'node:path';
|
||||
import { basename, dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import * as hardware from './hardware.mjs';
|
||||
@@ -88,7 +89,7 @@ const native=createNativeControl({control,appUpdater,directory:store.DATA_DIR,mo
|
||||
state and the chat falls back to the direct path with a notice, never silently to another model. */
|
||||
const agent = createAgentBridge({
|
||||
dataDir: store.DATA_DIR,
|
||||
componentsDir: process.env.STRATA_COMPONENTS_DIR ?? null,
|
||||
componentsDir: componentsDirectory(),
|
||||
localInstances: () => native.readyInstances().map(i => ({
|
||||
id: i.id, label: i.label, baseUrl: `http://127.0.0.1:${i.port}/v1`, modelId: i.apiModelId,
|
||||
context: i.metrics?.engine?.max_context ?? i.context ?? undefined, key: i.key, vision: i.vision,
|
||||
@@ -481,12 +482,12 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI
|
||||
}
|
||||
}
|
||||
|
||||
async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='high' }) {
|
||||
async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='high', thinkingBudget=0 }) {
|
||||
if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, onFrame, signal, workspaceId });
|
||||
if(native.hasLive()||nativeModelId){
|
||||
let instance;try{instance=native.resolveInstance(nativeModelId??native.state().defaultId);}catch(e){onFrame({type:'error',message:e.message});return {error:e.message};}const started=Date.now(),cancel=new AbortController();
|
||||
const entry=serving.open({client:client??'Strata chat',endpoint:'/chat/completions',model:instance.apiModelId,instanceId:instance.id,gpuIds:instance.gpus.map(String),cancel:()=>cancel.abort()});
|
||||
try{serving.mark(entry.id,{state:'generating'});const applied=selectSkills(skillState,message,workspaceId);const result=await proxyCompletion({baseUrl:`http://127.0.0.1:${instance.port}/v1`,modelId:instance.apiModelId,authorization:instance.key,message,history,images,extra:{strata_mcp:useTools===true,reasoning_effort:({off:'none',max:'high'}[String(thinking).toLowerCase()]??String(thinking).toLowerCase())},systemPrompt:[SYSTEM_PROMPT,skillInstructions(applied)].filter(Boolean).join('\n\n'),signal:signal?AbortSignal.any([signal,cancel.signal]):cancel.signal,onFrame:frame=>onFrame({...frame,requestId:entry.id,model:instance.label,contextMax:instance.metrics?.engine?.max_context??instance.context,skills:applied.map(s=>s.name)})});serving.mark(entry.id,{...result,usageSource:result.usageSource});serving.finish(entry.id,{tokensOut:result.tokensOut,durationMs:Date.now()-started});return result;}catch(e){serving.finish(entry.id,{durationMs:Date.now()-started,error:e.message});onFrame({type:'error',message:e.message,requestId:entry.id});return {error:e.message};}
|
||||
try{serving.mark(entry.id,{state:'generating'});const applied=selectSkills(skillState,message,workspaceId);const result=await proxyCompletion({baseUrl:`http://127.0.0.1:${instance.port}/v1`,modelId:instance.apiModelId,authorization:instance.key,message,history,images,extra:{strata_mcp:useTools===true,...(thinkingBudget>0&&String(thinking).toLowerCase()!=='off'?{reasoning_budget_tokens:thinkingBudget}:{}),reasoning_effort:({off:'none',max:'high'}[String(thinking).toLowerCase()]??String(thinking).toLowerCase())},systemPrompt:[SYSTEM_PROMPT,skillInstructions(applied)].filter(Boolean).join('\n\n'),signal:signal?AbortSignal.any([signal,cancel.signal]):cancel.signal,onFrame:frame=>onFrame({...frame,requestId:entry.id,model:instance.label,contextMax:instance.metrics?.engine?.max_context??instance.context,skills:applied.map(s=>s.name)})});serving.mark(entry.id,{...result,usageSource:result.usageSource});serving.finish(entry.id,{tokensOut:result.tokensOut,durationMs:Date.now()-started});return result;}catch(e){serving.finish(entry.id,{durationMs:Date.now()-started,error:e.message});onFrame({type:'error',message:e.message,requestId:entry.id});return {error:e.message};}
|
||||
}
|
||||
runtimeState();
|
||||
let instance;
|
||||
@@ -774,6 +775,24 @@ async function api(req, res, path, method, url) {
|
||||
if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req)));
|
||||
if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));}
|
||||
if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()});
|
||||
if(path==='/api/native/logs/save'&&method==='POST'){
|
||||
/* Diagnostics to a file: the engine messages the app kept, failed operations, and the tail of each model's server log under Control.
|
||||
Written to the user's Downloads folder (the window cannot save a download); the path is returned to show. */
|
||||
const NL=String.fromCharCode(10);
|
||||
const lines=[`Strata diagnostics ${new Date().toISOString()}`,`Version ${native.state().version??'unknown'}`,'','== Engine messages =='];
|
||||
for(const l of native.logs())lines.push(`${l.at} ${l.instanceId}: ${l.line}`);
|
||||
lines.push('','== Operations ==');for(const j of native.state().jobs)lines.push(`${j.startedAt} ${j.kind} ${j.state}${j.error?`: ${j.error}`:''}${j.details?`${NL} ${j.details}`:''}`);
|
||||
try{const runtime=process.env.STRATA_RUNTIME_DIR??join(dirname(componentsDirectory()),'runtime');for(const name of readdirSync(runtime).filter(n=>n.endsWith('.server.log'))){lines.push('',`== ${name} (last lines) ==`,...readFileSync(join(runtime,name),'utf8').split(NL).slice(-200));}}catch{/* no server logs yet */}
|
||||
const folder=join(process.env.USERPROFILE??process.env.HOME??homedir(),'Downloads');mkdirSync(folder,{recursive:true});
|
||||
const file=join(folder,`strata-diagnostics-${new Date().toISOString().replace(/[:.]/g,'-').slice(0,19)}.txt`);writeFileSync(file,lines.join(NL),'utf8');
|
||||
return json(res,200,{path:file});}
|
||||
if(path==='/api/native/local/preview'&&method==='POST'){
|
||||
/* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */
|
||||
const typed=await typedFolder((await readBody(req)).path,{isAbsolute});
|
||||
const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files');
|
||||
if(picked.unavailable)return error(res,501,`${TYPE_A_PATH} ${picked.reason}`);
|
||||
if(picked.cancelled)return json(res,200,{cancelled:true});
|
||||
return json(res,200,{path:picked.path,preview:await native.localPreview(picked.path)});}
|
||||
if(path==='/api/native/benchmark'&&method==='GET')return json(res,200,native.benchmarkReport());
|
||||
const nativeOperation=/^\/api\/native\/operations\/([a-z0-9-]+)\/cancel$/.exec(path);
|
||||
if(nativeOperation&&method==='POST')return json(res,200,await native.cancel(nativeOperation[1]));
|
||||
@@ -1423,7 +1442,7 @@ async function api(req, res, path, method, url) {
|
||||
sessionId: typeof body.sessionId === 'string' ? body.sessionId : null,
|
||||
remoteModel: body.remoteModel ?? null,
|
||||
nativeModelId:body.nativeModelId,
|
||||
images,useTools:body.useTools===true,thinking:body.thinking??'high',
|
||||
images,useTools:body.useTools===true,thinking:body.thinking??'high',thinkingBudget:Number.isInteger(body.thinkingBudget)&&body.thinkingBudget>0?Math.min(body.thinkingBudget,262144):0,
|
||||
});
|
||||
res.end();
|
||||
return undefined;
|
||||
|
||||
@@ -278,6 +278,12 @@ export async function proxyCompletion({ baseUrl, message, history = [], systemPr
|
||||
let streaming = true;
|
||||
let writing = false;
|
||||
let timings=null,finishReason=null;
|
||||
/* The speed shown while it streams is the decode speed of everything generated, reasoning included, from the first token: tokens
|
||||
(one per streamed chunk, or characters / 4 when the server batches) over the time since the first token, never the visible
|
||||
answer over the whole wall time. The engine's own numbers replace it when the answer is done. */
|
||||
let chunks=0,chars=0,lastStats=0;
|
||||
const liveStats=()=>{if(supervised||firstTokenAt===null)return;const now=Date.now();if(now-lastStats<400)return;const seconds=(now-firstTokenAt)/1000;if(seconds<.5)return;lastStats=now;
|
||||
const tokens=chars/Math.max(1,chunks)<8?chunks:Math.ceil(chars/4);onFrame({type:'stats',tokensOut:tokens,tps:Number((tokens/seconds).toFixed(1)),source:'stream'});};
|
||||
|
||||
const metricsTicker = supervised
|
||||
? setInterval(() => {
|
||||
@@ -325,12 +331,16 @@ export async function proxyCompletion({ baseUrl, message, history = [], systemPr
|
||||
if (delta.reasoning_content) {
|
||||
if (firstTokenAt === null) engine?.beginThinking();
|
||||
if (firstTokenAt === null) firstTokenAt = Date.now();
|
||||
chunks++; chars+=delta.reasoning_content.length;
|
||||
onFrame({ type: 'reasoning', text: delta.reasoning_content });
|
||||
liveStats();
|
||||
}
|
||||
if (delta.content) {
|
||||
if (!writing) { engine?.beginGenerating(); writing = true; }
|
||||
if (firstTokenAt === null) firstTokenAt = Date.now();
|
||||
chunks++; chars+=delta.content.length;
|
||||
onFrame({ type: 'delta', text: delta.content });
|
||||
liveStats();
|
||||
}
|
||||
}
|
||||
if (done) break;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Native Strata control plane. All user actions are explicit; opening the UI only reads state. */
|
||||
import { spawn } from 'node:child_process';
|
||||
import { randomBytes, randomUUID, createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs';
|
||||
import { join, resolve, dirname, basename } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createServer } from 'node:net';
|
||||
@@ -10,6 +10,7 @@ import { resourceSettings } from './native-resources.mjs';
|
||||
import { resolvePython, venvPython } from './python-resolver.mjs';
|
||||
import os from 'node:os';
|
||||
import { runtimeVision } from './native-vision.mjs';
|
||||
import { componentsDirectory, installerEnvironment } from './control-runtime.mjs';
|
||||
import { createEngineStep } from './engine-step.mjs';
|
||||
import { plainError, PHASE_TEXT } from './update-messages.mjs';
|
||||
|
||||
@@ -30,22 +31,45 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
comes from the component folder, and a start is `strata runtime start` under the owner runtime. Nothing is installed,
|
||||
updated or fetched from here. Without `control` (a source checkout) every path below is the original one. */
|
||||
const packaged=!!control;
|
||||
/* In the packaged app the model catalog, the GPU probe and the install job are Control's bundled tools/strata_mcp.py and
|
||||
setup.py, run on Control's own Python in the installer's mode (STRATA_CONTROL_INSTALL: no pip, no engine, no compiler).
|
||||
The install only runs when the user clicks Download; starting and serving (control.start) keep STRATA_NO_ACQUIRE. */
|
||||
const defaultInstall=()=>join(dirname(componentsDirectory()),'install');
|
||||
let packagedInstall=null;
|
||||
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;
|
||||
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,engineAbort,rawResult,...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 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,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};}
|
||||
let sourceCache={path:'',time:0,text:''};
|
||||
function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}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'};})};}
|
||||
function repo(){if(packaged){const base=[preferences.installDir,snapshot.installDir].find(d=>d&&existsSync(d))??control.control.dir;return realpathSync(base);}const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
|
||||
const modelArena=id=>({arenaGb:(snapshot.catalog?.families??[]).flatMap(f=>f.sizes??[]).find(s=>s.id===id)?.experts_gb});
|
||||
/* A start that ends with `server_exited` carries the engine's last log line with it; the app turns the code into words and
|
||||
keeps this text under "Details" (src/lib/plain-errors.ts). */
|
||||
function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;return tail&&!text.includes(tail)?`${text}: ${tail}`:text;}
|
||||
/* A run config the app's install job wrote names files inside the app's own Control folder (`cwd`, `--expert-profile`). When the
|
||||
app is reinstalled to another folder, or an update moves Control, those absolute paths point at nothing and every installed
|
||||
model breaks. At every read of the installed models, a path that ends up inside a folder called `control` that no longer
|
||||
exists is pointed at the Control this app has now, when the file is there. The config is saved (with a .bak) only then. */
|
||||
function repairControlPaths(dir){if(!packaged||!dir||!existsSync(dir))return;let names=[];try{names=readdirSync(dir).filter(n=>/^strata-[a-z0-9_-]+\.json$/i.test(n));}catch{return;}
|
||||
const here=control.control.dir,inside=/^(.+?[\/]control)(?=[\/]|$)(.*)$/i;
|
||||
const fix=value=>{if(typeof value!=='string')return value;const m=value.match(inside);if(!m||existsSync(value)||resolve(m[1]).toLowerCase()===resolve(here).toLowerCase())return value;const candidate=join(here,m[2]);return existsSync(candidate)?candidate:value;};
|
||||
for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue;
|
||||
const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})};
|
||||
if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}}
|
||||
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,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,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'};})};}
|
||||
function installRoot(){const found=[preferences.installDir,packagedInstall,snapshot.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
|
||||
function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
|
||||
function python(){return resolvePython({repo:preferences.repo});}
|
||||
function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}
|
||||
function disconnect(){child?.kill();child=null;definitions=[];for(const p of pending.values()){clearTimeout(p.alarm);p.reject(new Error('Native control connection closed.'));}pending.clear();}
|
||||
async function connect(){if(closing)throw new Error("The host is shutting down.");if(child&&definitions.length)return;if(!connecting)connecting=startClient().finally(()=>{connecting=null;});return connecting;}
|
||||
async function startClient(){
|
||||
const folder=repo();
|
||||
buffer='';const py0=python();const client=child=spawnProcess(py0.command,[...py0.args,join(folder,'tools/strata_mcp.py')],{cwd:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});
|
||||
buffer='';const py0=packaged?{command:control.control.python,args:[]}:python();
|
||||
const script=packaged?join(control.control.dir,'tools/strata_mcp.py'):join(folder,'tools/strata_mcp.py');
|
||||
const client=child=spawnProcess(py0.command,[...py0.args,script,...(packaged?['--root',folder,'--src',control.control.dir]:[])],{cwd:packaged?control.control.dir:folder,windowsHide:true,stdio:['pipe','pipe','pipe'],env:packaged?installerEnvironment(control.control,{installDir:folder}):{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8'}});
|
||||
client.stdout.on('data',chunk=>{if(child!==client)return;buffer+=chunk.toString();let end;while((end=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);let message;try{message=JSON.parse(line);}catch{continue;}const p=pending.get(message.id);if(p){clearTimeout(p.alarm);pending.delete(message.id);message.error?p.reject(new Error(message.error.message)):p.resolve(message.result);}}});
|
||||
child.stderr.on('data',chunk=>append('control',chunk.toString()));
|
||||
client.on('error',error=>{if(child===client){snapshot.error=error.message;disconnect();}});
|
||||
@@ -55,33 +79,42 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
definitions=(await send('tools/list',{})).tools??[];
|
||||
}
|
||||
async function controlTool(name){
|
||||
if(name==='strata_models')return {families:[],sizes:[],note:'Model files are installed from the Terminal; the app fetches nothing while it runs.'};
|
||||
if(name==='strata_status'){
|
||||
const [list,engine]=await Promise.all([control.installedModels({installDir:preferences.installDir}),control.engine()]);
|
||||
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}));
|
||||
for(const dir of [preferences.installDir,packagedInstall,installRoot()])repairControlPaths(dir);
|
||||
let list=await control.installedModels({installDir:preferences.installDir&&existsSync(preferences.installDir)?preferences.installDir:null});
|
||||
if(!preferences.installDir&&!(list.models??[]).length){const own=installRoot();if(realpathSync(list.install_dir)!==own)list=await control.installedModels({installDir:own});}
|
||||
if(!preferences.installDir&&list.install_dir&&![preferences.installDir,packagedInstall,installRoot()].some(d=>d&&resolve(d).toLowerCase()===resolve(list.install_dir).toLowerCase())){repairControlPaths(list.install_dir);list=await control.installedModels({installDir:list.install_dir});}
|
||||
packagedInstall=list.install_dir;
|
||||
const engine=await control.engine();
|
||||
const installer=await mcpCall('strata_status',{hardware:true}).catch(error=>({error:error.message}));
|
||||
const disk=Object.fromEntries((installer.installed?.models??[]).map(m=>[m.model,{diskGb:m.disk_gb,diskBytes:m.disk_bytes}]));
|
||||
const models=(list.models??[]).filter(m=>m.component_status!=='invalid'&&m.source_config).map(m=>({...(disk[m.id]??{}),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,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};
|
||||
hardware:installer.hardware?{...installer.hardware,cpu:{...(installer.hardware.cpu??{}),cores:installer.hardware.cpu?.cores??cores},gpus:installer.hardware.gpus??[]}:{cpu:{cores},ram_gb:Math.round(os.totalmem()/1024**3),gpus:[]},
|
||||
recommendation:installer.recommendation??null,installerError:installer.error??null,install:installer.install??null,running:null};
|
||||
}
|
||||
if(name==='strata_install')throw new Error(NO_INSTALL);
|
||||
throw new Error(`Strata Control has no ${name}.`);
|
||||
}
|
||||
async function tool(name,args={}){if(packaged)return controlTool(name,args);await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}
|
||||
async function tool(name,args={}){if(packaged&&name==='strata_status')return controlTool(name,args);return mcpCall(name,args);}
|
||||
async function mcpCall(name,args={}){await connect();if(!definitions.some(d=>d.name===name))throw new Error(`This Strata installation does not support ${name}. Update the installation first.`);const result=await send('tools/call',{name,arguments:args},120000);let value=result.structuredContent;if(!value){const text=result.content?.find(c=>c.type==='text')?.text;try{value=JSON.parse(text);}catch{value={summary:text};}}if(result.isError)throw new Error(value?.error??value?.summary??'Native operation failed.');return value;}
|
||||
async function refresh(force=false){
|
||||
if(closing)return state();
|
||||
if(refreshing)return refreshing;if(!force&&Date.now()-lastRead<15000)return state();
|
||||
refreshing=(async()=>{try{const [catalog,status]=await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});return refreshing;
|
||||
/* A read that is not forced never makes the window wait for the (slow) status of Control: it gets the last state at once, and a stale one
|
||||
is refreshed in the background. Only the first read, and a forced one after an operation, waits. */
|
||||
if(refreshing)return !force&&snapshot.available?state():refreshing;if(!force&&Date.now()-lastRead<45000)return state();
|
||||
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);const noImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,images:false,sizes:(f.sizes??[]).map(s=>({...s,images:false}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:packaged?noImages(catalog):catalog,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
|
||||
}
|
||||
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
|
||||
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
|
||||
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
|
||||
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(){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};}
|
||||
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];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]])),...(packaged?{vision:'no'}:{}),confirm};}
|
||||
|
||||
function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,...(error.details?{details:error.details}:{}),finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}
|
||||
async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}
|
||||
@@ -122,13 +155,22 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
function terminate(proc,signal='SIGTERM'){if(!proc)return;if(process.platform!=='win32'&&proc.pid){try{process.kill(-proc.pid,signal);return;}catch{}}proc.kill(signal);}
|
||||
async function stopProcess(proc){if(!proc||proc.exitCode!=null)return;await new Promise(resolve=>{const timeout=setTimeout(()=>{terminate(proc,'SIGKILL');resolve();},8000);proc.once('exit',()=>{clearTimeout(timeout);resolve();});terminate(proc);});}
|
||||
async function unload(id,force=false){const instance=instances.get(id);if(!instance)throw new Error('This model is no longer loaded.');if(!force&&[...jobs.values()].some(j=>j.kind==='benchmark'&&j.state==='running'&&j.instanceId===id))throw new Error('Stop the benchmark before unloading this model.');if(!force&&busy(requests().filter(r=>r.instanceId===id)))throw new Error('Finish or cancel this model’s requests first.');instance.status='unloading';if(instance.profile){try{await control.stop(instance.profile);}catch(error){if(!force){instance.status='error';instance.error=error.message;emit();throw error;}}}else await stopProcess(processes.get(id));processes.delete(id);instances.delete(id);try{unlinkSync(instance.configPath);}catch{}if(defaultId===id)defaultId=instances.keys().next().value??null;emit();return state();}
|
||||
/* Delete a downloaded model: stop it first, then the installer removes the model's own files and its run config and keeps
|
||||
whatever another installed model still uses (shared MTP draft, shared PLE shard). */
|
||||
async function removeModel(job,args){if(!safeId(args.model))throw new Error('Choose an installed model.');
|
||||
if(externalRunning().length)throw new Error('Stop the native server running outside this UI before deleting a model.');
|
||||
for(const instance of [...instances.values()].filter(i=>i.model===args.model)){if(busy(requests().filter(r=>r.instanceId===instance.id)))throw new Error('Finish or cancel requests before deleting this model.');await unload(instance.id);}
|
||||
job.summary='Deleting downloaded files…';emit();
|
||||
const result=await tool('strata_remove',{model:args.model,confirm:true});
|
||||
if(result.failed?.length)throw new Error(`Some files could not be removed: ${result.failed.slice(0,3).join('; ')}`);
|
||||
await refresh(true);return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};}
|
||||
async function loadEngine(job,args){
|
||||
await refresh(true);if(job.state!=='running')return;const {config,entry}=record(args.model);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.');
|
||||
if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.');
|
||||
if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.');
|
||||
const vision=runtimeVision(config,args.vision);
|
||||
const visionPreferences=args.vision!==undefined?{ui_vision_enabled:args.vision!=='no',ui_vision_device:args.vision==='no'?config.ui_vision_device??'yes':args.vision}:{};
|
||||
const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile):null;
|
||||
const resources=args.resourceProfile?resourceSettings({...config,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model)):null;
|
||||
const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision};
|
||||
if(args.gpus!==undefined){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');}
|
||||
if(cfg.vram_reserve_mib!==undefined&&cfg.vram_reserve_mib!==null){cfg.args=[...(cfg.args??[])];const at=cfg.args.indexOf('--vram-reserve-mib');if(at>=0)cfg.args.splice(at,2);cfg.args.push('--vram-reserve-mib',String(cfg.vram_reserve_mib));}if(cfg.vision){if(cfg.vision_tokens!=null)cfg.vision={...cfg.vision,max_tokens:cfg.vision_tokens};if(cfg.vision_min_tokens!=null)cfg.vision={...cfg.vision,min_tokens:cfg.vision_min_tokens};}cfg.mcp={...(cfg.mcp??{}),...(cfg.mcp_timeout_s!=null?{timeout_s:cfg.mcp_timeout_s}:{}),...(cfg.mcp_max_rounds!=null?{max_rounds:cfg.mcp_max_rounds}:{}),...(cfg.mcp_max_result_chars!=null?{max_result_chars:cfg.mcp_max_result_chars}:{})};
|
||||
@@ -155,7 +197,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
instances.set(id,instance);if(!defaultId||!args.multiple||wasDefault)defaultId=id;emit();
|
||||
started=control.stop(instance.profile).catch(()=>{}).then(()=>control.saveProfile(instance.profile,configPath)).then(()=>control.start(instance.profile,{waitSeconds:300}));
|
||||
started.then(()=>append(id,'Strata Control reports the engine is ready.'),error=>{append(id,error.message);});
|
||||
try{await started;}catch(error){instance.status='error';instance.error=error.message;emit();throw error;}
|
||||
try{await started;}catch(error){const said=humanStartError(error);instance.status='error';instance.error=said;emit();throw new Error(said);}
|
||||
} else {
|
||||
proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}});
|
||||
instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id;
|
||||
@@ -171,7 +213,10 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
if(instance.profile)await control.stop(instance.profile).catch(()=>{});else await stopProcess(proc);instance.status='error';instance.error='Loading took more than five minutes. Check the engine log and free memory.';throw new Error(instance.error);
|
||||
}
|
||||
async function freePort(requested){for(let port=Number(requested??18500);port<=Number(requested??18500)+20;port++){if(!Number.isInteger(port)||port<1024||port>65535)throw new Error('Choose a port from 1024 to 65535.');if([...instances.values()].some(i=>i.port===port)){if(requested)throw new Error('This private engine port is already in use.');continue;}const available=await new Promise(resolve=>{const probe=createServer();probe.once('error',()=>resolve(false));probe.listen(port,'127.0.0.1',()=>probe.close(()=>resolve(true)));});if(available)return port;if(requested)throw new Error('This private engine port is already in use.');}throw new Error('No free private engine port was found.');}
|
||||
async function poll(){if(polling||closing)return;polling=true;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics?requests=all`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');instance.metrics=await response.json();const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}
|
||||
let pollCount=0;
|
||||
/* The engine's metrics carry every finished request with `?requests=all`: a long session makes that a large JSON that the host parses and
|
||||
pushes to the window every 2 s. The last dozen is what the app shows live; the full list is refreshed every tenth poll. */
|
||||
async function poll(){if(polling||closing)return;polling=true;const full=pollCount++%10===0;try{await Promise.all([...instances.values()].map(async instance=>{if(instance.status!=='ready')return;try{const response=await fetcher(`http://127.0.0.1:${instance.port}/metrics${full?'?requests=all':''}`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(!response.ok)throw new Error('Metrics unavailable');const fresh=await response.json();const older=instance.metrics?.requests,recent=fresh.requests;instance.metrics=full||!Array.isArray(older)||!Array.isArray(recent)||!recent.length?fresh:{...fresh,requests:[...recent,...older.filter(r=>Number(r.time)<Math.min(...recent.map(x=>Number(x.time))))]};const tools=await fetcher(`http://127.0.0.1:${instance.port}/mcp`,{headers:{authorization:`Bearer ${instance.key}`},signal:AbortSignal.timeout(1500)});if(tools.ok)instance.metrics.mcp=await tools.json();instance.phase=instance.metrics.live?.state??'idle';}catch{instance.metrics=null;instance.phase='unavailable';}}));emit();}finally{polling=false;}}
|
||||
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;}
|
||||
@@ -216,29 +261,30 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
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){
|
||||
await refresh(true);if(job.state!=='running')return;
|
||||
const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile);
|
||||
const chosen=record(args.model);resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));
|
||||
if(!chosen.entry.ready)throw new Error('Prepare the model before tuning.');
|
||||
if(externalRunning().length)throw new Error('Stop the native server outside this UI before tuning.');
|
||||
if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.');
|
||||
for(const id of [...instances.keys()])await unload(id);
|
||||
if(job.state!=='running')return;
|
||||
const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile);writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});
|
||||
const initialValues=resourceSettings(chosen.config,snapshot.hardware,args.profile,modelArena(args.model));writeModelConfig(chosen.path,{...chosen.config,...initialValues,ui_resource_profile:args.profile});
|
||||
if(args.calibrate!==false&&state().capabilities.calibration){job.summary='Measuring the best engine settings for this computer…';emit();await program(job,args);}
|
||||
if(job.state!=='running')return;
|
||||
const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile);
|
||||
const current=record(args.model),values=resourceSettings(current.config,snapshot.hardware,args.profile,modelArena(args.model));
|
||||
const next={...current.config,...values,ui_resource_profile:args.profile};
|
||||
writeModelConfig(current.path,next);
|
||||
job.summary='Applying your resource preference and loading the model…';emit();
|
||||
const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:args.vision});
|
||||
const loaded=await loadEngine(job,{model:args.model,multiple:false,vision:current.config.vision?args.vision:'no'});
|
||||
if(job.state!=='running'||!loaded?.instanceId)return;
|
||||
job.summary='Checking your model’s speed…';emit();
|
||||
const measured=await benchmark(job,{instanceId:loaded.instanceId});
|
||||
return {...loaded,...measured,summary:'Your model is tuned and ready.',profile:args.profile};
|
||||
}
|
||||
function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):program(job,args),{guided:args.guided===true,model:args.model});}
|
||||
function operation(kind,args={}){if(!['install','load','benchmark','tune','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');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==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model});}
|
||||
async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();}
|
||||
async function close(){closing=true;clearInterval(timer);const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();}
|
||||
async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();}
|
||||
// Remove nonserializable process references from public jobs.
|
||||
const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;};
|
||||
return {state:publicState,refresh,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};
|
||||
async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());}
|
||||
return {state:publicState,refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Headroom is a worker/memory budget, not a hard utilisation throttle. */
|
||||
export function resourceSettings(config,hardware,profile){
|
||||
export function resourceSettings(config,hardware,profile,model={}){
|
||||
if(!['work','performance'].includes(profile))throw new Error('Choose a resource preference.');
|
||||
const args=[...(config.args??[])];
|
||||
const remove=flag=>{for(let at=args.indexOf(flag);at>=0;at=args.indexOf(flag))args.splice(at,2);};
|
||||
@@ -15,10 +15,21 @@ export function resourceSettings(config,hardware,profile){
|
||||
args.push('--pool-workers',String(previous>0?Math.min(previous,workers):workers));
|
||||
}
|
||||
// Preserve calibrated worker counts and the installation's safety/vision reserve.
|
||||
const safety=Math.max(config.vision?2048:700,baseline.reserve);
|
||||
const placement=Array.isArray(config.gpu)?config.gpu:[config.gpu??0];
|
||||
const gpuMemory=(hardware?.gpus??[]).filter(g=>placement.includes(g.index)).map(g=>g.vram_gb).filter(n=>Number.isFinite(n)&&n>0);
|
||||
/* The engine warns below ~1-1.5 GiB of free VRAM (the driver then pages GPU memory to system RAM and decoding falls to a few tokens a
|
||||
second, #2065), so neither profile may reserve less: 1536 MiB on a card of 16 GB or less, 1024 above; with pictures 2048. */
|
||||
const floor=gpuMemory.length&&Math.min(...gpuMemory)>16?1024:1536;
|
||||
const safety=Math.max(config.vision?2048:floor,baseline.reserve);
|
||||
const reserve=profile==='work'&&gpuMemory.length?Math.max(safety,Math.floor(Math.min(...gpuMemory)*1024*.2)):safety;
|
||||
remove('--vram-reserve-mib');args.push('--vram-reserve-mib',String(reserve));
|
||||
return {args,vram_reserve_mib:reserve,ui_resource_baseline:baseline};
|
||||
// RAM: "leave 20% for my work" keeps the model's RAM within 80% of the PC. A model whose experts do not fit there (the
|
||||
// setup rule: experts plus 10 GB) keeps only that many GiB of them in RAM and reads the rest from the model files
|
||||
// (--resident-budget-gib, which implies --mmap-experts). Full performance takes the budget out again.
|
||||
if(baseline.ramBudget)remove('--resident-budget-gib');
|
||||
const ram=Number(hardware?.ram_gb)||0,arena=Number(model?.arenaGb)||0;let ramBudget=false;
|
||||
if(profile==='work'&&ram>0&&arena>0&&!['--resident-experts','--mmap-experts','--resident-budget-gib'].some(f=>args.includes(f))&&ram*.8<arena+10){
|
||||
args.push('--resident-budget-gib',String(Math.max(8,Math.min(Math.floor(ram*.8)-10,Math.floor(arena/1.073741824)))));ramBudget=true;
|
||||
}
|
||||
return {args,vram_reserve_mib:reserve,ui_resource_baseline:{...baseline,ramBudget}};
|
||||
}
|
||||
@@ -20,6 +20,8 @@ const modes: {
|
||||
{ value: 'bypass', label: 'Bypass permissions', hint: 'Skip permission prompts' },
|
||||
];
|
||||
const efforts = ['Off', 'Low', 'Medium', 'High', 'Max'];
|
||||
/** The most tokens a reply may spend thinking (the server's reasoning_budget_tokens); 0 = no limit. */
|
||||
const THINKING_BUDGETS: [number, string][] = [[0, 'No limit'], [2048, '2K'], [8192, '8K'], [32768, '32K']];
|
||||
const textTypes = /\.(txt|md|markdown|csv|tsx?|jsx?|py|json|css|rs|go|sh|html?|ya?ml|toml|xml|log)$/i;
|
||||
const photoTypes = /\.(png|jpe?g|webp|gif|svg)$/i;
|
||||
export function ComposerControls({ session, onPreview, onAttach, onError, onSlash, streaming, draft, onDraft }: {
|
||||
@@ -48,6 +50,7 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas
|
||||
attachLatest.current = onAttach;
|
||||
const mode = modes.find(m => m.value === session?.preferences?.mode) ?? modes[0];
|
||||
const effort = efforts.includes(session?.preferences?.thinking ?? '') ? session!.preferences!.thinking! : 'High';
|
||||
const budget = session?.preferences?.thinkingBudget ?? 0;
|
||||
const shortcut = MOD === '⌘' ? '⌘⇧A' : 'Ctrl+Shift+A';
|
||||
async function openFile(selected: File | undefined) {
|
||||
if (!selected)
|
||||
@@ -160,7 +163,7 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas
|
||||
<button role="menuitem" className="menu__item" onClick={() => { setMenu(false); onSlash(); }}><span className="slash-command-icon" aria-hidden="true">/</span>{tr("Slash commands")}</button>
|
||||
</FloatingMenu> : null)}
|
||||
{tr(preferences ? <FloatingMenu anchor={preferences === 'mode' ? modeTrigger.current : thinkingTrigger.current} title={tr(preferences === 'mode' ? 'Mode' : 'Reasoning effort')} width={preferences === 'mode' ? 330 : 280} onClose={() => setPreferences(null)}>
|
||||
{tr(preferences === 'mode' ? <>{tr(modes.map((option, index) => <button key={option.value} role="menuitemradio" aria-checked={mode.value === option.value} className="menu__item composer-mode-option" onClick={() => { setChatPreferences(session?.id, { mode: option.value }); setPreferences(null); }}><span><strong>{tr(option.label)}</strong><small>{tr(option.hint)}</small></span>{tr(mode.value === option.value ? <Icon name="check" size={16}/> : null)}<kbd className="menu-shortcut">{tr(index + 1)}</kbd></button>))}</> : <><div className="reasoning-menu-model"><Icon name={apiModel ? 'link' : modelFamilyIcon(loaded?.family)} size={18}/><strong>{tr(apiModel?.name ?? loaded?.family ?? 'No model loaded')}</strong></div><p className="composer-menu-heading">{tr("Reasoning effort")}</p>{tr(efforts.map(option => <button key={option} role="menuitemradio" aria-checked={effort === option} className="menu__item" onClick={() => { setChatPreferences(session?.id, { thinking: option }); setPreferences(null); }}>{tr(option)}<span className="spacer"/>{tr(effort === option ? <Icon name="check" size={16}/> : null)}</button>))}</>)}
|
||||
{tr(preferences === 'mode' ? <>{tr(modes.map((option, index) => <button key={option.value} role="menuitemradio" aria-checked={mode.value === option.value} className="menu__item composer-mode-option" onClick={() => { setChatPreferences(session?.id, { mode: option.value }); setPreferences(null); }}><span><strong>{tr(option.label)}</strong><small>{tr(option.hint)}</small></span>{tr(mode.value === option.value ? <Icon name="check" size={16}/> : null)}<kbd className="menu-shortcut">{tr(index + 1)}</kbd></button>))}</> : <><div className="reasoning-menu-model"><Icon name={apiModel ? 'link' : modelFamilyIcon(loaded?.family)} size={18}/><strong>{tr(apiModel?.name ?? loaded?.family ?? 'No model loaded')}</strong></div><p className="composer-menu-heading">{tr("Reasoning effort")}</p>{tr(efforts.map(option => <button key={option} role="menuitemradio" aria-checked={effort === option} className="menu__item" onClick={() => { setChatPreferences(session?.id, { thinking: option }); setPreferences(null); }}>{tr(option)}<span className="spacer"/>{tr(effort === option ? <Icon name="check" size={16}/> : null)}</button>))}<p className="composer-menu-heading">{tr("Thinking budget")}</p>{tr(THINKING_BUDGETS.map(([value, label]) => <button key={value} role="menuitemradio" aria-checked={budget === value} disabled={effort === 'Off'} className="menu__item" onClick={() => { setChatPreferences(session?.id, { thinkingBudget: value }); setPreferences(null); }}>{tr(label)}<span className="spacer"/>{tr(budget === value ? <Icon name="check" size={16}/> : null)}</button>))}</>)}
|
||||
</FloatingMenu> : null)}
|
||||
|
||||
<Dialog open={urlOpen} title={tr("Open a website")} onClose={() => setUrlOpen(false)} actions={<><Btn onClick={() => setUrlOpen(false)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!url.trim()} onClick={() => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { nativeAction, useNative, type NativeJob } from '../lib/native';
|
||||
import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store';
|
||||
import type { LocalModelFolder, SetupState } from '../lib/types';
|
||||
import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download';
|
||||
import { installProgress, useDownloadEta } from '../lib/download-eta';
|
||||
import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog';
|
||||
type Choices = NonNullable<NonNullable<SetupState['choices']>['onboarding']>;
|
||||
function radioKeys(event: KeyboardEvent<HTMLDivElement>) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key))
|
||||
@@ -22,10 +23,10 @@ export function GuidedSetup() {
|
||||
const families = nativeCatalogModels(native?.catalog?.families ?? []);
|
||||
const saved = !setup?.complete && !setup?.choices?.onboarding?.manual ? setup?.choices?.onboarding : undefined;
|
||||
const [step, setStep] = useState(saved?.manual || setup?.complete ? 1 : saved?.step ?? 1);
|
||||
const [family, setFamily] = useState(saved?.family ?? native?.catalog?.recommendation.family ?? native?.catalog?.families[0]?.family ?? '');
|
||||
const [family, setFamily] = useState(saved?.family ?? native?.catalog?.recommendation?.family ?? native?.catalog?.families?.[0]?.family ?? '');
|
||||
const initialFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family));
|
||||
const [size, setSize] = useState(saved?.size ?? initialFamily?.sizes.find(s => s.model === native?.catalog?.recommendation.model)?.id ?? initialFamily?.sizes[0]?.id ?? '');
|
||||
const [context, setContext] = useState(saved?.context ?? native?.catalog?.recommendation.context ?? 32768);
|
||||
const [size, setSize] = useState(saved?.size ?? initialFamily?.sizes.find(s => s.model === native?.catalog?.recommendation?.model)?.id ?? initialFamily?.sizes[0]?.id ?? '');
|
||||
const [context, setContext] = useState(saved?.context ?? native?.catalog?.recommendation?.context ?? 32768);
|
||||
const [vision, setVision] = useState(saved?.vision ?? false), [directory, setDirectory] = useState(saved?.directory ?? '');
|
||||
const [profile, setProfile] = useState<'work' | 'performance'>(saved?.profile ?? 'work');
|
||||
const [installJobId, setInstallJobId] = useState(saved?.installJobId ?? ''), [tuneJobId, setTuneJobId] = useState(saved?.tuneJobId ?? '');
|
||||
@@ -66,7 +67,7 @@ export function GuidedSetup() {
|
||||
navigate('chat', undefined, { settings: '1' });
|
||||
}
|
||||
else
|
||||
go(manual ? 'models' : 'chat');
|
||||
go(manual || preparing ? 'models' : 'chat');
|
||||
}
|
||||
catch (e) {
|
||||
leaving.current = false;
|
||||
@@ -141,7 +142,7 @@ export function GuidedSetup() {
|
||||
await persist(4, { tuneJobId: result.id });
|
||||
});
|
||||
}
|
||||
const progress = installJob?.result?.install?.download;
|
||||
const progress = installProgress(installJob?.result?.install);
|
||||
const preparing = installJob?.state === 'running';
|
||||
const stopped = installJob && ['error', 'cancelled'].includes(installJob.state);
|
||||
useEffect(() => {
|
||||
@@ -161,6 +162,7 @@ export function GuidedSetup() {
|
||||
return () => { cancelled = true; };
|
||||
}, [step, plan, preparing, native?.available, version?.id, context, directory]);
|
||||
const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing);
|
||||
const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id);
|
||||
const title = step === 1 ? 'State of the art. At home.' : step === 2 ? 'Select the model you want to run.' : step === 3 ? 'Downloading the model...' : tuneJob?.state === 'running' ? 'A little tuning. A better fit.' : 'How you would like to work with Strata?';
|
||||
function changeDownloadFolder() { void perform(async () => { await advance(2); setFolderOpen(true); }); }
|
||||
return <div className="setup guided-onboarding" data-step={step}>
|
||||
@@ -183,7 +185,7 @@ export function GuidedSetup() {
|
||||
</> : <div className="onboard-engine-connect"><Icon name="models" size={24}/><strong>{tr("Connect your Strata installation")}</strong><Btn onClick={() => void skip(false, 'Engine')}>{tr("Connect engine")}</Btn></div>)}
|
||||
</div> : step === 3 ? <div className="onboard-prepare-stage">
|
||||
<section className="onboard-download"><div className="onboard-download-identity"><Icon name="models" size={19}/><strong>{tr(selectedFamily?.title)}</strong><span>{tr(version ? catalogVersionLabel(version) : '')}</span><small>{tr(version?.model)}</small></div><OnboardingArt kind="download" progress={progress?.percent ?? 0} counter={counter}/><div className="onboard-download-info">
|
||||
{tr(preparing ? <div><strong className="onboard-download-status">{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}</strong><div className="onboard-progress" data-indeterminate={!progress}>{tr(progress ? <progress max={100} value={progress.percent ?? 0} aria-label={tr("Current file download progress")}/> : <span />)}</div><div className="onboard-progress-meta"><span>{tr(progress ? `${progress.percent ?? 0}% of this file` : 'Getting files ready…')}</span><button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${installJob!.id}/cancel`); })}>{tr("Stop")}</button></div></div> : <>{tr(stopped ? <OnboardingError message={installJob?.error ?? 'Download stopped. Ready when you are.'} onFolder={changeDownloadFolder}/> : null)}{tr(plan?.plan?.disk_short ? <OnboardingError message={plan.plan.disk_short} onFolder={changeDownloadFolder}/> : null)}</>)}
|
||||
{tr(preparing ? <div><strong className="onboard-download-status">{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}</strong><div className="onboard-progress" data-indeterminate={!progress}>{tr(progress ? <progress max={100} value={progress.percent ?? 0} aria-label={tr("Current file download progress")}/> : <span />)}</div><div className="onboard-progress-meta"><span>{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}</span><div className="onboard-progress-actions">{tr(eta ? <span aria-live="off">{eta}</span> : null)}<button disabled={pending} onClick={() => void perform(async () => { await nativeAction(`operations/${installJob!.id}/cancel`); })}>{tr("Stop")}</button></div></div></div> : <>{tr(stopped ? <OnboardingError message={installJob?.error ?? 'Download stopped. Ready when you are.'} onFolder={changeDownloadFolder}/> : null)}{tr(plan?.plan?.disk_short ? <OnboardingError message={plan.plan.disk_short} onFolder={changeDownloadFolder}/> : null)}</>)}
|
||||
<small className="onboard-download-location" title={tr(folder)}><Icon name="folder" size={16}/><span><span>{tr("Save to")}</span><strong>{tr(modelFolderLabel(folder))}</strong></span>{tr(!preparing ? <button type="button" onClick={changeDownloadFolder}>{tr("Change")}</button> : null)}</small>
|
||||
</div></section><OnboardingTour page={tour} onChange={setTour}/>
|
||||
</div> : <div className="onboard-tune-stage">
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { tr } from '../lib/i18n';
|
||||
import { useState } from 'react';
|
||||
import { Btn, Dialog, ErrorNotice } from './ui';
|
||||
import { nativeAction, nativeState, refreshNative, useNative, type NativeJob } from '../lib/native';
|
||||
import { catalogVersionLabel, nativeCatalogModels } from '../lib/native-catalog';
|
||||
import { sizeGb } from '../lib/format';
|
||||
|
||||
/** Delete a downloaded (native) model: its own files and run config. What another installed model still uses stays. A loaded model
|
||||
* is unloaded first by the host. Same dialog and words as deleting a version of the managed library. */
|
||||
export function NativeDeleteDialog({ id, onClose }: { id: string | null; onClose: () => void }) {
|
||||
const native = useNative();
|
||||
const [pending, setPending] = useState(false), [error, setError] = useState('');
|
||||
const entry = native?.installed?.models.find(m => m.model === id);
|
||||
const label = (() => { const sizes = nativeCatalogModels(native?.catalog?.families ?? []).flatMap(f => f.sizes); const v = sizes.find(s => s.id === id); return v ? `${catalogVersionLabel(v)} · ${v.model}` : entry?.model_name ?? id ?? ''; })();
|
||||
const running = !!native?.instances.some(i => i.model === id);
|
||||
const busy = !!native?.jobs.some(j => j.state === 'running');
|
||||
const gb = entry?.diskGb ?? 0;
|
||||
function close() { if (!pending) { onClose(); setError(''); } }
|
||||
async function remove() {
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const job = await nativeAction<NativeJob>('operations', { kind: 'remove', args: { model: id } });
|
||||
for (let i = 0; i < 600; i++) {
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
await refreshNative(true).catch(() => undefined);
|
||||
const current = nativeState()?.jobs.find(j => j.id === job.id);
|
||||
if (current && current.state !== 'running') {
|
||||
if (current.state === 'error') throw new Error(current.error ?? 'Could not delete this version.');
|
||||
break;
|
||||
}
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
||||
finally { setPending(false); }
|
||||
}
|
||||
return <Dialog open={!!id} compact title={tr("Delete this version?")} onClose={close} actions={<><Btn disabled={pending} onClick={close}>{tr("Keep version")}</Btn><Btn variant="danger" disabled={pending || busy || !entry} onClick={() => void remove()}>{tr(pending ? 'Working…' : 'Delete version')}</Btn></>}>
|
||||
<p>{tr(label)}{tr(gb ? ` · ${sizeGb(gb)}` : '')}</p>
|
||||
{tr(entry ? <p className="small muted storage-delete-note">{tr('Remove {0} GB of downloaded files. You can download this version again.', [gb ? gb.toFixed(1) : '0'])}{tr(running ? ' ' : '')}{tr(running ? 'The running model will be unloaded and its files deleted.' : '')}</p> : <p className="small muted">{tr("This version is no longer downloaded.")}</p>)}
|
||||
{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
</Dialog>;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { tr } from '../lib/i18n';
|
||||
import { useState } from 'react';
|
||||
import { Screen } from './layout';
|
||||
import { Btn, ErrorNotice, Icon } from './ui';
|
||||
import { api } from '../lib/client';
|
||||
import { nativeAction, useNative, type NativeJob } from '../lib/native';
|
||||
import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog';
|
||||
import { sizeGb } from '../lib/format';
|
||||
import { NativeProgress } from './NativeModels';
|
||||
|
||||
interface Preview { path: string; preview: { file_count: number; total_bytes: number; file_set_status: string; issues: string[]; candidate_selection: { family: string; model: string } | null } }
|
||||
|
||||
/** The words for why a folder of GGUF files cannot be used: a sentence and what to do, the checker's own codes under Details. */
|
||||
function problem(issues: string[]): { message: string; next: string } {
|
||||
const has = (re: RegExp) => issues.some(i => re.test(i));
|
||||
if (has(/incomplete_or_invalid_shard_set|multiple_model_groups/))
|
||||
return { message: 'Some parts of this model are missing, or the folder holds more than one model.', next: 'Put every part of one model in one folder, then check again.' };
|
||||
if (has(/unrecognized_or_unsupported_model_variant|unsupported_architecture|unsupported_or_missing_architecture|expert_quantization|tokenizer/))
|
||||
return { message: 'Strata can’t run these files yet.', next: 'Strata runs the Qwen3.8-Flash-Next models. Download one from Models, or choose a folder with its files.' };
|
||||
return { message: 'These files could not be checked.', next: 'Check that the folder holds complete GGUF files, then try again.' };
|
||||
}
|
||||
|
||||
/** "Use a local GGUF": choose the folder of a model you already have, Strata checks it, and prepares and loads it without copying
|
||||
* or downloading the model files. The same page layout and cards as the optimized models page. */
|
||||
export function NativeLocalModel({ onBack }: { onBack: () => void }) {
|
||||
const native = useNative();
|
||||
const [typed, setTyped] = useState(''), [checked, setChecked] = useState<Preview | null>(null), [pending, setPending] = useState(false), [error, setError] = useState(''), [jobId, setJobId] = useState('');
|
||||
const job = native?.jobs.find(j => j.id === jobId);
|
||||
const active = native?.jobs.find(j => j.state === 'running');
|
||||
const selection = checked?.preview.candidate_selection;
|
||||
const usable = !!checked && checked.preview.file_set_status === 'plausible' && !!selection;
|
||||
const version = selection ? nativeCatalogModels(native?.catalog?.families ?? []).flatMap(f => f.sizes).find(s => s.sourceFamily === selection.family && s.model === selection.model) : undefined;
|
||||
const family = selection ? nativeCatalogModels(native?.catalog?.families ?? []).find(f => f.sizes.some(s => s.sourceFamily === selection.family && s.model === selection.model)) : undefined;
|
||||
async function check(path: string) {
|
||||
setPending(true);
|
||||
setError('');
|
||||
setChecked(null);
|
||||
try {
|
||||
const result = await api.post<Preview & { cancelled?: boolean }>('/api/native/local/preview', { path });
|
||||
if (!result.cancelled) {
|
||||
setChecked(result);
|
||||
setTyped(result.path);
|
||||
}
|
||||
}
|
||||
catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
||||
finally { setPending(false); }
|
||||
}
|
||||
async function prepare() {
|
||||
if (!usable || !selection || !checked)
|
||||
return;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: checked.path, context: native?.catalog?.recommendation?.context ?? 32768, vision: 'no', kv: 'int8', loadAfter: true } });
|
||||
setJobId(result.id);
|
||||
}
|
||||
catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
||||
finally { setPending(false); }
|
||||
}
|
||||
const found = checked ? problem(checked.preview.issues) : null;
|
||||
return <Screen plainHeader title={tr("Model")} actions={<Btn onClick={onBack}>{tr("Strata optimized models")}</Btn>}>
|
||||
<div className="native-model-layout">
|
||||
<div className="stack stack--lg">
|
||||
<section className="st-card native-choice"><h2 className="h3">{tr("Use a local GGUF…")}</h2>
|
||||
<p className="small muted">{tr("Already have a supported model on this computer? Choose the folder that holds its files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.")}</p>
|
||||
<label className="input-field"><span>{tr("Folder with the GGUF files")}</span><input className="st-input" value={typed} placeholder={tr("Full path to the folder")} spellCheck={false} onChange={e => setTyped(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && typed.trim()) void check(typed); }}/></label>
|
||||
<div className="native-settings-actions"><Btn icon="folder" disabled={pending || !!active} onClick={() => void check('')}>{tr("Choose folder")}</Btn><Btn disabled={pending || !typed.trim() || !!active} onClick={() => void check(typed)}>{tr(pending && !jobId ? 'Checking…' : 'Check files')}</Btn></div>
|
||||
</section>
|
||||
{tr(checked ? <section className="st-card native-choice">{tr(usable ? <>
|
||||
<h2 className="h3">{tr(family ? family.title : 'Model found')}</h2>
|
||||
<p><strong>{tr(version ? catalogVersionLabel(version) : selection?.model ?? '')}</strong> · {tr(selection?.model ?? '')}</p>
|
||||
<p className="small muted">{tr("{0} files · {1}", [checked.preview.file_count, sizeGb(checked.preview.total_bytes / 1024 ** 3)])}</p>
|
||||
<div className="native-model-actions"><Btn variant="primary" icon="models" disabled={pending || !!active} onClick={() => void prepare()}>{tr(pending ? 'Checking…' : 'Prepare and load')}</Btn></div>
|
||||
</> : <>
|
||||
<h2 className="h3">{tr(found!.message)}</h2>
|
||||
<p className="small muted">{tr(found!.next)}</p>
|
||||
{tr(checked.preview.issues.length ? <details><summary className="small">{tr("Details")}</summary><pre className="small muted error-detail-text">{checked.preview.issues.join(String.fromCharCode(10))}</pre></details> : null)}
|
||||
</>)}</section> : null)}
|
||||
{tr(active ? <NativeProgress job={active}/> : job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} detail={job.details}/> : job?.state === 'done' ? <p className="small" role="status"><Icon name="check" size={15}/> {tr(job.summary)}</p> : null)}
|
||||
{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
</div>
|
||||
<aside className="stack stack--lg"><section className="st-card"><h2 className="h4">{tr("This computer")}</h2><p>{tr(native?.hardware?.ram_gb || '—')}{tr(" GB RAM")}</p>{tr(native?.hardware?.gpus.length ? native.hardware.gpus.map(g => <p className="small" key={g.index}>{tr(g.name)} · {tr(g.vram_gb)}{tr(" GB")}</p>) : null)}</section></aside>
|
||||
</div>
|
||||
</Screen>;
|
||||
}
|
||||
@@ -2,6 +2,10 @@ import { tr } from '../lib/i18n';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Screen } from './layout';
|
||||
import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui';
|
||||
import { installProgress, useDownloadEta } from '../lib/download-eta';
|
||||
import { sizeGb } from '../lib/format';
|
||||
import { NativeDeleteDialog } from './NativeDelete';
|
||||
import { plainFailureText } from '../lib/plain-errors';
|
||||
import { api } from '../lib/client';
|
||||
import { go, setSettingsSection, selectRemoteModel, pushToast } from '../lib/store';
|
||||
import { nativeAction, useNative, type NativeJob } from '../lib/native';
|
||||
@@ -9,7 +13,6 @@ import { NativeSettings } from './NativeSettings';
|
||||
import { RunImageModel } from './RunImageModel';
|
||||
import { useStore } from '../lib/store';
|
||||
import { NativePresets } from './NativePresets';
|
||||
import { NativeBenchmark } from './NativeOperations';
|
||||
import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog';
|
||||
export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: {
|
||||
onOtherModels: () => void;
|
||||
@@ -22,24 +25,36 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
|
||||
const manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false);
|
||||
const [expert, setExpert] = useState(manual), [multiple, setMultiple] = useState(false), [gpus, setGpus] = useState<number[]>([]), [kv, setKv] = useState('int8'), [lowRam, setLowRam] = useState('auto'), [split, setSplit] = useState('auto'), [deviceChoice, setDeviceChoice] = useState('auto');
|
||||
const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work');
|
||||
const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false);
|
||||
const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState<Record<string, any> | null>(null), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false);
|
||||
const presetPending = useRef(false);
|
||||
const [deleting, setDeleting] = useState<string | null>(null);
|
||||
const families = nativeCatalogModels(native?.catalog?.families ?? []);
|
||||
const expertSection = useRef<HTMLElement>(null);
|
||||
useEffect(() => { if (expert)
|
||||
expertSection.current?.scrollIntoView({ block: 'start', behavior: 'smooth' }); }, [expert]);
|
||||
const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0];
|
||||
const installed = native?.installed?.models.find(m => m.model === selectedSize?.id);
|
||||
// The model that is running is shown as running, with Unload: not offered for loading again.
|
||||
const downloaded = native?.installed?.models ?? [], allSizes = families.flatMap(f => f.sizes);
|
||||
const loadedSelected = native?.instances.find(i => i.model === selectedSize?.id && i.status === 'ready');
|
||||
// A model that is already on this PC loads as it was prepared: the page shows its settings, so loading it never asks to download.
|
||||
useEffect(() => { if (installed?.ready) {
|
||||
if (installed.context)
|
||||
setContext(installed.context);
|
||||
if (installed.kv)
|
||||
setKv(installed.kv as typeof kv);
|
||||
setLowRam((installed.lowRamMode ?? 'auto') as typeof lowRam);
|
||||
} }, [installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.lowRamMode]);
|
||||
const active = native?.jobs.find(j => j.state === 'running');
|
||||
const job = native?.jobs.find(j => j.id === jobId) ?? (!jobId ? native?.jobs.filter(j => ['load', 'install'].includes(j.kind)).at(-1) : undefined);
|
||||
const noFit = selectedSize?.on_this_pc === 'does not fit';
|
||||
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(expert && gpus.length ? { gpus: gpus.join(',') } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), expert, multiple]);
|
||||
const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' };
|
||||
useEffect(() => { if (!native?.catalog || family)
|
||||
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const f = loadedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
|
||||
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const f = loadedFamily ?? installedFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
|
||||
setFamily(f.family);
|
||||
setSize(f.sizes.find(s => s.id === current?.model || s.model === rec.model)?.id ?? f.sizes[0]?.id ?? '');
|
||||
setContext(rec.context ?? 32768);
|
||||
setSize(f.sizes.find(s => s.id === current?.model)?.id ?? f.sizes.find(s => have.has(s.id))?.id ?? f.sizes.find(s => s.model === rec.model)?.id ?? f.sizes[0]?.id ?? '');
|
||||
setContext(('context' in rec ? rec.context : undefined) ?? 32768);
|
||||
} }, [native?.catalog]);
|
||||
useEffect(() => { if (presetPending.current) {
|
||||
presetPending.current = false;
|
||||
@@ -77,11 +92,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
|
||||
return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/><Btn icon="models" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></div> : null)}
|
||||
<div className="native-model-layout">
|
||||
<div className="stack stack--lg">
|
||||
{tr(native?.instances.length && expert ? <section className="st-card native-running"><h2 className="h4">{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}</h2>{tr(native.instances.map(i => <div key={i.id}><span><strong>{tr(i.label)}</strong><small>{tr(i.gpus.length ? i.gpus.map(g => `GPU ${g + 1}`).join(' + ') : 'Automatic GPU')} · {tr(i.status === 'ready' ? i.phase : i.status)}{tr(native.defaultId === i.id ? ' · Chat default' : '')}</small>{tr(i.error ? <small className="inline-error">{tr(i.error)}</small> : null)}</span>{tr(expert && multiple && native.defaultId !== i.id ? <Btn size="sm" variant="ghost" onClick={() => void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")}</Btn> : null)}<Btn size="sm" disabled={pending || !!active} onClick={() => void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}</Btn></div>))}</section> : null)}
|
||||
{tr(native?.instances.length && expert ? <section className="st-card native-running"><h2 className="h4">{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}</h2>{tr(native.instances.map(i => <div key={i.id}><span><strong>{tr(i.label)}</strong><small>{tr(i.gpus.length ? i.gpus.map(g => `GPU ${g + 1}`).join(' + ') : 'Automatic GPU')} · {tr(i.status === 'ready' ? i.phase : i.status)}{tr(native.defaultId === i.id ? ' · Chat default' : '')}</small>{tr(i.error ? <small className="inline-error">{tr(plainFailureText(i.error).message)}</small> : null)}</span>{tr(expert && multiple && native.defaultId !== i.id ? <Btn size="sm" variant="ghost" onClick={() => void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")}</Btn> : null)}<Btn size="sm" disabled={pending || !!active} onClick={() => void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}</Btn></div>))}</section> : null)}
|
||||
<section className="st-card native-choice">{tr(selectedFamily && !selectedSize ? <><h2 className="h3">{tr("This model needs a newer engine.")}</h2><p className="small muted">{tr("Update your engine or import a local GGUF for this model.")}</p><Btn onClick={() => { setSettingsSection('Engine'); go('settings'); }}>{tr("Update engine")}</Btn><Btn variant="ghost" onClick={onImport ?? onOtherModels}>{tr("Use a local GGUF\u2026")}</Btn></> : null)}{tr(!selectedFamily ? <><h2 className="h3">{tr("Set up Strata")}</h2><p className="small muted">{tr("Connect your local installation to choose an optimized model.")}</p><Btn variant="primary" onClick={onConnectEngine ?? (() => { setSettingsSection('Engine'); go('settings'); })}>{tr("Connect engine")}</Btn>{tr(native?.error ? <p className="small inline-error">{tr(native.error)}</p> : null)}<Btn variant="ghost" onClick={onOtherModels}>{tr("Other local models")}</Btn></> : null)}
|
||||
{tr(selectedSize ? <><label className="input-field"><span>{tr("Version")}</span><Select ariaLabel={tr("Model version")} value={selectedSize.id} options={[...selectedFamily!.sizes.map(s => ({ value: s.id, label: `${catalogVersionLabel(s)} · ${s.model} · ${s.download_gb.toFixed(1)} GB${s.installed ? ` · ${tr('Downloaded')}` : ''}` })), { value: 'local-import', label: 'Use a local GGUF…' }]} onChange={id => id === 'local-import' ? (onImport ?? onOtherModels)() : setSize(id)}/></label><p className="small muted">{tr(selectedSize.about)}</p><div className="native-choice-facts"><span><Icon name="memory" size={16}/>{tr(selectedSize.ram_needed_gb)}{tr(" GB RAM class")}</span></div>
|
||||
{tr(noFit ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("May run slower \u00B7 Model data can be read from SSD.")}</p> : null)}
|
||||
<div className="native-image-reading"><label><input type="checkbox" checked={vision !== 'no'} disabled={!selectedSize?.images || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}<small>{tr("Optional")}</small></strong><small>{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}</small></span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div>
|
||||
{tr(selectedSize?.images ? <div className="native-image-reading"><label><input type="checkbox" checked={vision !== 'no'} disabled={!selectedSize?.images || !!active} onChange={e => setVision(e.target.checked ? 'yes' : 'no')}/><span><strong>{tr("Read pictures ")}<small>{tr("Optional")}</small></strong><small>{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}</small></span></label>{tr(expert && vision !== 'no' ? <Select ariaLabel={tr("Image encoder device")} value={vision === 'yes' ? 'yes' : vision} options={[{ value: 'yes', label: 'Automatic' }, { value: 'gpu', label: 'GPU' }, { value: 'cpu', label: 'CPU' }]} onChange={setVision}/> : null)}</div> : null)}
|
||||
</> : null)}
|
||||
</section>
|
||||
{tr(selectedFamily ? <section className="st-card"><div className="section-toolbar"><h2 className="h4">{tr("Conversation context")}</h2><span className="small muted">{tr(context / 1024)}{tr("K tokens")}</span></div><p className="small muted">{tr("How much your model can keep in mind.")}</p><Select ariaLabel={tr("Conversation context")} value={String(context)} options={(native?.catalog?.contexts ?? [8192, 32768, 65536, 131072, 262144]).map(n => ({ value: String(n), label: `${n / 1024}K` }))} onChange={n => setContext(Number(n))}/></section> : null)}
|
||||
@@ -91,18 +106,32 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
|
||||
{tr(active ? <NativeProgress job={active}/> : null)}
|
||||
{tr(job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} action={tr("Retry")} onRetry={() => void load()}/> : null)}
|
||||
{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
<div className="native-model-actions">{tr(onReady && native?.instances.some(i => i.status === 'ready') ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <><Btn icon="gauge" disabled={!native?.instances.some(i => i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")}</Btn><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || expert && deviceChoice === 'split' && gpus.length < 2} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div>
|
||||
<div className="native-model-actions">{tr(loadedSelected ? <><Btn disabled={pending || !!active} onClick={() => void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}</Btn>{tr(onReady ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <span className="native-ready">{tr("Ready")}</span>)}</> : onReady && native?.instances.some(i => i.status === 'ready') ? <Btn variant="primary" onClick={onReady}>{tr("Start chatting")}</Btn> : <><Btn variant="primary" icon="models" disabled={pending || !native?.available || !!active || !selectedSize || expert && deviceChoice === 'split' && gpus.length < 2} onClick={() => void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')}</Btn></>)}</div>
|
||||
</div>
|
||||
<aside className="stack stack--lg"><section className="st-card"><h2 className="h4">{tr("This computer")}</h2><p>{tr(native?.hardware?.ram_gb || hardware?.memory.totalGb || '—')}{tr(" GB RAM")}</p>{tr(native?.hardware?.gpus.length ? native.hardware.gpus.map(g => <p className="small" key={g.index}>{tr(g.name)} · {tr(g.vram_gb)}{tr(" GB")}</p>) : <p className="small muted">{tr("No supported GPU reported by this installation.")}</p>)}<p className="small muted">{tr("Compatibility and sizes come from your installed Strata version.")}</p></section><section className="st-card"><h2 className="h4">{tr("Model files")}</h2><p className="small muted">{tr("Strata prepares all shards, the draft layer and shared files. Completed downloads are reused.")}</p><code className="native-path">{installed?.dataFolder ?? native?.downloadDirectory ?? native?.installed?.data_folder ?? 'Choose an installation'}</code><Btn size="sm" variant="ghost" onClick={() => { setSettingsSection('Storage'); go('settings'); }}>{tr("Storage settings")}</Btn></section><Btn size="sm" variant="ghost" onClick={onOtherModels}>{tr("Other local models\u2026")}</Btn></aside>
|
||||
</div>
|
||||
<Dialog open={!!plan} title={tr("Download and prepare")} compact onClose={() => !pending && setPlan(null)} actions={<><Btn disabled={pending} onClick={() => setPlan(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={pending || !!plan?.plan?.disk_short} onClick={() => void download()}>{tr("Download & load")}</Btn></>}><p><strong>{tr(plan?.plan?.title ?? selectedFamily?.title)}</strong>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}</p>{tr(plan?.plan?.disk_short ? <ErrorNotice message={plan.plan.disk_short}/> : null)}<p className="small muted">{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}</p><p className="small muted">{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}</p>{tr(selectedSize?.images ? <p className="small muted">{tr("Vision encoder files are included. Picture reading loads only when enabled.")}</p> : null)}</Dialog>
|
||||
<Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="stack"><p className="strong">{tr(selectedFamily?.title)}</p><div className="st-tablewrap"><table className="st-table"><thead><tr><th>{tr("Version")}</th><th>{tr("Download")}</th><th>{tr("Status")}</th><th></th></tr></thead><tbody>{tr(selectedFamily?.sizes.map(v => <tr key={v.id}><td><strong>{tr(catalogVersionLabel(v))}</strong><small>{tr(v.model)} · {tr(v.about)}</small></td><td>{tr(v.download_gb.toFixed(1))}{tr(" GB")}</td><td>{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')}</td><td><Btn size="sm" disabled={!!active} onClick={() => { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}</Btn></td></tr>))}</tbody></table></div><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}</Btn><p className="xs muted">{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}</p></div></Dialog>
|
||||
<NativeBenchmark open={benchmark} onClose={() => setBenchmark(false)}/>
|
||||
<NativeDeleteDialog id={deleting} onClose={() => setDeleting(null)}/>
|
||||
<Dialog open={manage} title={tr("Manage models")} onClose={() => setManage(false)} actions={<Btn onClick={() => setManage(false)}>{tr("Done")}</Btn>}><div className="native-manage">
|
||||
{tr(downloaded.length ? <div className="native-manage-list" role="list">{tr(downloaded.map(m => { const v = allSizes.find(x => x.id === m.model), loaded = native?.instances.some(i => i.model === m.model && i.status === 'ready'); return <div className="native-manage-row" role="listitem" key={m.model} data-selected={selectedSize?.id === m.model || undefined}>
|
||||
<span className="native-manage-name"><strong>{tr(v ? `${catalogVersionLabel(v)}` : m.model_name ?? m.model)}</strong><small>{tr(v ? v.model : m.model)}{tr(m.diskGb ? ` · ${sizeGb(m.diskGb)}` : '')}</small></span>
|
||||
<span className={loaded ? 'st-pill st-pill--accent' : 'st-pill'}>{tr(loaded ? 'Loaded' : 'Downloaded')}</span>
|
||||
<span className="native-manage-actions"><Btn size="sm" disabled={!!active || !v} onClick={() => { if (v) setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === m.model ? 'Selected' : 'Use version')}</Btn><Btn size="sm" variant="danger" disabled={!!active} onClick={() => setDeleting(m.model)}>{tr("Delete")}</Btn></span>
|
||||
</div>; }))}</div> : <p className="small muted native-manage-empty">{tr("No downloaded models")}</p>)}
|
||||
<div className="native-manage-foot"><Btn variant="ghost" icon="folder" onClick={() => { setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF…")}</Btn></div>
|
||||
</div></Dialog>
|
||||
</Screen>;
|
||||
}
|
||||
/** setup's "5/7: downloading …" as a sentence a person can read. */
|
||||
function installStepLabel(step?: string): string {
|
||||
const n = Number(step?.match(/^(\d+)\//)?.[1]);
|
||||
if (!n)
|
||||
return step ? 'Getting things ready…' : 'Downloading and preparing model files…';
|
||||
return n <= 2 ? 'Checking your computer…' : n <= 4 ? 'Getting things ready…' : n === 5 ? 'Downloading your model…' : n === 6 ? 'Preparing your model for Strata…' : 'Finishing up…';
|
||||
}
|
||||
export function NativeProgress({ job }: {
|
||||
job: NativeJob;
|
||||
}) { const download = job.result?.install?.download; const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try {
|
||||
}) { const download = installProgress(job.result?.install); const detailsText = [job.details, job.result?.install?.engine?.details].filter(Boolean).join('\n'); const eta = useDownloadEta(job.kind === 'install' ? download : undefined, job.id); const [stopping, setStopping] = useState(false), [error, setError] = useState(''); async function stop() { setStopping(true); setError(''); try {
|
||||
await nativeAction(`operations/${job.id}/cancel`);
|
||||
}
|
||||
catch (e) {
|
||||
@@ -110,4 +139,4 @@ catch (e) {
|
||||
}
|
||||
finally {
|
||||
setStopping(false);
|
||||
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' ? <Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file)} · {tr(download.percent ?? 0)}%</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p></details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
|
||||
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' ? <div className="onboard-progress-actions">{tr(eta ? <span className="small muted">{eta}</span> : null)}<Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn></div> : null)}</div><p className="small">{tr(job.kind === 'install' ? installStepLabel(job.result?.install?.step) : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file === 'model files' ? 'Model files' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}</p></> : null)}<details><summary className="small">{tr("Details")}</summary><p className="small muted">{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}</p>{tr(detailsText ? <pre className="small muted error-detail-text">{detailsText}</pre> : null)}</details>{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
|
||||
@@ -2,8 +2,7 @@ import {localeTag} from '../lib/i18n';
|
||||
import { tr } from '../lib/i18n';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '../lib/client';
|
||||
import { nativeAction, refreshNative, useNative, type NativeJob } from '../lib/native';
|
||||
import { NativeSettings } from './NativeSettings';
|
||||
import { nativeAction, useNative, type NativeJob } from '../lib/native';
|
||||
import { Btn, Dialog, ErrorNotice, Select } from './ui';
|
||||
import { NativeProgress } from './NativeModels';
|
||||
export function NativeBenchmark({ open, onClose }: {
|
||||
@@ -48,57 +47,60 @@ export function NativeBenchmark({ open, onClose }: {
|
||||
}
|
||||
export function NativeOperations() {
|
||||
const native = useNative();
|
||||
const [repository, setRepository] = useState(''), [model, setModel] = useState(''), [error, setError] = useState(''), [pending, setPending] = useState(false), [benchmark, setBenchmark] = useState(false), [logs, setLogs] = useState<{
|
||||
const [error, setError] = useState(''), [saved, setSaved] = useState(''), [saving, setSaving] = useState(false);
|
||||
const [logs, setLogs] = useState<{
|
||||
at: string;
|
||||
instanceId: string;
|
||||
line: string;
|
||||
}[]>([]), [showLogs, setShowLogs] = useState(false), [confirm, setConfirm] = useState('');
|
||||
const installed = native?.installed?.models ?? [], selected = installed.find(i => i.model === model) ?? installed[0], active = native?.jobs.find(j => j.state === 'running');
|
||||
useEffect(() => { setRepository(native?.repo ?? ''); }, [native?.repo]);
|
||||
}[]>([]), [showLogs, setShowLogs] = useState(false), [confirm, setConfirm] = useState(false);
|
||||
const [update, setUpdate] = useState<'checking' | 'available' | 'current' | 'unknown'>('checking');
|
||||
const active = native?.jobs.find(j => j.state === 'running');
|
||||
// The engine's update is offered only when the update check says there is one.
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
void api.get<{ engine?: { status?: string } }>('/api/updates/check').then(r => { if (alive) setUpdate(r.engine?.status === 'available' ? 'available' : r.engine?.status === 'current' ? 'current' : 'unknown'); }).catch(() => { if (alive) setUpdate('unknown'); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!showLogs)
|
||||
return;
|
||||
let current = true;
|
||||
const load = () => void api.get<{
|
||||
const read = () => void api.get<{
|
||||
logs: typeof logs;
|
||||
}>('/api/native/logs').then(value => {
|
||||
if (current)
|
||||
setLogs(value.logs);
|
||||
}).catch(e => setError(e.message));
|
||||
load();
|
||||
const timer = setInterval(load, 2500);
|
||||
return () => { current = false; clearInterval(timer); };
|
||||
}>('/api/native/logs').then(value => { setLogs(value.logs); }).catch(() => { });
|
||||
read();
|
||||
const timer = setInterval(read, 2000);
|
||||
return () => clearInterval(timer);
|
||||
}, [showLogs]);
|
||||
async function connect() {
|
||||
setPending(true);
|
||||
async function updateEngine() {
|
||||
setError('');
|
||||
try {
|
||||
await api.patch('/api/native', { repository });
|
||||
await refreshNative(true);
|
||||
await nativeAction('operations', { kind: 'update-engine' });
|
||||
setConfirm(false);
|
||||
}
|
||||
catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
// The window cannot save a download, so the host writes the file to Downloads and says where.
|
||||
async function saveLogs() {
|
||||
setSaving(true);
|
||||
setSaved('');
|
||||
setError('');
|
||||
try {
|
||||
const result = await api.post<{ path: string }>('/api/native/logs/save', {});
|
||||
setSaved(result.path);
|
||||
}
|
||||
catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
finally {
|
||||
setPending(false);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
async function operate(kind: string) {
|
||||
setError('');
|
||||
try {
|
||||
await nativeAction('operations', { kind, args: { model: selected?.model } });
|
||||
setConfirm('');
|
||||
}
|
||||
catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
function exportLogs() { const url = URL.createObjectURL(new Blob([logs.map(l => `${l.at} ${l.instanceId}: ${l.line}`).join('\n')], { type: 'text/plain' })); const a = document.createElement('a'); a.href = url; a.download = 'strata-engine.log'; a.click(); URL.revokeObjectURL(url); }
|
||||
return <div className="stack stack--lg native-engine-settings"><section className="st-card"><div className="section-toolbar"><h2 className="h3">{tr("Engine installation")}</h2><span className="st-pill">{tr(native?.available ? 'Connected' : 'Setup needed')}</span></div><p className="small muted">{tr("Your local Strata installation handles optimized models, companion files and engine updates.")}</p><details open={!native?.available}><summary className="small">{tr("Installation folder")}</summary><label className="input-field"><span>{tr("Strata folder")}</span><input className="st-input" aria-label={tr("Strata installation folder")} placeholder={tr("Folder containing setup.py")} value={repository} onChange={e => setRepository(e.target.value)}/></label><div className="native-settings-actions"><Btn disabled={pending || !repository.trim() || !!active} onClick={() => void connect()}>{tr(pending ? 'Connecting…' : 'Connect installation')}</Btn><Btn disabled={!!active} onClick={() => void refreshNative(true)}>{tr("Check again")}</Btn><a className="st-btn st-btn--ghost" href="https://github.com/Niko1221/Strata" target="_blank" rel="noreferrer">{tr("Get Strata")}</a></div></details>{tr(native?.error ? <p className="small inline-error">{tr(native.error)}</p> : <p className="small muted">{tr(native?.summary)}</p>)}</section>
|
||||
{tr(installed.length ? <section className="st-card"><h2 className="h3">{tr("Model settings & tools")}</h2><Select ariaLabel={tr("Native settings model")} value={selected?.model ?? ''} options={installed.map(m => ({ value: m.model, label: m.model_name ?? m.model }))} onChange={setModel}/>{tr(selected ? <NativeSettings model={selected.model}/> : null)}</section> : <p className="small muted">{tr("Prepare a model in Models to configure its engine parameters and MCP tools.")}</p>)}
|
||||
<section className="st-card"><h2 className="h3">{tr("Performance")}</h2><p className="small muted">{tr("Measure speed with a short test. Expert calibration tries engine settings and saves the fastest measured configuration.")}</p><div className="native-settings-actions"><Btn icon="gauge" disabled={!native?.instances.some(i => i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Measure speed")}</Btn><Btn disabled={!native?.capabilities.calibration || !selected?.ready || !!active} onClick={() => setConfirm('calibrate')}>{tr("Calibrate engine\u2026")}</Btn></div>{tr(!native?.capabilities.calibration ? <p className="xs muted">{tr("Calibration is available on NVIDIA hardware supported by the installed version. Short benchmarks work with any running native instance.")}</p> : null)}</section>
|
||||
<section className="st-card"><div className="section-toolbar"><h2 className="h3">{tr("Diagnostics")}</h2><Btn size="sm" onClick={() => setShowLogs(v => !v)}>{tr(showLogs ? 'Hide logs' : 'View engine logs')}</Btn></div><p className="small muted">{tr("Downloads, preparation and engine failures include their original messages here.")}</p>{tr(showLogs ? <><pre className="native-log" aria-label={tr("Engine log")}>{logs.length ? logs.map(l => `${l.at} · ${l.line}`).join('\n') : 'No engine messages yet.'}</pre><Btn size="sm" icon="download" onClick={exportLogs}>{tr("Save logs")}</Btn></> : null)}{tr(native?.jobs.filter(j => j.state === 'error').slice(-3).map(j => <ErrorNotice key={j.id} message={j.error ?? j.summary}/>))}</section>
|
||||
return <div className="stack stack--lg native-engine-settings">
|
||||
<section className="st-card"><div className="section-toolbar"><h2 className="h3">{tr("Update component")}</h2>{tr(update === 'available' ? <Btn size="sm" variant="primary" disabled={!!active || (native?.instances.length ?? 0) > 0} onClick={() => setConfirm(true)}>{tr("Update available")}</Btn> : null)}</div><p className="small muted">{tr("Update the engine for this computer. Your models and settings are kept.")}</p>{tr(update === 'current' ? <p className="small muted">{tr("Up to date")}</p> : null)}{tr(update === 'available' && (native?.instances.length ?? 0) > 0 ? <p className="small muted">{tr("Open Models and unload the running native models first.")}</p> : null)}</section>
|
||||
<section className="st-card"><div className="section-toolbar"><h2 className="h3">{tr("Diagnostics")}</h2><Btn size="sm" onClick={() => setShowLogs(v => !v)}>{tr(showLogs ? 'Hide logs' : 'View engine logs')}</Btn></div><p className="small muted">{tr("Downloads, preparation and engine failures include their original messages here.")}</p>{tr(showLogs ? <pre className="native-log" aria-label={tr("Engine log")}>{logs.length ? logs.map(l => `${l.at} · ${l.line}`).join(String.fromCharCode(10)) : 'No engine messages yet.'}</pre> : null)}<div className="native-settings-actions"><Btn size="sm" icon="download" disabled={saving} onClick={() => void saveLogs()}>{tr(saving ? 'Working…' : 'Save logs')}</Btn></div>{tr(saved ? <p className="small" role="status">{tr("Saved to {0}", [saved])}</p> : null)}{tr(native?.jobs.filter(j => j.state === 'error').slice(-3).map(j => <ErrorNotice key={j.id} message={j.error ?? j.summary} detail={j.details}/>))}</section>
|
||||
{tr(active ? <NativeProgress job={active}/> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
<NativeBenchmark open={benchmark} onClose={() => setBenchmark(false)}/><Dialog open={!!confirm} compact title={tr("Calibrate this computer?")} onClose={() => setConfirm('')} actions={<><Btn onClick={() => setConfirm('')}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!active || (native?.instances.length ?? 0) > 0} onClick={() => void operate('calibrate')}>{tr("Start calibration")}</Btn></>}><p>{tr("The computer will be busy for about 5–15 minutes. Unload models first.")} {tr("Strata will calibrate {0} and save the fastest measured settings.", [selected?.model_name ?? tr("The selected model")])}</p></Dialog>
|
||||
<Dialog open={confirm} compact title={tr("Update engine?")} onClose={() => setConfirm(false)} actions={<><Btn onClick={() => setConfirm(false)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!!active || (native?.instances.length ?? 0) > 0} onClick={() => void updateEngine()}>{tr("Update")}</Btn></>}><p>{tr("The native installer updates the installation. Model files and settings are kept. Unload native models before updating.")}</p></Dialog>
|
||||
</div>;
|
||||
}
|
||||
@@ -5,10 +5,12 @@ import { changeModelDirectory, getState, lifecycleStatus, removeVariant, runtime
|
||||
import { pickerGroups, pickerVersionState } from '../lib/model-picker';
|
||||
import { sizeGb } from '../lib/format';
|
||||
import { useNative } from '../lib/native';
|
||||
import { NativeDeleteDialog } from './NativeDelete';
|
||||
export function SettingsStorage() {
|
||||
const state = useStore(s => s);
|
||||
const native = useNative();
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [nativeDeleting, setNativeDeleting] = useState<string | null>(null);
|
||||
const [pending, setPending] = useState(false), [error, setError] = useState('');
|
||||
const [editing, setEditing] = useState(false), [directory, setDirectory] = useState('');
|
||||
const [directoryPending, setDirectoryPending] = useState(false), [directoryError, setDirectoryError] = useState(''), [notice, setNotice] = useState('');
|
||||
@@ -95,6 +97,10 @@ export function SettingsStorage() {
|
||||
...versions.map(v => ({ value: v.id, label: `${v.local ? v.name : v.family} · ${v.quant} · ${sizeGb(v.diskGb)}${v.local ? ' · Local' : ''}`, disabled: pickerVersionState(v, library?.loaded ?? null).busy })),
|
||||
]} onChange={id => { setError(''); setSelected(id); }}/>
|
||||
</Field>
|
||||
{tr(native?.installed?.models.length ? <Field label={tr("Downloaded models")} hint={tr("{0} on this computer. Choose a version to delete its files.", [sizeGb((native.installed.models).reduce((n, m) => n + (m.diskGb ?? 0), 0))])}>
|
||||
<div className="stack">{tr(native.installed.models.map(m => <div className="row" key={m.model}><span><strong>{tr(m.model_name || m.model)}</strong> <small className="muted">{tr(m.model)} · {tr(sizeGb(m.diskGb ?? 0))}{tr(native.instances.some(i => i.model === m.model) ? <> · {tr('Loaded')}</> : null)}</small></span><Btn size="sm" variant="danger" disabled={!!native.jobs.some(j => j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}</Btn></div>))}</div>
|
||||
</Field> : null)}
|
||||
<NativeDeleteDialog id={nativeDeleting} onClose={() => setNativeDeleting(null)}/>
|
||||
<Dialog open={!!selected} compact title={tr(version?.local ? 'Remove from Strata?' : `Delete ${version?.quant ?? 'model version'}?`)} onClose={close} actions={<><Btn disabled={pending} onClick={close}>{tr("Keep version")}</Btn><Btn variant="danger" disabled={pending || unavailable} onClick={() => void remove()}>{tr(pending ? 'Working…' : version?.local ? 'Remove model' : 'Delete version')}</Btn></>}>
|
||||
<p>{tr(version ? `${version.local ? version.name : version.family} · ${version.quant} · ${sizeGb(version.diskGb)}` : 'This version is no longer downloaded.')}</p>
|
||||
{tr(version ? <p className="small muted storage-delete-note">{tr(version.local ? `${running ? 'The model will be unloaded and removed from Strata.' : 'The model will be removed from Strata.'} Your original GGUF files stay in their folder.` : `${running ? 'The running model will be unloaded and its files deleted.' : 'Its files will be deleted from this computer.'} You can download it again in Models.`)}</p> : null)}
|
||||
|
||||
@@ -63,14 +63,13 @@ export function SettingsUpdates() {
|
||||
return <div className="settings-version" data-update={update?.status}>
|
||||
<Icon name={name === 'Strata' ? 'layers' : 'engine'} size={20}/>
|
||||
<span><strong>{tr(name)}</strong><small>{tr(version ?? 'Version unavailable')}</small>{tr(!checking && update ? <small className="settings-version__message">{tr(update.message)}</small> : null)}</span>
|
||||
{tr(!checking && update?.status === 'available' && update.releaseUrl ? <a className="st-btn st-btn--secondary st-btn--sm" href={update.releaseUrl} target="_blank" rel="noreferrer" title={tr("Open the release page to update this installation")}>{tr("Get update")}<Icon name="download" size={15}/></a> : <span className="settings-version__label">{tr(checking ? 'Checking…' : update ? labels[update.status] : version === 'Not installed' ? 'Not installed' : 'Installed')}</span>)}
|
||||
{tr(!checking && update?.status === 'available' ? (native?.available ? <Btn size="sm" variant="primary" disabled={!!active || (name === 'Engine' && !native.installed?.models.length && !native.capabilities.componentUpdates)} onClick={() => setConfirm(name === 'Strata' ? 'update-strata' : 'update-engine')}>{tr("Update available")}</Btn> : update.releaseUrl ? <a className="st-btn st-btn--secondary st-btn--sm" href={update.releaseUrl} target="_blank" rel="noreferrer" title={tr("Open the release page to update this installation")}>{tr("Update available")}<Icon name="download" size={15}/></a> : <span className="settings-version__label">{tr(labels[update.status])}</span>) : <span className="settings-version__label">{tr(checking ? 'Checking…' : update ? labels[update.status] : version === 'Not installed' ? 'Not installed' : 'Installed')}</span>)}
|
||||
</div>;
|
||||
}
|
||||
return <>
|
||||
<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 && !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,6 +6,7 @@ import { ContextRing } from './ContextRing';
|
||||
import { Popover } from './Popover';
|
||||
import { chatMetrics, compactTokens, elapsed } from '../lib/chat-metrics';
|
||||
import { useStore } from '../lib/store';
|
||||
import { useNative } from '../lib/native';
|
||||
import type { Session } from '../lib/types';
|
||||
function Chip({ icon, visual, label, title, children }: {
|
||||
icon?: IconName;
|
||||
@@ -46,7 +47,11 @@ export function ChatTelemetry({ session }: {
|
||||
}) {
|
||||
const monitor = useStore(s => s.monitor);
|
||||
const engine = useStore(s => s.engine);
|
||||
const m = chatMetrics(session, monitor, engine ? contextTokens(engine.beginner.contextLength) : undefined);
|
||||
// The context shown is the one the loaded model runs with (the engine's own --max-context), not a catalog or settings default.
|
||||
const native = useNative();
|
||||
const running = native?.instances.find(i => i.id === native.defaultId && i.status === 'ready') ?? native?.instances.find(i => i.status === 'ready');
|
||||
const runningContext = running ? Number(running.metrics?.engine?.max_context) || running.context || undefined : undefined;
|
||||
const m = chatMetrics(session, monitor, runningContext ?? (engine ? contextTokens(engine.beginner.contextLength) : undefined));
|
||||
const speed = useCalmSpeed(m.speed, session?.id ?? null, m.streaming);
|
||||
if (!m.hasReplies)
|
||||
return null;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { tr } from '../lib/i18n';
|
||||
import { createContext, useContext, useCallback, useEffect, useId, useRef, useState, type AriaAttributes, type CSSProperties, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { cx, userError } from '../lib/format';
|
||||
import { plainFailure } from '../lib/plain-errors';
|
||||
import { dismissActionError, dismissToast, holdToast, releaseToast, useStore } from '../lib/store';
|
||||
import { isTopSurface, useSurfaceFocus } from '../lib/focus';
|
||||
/* -------------------------------------------------------------------- icon */
|
||||
@@ -514,12 +515,18 @@ export function MetricGrid({ children, min = 200 }: {
|
||||
</div>);
|
||||
}
|
||||
/** Shared, announced error with a cause and a concrete recovery action. */
|
||||
export function ErrorNotice({ message, next, action, onRetry }: {
|
||||
export function ErrorNotice({ message, next, action, onRetry, detail }: {
|
||||
message: string;
|
||||
next?: string;
|
||||
action?: string;
|
||||
onRetry?: () => void;
|
||||
detail?: string;
|
||||
}) {
|
||||
return <div className="error-notice" role="alert"><Icon name="error" size={18}/><div><strong>{tr(userError(message))}</strong>{tr(next ? <p>{tr(next)}</p> : null)}</div>{tr(onRetry ? <Btn size="sm" onClick={onRetry}>{tr(action ?? 'Try again')}</Btn> : null)}</div>;
|
||||
// A known failure is shown as a sentence and a next step; the original text stays under Details for experts.
|
||||
const plain = plainFailure(message);
|
||||
const known = plain.kind !== 'plain';
|
||||
const nextStep = known ? (plain.next ? tr(plain.next) : next) : next;
|
||||
const raw = detail ?? (known ? plain.detail : undefined);
|
||||
return <div className="error-notice" role="alert"><Icon name="error" size={18}/><div><strong>{tr(known ? plain.message : userError(message))}</strong>{tr(nextStep ? <p>{tr(nextStep)}</p> : null)}{tr(raw ? <details className="error-detail"><summary className="small">{tr("Details")}</summary><pre className="small muted">{raw}</pre></details> : null)}</div>{tr(onRetry ? <Btn size="sm" onClick={onRetry}>{tr(action ?? 'Try again')}</Btn> : null)}</div>;
|
||||
}
|
||||
export function PreviewBadge() { const demo = useStore(s => s.library?.mode === 'simulated'); return demo ? <span className="preview-badge">{tr("Preview build")}</span> : null; }
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { tr } from './i18n';
|
||||
|
||||
/** Minutes left from recent samples of "GB done": the rate over the last minute and a half, so a stall or a burst does not
|
||||
* swing the estimate. Null until there is enough to say (about 10 s of samples) or when nothing is moving. */
|
||||
export function etaMinutes(samples: { at: number; done: number }[], remainingGb: number | undefined): number | null {
|
||||
if (!Number.isFinite(remainingGb) || samples.length < 2) return null;
|
||||
const first = samples[0], last = samples[samples.length - 1];
|
||||
const seconds = (last.at - first.at) / 1000, gained = last.done - first.done;
|
||||
if (seconds < 10 || gained <= 0) return null;
|
||||
return Math.max(1, Math.ceil((remainingGb! / (gained / seconds)) / 60));
|
||||
}
|
||||
|
||||
export function etaLabel(minutes: number | null): string {
|
||||
if (minutes === null) return '';
|
||||
if (minutes >= 90) {
|
||||
const h = Math.floor(minutes / 60), m = minutes % 60;
|
||||
return m ? tr('About {0} h {1} min left', [h, m]) : tr('About {0} h left', [h]);
|
||||
}
|
||||
return tr('About {0} min left', [minutes]);
|
||||
}
|
||||
|
||||
/** The approximate time left of a running download, for the progress bar. `key` restarts the estimate for another job. */
|
||||
export function useDownloadEta(download: { done_gb?: number; remaining_gb?: number } | undefined, key: string | undefined): string {
|
||||
const samples = useRef<{ at: number; done: number }[]>([]);
|
||||
const owner = useRef<string | undefined>(undefined);
|
||||
const [label, setLabel] = useState('');
|
||||
const done = download?.done_gb, remaining = download?.remaining_gb;
|
||||
useEffect(() => {
|
||||
if (owner.current !== key) { owner.current = key; samples.current = []; }
|
||||
if (!Number.isFinite(done)) { setLabel(''); return; }
|
||||
const now = Date.now();
|
||||
const list = samples.current;
|
||||
if (!list.length || list[list.length - 1].done !== done) list.push({ at: now, done: done! });
|
||||
while (list.length > 2 && now - list[0].at > 90_000) list.shift();
|
||||
setLabel(etaLabel(etaMinutes(list, remaining)));
|
||||
}, [done, remaining, key]);
|
||||
return label;
|
||||
}
|
||||
|
||||
/** What the progress UI reads from an install job's `install` object: the parts it is downloading (the model's files and,
|
||||
* when the job adds it, the engine) summed into ONE count. A part is {kind, name, done_gb, total_gb, state}. Without `parts`
|
||||
* the job's combined `download` fields ({done_gb, total_gb, remaining_gb, percent}) are used as they are. */
|
||||
export interface InstallParts { parts?: { done_gb?: number; total_gb?: number; state?: string }[]; download?: { done_gb?: number; total_gb?: number; remaining_gb?: number; percent?: number; file?: string } }
|
||||
export function installProgress(install: InstallParts | undefined): { done_gb: number; total_gb: number; remaining_gb: number; percent: number; file?: string } | undefined {
|
||||
const parts = (install?.parts ?? []).filter(p => Number.isFinite(p.total_gb) && (p.total_gb ?? 0) > 0 && p.state !== 'skipped' && p.state !== 'current');
|
||||
if (parts.length) {
|
||||
const total = parts.reduce((n, p) => n + (p.total_gb ?? 0), 0);
|
||||
const done = Math.min(total, parts.reduce((n, p) => n + Math.min(p.done_gb ?? 0, p.total_gb ?? 0), 0));
|
||||
return { done_gb: done, total_gb: total, remaining_gb: Math.max(0, total - done), percent: Math.min(99, Math.floor(100 * done / total)), file: install?.download?.file };
|
||||
}
|
||||
const d = install?.download;
|
||||
if (d && Number.isFinite(d.done_gb) && Number.isFinite(d.total_gb)) return { done_gb: d.done_gb!, total_gb: d.total_gb!, remaining_gb: Number.isFinite(d.remaining_gb) ? d.remaining_gb! : Math.max(0, d.total_gb! - d.done_gb!), percent: d.percent ?? 0, file: d.file };
|
||||
return undefined;
|
||||
}
|
||||
@@ -46,3 +46,15 @@ export function nativeMonitorData(native:NativeState,inventory:Hardware|null,sel
|
||||
totals:{tokensIn:tokenTotal('prompt_tokens'),tokensOut:tokenTotal('output_tokens'),requests:tokenTotal('requests'),avgTps:NaN,since:selected?.loadedAt??instances[0]?.loadedAt??new Date().toISOString(),ttftMs:NaN,cachedTokens:tokenTotal('reused'),uncachedTokens:tokenTotal('prompt_tokens')-tokenTotal('reused'),promptMs:hasReading(tokenTotal('prompt_ms'))?tokenTotal('prompt_ms'):undefined,decodeMs:hasReading(tokenTotal('decode_ms'))?tokenTotal('decode_ms'):undefined}
|
||||
};
|
||||
}
|
||||
|
||||
/** GPU temperature, load, VRAM, power and PCIe come from the engine's metrics while a model runs. With no model loaded (or an engine that
|
||||
* reports none of them) the host's own sensors fill in: nvidia-smi, or the AMD/Intel sysfs readings the host probes itself. */
|
||||
export function withHostSensors(live:MonitorState,host:MonitorState|null):MonitorState{
|
||||
const s=host?.hardware,h=live.hardware;if(!s||!h)return live;
|
||||
const empty=(g:GpuReading)=>![g.utilizationPct,g.temperatureC,g.memoryUsedGb,g.powerW].some(hasReading);
|
||||
const pick=<T,>(a:T,b:T)=>hasReading(a as unknown)?a:b;
|
||||
return {...live,hardware:{...h,
|
||||
gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);return sensor&&empty(g)?{...g,...sensor}:g;}),
|
||||
gpuLoad:pick(h.gpuLoad,s.gpuLoad),vramUsedGb:pick(h.vramUsedGb,s.vramUsedGb),vramTotalGb:pick(h.vramTotalGb,s.vramTotalGb),gpuTempC:pick(h.gpuTempC,s.gpuTempC),
|
||||
powerW:pick(h.powerW,s.powerW),powerLimitW:pick(h.powerLimitW,s.powerLimitW),pcieRxMbs:pick(h.pcieRxMbs,s.pcieRxMbs)}};
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import type { Hardware, RuntimeModels } from './types';
|
||||
export interface NativeSize {id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean}
|
||||
export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]}
|
||||
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 NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;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;componentUpdates?: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;diskGb?:number;diskBytes?:number;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,44 @@
|
||||
/**
|
||||
* Plain words for failures. The host and Control speak in codes and log lines (`server_exited`, exit codes, "component-missing",
|
||||
* a Python message); a person needs what happened and what to do next. Every message the UI shows through ErrorNotice or a toast
|
||||
* passes through here: a known failure becomes a sentence and a next step, and the original text stays one click away under
|
||||
* "Details" for experts. Strings are fixed so every language has them.
|
||||
*/
|
||||
import { tr } from './i18n';
|
||||
|
||||
export interface PlainFailure { message: string; next?: string; detail?: string; kind: string }
|
||||
|
||||
interface Rule { kind: string; match: RegExp; message: string; next?: string; detail?: (m: RegExpMatchArray, raw: string) => string | undefined }
|
||||
|
||||
const MEMORY = 'The model stopped while starting, most likely because the PC ran low on memory.';
|
||||
const MEMORY_NEXT = 'Close other programs and try again, or choose “Leave 20% for my work”. In Expert mode you can also turn on the low-RAM option, so part of the model is read from the SSD.';
|
||||
|
||||
/** Order matters: the first rule that matches wins. */
|
||||
const RULES: Rule[] = [
|
||||
{ kind: 'picture-reading', match: /vision files|picture reading/i, message: 'Picture reading isn’t available for this model.', next: 'Turn off picture reading and try again.' },
|
||||
{ kind: 'memory', match: /server_exited|engine stopped|exited before|died before|out of memory|memory guard|\boom\b|killed/i, message: MEMORY, next: MEMORY_NEXT },
|
||||
{ kind: 'slow-load', match: /loading took more than/i, message: 'Loading is taking too long.', next: 'The PC may be short on memory. Close other programs and try again.' },
|
||||
{ kind: 'engine-missing', match: /no engine for this pc|engine component|never downloads an engine|engine .*not installed|no strata engine/i, message: 'Strata’s engine for this computer isn’t installed yet.', next: 'It is added when you download a model. Download your model again to add it.' },
|
||||
{ kind: 'network', match: /cannot reach|could not reach|can't reach|timed out|econn|enotfound|getaddrinfo|urlopen|connection (?:reset|refused|aborted)|network is unreachable/i, message: 'The download couldn’t reach the internet.', next: 'Check your connection, then press Resume download.' },
|
||||
{ kind: 'integrity', match: /sha-?256|checksum|does not match|did not match|hash mismatch|safety check/i, message: 'A downloaded file didn’t pass Strata’s safety check.', next: 'Press Resume download and Strata will fetch it again.' },
|
||||
{ kind: 'assistant-missing', match: /agent component|deepseek harness|component-missing|harness .*not (?:installed|found)/i, message: 'The coding assistant isn’t installed on this computer yet.', next: 'Chat works without it.' },
|
||||
{ kind: 'control', match: /strata control (?:could not start|did not answer|stopped)|control did not answer/i, message: 'Strata couldn’t read its own components.', next: 'Close and reopen Strata. If this keeps happening, reinstall the app.' },
|
||||
{ kind: 'technical', match: /traceback|\bexit(?:ed)?(?: code)? \d+|errno|ERR_[A-Z_]+|\bat \S+:\d+|\[X\]|\bENOENT\b|\bEPERM\b|\bEACCES\b/i, message: 'Something went wrong.', next: 'Try again. If it keeps happening, open Details and share them when you ask for help.' },
|
||||
];
|
||||
|
||||
/** The message as a person should read it, its next step, and the original text for the Details disclosure. */
|
||||
export function plainFailure(raw: string | null | undefined): PlainFailure {
|
||||
const text = String(raw ?? '').replace(/^\s*Fixture:\s*/i, '').trim();
|
||||
for (const rule of RULES) {
|
||||
const m = text.match(rule.match);
|
||||
if (!m) continue;
|
||||
return { kind: rule.kind, message: rule.message, next: rule.next, detail: rule.detail ? rule.detail(m, text) : text };
|
||||
}
|
||||
return { kind: 'plain', message: text.replace(/^./, c => c.toUpperCase()) };
|
||||
}
|
||||
|
||||
/** Translated copy of a failure, ready to show. */
|
||||
export function plainFailureText(raw: string | null | undefined) {
|
||||
const f = plainFailure(raw);
|
||||
return { ...f, message: tr(f.message), next: f.next ? tr(f.next) : undefined };
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { plainFailure, plainFailureText } from './plain-errors';
|
||||
import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';
|
||||
import { updateAgent } from './agents';
|
||||
import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipRun, type TimeSkipVersion } from './time-skip';
|
||||
@@ -136,11 +137,11 @@ export interface Prefs {
|
||||
const PREFS_DEFAULTS: Prefs = {
|
||||
language: 'en',
|
||||
fontFamily: '',
|
||||
theme: 'light',
|
||||
theme: 'system',
|
||||
contrast: 'standard',
|
||||
rail: false,
|
||||
focus: false,
|
||||
contentFontSize: 16,
|
||||
contentFontSize: 14,
|
||||
density: 'comfortable',
|
||||
motion: 'system',
|
||||
transparency: 'translucent',
|
||||
@@ -187,7 +188,7 @@ function loadPrefs(): Prefs {
|
||||
...parsed,
|
||||
language: validLanguage(parsed.language) ? parsed.language : 'en',
|
||||
fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '',
|
||||
contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 16)),
|
||||
contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)),
|
||||
};
|
||||
} catch {
|
||||
/* fall through to the next key */
|
||||
@@ -1324,6 +1325,7 @@ export async function sendMessage(text: string) {
|
||||
images:await Promise.all(pictures.map(photoData)),
|
||||
useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true,
|
||||
thinking:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinking??'High',
|
||||
thinkingBudget:state.sessions.find(s=>s.id===sessionId)?.preferences?.thinkingBudget??0,
|
||||
// The Mode menu's choice for this chat, read when the turn starts; the host applies it to the agent.
|
||||
mode:state.sessions.find(s=>s.id===sessionId)?.preferences?.mode??'manual',
|
||||
// So a skill narrowed to another workspace does not fire here.
|
||||
@@ -1341,7 +1343,7 @@ export async function sendMessage(text: string) {
|
||||
} else if (type === 'notice') {
|
||||
// The host says why this chat is not using the agent. One toast per reason per page load.
|
||||
const code = String(frame.code ?? 'notice');
|
||||
if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', String(frame.message ?? '')); }
|
||||
if (!noticed.has(code)) { noticed.add(code); pushToast('info', 'Agent', plainFailureText(String(frame.message ?? '')).message); }
|
||||
} else if (type === 'agent-tool') {
|
||||
const tool = frame.tool as ToolCall;
|
||||
patchAssistant(m => {
|
||||
@@ -1352,7 +1354,7 @@ export async function sendMessage(text: string) {
|
||||
} else if (type === 'agent') {
|
||||
patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) }));
|
||||
} else if (type === 'delta') {
|
||||
patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil(content.length/4)); const seconds=Math.max(.1,(performance.now()-started)/1000); return {...m,content,tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),tps:count/seconds,usageSource:'estimated'}; });
|
||||
patchAssistant((m) => { const content=m.content+String(frame.text??''); const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });
|
||||
} else if (type === 'artifacts' && Array.isArray(frame.artifacts)) {
|
||||
patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] }));
|
||||
} else if(type==='native-tool'){
|
||||
@@ -1368,7 +1370,7 @@ export async function sendMessage(text: string) {
|
||||
tps: typeof frame.tps === 'number' ? frame.tps : m.tps,
|
||||
}));
|
||||
} else if (type === 'error') {
|
||||
patchAssistant((m) => ({ ...m, error: String(frame.message ?? 'Engine error'), streaming: false }));
|
||||
patchAssistant((m) => ({ ...m, error: plainFailure(String(frame.message ?? 'Engine error')).message, streaming: false }));
|
||||
} else if (type === 'done') {
|
||||
patchSession(sessionId, (sess) => ({
|
||||
...sess,
|
||||
|
||||
@@ -388,7 +388,7 @@ export interface Session {
|
||||
previewOpen?: string;
|
||||
closedPreviews?: string[];
|
||||
showcaseAgentStates?: boolean;
|
||||
preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; mode?: ChatMode; useTools?:boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null };
|
||||
preferences?: { access?: 'read' | 'write' | 'full'; thinking?: string; thinkingBudget?: number; mode?: ChatMode; useTools?:boolean; /** This chat's API model; absent or null means the local model. */ remoteModel?: RemoteModelSelection | null };
|
||||
/** A branch does not have retained per-turn input usage. */
|
||||
statsAvailable?: boolean;
|
||||
id: string;
|
||||
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "Prüfe, ob die Engine verbunden und dieses Modell installiert ist, und versuche es erneut.",
|
||||
"s2568": "Ausgeführt",
|
||||
"s2569": "In diesem Modus nicht erlaubt. Es wurde nichts ausgeführt.",
|
||||
"s2570": "Vorschau erneut abspielen"
|
||||
"s2570": "Vorschau erneut abspielen",
|
||||
"s2571": "Noch etwa {0} Min.",
|
||||
"s2572": "Noch etwa {0} Std. {1} Min.",
|
||||
"s2573": "Noch etwa {0} Std.",
|
||||
"s2574": "Standardmäßig folgt es den Einstellungen Ihres Computers.",
|
||||
"s2575": "Für dieses Modell ist das Lesen von Bildern nicht verfügbar.",
|
||||
"s2576": "Schalten Sie das Lesen von Bildern aus und versuchen Sie es erneut.",
|
||||
"s2577": "Das Modell wurde beim Start beendet, wahrscheinlich weil dem PC der Arbeitsspeicher ausging.",
|
||||
"s2578": "Schließen Sie andere Programme und versuchen Sie es erneut, oder wählen Sie „20 % für meine Arbeit frei lassen“. Im Expertenmodus können Sie außerdem die Option für wenig Arbeitsspeicher aktivieren, damit ein Teil des Modells von der SSD gelesen wird.",
|
||||
"s2579": "Das Laden dauert zu lange.",
|
||||
"s2580": "Dem PC fehlt möglicherweise Arbeitsspeicher. Schließen Sie andere Programme und versuchen Sie es erneut.",
|
||||
"s2581": "Die Strata-Engine für diesen Computer ist noch nicht installiert.",
|
||||
"s2582": "Sie wird beim Herunterladen eines Modells hinzugefügt. Laden Sie Ihr Modell erneut herunter, um sie hinzuzufügen.",
|
||||
"s2583": "Der Download konnte das Internet nicht erreichen.",
|
||||
"s2584": "Prüfen Sie Ihre Verbindung und drücken Sie dann „Download fortsetzen“.",
|
||||
"s2585": "Eine heruntergeladene Datei hat die Sicherheitsprüfung von Strata nicht bestanden.",
|
||||
"s2586": "Drücken Sie „Download fortsetzen“, dann lädt Strata sie erneut herunter.",
|
||||
"s2587": "Der Coding-Assistent ist auf diesem Computer noch nicht installiert.",
|
||||
"s2588": "Der Chat funktioniert auch ohne ihn.",
|
||||
"s2589": "Strata konnte seine eigenen Komponenten nicht lesen.",
|
||||
"s2590": "Schließen Sie Strata und öffnen Sie es erneut. Tritt das Problem weiterhin auf, installieren Sie die App neu.",
|
||||
"s2591": "Etwas ist schiefgelaufen.",
|
||||
"s2592": "Versuchen Sie es erneut. Tritt das Problem weiterhin auf, öffnen Sie „Details“ und geben Sie diese bei einer Supportanfrage an.",
|
||||
"s2593": "Ihr Computer wird geprüft …",
|
||||
"s2594": "Alles wird vorbereitet …",
|
||||
"s2595": "Ihr Modell wird heruntergeladen …",
|
||||
"s2596": "Ihr Modell wird für Strata vorbereitet …",
|
||||
"s2597": "Komponente aktualisieren",
|
||||
"s2598": "Aktualisiert die Engine für diesen Computer. Ihre Modelle und Einstellungen bleiben erhalten.",
|
||||
"s2599": "Gespeichert unter {0}",
|
||||
"s2600": "Haben Sie bereits ein unterstütztes Modell auf diesem Computer? Wählen Sie den Ordner mit seinen Dateien. Strata prüft sie, bereitet das Modell vor und lädt es. Es wird nichts kopiert oder heruntergeladen.",
|
||||
"s2601": "Ordner mit den GGUF-Dateien",
|
||||
"s2602": "Vollständiger Pfad zum Ordner",
|
||||
"s2603": "Dateien prüfen",
|
||||
"s2604": "Modell gefunden",
|
||||
"s2605": "{0} Dateien · {1}",
|
||||
"s2606": "Vorbereiten und laden",
|
||||
"s2607": "Teile dieses Modells fehlen, oder der Ordner enthält mehr als ein Modell.",
|
||||
"s2608": "Legen Sie alle Teile eines Modells in einen Ordner und prüfen Sie erneut.",
|
||||
"s2609": "Strata kann diese Dateien noch nicht ausführen.",
|
||||
"s2610": "Strata führt die Qwen3.8-Flash-Next-Modelle aus. Laden Sie eines unter „Modelle“ herunter oder wählen Sie einen Ordner mit dessen Dateien.",
|
||||
"s2611": "Diese Dateien konnten nicht geprüft werden.",
|
||||
"s2612": "Prüfen Sie, ob der Ordner vollständige GGUF-Dateien enthält, und versuchen Sie es erneut.",
|
||||
"s2613": "Denkbudget",
|
||||
"s2614": "Unbegrenzt"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "Check that the engine is connected and this model is installed, then try again.",
|
||||
"s2568": "Ran",
|
||||
"s2569": "Not allowed in this mode. Nothing ran.",
|
||||
"s2570": "Replay preview"
|
||||
"s2570": "Replay preview",
|
||||
"s2571": "About {0} min left",
|
||||
"s2572": "About {0} h {1} min left",
|
||||
"s2573": "About {0} h left",
|
||||
"s2574": "System follows your computer by default.",
|
||||
"s2575": "Picture reading isn’t available for this model.",
|
||||
"s2576": "Turn off picture reading and try again.",
|
||||
"s2577": "The model stopped while starting, most likely because the PC ran low on memory.",
|
||||
"s2578": "Close other programs and try again, or choose “Leave 20% for my work”. In Expert mode you can also turn on the low-RAM option, so part of the model is read from the SSD.",
|
||||
"s2579": "Loading is taking too long.",
|
||||
"s2580": "The PC may be short on memory. Close other programs and try again.",
|
||||
"s2581": "Strata’s engine for this computer isn’t installed yet.",
|
||||
"s2582": "It is added when you download a model. Download your model again to add it.",
|
||||
"s2583": "The download couldn’t reach the internet.",
|
||||
"s2584": "Check your connection, then press Resume download.",
|
||||
"s2585": "A downloaded file didn’t pass Strata’s safety check.",
|
||||
"s2586": "Press Resume download and Strata will fetch it again.",
|
||||
"s2587": "The coding assistant isn’t installed on this computer yet.",
|
||||
"s2588": "Chat works without it.",
|
||||
"s2589": "Strata couldn’t read its own components.",
|
||||
"s2590": "Close and reopen Strata. If this keeps happening, reinstall the app.",
|
||||
"s2591": "Something went wrong.",
|
||||
"s2592": "Try again. If it keeps happening, open Details and share them when you ask for help.",
|
||||
"s2593": "Checking your computer…",
|
||||
"s2594": "Getting things ready…",
|
||||
"s2595": "Downloading your model…",
|
||||
"s2596": "Preparing your model for Strata…",
|
||||
"s2597": "Update component",
|
||||
"s2598": "Update the engine for this computer. Your models and settings are kept.",
|
||||
"s2599": "Saved to {0}",
|
||||
"s2600": "Already have a supported model on this computer? Choose the folder that holds its files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.",
|
||||
"s2601": "Folder with the GGUF files",
|
||||
"s2602": "Full path to the folder",
|
||||
"s2603": "Check files",
|
||||
"s2604": "Model found",
|
||||
"s2605": "{0} files · {1}",
|
||||
"s2606": "Prepare and load",
|
||||
"s2607": "Some parts of this model are missing, or the folder holds more than one model.",
|
||||
"s2608": "Put every part of one model in one folder, then check again.",
|
||||
"s2609": "Strata can’t run these files yet.",
|
||||
"s2610": "Strata runs the Qwen3.8-Flash-Next models. Download one from Models, or choose a folder with its files.",
|
||||
"s2611": "These files could not be checked.",
|
||||
"s2612": "Check that the folder holds complete GGUF files, then try again.",
|
||||
"s2613": "Thinking budget",
|
||||
"s2614": "No limit"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "Comprueba que el motor esté conectado y este modelo esté instalado. Después, inténtalo de nuevo.",
|
||||
"s2568": "Ejecutado",
|
||||
"s2569": "No se permite en este modo. No se ejecutó nada.",
|
||||
"s2570": "Repetir vista previa"
|
||||
"s2570": "Repetir vista previa",
|
||||
"s2571": "Quedan unos {0} min",
|
||||
"s2572": "Quedan unas {0} h {1} min",
|
||||
"s2573": "Quedan unas {0} h",
|
||||
"s2574": "De forma predeterminada sigue el ajuste de tu equipo.",
|
||||
"s2575": "La lectura de imágenes no está disponible para este modelo.",
|
||||
"s2576": "Desactiva la lectura de imágenes e inténtalo de nuevo.",
|
||||
"s2577": "El modelo se detuvo al iniciarse, probablemente porque el equipo se quedó sin memoria.",
|
||||
"s2578": "Cierra otros programas e inténtalo de nuevo, o elige «Dejar el 20 % para mi trabajo». En el modo experto también puedes activar la opción de poca RAM para que una parte del modelo se lea desde el SSD.",
|
||||
"s2579": "La carga está tardando demasiado.",
|
||||
"s2580": "Puede que al equipo le falte memoria. Cierra otros programas e inténtalo de nuevo.",
|
||||
"s2581": "El motor de Strata para este equipo aún no está instalado.",
|
||||
"s2582": "Se añade al descargar un modelo. Vuelve a descargar tu modelo para añadirlo.",
|
||||
"s2583": "La descarga no pudo conectarse a internet.",
|
||||
"s2584": "Revisa tu conexión y pulsa «Reanudar descarga».",
|
||||
"s2585": "Un archivo descargado no superó la comprobación de seguridad de Strata.",
|
||||
"s2586": "Pulsa «Reanudar descarga» y Strata la obtendrá de nuevo.",
|
||||
"s2587": "El asistente de programación aún no está instalado en este equipo.",
|
||||
"s2588": "El chat funciona sin él.",
|
||||
"s2589": "Strata no pudo leer sus propios componentes.",
|
||||
"s2590": "Cierra y vuelve a abrir Strata. Si sigue ocurriendo, reinstala la aplicación.",
|
||||
"s2591": "Algo salió mal.",
|
||||
"s2592": "Inténtalo de nuevo. Si sigue ocurriendo, abre «Detalles» y compártelos cuando pidas ayuda.",
|
||||
"s2593": "Revisando tu equipo…",
|
||||
"s2594": "Preparando todo…",
|
||||
"s2595": "Descargando tu modelo…",
|
||||
"s2596": "Preparando tu modelo para Strata…",
|
||||
"s2597": "Actualizar componente",
|
||||
"s2598": "Actualiza el motor de este equipo. Tus modelos y ajustes se conservan.",
|
||||
"s2599": "Guardado en {0}",
|
||||
"s2600": "¿Ya tienes un modelo compatible en este equipo? Elige la carpeta con sus archivos. Strata los comprueba, prepara el modelo y lo carga. No se copia ni se descarga nada.",
|
||||
"s2601": "Carpeta con los archivos GGUF",
|
||||
"s2602": "Ruta completa de la carpeta",
|
||||
"s2603": "Comprobar archivos",
|
||||
"s2604": "Modelo encontrado",
|
||||
"s2605": "{0} archivos · {1}",
|
||||
"s2606": "Preparar y cargar",
|
||||
"s2607": "Faltan partes de este modelo, o la carpeta contiene más de un modelo.",
|
||||
"s2608": "Pon todas las partes de un modelo en una carpeta y vuelve a comprobar.",
|
||||
"s2609": "Strata aún no puede ejecutar estos archivos.",
|
||||
"s2610": "Strata ejecuta los modelos Qwen3.8-Flash-Next. Descarga uno en Modelos o elige una carpeta con sus archivos.",
|
||||
"s2611": "No se pudieron comprobar estos archivos.",
|
||||
"s2612": "Comprueba que la carpeta tenga archivos GGUF completos e inténtalo de nuevo.",
|
||||
"s2613": "Presupuesto de razonamiento",
|
||||
"s2614": "Sin límite"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "エンジンが接続され、このモデルがインストールされていることを確認してから、もう一度お試しください。",
|
||||
"s2568": "実行済み",
|
||||
"s2569": "このモードでは許可されていません。何も実行していません。",
|
||||
"s2570": "プレビューを再生"
|
||||
"s2570": "プレビューを再生",
|
||||
"s2571": "あと約 {0} 分",
|
||||
"s2572": "あと約 {0} 時間 {1} 分",
|
||||
"s2573": "あと約 {0} 時間",
|
||||
"s2574": "既定ではお使いのコンピューターの設定に従います。",
|
||||
"s2575": "このモデルでは画像の読み取りを使えません。",
|
||||
"s2576": "画像の読み取りをオフにして、もう一度お試しください。",
|
||||
"s2577": "モデルの起動中に停止しました。パソコンのメモリ不足が原因と考えられます。",
|
||||
"s2578": "他のプログラムを閉じてもう一度お試しいただくか、「作業用に 20% を残す」を選んでください。エキスパートモードでは、低メモリのオプションをオンにして、モデルの一部を SSD から読み込むこともできます。",
|
||||
"s2579": "読み込みに時間がかかっています。",
|
||||
"s2580": "パソコンのメモリが足りない可能性があります。他のプログラムを閉じて、もう一度お試しください。",
|
||||
"s2581": "このコンピューター用の Strata エンジンはまだインストールされていません。",
|
||||
"s2582": "モデルをダウンロードするときに一緒に追加されます。もう一度モデルをダウンロードして追加してください。",
|
||||
"s2583": "ダウンロードがインターネットに接続できませんでした。",
|
||||
"s2584": "接続を確認してから、「ダウンロードを再開」を押してください。",
|
||||
"s2585": "ダウンロードしたファイルが Strata の安全性チェックに合格しませんでした。",
|
||||
"s2586": "「ダウンロードを再開」を押すと、Strata がもう一度取得します。",
|
||||
"s2587": "このコンピューターにはコーディングアシスタントがまだインストールされていません。",
|
||||
"s2588": "これがなくてもチャットは使えます。",
|
||||
"s2589": "Strata が自身のコンポーネントを読み取れませんでした。",
|
||||
"s2590": "Strata を閉じて開き直してください。それでも改善しない場合は、アプリを再インストールしてください。",
|
||||
"s2591": "問題が発生しました。",
|
||||
"s2592": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。",
|
||||
"s2593": "お使いのコンピューターを確認しています…",
|
||||
"s2594": "準備をしています…",
|
||||
"s2595": "モデルをダウンロードしています…",
|
||||
"s2596": "Strata 用にモデルを準備しています…",
|
||||
"s2597": "コンポーネントを更新",
|
||||
"s2598": "このコンピューター用のエンジンを更新します。モデルと設定はそのまま残ります。",
|
||||
"s2599": "{0} に保存しました",
|
||||
"s2600": "対応モデルがすでにこのコンピューターにありますか? そのファイルがあるフォルダーを選んでください。Strata がファイルを確認し、モデルを準備して読み込みます。コピーやダウンロードは行いません。",
|
||||
"s2601": "GGUF ファイルのフォルダー",
|
||||
"s2602": "フォルダーのフルパス",
|
||||
"s2603": "ファイルを確認",
|
||||
"s2604": "モデルが見つかりました",
|
||||
"s2605": "{0} ファイル · {1}",
|
||||
"s2606": "準備して読み込む",
|
||||
"s2607": "このモデルの一部が足りないか、フォルダーに複数のモデルが入っています。",
|
||||
"s2608": "1 つのモデルのすべてのパーツを 1 つのフォルダーに入れてから、もう一度確認してください。",
|
||||
"s2609": "Strata はこれらのファイルをまだ実行できません。",
|
||||
"s2610": "Strata は Qwen3.8-Flash-Next のモデルを実行します。「モデル」からダウンロードするか、そのファイルのフォルダーを選んでください。",
|
||||
"s2611": "これらのファイルを確認できませんでした。",
|
||||
"s2612": "フォルダーに完全な GGUF ファイルがあることを確認して、もう一度お試しください。",
|
||||
"s2613": "思考の上限",
|
||||
"s2614": "上限なし"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "엔진이 연결되어 있고 이 모델이 설치되어 있는지 확인한 후 다시 시도하세요.",
|
||||
"s2568": "실행됨",
|
||||
"s2569": "이 모드에서는 허용되지 않습니다. 실행된 항목이 없습니다.",
|
||||
"s2570": "미리보기 다시 재생"
|
||||
"s2570": "미리보기 다시 재생",
|
||||
"s2571": "약 {0}분 남음",
|
||||
"s2572": "약 {0}시간 {1}분 남음",
|
||||
"s2573": "약 {0}시간 남음",
|
||||
"s2574": "기본적으로 컴퓨터 설정을 따릅니다.",
|
||||
"s2575": "이 모델에서는 이미지 읽기를 사용할 수 없습니다.",
|
||||
"s2576": "이미지 읽기를 끄고 다시 시도하세요.",
|
||||
"s2577": "모델이 시작 중에 멈췄습니다. 컴퓨터의 메모리가 부족했을 가능성이 큽니다.",
|
||||
"s2578": "다른 프로그램을 닫고 다시 시도하거나 “작업용으로 20% 남기기”를 선택하세요. 전문가 모드에서는 저메모리 옵션을 켜서 모델의 일부를 SSD에서 읽게 할 수도 있습니다.",
|
||||
"s2579": "불러오는 데 시간이 너무 오래 걸립니다.",
|
||||
"s2580": "컴퓨터의 메모리가 부족할 수 있습니다. 다른 프로그램을 닫고 다시 시도하세요.",
|
||||
"s2581": "이 컴퓨터용 Strata 엔진이 아직 설치되지 않았습니다.",
|
||||
"s2582": "모델을 다운로드할 때 함께 추가됩니다. 모델을 다시 다운로드하여 추가하세요.",
|
||||
"s2583": "다운로드가 인터넷에 연결되지 않았습니다.",
|
||||
"s2584": "연결을 확인한 다음 “다운로드 재개”를 누르세요.",
|
||||
"s2585": "다운로드한 파일이 Strata의 안전 검사를 통과하지 못했습니다.",
|
||||
"s2586": "“다운로드 재개”를 누르면 Strata가 다시 받아옵니다.",
|
||||
"s2587": "이 컴퓨터에는 코딩 어시스턴트가 아직 설치되지 않았습니다.",
|
||||
"s2588": "없어도 채팅은 사용할 수 있습니다.",
|
||||
"s2589": "Strata가 자체 구성 요소를 읽지 못했습니다.",
|
||||
"s2590": "Strata를 닫았다가 다시 여세요. 계속되면 앱을 다시 설치하세요.",
|
||||
"s2591": "문제가 발생했습니다.",
|
||||
"s2592": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요.",
|
||||
"s2593": "컴퓨터를 확인하는 중…",
|
||||
"s2594": "준비하는 중…",
|
||||
"s2595": "모델을 다운로드하는 중…",
|
||||
"s2596": "Strata용으로 모델을 준비하는 중…",
|
||||
"s2597": "구성 요소 업데이트",
|
||||
"s2598": "이 컴퓨터용 엔진을 업데이트합니다. 모델과 설정은 그대로 유지됩니다.",
|
||||
"s2599": "{0}에 저장했습니다",
|
||||
"s2600": "이 컴퓨터에 이미 지원되는 모델이 있나요? 파일이 있는 폴더를 선택하세요. Strata가 파일을 확인하고 모델을 준비한 뒤 불러옵니다. 복사하거나 다운로드하지 않습니다.",
|
||||
"s2601": "GGUF 파일이 있는 폴더",
|
||||
"s2602": "폴더의 전체 경로",
|
||||
"s2603": "파일 확인",
|
||||
"s2604": "모델을 찾았습니다",
|
||||
"s2605": "파일 {0}개 · {1}",
|
||||
"s2606": "준비 후 불러오기",
|
||||
"s2607": "이 모델의 일부가 없거나 폴더에 모델이 둘 이상 들어 있습니다.",
|
||||
"s2608": "한 모델의 모든 파일을 한 폴더에 넣은 뒤 다시 확인하세요.",
|
||||
"s2609": "Strata가 아직 이 파일을 실행할 수 없습니다.",
|
||||
"s2610": "Strata는 Qwen3.8-Flash-Next 모델을 실행합니다. 모델 화면에서 내려받거나 해당 파일이 있는 폴더를 선택하세요.",
|
||||
"s2611": "이 파일을 확인할 수 없습니다.",
|
||||
"s2612": "폴더에 완전한 GGUF 파일이 있는지 확인한 뒤 다시 시도하세요.",
|
||||
"s2613": "생각 예산",
|
||||
"s2614": "제한 없음"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "Verifique se o mecanismo está conectado e este modelo está instalado. Depois, tente novamente.",
|
||||
"s2568": "Executado",
|
||||
"s2569": "Não permitido neste modo. Nada foi executado.",
|
||||
"s2570": "Repetir prévia"
|
||||
"s2570": "Repetir prévia",
|
||||
"s2571": "Faltam cerca de {0} min",
|
||||
"s2572": "Faltam cerca de {0} h {1} min",
|
||||
"s2573": "Faltam cerca de {0} h",
|
||||
"s2574": "Por padrão, segue a configuração do seu computador.",
|
||||
"s2575": "A leitura de imagens não está disponível para este modelo.",
|
||||
"s2576": "Desative a leitura de imagens e tente novamente.",
|
||||
"s2577": "O modelo parou ao iniciar, provavelmente porque o computador ficou sem memória.",
|
||||
"s2578": "Feche outros programas e tente novamente, ou escolha “Deixar 20% para o meu trabalho”. No modo especialista, você também pode ativar a opção de pouca RAM, para que parte do modelo seja lida do SSD.",
|
||||
"s2579": "O carregamento está levando tempo demais.",
|
||||
"s2580": "O computador pode estar com pouca memória. Feche outros programas e tente novamente.",
|
||||
"s2581": "O motor do Strata para este computador ainda não está instalado.",
|
||||
"s2582": "Ele é adicionado ao baixar um modelo. Baixe seu modelo novamente para adicioná-lo.",
|
||||
"s2583": "O download não conseguiu acessar a internet.",
|
||||
"s2584": "Verifique sua conexão e pressione “Retomar download”.",
|
||||
"s2585": "Um arquivo baixado não passou na verificação de segurança do Strata.",
|
||||
"s2586": "Pressione “Retomar download” e o Strata o baixará novamente.",
|
||||
"s2587": "O assistente de programação ainda não está instalado neste computador.",
|
||||
"s2588": "O chat funciona sem ele.",
|
||||
"s2589": "O Strata não conseguiu ler seus próprios componentes.",
|
||||
"s2590": "Feche e abra o Strata novamente. Se o problema continuar, reinstale o aplicativo.",
|
||||
"s2591": "Algo deu errado.",
|
||||
"s2592": "Tente novamente. Se o problema continuar, abra “Detalhes” e compartilhe-os ao pedir ajuda.",
|
||||
"s2593": "Verificando seu computador…",
|
||||
"s2594": "Preparando tudo…",
|
||||
"s2595": "Baixando seu modelo…",
|
||||
"s2596": "Preparando seu modelo para o Strata…",
|
||||
"s2597": "Atualizar componente",
|
||||
"s2598": "Atualiza o motor deste computador. Seus modelos e configurações são mantidos.",
|
||||
"s2599": "Salvo em {0}",
|
||||
"s2600": "Já tem um modelo compatível neste computador? Escolha a pasta com os arquivos dele. O Strata os verifica, prepara o modelo e o carrega. Nada é copiado ou baixado.",
|
||||
"s2601": "Pasta com os arquivos GGUF",
|
||||
"s2602": "Caminho completo da pasta",
|
||||
"s2603": "Verificar arquivos",
|
||||
"s2604": "Modelo encontrado",
|
||||
"s2605": "{0} arquivos · {1}",
|
||||
"s2606": "Preparar e carregar",
|
||||
"s2607": "Faltam partes deste modelo, ou a pasta contém mais de um modelo.",
|
||||
"s2608": "Coloque todas as partes de um modelo em uma pasta e verifique de novo.",
|
||||
"s2609": "O Strata ainda não consegue executar esses arquivos.",
|
||||
"s2610": "O Strata executa os modelos Qwen3.8-Flash-Next. Baixe um em Modelos ou escolha uma pasta com os arquivos dele.",
|
||||
"s2611": "Não foi possível verificar esses arquivos.",
|
||||
"s2612": "Verifique se a pasta tem arquivos GGUF completos e tente novamente.",
|
||||
"s2613": "Orçamento de raciocínio",
|
||||
"s2614": "Sem limite"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "Убедитесь, что движок подключён и эта модель установлена, затем повторите попытку.",
|
||||
"s2568": "Выполнено",
|
||||
"s2569": "В этом режиме не разрешено. Ничего не запущено.",
|
||||
"s2570": "Повторить просмотр"
|
||||
"s2570": "Повторить просмотр",
|
||||
"s2571": "Осталось около {0} мин",
|
||||
"s2572": "Осталось около {0} ч {1} мин",
|
||||
"s2573": "Осталось около {0} ч",
|
||||
"s2574": "По умолчанию используется настройка вашего компьютера.",
|
||||
"s2575": "Чтение изображений недоступно для этой модели.",
|
||||
"s2576": "Отключите чтение изображений и повторите попытку.",
|
||||
"s2577": "Модель остановилась при запуске, скорее всего из-за нехватки памяти на компьютере.",
|
||||
"s2578": "Закройте другие программы и повторите попытку или выберите «Оставить 20% для моей работы». В режиме эксперта можно также включить режим малого объёма ОЗУ: часть модели будет читаться с SSD.",
|
||||
"s2579": "Загрузка занимает слишком много времени.",
|
||||
"s2580": "Возможно, на компьютере не хватает памяти. Закройте другие программы и повторите попытку.",
|
||||
"s2581": "Движок Strata для этого компьютера ещё не установлен.",
|
||||
"s2582": "Он добавляется при загрузке модели. Загрузите модель ещё раз, чтобы добавить его.",
|
||||
"s2583": "Не удалось подключиться к интернету для загрузки.",
|
||||
"s2584": "Проверьте подключение и нажмите «Возобновить загрузку».",
|
||||
"s2585": "Загруженный файл не прошёл проверку безопасности Strata.",
|
||||
"s2586": "Нажмите «Возобновить загрузку», и Strata загрузит файл заново.",
|
||||
"s2587": "Помощник по программированию ещё не установлен на этом компьютере.",
|
||||
"s2588": "Чат работает и без него.",
|
||||
"s2589": "Strata не удалось прочитать собственные компоненты.",
|
||||
"s2590": "Закройте и снова откройте Strata. Если проблема повторяется, переустановите приложение.",
|
||||
"s2591": "Что-то пошло не так.",
|
||||
"s2592": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью.",
|
||||
"s2593": "Проверяем ваш компьютер…",
|
||||
"s2594": "Подготовка…",
|
||||
"s2595": "Загружаем вашу модель…",
|
||||
"s2596": "Готовим вашу модель для Strata…",
|
||||
"s2597": "Обновить компонент",
|
||||
"s2598": "Обновляет движок для этого компьютера. Ваши модели и настройки сохраняются.",
|
||||
"s2599": "Сохранено в {0}",
|
||||
"s2600": "Уже есть поддерживаемая модель на этом компьютере? Выберите папку с её файлами. Strata проверит их, подготовит модель и загрузит её. Ничего не копируется и не скачивается.",
|
||||
"s2601": "Папка с файлами GGUF",
|
||||
"s2602": "Полный путь к папке",
|
||||
"s2603": "Проверить файлы",
|
||||
"s2604": "Модель найдена",
|
||||
"s2605": "Файлов: {0} · {1}",
|
||||
"s2606": "Подготовить и загрузить",
|
||||
"s2607": "Не хватает частей этой модели, либо в папке больше одной модели.",
|
||||
"s2608": "Положите все части одной модели в одну папку и проверьте снова.",
|
||||
"s2609": "Strata пока не может запустить эти файлы.",
|
||||
"s2610": "Strata запускает модели Qwen3.8-Flash-Next. Скачайте одну в разделе «Модели» или выберите папку с её файлами.",
|
||||
"s2611": "Не удалось проверить эти файлы.",
|
||||
"s2612": "Убедитесь, что в папке полные файлы GGUF, и повторите попытку.",
|
||||
"s2613": "Лимит размышлений",
|
||||
"s2614": "Без ограничений"
|
||||
}
|
||||
@@ -2568,5 +2568,49 @@
|
||||
"s2567": "请确认引擎已连接且此模型已安装,然后重试。",
|
||||
"s2568": "已运行",
|
||||
"s2569": "此模式下不允许,未执行任何操作。",
|
||||
"s2570": "重播预览"
|
||||
"s2570": "重播预览",
|
||||
"s2571": "大约还需 {0} 分钟",
|
||||
"s2572": "大约还需 {0} 小时 {1} 分钟",
|
||||
"s2573": "大约还需 {0} 小时",
|
||||
"s2574": "默认跟随你的电脑设置。",
|
||||
"s2575": "此模型暂不支持读取图片。",
|
||||
"s2576": "请关闭图片读取后重试。",
|
||||
"s2577": "模型在启动时停止了,很可能是因为电脑内存不足。",
|
||||
"s2578": "请关闭其他程序后重试,或选择“为我的工作留出 20%”。在专家模式中,你还可以开启低内存选项,让模型的一部分从固态硬盘读取。",
|
||||
"s2579": "加载时间过长。",
|
||||
"s2580": "电脑内存可能不足。请关闭其他程序后重试。",
|
||||
"s2581": "这台电脑还没有安装 Strata 引擎。",
|
||||
"s2582": "下载模型时会一并添加。请重新下载你的模型来添加它。",
|
||||
"s2583": "下载无法连接到互联网。",
|
||||
"s2584": "请检查网络连接,然后点击“继续下载”。",
|
||||
"s2585": "有一个下载的文件未通过 Strata 的安全检查。",
|
||||
"s2586": "点击“继续下载”,Strata 会重新获取该文件。",
|
||||
"s2587": "这台电脑还没有安装编程助手。",
|
||||
"s2588": "没有它也可以正常聊天。",
|
||||
"s2589": "Strata 无法读取自身的组件。",
|
||||
"s2590": "请关闭并重新打开 Strata。如果问题持续出现,请重新安装该应用。",
|
||||
"s2591": "出了点问题。",
|
||||
"s2592": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。",
|
||||
"s2593": "正在检查你的电脑…",
|
||||
"s2594": "正在做准备…",
|
||||
"s2595": "正在下载你的模型…",
|
||||
"s2596": "正在为 Strata 准备你的模型…",
|
||||
"s2597": "更新组件",
|
||||
"s2598": "更新这台电脑的引擎。你的模型和设置会保留。",
|
||||
"s2599": "已保存到 {0}",
|
||||
"s2600": "这台电脑上已经有受支持的模型了吗?请选择存放其文件的文件夹。Strata 会检查文件、准备模型并加载它,不会复制或下载任何内容。",
|
||||
"s2601": "存放 GGUF 文件的文件夹",
|
||||
"s2602": "文件夹的完整路径",
|
||||
"s2603": "检查文件",
|
||||
"s2604": "找到模型",
|
||||
"s2605": "{0} 个文件 · {1}",
|
||||
"s2606": "准备并加载",
|
||||
"s2607": "此模型缺少部分文件,或该文件夹里有多个模型。",
|
||||
"s2608": "请把同一个模型的所有文件放在一个文件夹里,然后重新检查。",
|
||||
"s2609": "Strata 暂时无法运行这些文件。",
|
||||
"s2610": "Strata 运行 Qwen3.8-Flash-Next 模型。请在“模型”中下载其中一个,或选择存放其文件的文件夹。",
|
||||
"s2611": "无法检查这些文件。",
|
||||
"s2612": "请确认文件夹里是完整的 GGUF 文件,然后重试。",
|
||||
"s2613": "思考预算",
|
||||
"s2614": "不限制"
|
||||
}
|
||||
@@ -566,7 +566,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
|
||||
|
||||
<div className="st-bubble">
|
||||
{tr(m.error ? (<ErrorNotice message={m.error} next={tr("Try sending the message again.")}/>) : null)}
|
||||
{tr(m.content ? (<Markdown text={m.timeSkipId ? timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error ? (<span className="typing" aria-label={tr("Generating")}>
|
||||
{tr(m.content ? (<Markdown text={m.timeSkipId ? timeSkipDone ? tr('The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.') : tr('Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.') : m.content} onOpenLink={onOpenLink} onPreviewHtml={content => onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming ? (<span className="typing" aria-label={tr("Generating")}>
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
|
||||
@@ -23,6 +23,7 @@ import { applyImageModel, getState, lifecycleStatus, loadRuntimeModel, loadVaria
|
||||
import type { ImageModelChoice, RuntimeModels, RuntimeModel } from '../lib/types';
|
||||
import { useNative } from '../lib/native';
|
||||
import { NativeModels } from '../components/NativeModels';
|
||||
import { NativeLocalModel } from '../components/NativeLocalModel';
|
||||
import { parseLocation } from '../lib/router';
|
||||
type Issue = {
|
||||
level: 'error' | 'warn';
|
||||
@@ -33,6 +34,8 @@ export function ModelRunScreen() {
|
||||
const native = useNative();
|
||||
const location = parseLocation(window.location.hash), entry = location.param;
|
||||
const [other, setOther] = useState(entry === 'local' || entry === 'local-import'), [importFirst, setImportFirst] = useState(entry === 'local-import');
|
||||
if (native && other)
|
||||
return <NativeLocalModel onBack={() => { setOther(false); setImportFirst(false); }}/>;
|
||||
if (native && !other)
|
||||
return <NativeModels onOtherModels={() => setOther(true)} onImport={() => { setImportFirst(true); setOther(true); }}/>;
|
||||
return <><LegacyModelRunScreen importFirst={importFirst} initialVariant={location.query.get('variant') ?? undefined}/>{tr(other ? <button className="st-btn native-return" onClick={() => setOther(false)}>{tr("Strata optimized models")}</button> : null)}</>;
|
||||
|
||||
@@ -15,7 +15,7 @@ import { gpuCapacity, gpuId, gpuMetric, hasReading } from '../lib/monitor-hardwa
|
||||
import { useStore } from '../lib/store';
|
||||
import type { Hardware, MonitorState, ServeRequest } from '../lib/types';
|
||||
import { useNative, nativeRouting, type NativeState } from '../lib/native';
|
||||
import { nativeMonitorData } from '../lib/native-monitor';
|
||||
import { nativeMonitorData, withHostSensors } from '../lib/native-monitor';
|
||||
const number = (value: number | null | undefined, digits = 0) => hasReading(value) ? value.toLocaleString(localeTag(), { maximumFractionDigits: digits, minimumFractionDigits: digits }) : '—';
|
||||
const percent = (used: number | null | undefined, total: number | null | undefined) => hasReading(used) && hasReading(total) && total > 0 ? Math.max(0, Math.min(100, used / total * 100)) : null;
|
||||
const sourceLabel = (source: string | undefined) => source === 'demo' ? 'Illustrative' : source === 'sensor' || source === 'engine' || source === 'reported' ? 'Measured' : source === 'estimated' ? 'Estimated' : 'Unavailable';
|
||||
@@ -65,7 +65,7 @@ function LegacyMonitorScreen({ native }: {
|
||||
const [instanceSelection, setInstanceSelection] = useState('all');
|
||||
const routing = native ? nativeRouting(native, inventory) : null;
|
||||
const runtime = routing && native ? { ...routing, instances: routing.instances.map(instance => { const raw = native.instances.find(item => item.id === instance.id)?.metrics?.live; return { ...instance, outputTps: raw?.tok_s ?? NaN, promptTps: raw?.prefill_tok_s_mean ?? NaN, active: raw ? (raw.running ?? (['reading', 'generating'].includes(raw.state) ? 1 : 0)) : NaN, queued: raw?.queued ?? NaN }; }) } : storedRuntime;
|
||||
const live = native ? nativeMonitorData(native, inventory, instanceSelection) : storedLive;
|
||||
const live = native ? withHostSensors(nativeMonitorData(native, inventory, instanceSelection), storedLive) : storedLive;
|
||||
const multipleModels = (runtime?.instances.length ?? 0) > 1;
|
||||
const selectedInstance = runtime?.instances.find(i => i.id === instanceSelection) ?? (!multipleModels ? runtime?.instances[0] : undefined);
|
||||
const selection = selectedInstance?.id ?? 'all';
|
||||
@@ -103,7 +103,8 @@ function LegacyMonitorScreen({ native }: {
|
||||
const data = frozen?.data ?? scoped, hardware = frozen?.hardware ?? inventory;
|
||||
if (!data)
|
||||
return <Screen title={tr("Monitor")}><p className="muted">{tr("Waiting for engine telemetry\u2026")}</p></Screen>;
|
||||
const devices = hardware?.gpus ?? [], processors = hardware?.processors?.length ? hardware.processors : hardware ? [{ ...hardware.cpu, id: 'cpu', socket: '' }] : [];
|
||||
// A display adapter that has no sensors and no memory of its own (an integrated one) cannot be measured; counting it would blank every total.
|
||||
const devices = (hardware?.gpus ?? []).filter(g => g.backend !== 'vulkan' || g.vramGb > 0), processors = hardware?.processors?.length ? hardware.processors : hardware ? [{ ...hardware.cpu, id: 'cpu', socket: '' }] : [];
|
||||
const gpuChoice = gpuSelection === 'assigned' && selectedInstance ? 'assigned' : devices.some(g => gpuId(g) === gpuSelection) ? gpuSelection : 'all';
|
||||
const cpuChoice = processors.some(p => p.id === cpuSelection) ? cpuSelection : 'all';
|
||||
const selectedGpus = gpuChoice === 'assigned' ? devices.filter(g => selectedInstance?.gpuIds.includes(gpuId(g))) : gpuChoice === 'all' ? devices : devices.filter(g => gpuId(g) === gpuChoice);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { NativeOperations } from '../components/NativeOperations';
|
||||
import { FontChoice } from '../components/FontChoice';
|
||||
import { LANGUAGES } from '../lib/i18n';
|
||||
import { setLanguage } from '../lib/store';
|
||||
import { CONTENT_FONT_RANGE, go, setContentFontSize, setContrast, setDensity, setFocus, setMotion, setShortcuts, setTheme, setTransparency, setUiScale, UI_SCALES, useStore, setSettingsSection } from '../lib/store';
|
||||
import { CONTENT_FONT_RANGE, setContentFontSize, setDensity, setFocus, setMotion, setShortcuts, setTheme, setTransparency, setUiScale, UI_SCALES, useStore, setSettingsSection } from '../lib/store';
|
||||
const PANELS = [{ name: 'Appearance', icon: 'sun', sections: ['General', 'Reading & focus'] }, { name: 'Models', icon: 'models', sections: [] }, { name: 'Storage', icon: 'disk', sections: ['Storage'] }, { name: 'Engine', icon: 'engine', sections: [] }, { name: 'About', icon: 'info', sections: ['About', 'Update', 'Privacy'] }] as const;
|
||||
export function SettingsScreen() {
|
||||
const prefs = useStore(s => s);
|
||||
@@ -26,15 +26,14 @@ export function SettingsScreen() {
|
||||
{ section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: <Select translateLabels={false} ariaLabel={tr("Language")} value={prefs.language} options={[...LANGUAGES]} onChange={value => setLanguage(value as typeof prefs.language)}/> },
|
||||
{ section: 'Reading & focus', label: 'Font', hint: 'Choose an installed font for the interface and conversations.', control: <FontChoice /> },
|
||||
{ section: 'General', label: 'Keyboard shortcuts', hint: 'Set the key combinations that feel natural to you.', aliases: 'command keys hotkeys', control: <Btn size="sm" onClick={() => setShortcuts(true)}>{tr("Edit shortcuts")}</Btn> },
|
||||
{ section: 'Reading & focus', label: 'Appearance', hint: 'Light is the default. System follows your computer.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> },
|
||||
{ section: 'Reading & focus', label: 'Appearance', hint: 'System follows your computer by default.', aliases: 'theme light dark system automatic', control: <Select value={prefs.theme} ariaLabel={tr("Appearance")} options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }, { value: 'system', label: 'System' }]} onChange={setTheme}/> },
|
||||
{ section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: <label className="row"><input aria-label={tr("Reading text size")} type="range" className="st-slider" min={CONTENT_FONT_RANGE.min} max={CONTENT_FONT_RANGE.max} value={prefs.contentFontSize} onChange={e => setContentFontSize(Number(e.target.value))}/><output>{tr(prefs.contentFontSize)}{tr(" px")}</output></label> },
|
||||
{ section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: <Select value={String(prefs.uiScale)} ariaLabel={tr("Interface size")} options={UI_SCALES.map(v => ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> },
|
||||
{ section: 'Reading & focus', label: 'Spacing', hint: 'Comfortable spacing by default.', aliases: 'density comfortable compact', control: <Select value={prefs.density} ariaLabel={tr("Interface spacing")} options={[{ value: 'comfortable', label: 'Comfortable' }, { value: 'compact', label: 'Compact' }]} onChange={setDensity}/> },
|
||||
{ section: 'Reading & focus', label: 'Motion', hint: 'Reduced motion also disables smooth scrolling.', aliases: 'animation system full reduced', control: <Select value={prefs.motion} ariaLabel={tr("Motion")} options={[{ value: 'system', label: 'Follow system' }, { value: 'full', label: 'Full' }, { value: 'reduced', label: 'Reduced' }]} onChange={setMotion}/> },
|
||||
{ section: 'Reading & focus', label: 'Transparency', hint: 'Translucent controls or solid surfaces. Text stays opaque.', aliases: 'blur glass liquid opaque translucent', control: <Select value={prefs.transparency} ariaLabel={tr("Transparency")} options={[{ value: 'translucent', label: 'Translucent' }, { value: 'opaque', label: 'Opaque' }]} onChange={setTransparency}/> },
|
||||
{ section: 'Reading & focus', label: 'Contrast', hint: 'Increase text and boundary contrast.', aliases: 'accessibility standard increased', control: <Select value={prefs.contrast} ariaLabel={tr("Contrast")} options={[{ value: 'standard', label: 'Standard / system' }, { value: 'increased', label: 'Increased' }]} onChange={setContrast}/> },
|
||||
{ section: 'Reading & focus', label: 'Focus reading', hint: 'Hides navigation in chat. Settings stays open above the conversation.', aliases: 'distraction quiet', control: <button className="st-toggle" role="switch" aria-checked={prefs.focus} aria-label={tr("Focus reading")} onClick={() => setFocus(!prefs.focus)}/> },
|
||||
{ section: 'Privacy', label: 'Collection and logs', hint: 'Strata sends no usage telemetry. Conversations stay in browser storage. When you choose an API model, that conversation and enabled skill instructions are sent to its provider. The UI request log keeps client, timing and token metadata in memory. Native API monitoring can retain request content in memory when enabled. Connected tools access the resources you configure.', aliases: 'telemetry reporting tracking privacy logging requests', control: <Btn size="sm" onClick={() => go('serving')}>{tr("View request log")}</Btn> },
|
||||
{ section: 'Privacy', label: 'Collection and logs', hint: 'Strata sends no usage telemetry. Conversations stay in browser storage. When you choose an API model, that conversation and enabled skill instructions are sent to its provider. The UI request log keeps client, timing and token metadata in memory. Native API monitoring can retain request content in memory when enabled. Connected tools access the resources you configure.', aliases: 'telemetry reporting tracking privacy logging requests', control: null },
|
||||
];
|
||||
function activate(name: typeof PANELS[number]['name']) {
|
||||
setSettingsSection(name);
|
||||
|
||||
@@ -715,3 +715,15 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; }
|
||||
.native-image-reading input[type=checkbox]:checked:after,.native-gpu-options input[type=checkbox]:checked:after{opacity:1}
|
||||
.native-image-reading input[type=checkbox]:focus-visible,.native-gpu-options input[type=checkbox]:focus-visible{outline:2px solid var(--st-accent);outline-offset:3px}
|
||||
.native-image-reading input[type=checkbox]:disabled,.native-gpu-options input[type=checkbox]:disabled{opacity:.5;cursor:default}
|
||||
/* Manage models: the downloaded models as a short list. Same surface, line and pill tokens as the settings version rows. */
|
||||
.native-manage { display:grid; gap:16px; min-width:min(560px,100%); }
|
||||
.native-manage-list { display:grid; gap:10px; }
|
||||
.native-manage-row { display:grid; grid-template-columns:minmax(0,1fr) auto auto; align-items:center; gap:14px; padding:14px 16px; border:1px solid var(--st-line); border-radius:var(--st-r-md,12px); background:var(--st-surface); }
|
||||
.native-manage-row[data-selected] { border-color:var(--st-accent); background:var(--st-accent-surface); }
|
||||
.native-manage-name { display:grid; gap:2px; min-width:0; }
|
||||
.native-manage-name strong { font-size:var(--st-fs-md); overflow-wrap:anywhere; }
|
||||
.native-manage-name small { color:var(--st-ink-muted); font-size:var(--st-fs-sm); }
|
||||
.native-manage-actions { display:flex; gap:8px; }
|
||||
.native-manage-empty { padding:24px 8px; text-align:center; }
|
||||
.native-manage-foot { padding-top:12px; border-top:1px solid var(--st-line-soft); }
|
||||
@media(max-width:600px){ .native-manage-row { grid-template-columns:1fr; } }
|
||||
@@ -452,11 +452,11 @@
|
||||
the text size — a fixed px allowance drifts at the extremes. */
|
||||
.app[data-focus='true'] .slashmenu,
|
||||
.app[data-focus='true'] .chat__inner {
|
||||
font-size: var(--st-content-fs, 16px);
|
||||
font-size: var(--st-content-fs, 14px);
|
||||
max-width: calc(var(--st-measure) + 2.5em);
|
||||
}
|
||||
.app[data-focus='true'] .composer__inner {
|
||||
font-size: var(--st-content-fs, 16px);
|
||||
font-size: var(--st-content-fs, 14px);
|
||||
/* the same column, less the transcript's 28px padding on each side */
|
||||
max-width: calc(var(--st-measure) + 2.5em - 56px);
|
||||
}
|
||||
@@ -474,8 +474,8 @@
|
||||
— the same scoping DSH uses for its 10–22px content setting. */
|
||||
.st-msg--assistant .st-bubble,
|
||||
.st-msg--user .st-bubble {
|
||||
font-size: var(--st-content-fs, 16px);
|
||||
line-height: calc(var(--st-content-fs, 16px) * 1.62);
|
||||
font-size: var(--st-content-fs, 14px);
|
||||
line-height: calc(var(--st-content-fs, 14px) * 1.62);
|
||||
}
|
||||
|
||||
/* Density — the difference between scanning data and reading it. */
|
||||
@@ -3902,9 +3902,10 @@ textarea.st-input {
|
||||
composer, and only while there is something below the fold worth reaching. */
|
||||
.jumplatest {
|
||||
position: sticky;
|
||||
bottom: 12px;
|
||||
bottom: 16px;
|
||||
z-index: 3;
|
||||
margin: 0 auto;
|
||||
/* clear of the navigation above it where it sits at the top of the transcript, and of the messages beside it */
|
||||
margin: 14px auto 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
@@ -6993,3 +6994,18 @@ textarea {
|
||||
white-space: normal;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* The reading size reaches everything in a conversation, not only paragraphs: headings, inline code, tables, code blocks and the
|
||||
model's reasoning keep their usual proportion (18px, 13px, 13px at the 16px default) at any size. */
|
||||
.st-bubble h2, .st-bubble h3, .st-bubble h4 { font-size: 1.125em; }
|
||||
.st-bubble .md-code { font-size: .8125em; }
|
||||
.st-bubble .md-table { font-size: calc(var(--st-content-fs, 14px) * .8125); }
|
||||
.st-bubble .md-table th, .st-bubble .md-table td { font-size: inherit; }
|
||||
.st-bubble .st-code pre, .st-bubble .st-code pre code, .st-bubble .st-code .syntax-text { font-size: calc(var(--st-content-fs, 14px) * .8125); }
|
||||
.st-msg--assistant .st-collapse__body { font-size: calc(var(--st-content-fs, 14px) * .8125); }
|
||||
.error-notice .error-detail { margin-top: 6px; }
|
||||
.error-notice .error-detail pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); }
|
||||
.error-detail-text { white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0 0; font-family: var(--st-font-mono); }
|
||||
/* What you type and the small print under each message follow the reading size too, so the whole conversation changes together. */
|
||||
.st-composer textarea { font-size: var(--st-content-fs, 14px); }
|
||||
.st-msg__meta, .st-msg__meta time { font-size: calc(var(--st-content-fs, 14px) * .8125); }
|
||||
@@ -241,3 +241,5 @@
|
||||
@keyframes onboard-sharing-app{0%,100%{transform:translateY(0)}50%{transform:translateY(-3px)}}
|
||||
@keyframes onboard-sharing-flow{to{transform:translateX(100%)}}
|
||||
@media(max-width:700px){.onboard-sharing{grid-template-columns:1fr;gap:20px;padding:22px}.onboard-sharing-computer{width:min(300px,100%);justify-self:center}.onboard-sharing-caption{font-size:14px}.onboard-sharing-numbers{justify-content:space-between;gap:20px}.onboard-sharing-headroom{padding-left:20px}.guided-onboarding .onboard-resource-options>button{padding:16px;grid-template-columns:1fr;gap:7px}.guided-onboarding .onboard-resource-options small{grid-column:1;grid-row:4;justify-self:start}.guided-onboarding .onboard-resource-options strong{font-size:13px}.guided-onboarding .onboard-resource-options p{font-size:11px}.guided-onboarding .onboard-load-vision,.guided-onboarding .onboard-calibration{padding:14px}.guided-onboarding .onboard-load-vision strong,.guided-onboarding .onboard-calibration strong{font-size:12px}}
|
||||
.onboard-progress-actions{display:flex;align-items:center;gap:10px}
|
||||
.onboard-tune-stage:has(.error-notice) .onboard-sharing{display:none}
|
||||
@@ -26,7 +26,7 @@ const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
async function startHost(t, { home, ws, harness = HARNESS } = {}) {
|
||||
const port = await freePort();
|
||||
const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0' };
|
||||
const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), STRATA_WORKSPACE: ws, STRATA_REAL_ENGINE: '0', STRATA_COMPONENTS_DIR: join(home, 'components') };
|
||||
if (harness) env.STRATA_HARNESS_DIR = harness; else delete env.STRATA_HARNESS_DIR;
|
||||
const child = spawn(process.execPath, [HOST], { env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
||||
let log = '';
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const built = await build({ stdin: { contents: "export * from './src/lib/download-eta';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' }, external: ['react'] });
|
||||
const src = built.outputFiles[0].text.replace(/from\s*["']react["']/, 'from "data:text/javascript,export const useRef=()=>({current:null}),useEffect=()=>{},useState=v=>[v,()=>{}]"');
|
||||
const { etaMinutes, etaLabel, installProgress } = await import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
|
||||
|
||||
test('the time left comes from the recent rate, and says nothing until there is one', () => {
|
||||
assert.equal(etaMinutes([{ at: 0, done: 1 }], 50), null);
|
||||
assert.equal(etaMinutes([{ at: 0, done: 1 }, { at: 5000, done: 3 }], 50), null, 'under ten seconds of samples');
|
||||
assert.equal(etaMinutes([{ at: 0, done: 1 }, { at: 20000, done: 1 }], 50), null, 'nothing moved');
|
||||
assert.equal(etaMinutes([{ at: 0, done: 0 }, { at: 20000, done: 10 }], 60), 2, '0.5 GB/s, 60 GB left: 120 s');
|
||||
assert.equal(etaMinutes([{ at: 0, done: 0 }, { at: 60000, done: 1 }], 0.1), 1, 'never below one minute');
|
||||
});
|
||||
|
||||
test('the label is minutes, and hours past an hour and a half', () => {
|
||||
assert.equal(etaLabel(null), '');
|
||||
assert.equal(etaLabel(3), 'About 3 min left');
|
||||
assert.equal(etaLabel(125), 'About 2 h 5 min left');
|
||||
assert.equal(etaLabel(120), 'About 2 h left');
|
||||
});
|
||||
|
||||
test('one count over all the parts of the job: the model files and, when there is one, the engine', () => {
|
||||
const model = { kind: 'model', done_gb: 30, total_gb: 60, state: 'downloading' };
|
||||
const engine = { kind: 'engine', done_gb: 0.3, total_gb: 0.7, state: 'downloading' };
|
||||
const both = installProgress({ parts: [model, engine], download: { done_gb: 0, total_gb: 1 } });
|
||||
assert.equal(both.total_gb, 60.7);
|
||||
assert.ok(Math.abs(both.done_gb - 30.3) < 1e-9);
|
||||
assert.equal(both.percent, 49);
|
||||
assert.ok(Math.abs(both.remaining_gb - 30.4) < 1e-9);
|
||||
const modelOnly = installProgress({ parts: [model] });
|
||||
assert.equal(modelOnly.total_gb, 60);
|
||||
assert.equal(installProgress({ parts: [model, { ...engine, state: 'skipped' }, { kind: 'engine', state: 'current', total_gb: 1, done_gb: 1 }] }).total_gb, 60, 'a part that is skipped or already current is not downloaded');
|
||||
// no parts: the job's own combined figures
|
||||
assert.deepEqual(installProgress({ download: { done_gb: 5, total_gb: 50, percent: 10 } }), { done_gb: 5, total_gb: 50, remaining_gb: 45, percent: 10, file: undefined });
|
||||
assert.equal(installProgress({}), undefined);
|
||||
assert.equal(installProgress(undefined), undefined);
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdtempSync,readFileSync,rmSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join,resolve} from 'node:path';
|
||||
import {createRequire} from 'node:module';
|
||||
import {build} from 'esbuild';
|
||||
|
||||
/* The installed app crashed on its first screen ("Cannot read properties of undefined (reading 'family')") when the
|
||||
catalog it was given had no `recommendation` and no families. Render the real GuidedSetup and NativeModels components
|
||||
(react-dom/server) with the state libraries replaced by fixed values, for every shape of an empty or failed catalog. */
|
||||
const root=resolve(import.meta.dirname,'..');
|
||||
/** Every export of the real module becomes a harmless no-op, except the few that carry the fixed state. */
|
||||
function stubFor(file,overrides){
|
||||
const source=readFileSync(resolve(root,'src/lib',file),'utf8');
|
||||
const names=new Set([...source.matchAll(/export\s+(?:async\s+)?(?:function\*?|const|let|var|class)\s+([A-Za-z_$][\w$]*)/g)].map(m=>m[1]));
|
||||
for(const m of source.matchAll(/export\s*\{([^}]*)\}/g))for(const part of m[1].split(','))names.add(part.split(/\s+as\s+/).pop().trim());
|
||||
names.delete('');
|
||||
const lines=[...names].filter(n=>!(n in overrides)).map(n=>`export const ${n}=(...a)=>Promise.resolve({});`);
|
||||
for(const [n,v] of Object.entries(overrides))lines.push(`export const ${n}=${v};`);
|
||||
return lines.join(String.fromCharCode(10));
|
||||
}
|
||||
const stubs={
|
||||
native:stubFor('native.ts',{useNative:'()=>globalThis.__native',nativeState:'()=>globalThis.__native'}),
|
||||
store:stubFor('store.ts',{useStore:'sel=>sel(globalThis.__store)'}),
|
||||
client:stubFor('client.ts',{}),
|
||||
router:stubFor('router.ts',{}),
|
||||
};
|
||||
|
||||
let dir,mod;
|
||||
async function load(){
|
||||
if(mod)return mod;
|
||||
dir=mkdtempSync(join(tmpdir(),'strata-gs-'));
|
||||
const stubPlugin={name:'stubs',setup(b){
|
||||
b.onResolve({filter:/\/lib\/(native|store|client|router)$/},args=>({path:args.path.split('/').pop(),namespace:'stub'}));
|
||||
b.onLoad({filter:/.*/,namespace:'stub'},args=>({contents:stubs[args.path],loader:'js',resolveDir:root}));
|
||||
}};
|
||||
const entry=join(dir,'entry.tsx');
|
||||
const out=join(dir,'out.cjs');
|
||||
await build({
|
||||
stdin:{contents:`export {GuidedSetup} from ${JSON.stringify(resolve(root,'src/components/GuidedSetup.tsx'))};
|
||||
export {NativeModels} from ${JSON.stringify(resolve(root,'src/components/NativeModels.tsx'))};
|
||||
export {renderToString} from 'react-dom/server'; export {createElement} from 'react';`,resolveDir:root,sourcefile:'entry.tsx',loader:'tsx'},
|
||||
bundle:true,format:'cjs',platform:'node',outfile:out,jsx:'automatic',logLevel:'silent',plugins:[stubPlugin],
|
||||
loader:{'.svg':'dataurl','.png':'dataurl','.css':'empty'},
|
||||
});
|
||||
globalThis.window??=globalThis;globalThis.matchMedia??=()=>({matches:false,addEventListener(){},removeEventListener(){}});
|
||||
mod=createRequire(import.meta.url)(out);
|
||||
return mod;
|
||||
}
|
||||
test.after(()=>{if(dir)rmSync(dir,{recursive:true,force:true});});
|
||||
|
||||
const store=(complete=false)=>({setup:{complete,choices:{},app:{modelsDir:''}},hardware:null});
|
||||
const base={available:true,repo:'',summary:'',error:null,installed:{models:[],data_folder:'',engine:{version:null}},hardware:null,instances:[],jobs:[],defaultId:null,fields:[],capabilities:{}};
|
||||
const catalogs={
|
||||
'no catalog at all':null,
|
||||
'the packaged host before it had a catalog':{families:[],sizes:[]},
|
||||
'no recommendation':{families:[],contexts:[32768]},
|
||||
'recommendation with nothing in it':{families:[],contexts:[],recommendation:{family:null,model:null}},
|
||||
'no families key':{contexts:[]},
|
||||
'a family without sizes':{families:[{family:'qwen',title:'Qwen3.8-Flash-Next',sizes:[]}],contexts:[32768]},
|
||||
};
|
||||
|
||||
for(const [name,catalog] of Object.entries(catalogs)){
|
||||
for(const component of ['GuidedSetup','NativeModels']){
|
||||
test(`${component} renders with ${name}`,async()=>{
|
||||
const m=await load();
|
||||
globalThis.__native={...base,catalog};globalThis.__store=store();
|
||||
let html;
|
||||
assert.doesNotThrow(()=>{html=m.renderToString(m.createElement(m[component]));});
|
||||
assert.equal(typeof html,'string');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('GuidedSetup lists the real catalog when it has one',async()=>{
|
||||
const m=await load();
|
||||
globalThis.__native={...base,catalog:{families:[{family:'qwen',title:'Qwen3.8-Flash-Next',about:'',images:true,experimental:false,sizes:[
|
||||
{id:'iq3_xxs',model:'IQ3_XXS',download_gb:75.8,ram_gb:60,about:'',on_this_pc:'fits',installed:false}]}],contexts:[32768],
|
||||
recommendation:{family:'qwen',model:'IQ3_XXS',context:32768},context_note:''}};
|
||||
globalThis.__store={...store(),setup:{complete:false,choices:{onboarding:{step:2,manual:false}},app:{modelsDir:''}}};
|
||||
const html=m.renderToString(m.createElement(m.GuidedSetup));
|
||||
assert.match(html,/IQ3_XXS/);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const built = await build({ stdin: { contents: "export * from './src/lib/native-monitor';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
|
||||
const { withHostSensors } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
const none = { id: 'GPU-1', utilizationPct: null, temperatureC: null, memoryUsedGb: null, powerW: null, powerLimitW: null, pcieRxMbs: null };
|
||||
const live = { hardware: { gpus: [none], gpuLoad: NaN, vramUsedGb: NaN, vramTotalGb: 11.9, gpuTempC: NaN, powerW: NaN, powerLimitW: NaN, pcieRxMbs: NaN, cpuLoad: 20 } };
|
||||
const host = { hardware: { gpus: [{ id: 'GPU-1', utilizationPct: 7, temperatureC: 41, memoryUsedGb: 0.9, powerW: 22, powerLimitW: 250, pcieRxMbs: 3 }], gpuLoad: 7, vramUsedGb: 0.9, vramTotalGb: 11.9, gpuTempC: 41, powerW: 22, powerLimitW: 250, pcieRxMbs: 3 } };
|
||||
|
||||
test('with no model loaded the GPU temperature, load, VRAM, power and PCIe come from the host sensors', () => {
|
||||
const out = withHostSensors(live, host);
|
||||
assert.equal(out.hardware.gpus[0].temperatureC, 41);
|
||||
assert.equal(out.hardware.gpus[0].memoryUsedGb, 0.9);
|
||||
assert.equal(out.hardware.gpuLoad, 7);
|
||||
assert.equal(out.hardware.powerW, 22);
|
||||
assert.equal(out.hardware.pcieRxMbs, 3);
|
||||
assert.equal(out.hardware.cpuLoad, 20, 'what the engine reported is kept');
|
||||
});
|
||||
|
||||
test('what a running engine reports wins over the host sensors', () => {
|
||||
const running = { hardware: { ...live.hardware, gpus: [{ ...none, temperatureC: 55, utilizationPct: 90 }], gpuTempC: 55, gpuLoad: 90 } };
|
||||
const out = withHostSensors(running, host);
|
||||
assert.equal(out.hardware.gpus[0].temperatureC, 55);
|
||||
assert.equal(out.hardware.gpuLoad, 90);
|
||||
});
|
||||
|
||||
test('no host monitor, no change', () => {
|
||||
assert.equal(withHostSensors(live, null), live);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
|
||||
import { join, basename } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
@@ -95,8 +96,10 @@ function packagedFixture({ engineUsable = true } = {}) {
|
||||
});
|
||||
const calls = [];
|
||||
const spawned = [];
|
||||
const rpc = [];
|
||||
let startFailure = null;
|
||||
const control = {
|
||||
control: { dir: join(root, 'control') }, version: '0.1.45',
|
||||
control: { dir: join(root, 'control'), python: join(root, 'control', 'python', 'python.exe') }, version: '0.1.45',
|
||||
async installedModels(options) { calls.push(['installedModels', options?.installDir ?? null]); return { install_dir: install, models: configs.map(c => ({ id: c.id, name: `Qwen ${c.id}`, source_config: c.path, component_status: 'present', context_tokens: 32768, backend: 'cuda' })) }; },
|
||||
async engine() {
|
||||
calls.push(['engine']);
|
||||
@@ -104,14 +107,45 @@ function packagedFixture({ engineUsable = true } = {}) {
|
||||
? { usable: true, backend: 'cuda', components_dir: 'E:\\c', engine: { version: '0.1.45', platform: 'windows-x86_64', backend: 'cuda', exe: 'E:\\engine\\strata.exe', root: 'E:\\engine' } }
|
||||
: { usable: false, notice: 'No engine for this PC was found in E:\\c: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', backend: 'cuda', engine: null, components_dir: 'E:\\c' };
|
||||
},
|
||||
async importPlan(path) { calls.push(['importPlan', path]); return { file_set_status: 'plausible', candidate_selection: { family: 'qwen', model: 'IQ3_S' }, file_count: 2, total_bytes: 1e9, issues: [] }; },
|
||||
async saveProfile(name, path) { calls.push(['saveProfile', name, basename(path)]); return {}; },
|
||||
async start(name, options) { calls.push(['start', name, options?.waitSeconds]); return { ok: true, state: 'ready' }; },
|
||||
async start(name, options) { calls.push(['start', name, options?.waitSeconds]); if (startFailure) { const e = new Error(startFailure.message); e.output = startFailure.output; throw e; } return { ok: true, state: 'ready' }; },
|
||||
async stop(name) { calls.push(['stop', name]); return { ok: true, state: 'stopped' }; },
|
||||
};
|
||||
const requests = [];
|
||||
const fetcher = async url => { calls.push(['fetch', url.replace(/:\d+/, ':PORT')]); return Response.json({ status: 'ok' }); };
|
||||
const native = createNativeControl({ control, directory: data, spawnProcess: (...args) => { spawned.push(args); throw new Error('no process may be started by the host in packaged mode'); }, fetcher, requests: () => requests });
|
||||
return { native, calls, spawned, install, root, cleanup: () => { rmSync(root, { recursive: true, force: true }); } };
|
||||
// The only process the host may start is Control's installer (its bundled tools/strata_mcp.py on Control's Python); the fake
|
||||
// answers like it: the catalog, the hardware with the GPUs, and an install plan or job.
|
||||
const catalog = { families: [{ family: 'qwen', title: 'Qwen3.8-Flash-Next', about: 'x', images: true, experimental: false, sizes: [
|
||||
{ id: 'q2_0', model: 'Q2_0', download_gb: 66.4, ram_needed_gb: 48, about: 'fast', on_this_pc: 'fits', installed: false, images: true, experimental: false },
|
||||
{ id: 'iq3_xxs', model: 'IQ3_XXS', download_gb: 75.8, ram_needed_gb: 60, about: 'balanced', on_this_pc: 'fits', installed: false, images: true, experimental: false }] }],
|
||||
contexts: [8192, 32768], recommendation: { family: 'qwen', model: 'IQ3_XXS', context: 32768 }, context_note: '' };
|
||||
const hardware = { ram_gb: 63, cpu: { name: 'cpu', cores: 12 }, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9, usable: true }] };
|
||||
let installJob = null;
|
||||
const spawnProcess = (command, args, options) => {
|
||||
spawned.push({ command, args, options });
|
||||
if (!String(args[0]).endsWith('strata_mcp.py')) throw new Error('no process but the installer may be started by the host in packaged mode: ' + command + ' ' + args.join(' '));
|
||||
const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.exitCode = null;
|
||||
child.kill = () => { child.exitCode = 0; queueMicrotask(() => child.emit('exit', 0)); return true; };
|
||||
child.stdin = { write(line) {
|
||||
const message = JSON.parse(line); if (!message.id) return;
|
||||
if (message.method === 'tools/call') rpc.push(message.params);
|
||||
let result;
|
||||
if (message.method === 'initialize') result = { protocolVersion: '2024-11-05' };
|
||||
else if (message.method === 'tools/list') result = { tools: ['strata_models', 'strata_status', 'strata_install', 'strata_remove'].map(name => ({ name })) };
|
||||
else if (message.params.name === 'strata_models') result = { structuredContent: catalog };
|
||||
else if (message.params.name === 'strata_remove') result = { structuredContent: { summary: 'Deleted', plan: { gb: 1.2 }, failed: [] } };
|
||||
else if (message.params.name === 'strata_status') result = { structuredContent: { hardware, recommendation: catalog.recommendation, install: installJob, running: [], summary: 'x' } };
|
||||
else if (message.params.arguments?.confirm) { installJob = { running: false, exit_code: 0 }; result = { structuredContent: { summary: 'Install started', plan: { download_gb: 66.4 }, install: { running: true, step: 'downloading' } } }; }
|
||||
else if (message.params.arguments?.cancel === undefined && message.params.arguments?.confirm === undefined) result = { structuredContent: { summary: 'Install finished', install: { running: false, exit_code: 0 } } };
|
||||
else result = { structuredContent: { summary: 'Plan', plan: { title: 'Qwen3.8-Flash-Next Q2_0', download_gb: 66.4, disk_short: null } } };
|
||||
queueMicrotask(() => child.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + String.fromCharCode(10))));
|
||||
} };
|
||||
return child;
|
||||
};
|
||||
const native = createNativeControl({ control, directory: data, spawnProcess, fetcher, requests: () => requests });
|
||||
const others = () => spawned.filter(s => !String(s.args[0]).endsWith('strata_mcp.py'));
|
||||
return { native, calls, spawned, others, rpc, failStart: v => { startFailure = v; }, catalog, hardware, install, root, 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'); };
|
||||
|
||||
@@ -125,7 +159,19 @@ test('packaged: models come from Control, no python, git or engine process is st
|
||||
assert.equal(state.packaged, true);
|
||||
assert.match(state.summary, /engine 0\.1\.45/);
|
||||
assert.equal(state.version, '0.1.45');
|
||||
assert.equal(f.spawned.length, 0);
|
||||
assert.equal(f.others().length, 0, 'nothing but the installer is started');
|
||||
// the catalog, the GPUs and the recommendation come from the bundled installer, run on Control's own Python
|
||||
assert.equal(state.catalog.families[0].sizes.length, 2);
|
||||
assert.equal(state.catalog.recommendation.model, 'IQ3_XXS');
|
||||
assert.equal(state.hardware.gpus[0].name, 'NVIDIA GeForce RTX 5070');
|
||||
assert.equal(state.hardware.ram_gb, 63);
|
||||
const installer = f.spawned[0];
|
||||
assert.equal(installer.command, join(f.root, 'control', 'python', 'python.exe'));
|
||||
assert.deepEqual(installer.args.slice(1), ['--root', f.install, '--src', join(f.root, 'control')]);
|
||||
assert.equal(installer.options.env.STRATA_CONTROL_INSTALL, '1');
|
||||
assert.equal(installer.options.env.STRATA_NO_ACQUIRE, '1', 'the installer process itself may not acquire; only its explicit install job does');
|
||||
assert.equal(installer.options.env.STRATA_INSTALL_DIR, f.install);
|
||||
assert.equal(installer.options.env.PYTHONNOUSERSITE, '1');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
@@ -146,7 +192,7 @@ test('packaged: load = saved profile + runtime start under Control; unload = run
|
||||
await f.native.unload(first.id);
|
||||
assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);
|
||||
assert.equal(f.native.state().instances.length, 1);
|
||||
assert.equal(f.spawned.length, 0, 'the host never spawned anything itself');
|
||||
assert.equal(f.others().length, 0, 'the host never spawned anything itself');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
@@ -159,20 +205,50 @@ test('packaged: no engine for this PC is the notice, and nothing is started', as
|
||||
assert.match(job.error, /No engine for this PC/);
|
||||
assert.match(job.error, /never downloads an engine/);
|
||||
assert.equal(f.calls.some(c => ['saveProfile', 'start'].includes(c[0])), false);
|
||||
assert.equal(f.spawned.length, 0);
|
||||
assert.equal(f.others().length, 0);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: install, update, rollback and calibration are refused with the Terminal notice and start nothing', async () => {
|
||||
test('packaged: the user can download and prepare a model: the plan and the install job go to the bundled installer, the engine is not touched', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
for (const [kind, args] of [['install', { family: 'qwen', model: 'IQ2_XS' }], ['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) {
|
||||
const plan = await f.native.plan({ family: 'qwen', model: 'Q2_0' });
|
||||
assert.equal(plan.plan.title, 'Qwen3.8-Flash-Next Q2_0');
|
||||
const planned = f.rpc.at(-1);
|
||||
assert.equal(planned.name, 'strata_install');
|
||||
assert.equal(planned.arguments.confirm, false, 'a plan changes nothing');
|
||||
const job = await finish(f.native, f.native.operation('install', { family: 'qwen', model: 'Q2_0' }).id);
|
||||
assert.equal(job.state, 'done', job.error);
|
||||
const started = f.rpc.filter(c => c.name === 'strata_install' && c.arguments.confirm);
|
||||
assert.equal(started.length, 1);
|
||||
assert.equal(started[0].arguments.family, 'qwen');
|
||||
assert.equal(started[0].arguments.model, 'Q2_0');
|
||||
assert.equal(f.others().length, 0, 'the host starts no pip, git, python of its own or engine');
|
||||
assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0, 'installing does not start an engine');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: the installer works in a folder the app can write, never in the read-only bundle', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
assert.equal(existsSync(f.install), true);
|
||||
assert.notEqual(f.native.state().installDir, join(f.root, 'control'));
|
||||
assert.equal(f.spawned[0].args.at(-3), f.install);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: update, rollback and calibration are refused with the Terminal notice and start nothing', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
for (const [kind, args] of [['update-engine', {}], ['update-strata', {}], ['rollback', {}], ['calibrate', { model: 'iq3_s' }]]) {
|
||||
const job = await finish(f.native, f.native.operation(kind, args).id);
|
||||
assert.equal(job.state, 'error', kind);
|
||||
assert.match(job.error, /Terminal|calibrates NVIDIA|No saved previous engine/, `${kind}: ${job.error}`);
|
||||
}
|
||||
assert.equal(f.spawned.length, 0);
|
||||
assert.equal(f.others().length, 0);
|
||||
assert.equal(f.calls.filter(c => ['saveProfile', 'start'].includes(c[0])).length, 0);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
@@ -210,3 +286,80 @@ test('createControl asks the CLI for the engine, models and runtime and reads th
|
||||
]);
|
||||
assert.equal(createControl({ control: null }), null);
|
||||
});
|
||||
|
||||
test('packaged: the catalog offers no picture reading (app installs have none), and an install asks for none', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
const state = await f.native.refresh(true);
|
||||
assert.ok(state.catalog.families[0].sizes.every(s => s.images === false));
|
||||
assert.ok(state.catalog.families.every(fam => fam.images === false));
|
||||
await f.native.plan({ family: 'qwen', model: 'Q2_0', vision: 'yes' });
|
||||
assert.equal(f.rpc.at(-1).arguments.vision, 'no');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: an engine that stops while loading keeps the code and the last engine line for the Details disclosure', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
f.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } });
|
||||
const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);
|
||||
assert.equal(job.state, 'error');
|
||||
assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: a run config that points into an old Control folder is repaired to this Control (a reinstall or an update moved it)', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
const here = join(f.root, 'control');
|
||||
mkdirSync(join(here, 'data'), { recursive: true });
|
||||
writeFileSync(join(here, 'data', 'expert-profile.bin'), 'profile');
|
||||
const path = join(f.install, 'strata-iq2_xs.json');
|
||||
const old = 'C:/Users/Alex/AppData/Local/Temp/strata-life-install/control';
|
||||
writeFileSync(path, JSON.stringify({ exe: 'component:strata-engine', cwd: old, args: ['--pack', 'D:/Strata/packs/x', '--expert-profile', old + '/data/expert-profile.bin', '--max-context', '32768'], model_name: 'x', port: 8080 }));
|
||||
await f.native.refresh(true);
|
||||
const repaired = JSON.parse(readFileSync(path, 'utf8'));
|
||||
assert.equal(repaired.cwd.toLowerCase(), here.toLowerCase());
|
||||
assert.equal(repaired.args[repaired.args.indexOf('--expert-profile') + 1].toLowerCase(), join(here, 'data', 'expert-profile.bin').toLowerCase());
|
||||
assert.equal(repaired.args[1], 'D:/Strata/packs/x', 'paths outside Control are left alone');
|
||||
assert.ok(existsSync(path + '.bak'), 'the old config is kept');
|
||||
// a config that is already right, or whose new target is not there, is not touched
|
||||
const before = readFileSync(path, 'utf8');
|
||||
await f.native.refresh(true);
|
||||
assert.equal(readFileSync(path, 'utf8'), before);
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: deleting a downloaded model unloads it first, then the installer removes its files', async () => {
|
||||
const f = packagedFixture();
|
||||
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);
|
||||
assert.equal(f.native.state().instances.length, 1);
|
||||
const job = await finish(f.native, f.native.operation('remove', { model: 'iq2_xs' }).id);
|
||||
assert.equal(job.state, 'done', job.error);
|
||||
assert.equal(f.native.state().instances.length, 0, 'the loaded model was unloaded first');
|
||||
assert.deepEqual(f.calls.filter(c => c[0] === 'stop').at(-1), ['stop', 'app-1']);
|
||||
const removed = f.rpc.filter(c => c.name === 'strata_remove');
|
||||
assert.equal(removed.length, 1);
|
||||
assert.deepEqual(removed[0].arguments, { model: 'iq2_xs', confirm: true });
|
||||
assert.equal(f.others().length, 0);
|
||||
const bad = await finish(f.native, f.native.operation('remove', { model: '../x' }).id);
|
||||
assert.equal(bad.state, 'error', 'an id that is not an installed model is refused');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
|
||||
test('packaged: a local GGUF folder is checked by Control, then installed from where it is (no download)', async () => {
|
||||
const f = packagedFixture();
|
||||
try {
|
||||
await f.native.refresh(true);
|
||||
const preview = await f.native.localPreview('D:/models/iq3s');
|
||||
assert.equal(preview.candidate_selection.model, 'IQ3_S');
|
||||
assert.deepEqual(f.calls.find(c => c[0] === 'importPlan'), ['importPlan', 'D:/models/iq3s']);
|
||||
await assert.rejects(() => f.native.localPreview(' '), /Choose a folder/);
|
||||
await f.native.plan({ family: 'qwen', model: 'IQ3_S', gguf_dir: 'D:/models/iq3s' });
|
||||
assert.equal(f.rpc.at(-1).arguments.gguf_dir, 'D:/models/iq3s');
|
||||
} finally { await f.native.close(); f.cleanup(); }
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
|
||||
const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/${l}.json`, 'utf8'))])));
|
||||
const built = await build({ stdin: { contents: "export * from './src/lib/plain-errors'; export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
|
||||
const { plainFailure, plainFailureText, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
const cases = [
|
||||
['server_exited', 'memory', /ran low on memory/],
|
||||
['server_exited: memory guard: 5.1 GiB of RAM free is under the 6 GiB limit', 'memory', /ran low on memory/],
|
||||
['Engine stopped (exit 3). Open diagnostics or reload.', 'memory', /ran low on memory/],
|
||||
['Loading took more than five minutes. Check the engine log and free memory.', 'slow-load', /taking too long/],
|
||||
['No engine for this PC was found in C:/x/components: the component folder holds no engine package. The app never downloads an engine while it starts or serves.', 'engine-missing', /engine for this computer isn’t installed yet/],
|
||||
['cannot reach huggingface.co (<urlopen error [Errno 11001] getaddrinfo failed>)', 'network', /couldn’t reach the internet/],
|
||||
['sha256 mismatch for Qwen3.8-Flash-Next-00001-of-00002.gguf', 'integrity', /safety check/],
|
||||
['The agent component (DeepSeek Harness) is not installed.', 'assistant-missing', /coding assistant isn’t installed/],
|
||||
['component-missing', 'assistant-missing', /coding assistant/],
|
||||
['Strata Control did not answer within 60 s (models list).', 'control', /couldn’t read its own components/],
|
||||
['Prepare this model’s vision files before enabling picture reading.', 'picture-reading', /Picture reading isn’t available/],
|
||||
['Traceback (most recent call last):\n File "x.py", line 3', 'technical', /Something went wrong/],
|
||||
];
|
||||
|
||||
for (const [raw, kind, message] of cases) {
|
||||
test(`plain words for: ${raw.slice(0, 60)}`, () => {
|
||||
const f = plainFailure(raw);
|
||||
assert.equal(f.kind, kind);
|
||||
assert.match(f.message, message);
|
||||
assert.ok(f.next, 'a next step');
|
||||
assert.equal(f.detail, raw.trim(), 'the original text stays for Details');
|
||||
assert.doesNotMatch(f.message, /server_exited|exit \d|component-missing|Traceback/);
|
||||
});
|
||||
}
|
||||
|
||||
test('an ordinary sentence is left as it is and gets no Details', () => {
|
||||
const f = plainFailure('Some model files are missing. Use Download / repair to restore them.');
|
||||
assert.equal(f.kind, 'plain');
|
||||
assert.equal(f.detail, undefined);
|
||||
});
|
||||
|
||||
test('every plain message and next step is translated in all eight languages', () => {
|
||||
const en = catalogs.en;
|
||||
const ids = Object.fromEntries(Object.entries(en).map(([id, text]) => [text, id]));
|
||||
for (const [raw] of cases) {
|
||||
const f = plainFailure(raw);
|
||||
for (const text of [f.message, f.next]) {
|
||||
const id = ids[text];
|
||||
assert.ok(id, `"${text}" is in the catalog`);
|
||||
for (const l of languages) if (l !== 'en') assert.notEqual(catalogs[l][id], text, `${l}: "${text}" is translated`);
|
||||
}
|
||||
}
|
||||
setTranslationLanguage('de');
|
||||
assert.notEqual(plainFailureText('server_exited').message, plainFailure('server_exited').message);
|
||||
setTranslationLanguage('en');
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { resourceSettings } from '../server/native-resources.mjs';
|
||||
|
||||
const pc64 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9 }] };
|
||||
const iq3s = { arenaGb: 50.3 };
|
||||
const config = { gpu: 0, args: ['--native', 'x.gguf', '--max-context', '32768', '--pool-workers', '12'] };
|
||||
const flag = (args, name) => args[args.indexOf(name) + 1];
|
||||
|
||||
test('"leave 20% for my work" keeps the model within 80% of the RAM: a RAM budget for the experts', () => {
|
||||
const work = resourceSettings(config, pc64, 'work', iq3s);
|
||||
assert.ok(work.args.includes('--resident-budget-gib'), 'a model whose experts do not fit 80% of 63 GB gets a RAM budget');
|
||||
const gib = Number(flag(work.args, '--resident-budget-gib'));
|
||||
assert.ok(gib + 10 <= 63 * 0.8, `${gib} GiB plus the 10 GB the rest needs stays inside 80% of the RAM`);
|
||||
assert.equal(work.ui_resource_baseline.ramBudget, true);
|
||||
});
|
||||
|
||||
test('full performance takes that budget out again and keeps what the installation had', () => {
|
||||
const work = resourceSettings(config, pc64, 'work', iq3s);
|
||||
const back = resourceSettings({ ...config, args: work.args, ui_resource_profile: 'work', ui_resource_baseline: work.ui_resource_baseline }, pc64, 'performance', iq3s);
|
||||
assert.equal(back.args.includes('--resident-budget-gib'), false);
|
||||
assert.equal(flag(back.args, '--pool-workers'), '12');
|
||||
});
|
||||
|
||||
test('a model that fits, or one that already has a RAM mode, is left alone', () => {
|
||||
assert.equal(resourceSettings(config, { ...pc64, ram_gb: 128 }, 'work', iq3s).args.includes('--resident-budget-gib'), false);
|
||||
assert.equal(resourceSettings(config, pc64, 'work', { arenaGb: 34 }).args.includes('--resident-budget-gib'), false, 'Q2_0 fits 80% of 63 GB with 10 to spare');
|
||||
const own = { ...config, args: [...config.args, '--mmap-experts'] };
|
||||
assert.equal(resourceSettings(own, pc64, 'work', iq3s).args.includes('--resident-budget-gib'), false);
|
||||
assert.equal(resourceSettings(config, pc64, 'work').args.includes('--resident-budget-gib'), false, 'no model size, no change');
|
||||
});
|
||||
|
||||
test('neither profile reserves less VRAM than the engine\'s safe floor (the driver pages GPU memory below it and decoding collapses)', () => {
|
||||
const card12 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, vram_gb: 11.9 }] };
|
||||
const card24 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, vram_gb: 24 }] };
|
||||
for (const profile of ['work', 'performance']) {
|
||||
const lowConfig = { gpu: 0, args: ['--max-context', '32768', '--vram-reserve-mib', '700'] };
|
||||
assert.ok(resourceSettings(lowConfig, card12, profile).vram_reserve_mib >= 1536, `${profile} on 12 GB`);
|
||||
assert.ok(resourceSettings({ gpu: 0, args: [] }, card12, profile).vram_reserve_mib >= 1536, `${profile}, nothing configured`);
|
||||
assert.ok(resourceSettings(lowConfig, card24, profile).vram_reserve_mib >= 1024, `${profile} on 24 GB`);
|
||||
}
|
||||
assert.equal(resourceSettings({ gpu: 0, args: [] }, card12, 'performance').vram_reserve_mib, 1536);
|
||||
assert.equal(resourceSettings({ gpu: 0, args: [] }, card24, 'performance').vram_reserve_mib, 1024);
|
||||
assert.equal(resourceSettings({ gpu: 0, args: [], vram_reserve_mib: 2437 }, card12, 'performance').vram_reserve_mib, 2437, 'a larger reserve of the installation is kept');
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import { proxyCompletion } from '../server/inference.mjs';
|
||||
|
||||
/* The speed shown while an answer streams must be the decode speed of everything generated, reasoning included, from the first
|
||||
token (the owner saw 4-5 tok/s in chat while the engine log said 48-57): the stand-in engine streams 90 reasoning tokens at about
|
||||
40 a second, a 4 s "prompt" before the first one, then a short answer. */
|
||||
function engine({ promptMs, reasoning, answer, perSecond }) {
|
||||
return createServer((req, res) => {
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
||||
const send = obj => res.write(`data: ${JSON.stringify(obj)}\n\n`);
|
||||
let sent = 0;
|
||||
setTimeout(function tick() {
|
||||
if (sent < reasoning + answer) {
|
||||
send({ choices: [{ delta: sent < reasoning ? { reasoning_content: 'tok ' } : { content: 'ans ' } }] });
|
||||
sent++;
|
||||
return setTimeout(tick, 1000 / perSecond);
|
||||
}
|
||||
send({ choices: [], usage: { prompt_tokens: 20, completion_tokens: reasoning + answer } });
|
||||
res.write('data: [DONE]\n\n'); res.end();
|
||||
}, promptMs);
|
||||
});
|
||||
}
|
||||
|
||||
test('live speed counts reasoning tokens over decode time, not the answer over the whole wait', async () => {
|
||||
const server = engine({ promptMs: 4000, reasoning: 90, answer: 10, perSecond: 40 });
|
||||
await new Promise(r => server.listen(0, '127.0.0.1', r));
|
||||
const frames = [];
|
||||
try {
|
||||
const result = await proxyCompletion({ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, message: 'hi', onFrame: f => frames.push(f), engine: { beginReading() {}, beginThinking() {}, beginGenerating() {} } });
|
||||
const stats = frames.filter(f => f.type === 'stats');
|
||||
assert.ok(stats.length >= 2, 'live frames while it streams');
|
||||
const last = stats.at(-1);
|
||||
assert.ok(last.tps > 22 && last.tps < 80, `live tok/s ${last.tps} is the decode rate, not tokens over the wait including the prompt (~14)`);
|
||||
assert.ok(last.tokensOut >= 50, 'reasoning tokens are counted');
|
||||
assert.equal(result.tokensOut, 100);
|
||||
assert.ok(result.tps > 22 && result.tps < 80, `final tok/s ${result.tps}`);
|
||||
} finally { server.close(); }
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
/* The direct chat path (no agent): the composer's Reasoning effort menu reaches the server as reasoning_effort ("Off" -> "none", which the
|
||||
server turns into enable_thinking=false), and the Thinking budget as reasoning_budget_tokens, never when thinking is off. */
|
||||
const host = readFileSync(new URL('../server/index.mjs', import.meta.url), 'utf8');
|
||||
const composer = readFileSync(new URL('../src/components/ComposerControls.tsx', import.meta.url), 'utf8');
|
||||
const store = readFileSync(new URL('../src/lib/store.ts', import.meta.url), 'utf8');
|
||||
|
||||
test('Off is sent as none and Max as high; the budget only with thinking on', () => {
|
||||
assert.match(host, /reasoning_effort:\(\{off:'none',max:'high'\}/);
|
||||
assert.match(host, /thinkingBudget>0&&String\(thinking\)\.toLowerCase\(\)!=='off'\?\{reasoning_budget_tokens:thinkingBudget\}/);
|
||||
});
|
||||
|
||||
test('the budget travels from the menu to the request', () => {
|
||||
assert.match(composer, /THINKING_BUDGETS/);
|
||||
assert.match(composer, /thinkingBudget: value/);
|
||||
assert.match(store, /thinkingBudget:state\.sessions\.find/);
|
||||
assert.match(host, /thinkingBudget:Number\.isInteger\(body\.thinkingBudget\)/);
|
||||
});
|
||||
@@ -61,6 +61,20 @@ from pathlib import Path
|
||||
from strata_control import acquisition
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
# The desktop app runs this installer under Strata Control (its bundled Python, STRATA_CONTROL_INSTALL=1). The source
|
||||
# (tools/, data/, serve/) stays in ROOT, inside the app; everything the install writes (run configs, logs, third_party,
|
||||
# the data folder beside it) goes to home(), a per-user folder (STRATA_INSTALL_DIR). In that mode it installs no Python
|
||||
# package and no engine and compiles nothing: it downloads the model files, prepares them with the bundled tools and
|
||||
# writes a run config whose engine is "component:strata-engine". Outside that mode home() is ROOT and nothing changes.
|
||||
CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1"
|
||||
_CONTROL_HOME = Path(os.environ["STRATA_INSTALL_DIR"]).resolve() if CONTROL and os.environ.get("STRATA_INSTALL_DIR") else None
|
||||
|
||||
|
||||
def home() -> Path:
|
||||
"""Where an install writes (see above). A function, not a constant, so ROOT stays the one thing a caller can point elsewhere."""
|
||||
return _CONTROL_HOME or ROOT
|
||||
|
||||
|
||||
WIN = os.name == "nt"
|
||||
# #214: every Hugging Face file comes from a fixed commit of its repository (the `sha` of
|
||||
# https://huggingface.co/api/models/<repo> when this was pinned), so a checkout installs the same files on any
|
||||
@@ -548,6 +562,12 @@ def _urlopen(req, timeout=None):
|
||||
def run(cmd, cwd=None, env=None, check=True, quiet=False):
|
||||
"""An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start."""
|
||||
acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")")
|
||||
if CONTROL: # the app: only this Python running a bundled tool
|
||||
argv = [str(c) for c in cmd]
|
||||
if len(argv) < 2 or os.path.normcase(argv[0]) != os.path.normcase(sys.executable) or argv[1] == "-m" or \
|
||||
Path(argv[1]).resolve().parent != (ROOT / "tools").resolve():
|
||||
raise acquisition.AcquisitionRefused("the desktop app's installer only runs its bundled preparation tools; "
|
||||
+ " ".join(argv[:2]))
|
||||
say(" > " + " ".join(str(c) for c in cmd))
|
||||
r = subprocess.run([str(c) for c in cmd], cwd=cwd, env=env,
|
||||
stdout=subprocess.PIPE if quiet else None, stderr=subprocess.STDOUT if quiet else None,
|
||||
@@ -2018,12 +2038,12 @@ def check_shards(shards):
|
||||
|
||||
def get_llama_cpp():
|
||||
"""llama.cpp at the pinned commit (ggml for the build, gguf-py for the tools, mtmd for images), as a zip: no git."""
|
||||
llama = ROOT / "third_party" / "llama.cpp"
|
||||
llama = home() / "third_party" / "llama.cpp"
|
||||
if (llama / "ggml" / "CMakeLists.txt").exists() and (llama / "gguf-py").is_dir():
|
||||
return llama
|
||||
z = ROOT / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip"
|
||||
z = home() / "third_party" / f"llama.cpp-{LLAMA_CPP_COMMIT[:7]}.zip"
|
||||
download(LLAMA_CPP_ZIP, z, "llama.cpp source")
|
||||
tmp = ROOT / "third_party" / "_unpack"
|
||||
tmp = home() / "third_party" / "_unpack"
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
try:
|
||||
with zipfile.ZipFile(z) as f:
|
||||
@@ -2081,10 +2101,23 @@ def _installed(name: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def control_missing_packages() -> list:
|
||||
"""The Python packages the preparation tools need that this interpreter does not have (the app bundle has them all)."""
|
||||
import importlib.util
|
||||
return [m for m in ("numpy", "jinja2", "regex", "yaml", "tqdm", "requests", "PIL", "psutil")
|
||||
if importlib.util.find_spec(m) is None]
|
||||
|
||||
|
||||
def pip_install(packages, what):
|
||||
"""pip install into .venv, skipped when the same list was installed before. An install from before the pinned
|
||||
requirements (#214) recorded bare names: those packages are kept as they are (nothing is reinstalled), and the
|
||||
pinned dependencies it already has count as installed."""
|
||||
if CONTROL: # the app ships these (hash-locked); nothing is installed here
|
||||
missing = control_missing_packages()
|
||||
if missing:
|
||||
fail("this copy of Strata Control lacks " + ", ".join(missing), "reinstall the Strata app")
|
||||
ok(f"{what}: bundled with the app")
|
||||
return
|
||||
stamp = Path(sys.prefix) / ".strata-pip.json"
|
||||
have = json.loads(stamp.read_text(encoding="utf-8")) if stamp.exists() else []
|
||||
bare = {p.lower() for p in have if req_name(p) == p.lower()}
|
||||
@@ -4388,7 +4421,7 @@ def other_installs(settings: dict) -> list:
|
||||
"""Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders
|
||||
next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`)."""
|
||||
cands = [Path(p) for p in settings.get("installs", [])]
|
||||
for base in dict.fromkeys((ROOT.parent, ROOT.parent.parent)):
|
||||
for base in dict.fromkeys((home().parent, home().parent.parent)):
|
||||
try:
|
||||
for d in base.iterdir():
|
||||
if d.is_dir() and d.name.lower().startswith("strata"):
|
||||
@@ -4400,7 +4433,7 @@ def other_installs(settings: dict) -> list:
|
||||
for d in cands:
|
||||
try:
|
||||
d = d.resolve()
|
||||
if d != ROOT and d not in found and (d / "setup.py").is_file():
|
||||
if d != home() and d not in found and (d / "setup.py").is_file():
|
||||
found.append(d)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -4468,16 +4501,16 @@ def data_folder(requested: str | None) -> tuple:
|
||||
and of earlier Strata folders on the same drive into the data folder, and points their configs there."""
|
||||
settings = load_settings()
|
||||
dest = Path(requested).expanduser().resolve() if requested else \
|
||||
Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data"
|
||||
Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data"
|
||||
try:
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e: # e.g. no write access next to the Strata folder
|
||||
warn(f"cannot use {dest} for the model files ({e}): keeping them in {ROOT}")
|
||||
dest = ROOT
|
||||
warn(f"cannot use {dest} for the model files ({e}): keeping them in {home()}")
|
||||
dest = home()
|
||||
elsewhere = []
|
||||
# #198: the data folder remembered before (a --data-dir to a new place) is a source too, and so is a Strata-data
|
||||
# folder nested in any of them (an install that kept its models one level down)
|
||||
sources = [ROOT, *other_installs(settings)]
|
||||
sources = [home(), *other_installs(settings)]
|
||||
if settings.get("data_dir") and Path(settings["data_dir"]) != dest:
|
||||
sources.append(Path(settings["data_dir"]))
|
||||
sources += [f / "Strata-data" for f in list(sources) if (f / "Strata-data") != dest]
|
||||
@@ -4512,7 +4545,7 @@ def data_folder(requested: str | None) -> tuple:
|
||||
warn(f"some model files are still in {folder} (in use, or already in {dest})")
|
||||
else:
|
||||
ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)")
|
||||
installs = [str(ROOT)] + [p for p in settings.get("installs", []) if p != str(ROOT) and Path(p).is_dir()]
|
||||
installs = [str(home())] + [p for p in settings.get("installs", []) if p != str(home()) and Path(p).is_dir()]
|
||||
save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]})
|
||||
return dest, elsewhere
|
||||
|
||||
@@ -4522,7 +4555,7 @@ def data_folder_in_place() -> tuple:
|
||||
the settings and nothing else: no folder is created, nothing is moved or copied, no setting is saved. The run
|
||||
configs name their model files, so an install made by an earlier Strata starts from where it is."""
|
||||
settings = load_settings()
|
||||
dest = Path(settings["data_dir"]) if settings.get("data_dir") else ROOT.parent / "Strata-data"
|
||||
dest = Path(settings["data_dir"]) if settings.get("data_dir") else home().parent / "Strata-data"
|
||||
return dest, []
|
||||
|
||||
|
||||
@@ -4616,6 +4649,11 @@ def args_dropped(old: dict, cfg: dict) -> list[str]:
|
||||
return list(dict.fromkeys(f for f in flags(old) if f not in new))
|
||||
|
||||
|
||||
def engine_exe(eng: Path) -> str:
|
||||
"""The `exe` of a run config: the engine component in the app, else the engine binary's path."""
|
||||
return "component:strata-engine" if CONTROL else str(eng / EXE)
|
||||
|
||||
|
||||
def write_setup_config(cfg_path: Path, cfg: dict, source: Path | None = None) -> None:
|
||||
"""#629: setup's run config, written over an earlier one for the same model without losing what the user added
|
||||
to it: the keys setup does not write are carried over (carry_over), and the earlier file is kept as
|
||||
@@ -4765,7 +4803,7 @@ def model_config(path: Path) -> bool:
|
||||
|
||||
|
||||
def installed_configs():
|
||||
return [p for p in sorted(model_config_files(ROOT), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
return [p for p in sorted(model_config_files(home()), key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
if model_config(p)]
|
||||
|
||||
|
||||
@@ -5529,11 +5567,11 @@ def write_run_script(model, cfg_path, port, open_browser=True):
|
||||
serve = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
|
||||
"--port", str(port)] + (["--open"] if open_browser else [])
|
||||
if WIN:
|
||||
script = ROOT / f"run-{model.lower()}.bat"
|
||||
script = home() / f"run-{model.lower()}.bat"
|
||||
script.write_text("@echo off\r\ntitle Strata " + model + "\r\ncd /d \"" + str(ROOT) + "\"\r\n" +
|
||||
" ".join(f'"{x}"' for x in serve) + "\r\nif errorlevel 1 pause\r\n", encoding="utf-8")
|
||||
else:
|
||||
script = ROOT / f"run-{model.lower()}.sh"
|
||||
script = home() / f"run-{model.lower()}.sh"
|
||||
script.write_text("#!/bin/sh\ncd \"" + str(ROOT) + "\"\nexec " + " ".join(f'"{x}"' for x in serve) + "\n",
|
||||
encoding="utf-8")
|
||||
script.chmod(0o755)
|
||||
@@ -5611,9 +5649,33 @@ def sycl_setup(argv) -> int:
|
||||
return subprocess.call([sys.executable, str(script), *rest])
|
||||
|
||||
|
||||
def control_engine_step(gpu, vision):
|
||||
"""Step 4 in the app: the engine is the component folder's package (strata_control/engine_component.py), found if it is
|
||||
there and never fetched or built. A model can be downloaded and prepared before the engine is installed; the run config
|
||||
names "component:strata-engine" and the engine is looked up when the model is loaded. llama.cpp's source zip is fetched
|
||||
for gguf-py only (the preparation tools), as setup always did: no git, no compiler."""
|
||||
from strata_control import engine_component as EC
|
||||
llama = get_llama_cpp()
|
||||
ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py for the preparation tools)")
|
||||
try:
|
||||
found = EC.resolve(full=False)
|
||||
eng, meta = Path(found.root), {"version": found.version, "backend": found.backend, "source": "local"}
|
||||
ok(f"engine component: {found.version} ({found.platform}-{found.backend}) in {eng}")
|
||||
except EC.EngineMissing as e:
|
||||
eng = home() / "engine"
|
||||
meta = {"version": "99.0.0", "source": "local", "component": "missing"} # its version is checked when it loads
|
||||
warn(f"no engine is installed for this PC yet ({e}). The model is downloaded and prepared now; install the engine "
|
||||
"component for your GPU (a later step of the app, or the Terminal) before loading it")
|
||||
if vision != "none":
|
||||
warn("images are not part of the app's first release: images off for this model")
|
||||
return llama, eng, meta, [], gpu, "none"
|
||||
|
||||
|
||||
def engine_step(a, gpu, hip, amd, cuda_tk, vision):
|
||||
"""Step 4: llama.cpp's sources and the engine (ready-made, or compiled here). Returns (llama, engine folder, its
|
||||
BUILD.json, its library folders, the GPU (AMD on Windows: as the engine sees it), the image-encoder choice)."""
|
||||
if CONTROL:
|
||||
return control_engine_step(gpu, vision)
|
||||
llama = get_llama_cpp()
|
||||
ok(f"llama.cpp {LLAMA_CPP_COMMIT[:7]} (gguf-py, ggml, mtmd)")
|
||||
if hip and WIN: # AMD on Windows: the ready-made HIP engine (no compiler)
|
||||
@@ -5866,7 +5928,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
|
||||
if fam["arch"] not in engine_families(eng):
|
||||
fail(f"this engine ({meta.get('version')}) does not run {fam['title']} yet",
|
||||
"update Strata, or compile the engine with --build, and run setup again")
|
||||
ok(f"engine: {eng / EXE}")
|
||||
ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")
|
||||
|
||||
step(5, f"downloading {fam['title']} {model}")
|
||||
if gguf.exists() and done(gguf):
|
||||
@@ -5903,9 +5965,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
|
||||
if vram > 0:
|
||||
args += ["--expert-vram", f"{max(vram - 3.0 - a.vram_reserve_mib / 1024, 0):.1f}"]
|
||||
ok(f"VRAM kept free for other programs: about {a.vram_reserve_mib} MiB (the experts' share is set lower)")
|
||||
cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
|
||||
cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
|
||||
"model_name": f"{fam['name']}-{model.lower()}", "arch": fam["arch"],
|
||||
"log": str(ROOT / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port}
|
||||
"log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port}
|
||||
if cuda_tk == 12:
|
||||
cfg["cuda"] = 12
|
||||
if hip:
|
||||
@@ -5920,7 +5982,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
|
||||
if a.browser is not None:
|
||||
cfg["open_browser"] = a.browser
|
||||
cfg["args"] = recommend_pool_workers(cfg["args"]) # --pool-workers: this engine path's CPU expert threads too
|
||||
cfg_path = ROOT / f"strata-{tag.lower()}.json"
|
||||
cfg_path = home() / f"strata-{tag.lower()}.json"
|
||||
if vision != "none":
|
||||
old_cfg = cfg_path if cfg_path.is_file() else adopted
|
||||
vt = vision_tokens(getattr(a, "vision_tokens", None), vision, old_cfg)
|
||||
@@ -6762,7 +6824,7 @@ def main() -> int:
|
||||
if MODELS[model].get("budget") and engine_ver < need_engine:
|
||||
fail(f"{model} needs engine {'.'.join(map(str, need_engine))} or newer; this one is {meta.get('version')}",
|
||||
"update Strata (or compile the engine with --build) and run setup again")
|
||||
ok(f"engine: {eng / EXE}")
|
||||
ok("engine: the engine component (looked up when the model loads)" if CONTROL else f"engine: {eng / EXE}")
|
||||
|
||||
# ---- 5. the model files
|
||||
step(5, f"downloading {fam['title']} {model}")
|
||||
@@ -6862,7 +6924,7 @@ def main() -> int:
|
||||
run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
|
||||
env=env)
|
||||
# a setup run again without --draft-vocab keeps the subset this model's config chose before (cyrillic, fr, en)
|
||||
draft_vocab = a.draft_vocab or saved_draft_vocab(ROOT / f"strata-{tag.lower()}.json")
|
||||
draft_vocab = a.draft_vocab or saved_draft_vocab(home() / f"strata-{tag.lower()}.json")
|
||||
refresh_draft_vocab(rt, draft_vocab or "cjk")
|
||||
ok(f"MTP draft layer: {rt}")
|
||||
for line in draft_vocab_note(gpu.get("vram_gb", 0.0), draft_vocab): # #474: a recommendation, nothing changes
|
||||
@@ -7043,8 +7105,8 @@ def main() -> int:
|
||||
# the package's profile, with llama.cpp's flags (the engine takes the same ones)
|
||||
args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44",
|
||||
"--cvec-mode", "project", "--cvec-dir", "per-layer"]
|
||||
cfg = {"exe": str(eng / EXE), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
|
||||
"model_name": f"{fam['name']}-{model.lower()}", "log": str(ROOT / f"strata-{tag.lower()}.log"),
|
||||
cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(pack / "tokenizer"),
|
||||
"model_name": f"{fam['name']}-{model.lower()}", "log": str(home() / f"strata-{tag.lower()}.log"),
|
||||
"lib_dirs": lib_dirs, "port": port}
|
||||
if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/)
|
||||
cfg["cuda"] = 12
|
||||
@@ -7105,7 +7167,7 @@ def main() -> int:
|
||||
cfg["parallel"] = 1
|
||||
ok("parallel requests: one at a time (--parallel 1)")
|
||||
if vision != "none":
|
||||
old_cfg = ROOT / f"strata-{tag.lower()}.json"
|
||||
old_cfg = home() / f"strata-{tag.lower()}.json"
|
||||
vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted)
|
||||
cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only:
|
||||
"model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]),
|
||||
@@ -7116,7 +7178,7 @@ def main() -> int:
|
||||
warn("--vision-tokens: images are off for this model, so it is not used")
|
||||
if a.images: # only when given: else an earlier "images" is carried over
|
||||
cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir))
|
||||
cfg_path = ROOT / f"strata-{tag.lower()}.json"
|
||||
cfg_path = home() / f"strata-{tag.lower()}.json"
|
||||
cal = setup_calibration(cfg, hip) # #566: Linux HIP too; the tuning is offered on NVIDIA only
|
||||
if cal is not None:
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
|
||||
@@ -797,6 +797,20 @@ class Host:
|
||||
if "error" in result:
|
||||
self.last_error = result["error"]
|
||||
|
||||
def _log_tail(self, limit: int = 4096) -> str | None:
|
||||
"""The last lines the server wrote (a failed start is explained by them), or None. Bounded read, never raises."""
|
||||
try:
|
||||
with open(self.state_path.parent / f"{self.name}.server.log", "rb") as stream:
|
||||
stream.seek(0, os.SEEK_END)
|
||||
stream.seek(max(0, stream.tell() - limit))
|
||||
lines = [x.rstrip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()]
|
||||
except OSError:
|
||||
return None
|
||||
# not the indented frames of a Python traceback: the engine's own lines and the final exception line say why
|
||||
plain = [x for x in lines if not x[0].isspace() and not x.startswith("Traceback")]
|
||||
chosen = plain[-3:] or lines[-1:]
|
||||
return " | ".join(x[:200] for x in chosen) if chosen else None
|
||||
|
||||
def _status(self) -> dict:
|
||||
child = self.child
|
||||
base = {"ok": True, "profile": self.name, "host_pid": os.getpid(),
|
||||
@@ -809,7 +823,7 @@ class Host:
|
||||
return {**base, "state": "stopped"}
|
||||
if child.poll() is not None:
|
||||
return {**base, "ok": False, "state": "failed", "exit_code": child.returncode,
|
||||
"error": self.last_error or "server_exited"}
|
||||
"error": self.last_error or "server_exited", "log_tail": self._log_tail()}
|
||||
if self.ready_path is not None:
|
||||
try:
|
||||
ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
"""The desktop app's installer: tools/strata_mcp.py and setup.py run on Control's Python in STRATA_CONTROL_INSTALL mode.
|
||||
|
||||
What the owner asked for: a user installs the app, picks a model in it and downloads and prepares it, like any normal user.
|
||||
What must stay true: a start or a serve never acquires anything (tests/terminal/test_no_acquisition.py), and the install
|
||||
itself downloads model files only - no pip, no git, no compiler, no engine fetch, only the bundled preparation tools.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def load_setup(home: Path, name: str = "setup_control_mode"):
|
||||
"""setup.py imported as the app's installer: the mode is read when the module loads."""
|
||||
env = {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(home)}
|
||||
with mock.patch.dict(os.environ, env):
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / "setup.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class ControlModeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.home = Path(self.tmp.name) / "install"
|
||||
self.home.mkdir()
|
||||
self.S = load_setup(self.home)
|
||||
|
||||
def test_the_folder_everything_is_written_to_is_the_install_folder_not_the_bundle(self):
|
||||
S = self.S
|
||||
self.assertTrue(S.CONTROL)
|
||||
self.assertEqual(S.home(), self.home.resolve())
|
||||
self.assertEqual(S.ROOT, ROOT)
|
||||
# without the mode nothing moves: HOME is the source folder, as it always was
|
||||
spec = importlib.util.spec_from_file_location("setup_plain_mode", ROOT / "setup.py")
|
||||
plain = importlib.util.module_from_spec(spec)
|
||||
with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "0"}):
|
||||
spec.loader.exec_module(plain)
|
||||
self.assertFalse(plain.CONTROL)
|
||||
self.assertEqual(plain.home(), plain.ROOT)
|
||||
|
||||
def test_only_this_python_running_a_bundled_tool_may_run(self):
|
||||
S = self.S
|
||||
tool = ROOT / "tools" / "pack_index.py"
|
||||
for refused in (
|
||||
[sys.executable, "-m", "pip", "install", "numpy"],
|
||||
["pip", "install", "numpy"],
|
||||
["git", "clone", "https://example.invalid/x.git"],
|
||||
["cmake", "--build", "."],
|
||||
["winget", "install", "Nvidia.CUDA"],
|
||||
[sys.executable, str(self.home / "evil.py")], # a script outside the bundled tools
|
||||
[sys.executable, str(ROOT / "setup.py"), "--build"],
|
||||
[sys.executable],
|
||||
):
|
||||
with self.subTest(refused=refused), mock.patch.object(S.subprocess, "run", side_effect=AssertionError("ran")):
|
||||
with self.assertRaises(S.acquisition.AcquisitionRefused):
|
||||
S.run(refused)
|
||||
done = subprocess.CompletedProcess([], 0)
|
||||
with mock.patch.object(S.subprocess, "run", return_value=done) as runner:
|
||||
S.run([sys.executable, str(tool), "--help"], check=False)
|
||||
runner.assert_called_once()
|
||||
|
||||
def test_no_package_is_installed(self):
|
||||
S = self.S
|
||||
with mock.patch.object(S, "run", side_effect=AssertionError("pip")), \
|
||||
mock.patch.object(S, "control_missing_packages", return_value=[]):
|
||||
S.pip_install(["numpy==1"], "the packages") # the app ships them; nothing runs
|
||||
with mock.patch.object(S, "control_missing_packages", return_value=["numpy"]), \
|
||||
self.assertRaises(SystemExit):
|
||||
S.pip_install(["numpy==1"], "the packages")
|
||||
|
||||
def test_the_engine_is_the_component_and_a_missing_one_does_not_stop_the_download(self):
|
||||
S = self.S
|
||||
llama = self.home / "third_party" / "llama.cpp"
|
||||
(llama / "ggml").mkdir(parents=True)
|
||||
(llama / "ggml" / "CMakeLists.txt").write_text("", encoding="utf-8")
|
||||
(llama / "gguf-py").mkdir()
|
||||
empty = Path(self.tmp.name) / "components"
|
||||
empty.mkdir()
|
||||
gpu = {"index": 0, "vram_gb": 12.0}
|
||||
with mock.patch.dict(os.environ, {"STRATA_COMPONENTS_DIR": str(empty)}), \
|
||||
mock.patch.object(S, "download", side_effect=AssertionError("fetched")), \
|
||||
mock.patch.object(S, "build_engine", side_effect=AssertionError("built")), \
|
||||
mock.patch.object(S, "get_prebuilt", side_effect=AssertionError("fetched an engine")):
|
||||
found, eng, meta, libs, chosen, vision = S.engine_step(mock.Mock(build=False, prebuilt=None), gpu, False, [], 13, "gpu")
|
||||
self.assertEqual(found.resolve(), llama.resolve())
|
||||
self.assertEqual(libs, [])
|
||||
self.assertEqual(vision, "none") # images are not in the first app release
|
||||
self.assertEqual(meta["source"], "local")
|
||||
self.assertEqual(S.engine_exe(eng), "component:strata-engine")
|
||||
|
||||
def test_the_run_config_goes_to_the_install_folder_and_the_data_folder_sits_beside_it(self):
|
||||
S = self.S
|
||||
self.assertEqual(S.installed_configs(), [])
|
||||
(self.home / "strata-q2_0.json").write_text(json.dumps({"exe": "component:strata-engine", "args": ["--native", "x.gguf"],
|
||||
"tokenizer": "t"}), encoding="utf-8")
|
||||
with mock.patch.object(S, "model_config", return_value=True):
|
||||
self.assertEqual([p.name for p in S.installed_configs()], ["strata-q2_0.json"])
|
||||
with mock.patch.dict(os.environ, {"APPDATA": self.tmp.name, "XDG_CONFIG_HOME": self.tmp.name}):
|
||||
data, _ = S.data_folder_in_place()
|
||||
self.assertEqual(data, self.home.resolve().parent / "Strata-data")
|
||||
|
||||
def test_the_bundle_lists_everything_the_install_imports(self):
|
||||
sys.path.insert(0, str(ROOT / "apps" / "desktop" / "scripts"))
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("stage_control_for_test", ROOT / "apps" / "desktop" / "scripts" / "stage-control.py")
|
||||
stage = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(stage)
|
||||
finally:
|
||||
sys.path.pop(0)
|
||||
tools = stage.local_imports(ROOT, stage.INSTALLER_TOOLS)
|
||||
for need in ("strata_mcp", "iq_pack", "strata_pack", "canonical_xcheck", "pack_layer", "gguf_reader", "gguf_writer", "_paths"):
|
||||
self.assertIn(need, tools)
|
||||
out = Path(self.tmp.name) / "control"
|
||||
out.mkdir()
|
||||
record = stage.add_installer(out)
|
||||
for name in ("setup.py", "ref/load.py", "tools/strata_mcp.py", "tools/iq_pack.py", "data/draft_vocab.bin"):
|
||||
self.assertTrue((out / name).is_file(), name)
|
||||
self.assertIn("tools/strata_pack.py", record["files"])
|
||||
# every module setup.py's preparation steps run exists in the bundle
|
||||
for tool in ("iq_pack", "strata_pack", "pack_index", "strata_tokenizer", "mtp_fetch", "mtp_pack", "mtp_rt"):
|
||||
self.assertTrue((out / "tools" / f"{tool}.py").is_file(), tool)
|
||||
|
||||
|
||||
class InstallerServerTests(unittest.TestCase):
|
||||
"""tools/strata_mcp.py with its source (setup.py, serve/) apart from the install folder, as the app runs it."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name) / "install"
|
||||
self.root.mkdir()
|
||||
spec = importlib.util.spec_from_file_location("strata_mcp_for_test", ROOT / "tools" / "strata_mcp.py")
|
||||
self.mcp = importlib.util.module_from_spec(spec)
|
||||
with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(self.root)}):
|
||||
spec.loader.exec_module(self.mcp)
|
||||
|
||||
def test_the_catalog_comes_from_setup_py_in_the_bundle(self):
|
||||
s = self.mcp.Strata(self.root, ROOT)
|
||||
self.assertEqual(s.root, self.root.resolve())
|
||||
self.assertEqual(s.src, ROOT)
|
||||
models, families, contexts, source = s.tables()
|
||||
self.assertEqual(source, "setup.py")
|
||||
self.assertIn("qwen", families)
|
||||
self.assertIn("IQ3_XXS", models)
|
||||
self.assertEqual(s.python_override, sys.executable) # Control's own Python runs the install
|
||||
|
||||
def test_the_install_job_runs_on_control_python_without_a_venv_and_may_fetch_only_for_itself(self):
|
||||
s = self.mcp.Strata(self.root, ROOT)
|
||||
spec_path = self.root / "job.json"
|
||||
spec = {"job": "j1", "root": str(self.root), "src": str(ROOT), "control": True, "python": sys.executable,
|
||||
"base_python": sys.executable, "create_venv": False, "args": ["--yes", "--no-start"],
|
||||
"result": str(self.root / "result.json")}
|
||||
spec_path.write_text(json.dumps(spec), encoding="utf-8")
|
||||
seen = {}
|
||||
|
||||
class FakePopen:
|
||||
pid = 4242
|
||||
|
||||
def __init__(self, cmd, **kw):
|
||||
seen["cmd"], seen["kw"] = cmd, kw
|
||||
|
||||
def wait(self):
|
||||
return 0
|
||||
|
||||
with mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1", "PYTHONPATH": "x", "PYTHONHOME": "y"}), \
|
||||
mock.patch.object(self.mcp.subprocess, "Popen", FakePopen), \
|
||||
mock.patch.object(self.mcp, "proc_identity", return_value=None):
|
||||
self.assertEqual(self.mcp.install_job(str(spec_path)), 0)
|
||||
self.assertEqual(os.environ["STRATA_NO_ACQUIRE"], "1", "this process keeps the switch")
|
||||
self.assertEqual(seen["cmd"][:2], [sys.executable, str(ROOT / "setup.py")])
|
||||
env = seen["kw"]["env"]
|
||||
self.assertEqual(env["STRATA_CONTROL_INSTALL"], "1")
|
||||
self.assertEqual(env["STRATA_INSTALL_DIR"], str(self.root))
|
||||
self.assertNotIn("STRATA_NO_ACQUIRE", env, "the explicit install job may fetch the chosen model's files")
|
||||
self.assertNotIn("PYTHONPATH", env)
|
||||
self.assertNotIn("PYTHONHOME", env)
|
||||
self.assertFalse((self.root / ".venv").exists(), "no virtual environment, no pip")
|
||||
self.assertIsNotNone(s)
|
||||
|
||||
def test_a_two_file_model_has_one_combined_progress(self):
|
||||
"""The bar went 70 GB -> 0 -> up again because each file reported its own total. One total for the whole model now."""
|
||||
folder = self.root / "Strata-data" / "models" / "IQ3_S"
|
||||
folder.mkdir(parents=True)
|
||||
job = {"folder": str(folder), "total_gb": 0.004}
|
||||
step5 = {"step": "5/7: downloading Qwen3.8-Flash-Next IQ3_S"}
|
||||
seen = []
|
||||
# file 1 downloading, then complete, then file 2 starts: the combined figure only goes up
|
||||
for name, size in (("a.gguf.part", 400_000), ("a.gguf.part", 1_500_000)):
|
||||
(folder / name).write_bytes(b"x" * size)
|
||||
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
|
||||
(folder / "a.gguf.part").rename(folder / "a.gguf")
|
||||
(folder / "b.gguf.part").write_bytes(b"x" * 100_000)
|
||||
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
|
||||
(folder / "b.gguf.part").write_bytes(b"x" * 1_000_000)
|
||||
seen.append(self.mcp.combined_progress(dict(step5), job)["download"])
|
||||
done = [d["done_gb"] for d in seen]
|
||||
self.assertEqual(done, sorted(done), done)
|
||||
self.assertEqual(seen[-1]["total_gb"], 0.004)
|
||||
self.assertAlmostEqual(seen[-1]["remaining_gb"], 0.004 - seen[-1]["done_gb"], places=2)
|
||||
self.assertTrue(all(d["file"] == "model files" for d in seen))
|
||||
# not a download any more once setup is preparing the files
|
||||
self.assertNotIn("download", self.mcp.combined_progress({"step": "6/7: preparing the model for Strata", "download": {"x": 1}}, job))
|
||||
# a resumed install counts what is already on disk
|
||||
self.assertGreater(self.mcp.combined_progress(dict(step5), job)["download"]["done_gb"], 0)
|
||||
|
||||
@unittest.skipUnless(os.name == "nt" or sys.platform.startswith("linux"), "a PC with a GPU probe")
|
||||
def test_a_real_install_reaches_the_model_download_with_nothing_else_acquired(self):
|
||||
"""setup.py in the app's mode, as the install job runs it: steps 1-4 pass (PC check, packages bundled, engine component
|
||||
optional, llama.cpp source already present) and step 5 asks for the model file. The model host is a folder that does
|
||||
not exist, so nothing is downloaded; pip, git, cmake and winget shims that record any call must stay unused."""
|
||||
import setup as plain
|
||||
if not plain.gpus():
|
||||
self.skipTest("no NVIDIA GPU here: setup stops at step 1")
|
||||
import shutil
|
||||
if shutil.disk_usage(self.tmp.name).free < 130 * 10**9:
|
||||
self.skipTest("less than 130 GB free: setup stops at its disk check before the download step")
|
||||
home = Path(self.tmp.name) / "home"
|
||||
shims = Path(self.tmp.name) / "shims"
|
||||
for p in (home / "third_party" / "llama.cpp" / "ggml", home / "third_party" / "llama.cpp" / "gguf-py", shims):
|
||||
p.mkdir(parents=True)
|
||||
(home / "third_party" / "llama.cpp" / "ggml" / "CMakeLists.txt").write_text("", encoding="utf-8")
|
||||
log = Path(self.tmp.name) / "shim.log"
|
||||
for tool in ("pip", "pip3", "git", "cmake", "ninja", "winget", "curl", "wget", "cl", "make"):
|
||||
if os.name == "nt":
|
||||
(shims / f"{tool}.cmd").write_text(f"@echo {tool} %* >> \"{log}\"\r\n", encoding="utf-8")
|
||||
else:
|
||||
(shims / tool).write_text(f"#!/bin/sh\necho {tool} \"$@\" >> '{log}'\n", encoding="utf-8")
|
||||
(shims / tool).chmod(0o755)
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("STRATA_NO_ACQUIRE", "PYTHONPATH", "VIRTUAL_ENV")}
|
||||
env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(home), APPDATA=str(Path(self.tmp.name) / "appdata"),
|
||||
XDG_CONFIG_HOME=str(Path(self.tmp.name) / "xdg"), STRATA_COMPONENTS_DIR=str(Path(self.tmp.name) / "components"),
|
||||
HF_ENDPOINT=(Path(self.tmp.name) / "no-such-hf").as_uri(), PATH=str(shims) + os.pathsep + env.get("PATH", ""),
|
||||
PYTHONIOENCODING="utf-8")
|
||||
done = subprocess.run([sys.executable, str(ROOT / "setup.py"), "--yes", "--no-start", "--family", "qwen", "--model", "Q2_0",
|
||||
"--context", "32768", "--vision", "no", "--experimental-speed-projection", "off"],
|
||||
capture_output=True, text=True, env=env, cwd=str(ROOT), stdin=subprocess.DEVNULL, timeout=300)
|
||||
out = done.stdout + done.stderr
|
||||
self.assertNotEqual(done.returncode, 0)
|
||||
self.assertIn("bundled with the app", out)
|
||||
self.assertIn("Step 5: downloading", out)
|
||||
self.assertIn("Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", out)
|
||||
self.assertFalse(log.exists(), "something ran pip, git, cmake or a package manager: " + (log.read_text() if log.exists() else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
class FailedStartTests(unittest.TestCase):
|
||||
def test_a_failed_start_carries_the_last_lines_the_server_wrote(self):
|
||||
"""The app turns `server_exited` into words and keeps the reason under Details: Control reports the log's last lines."""
|
||||
from strata_control import runtime
|
||||
owner = [c for _, c in vars(runtime).items() if isinstance(c, type) and hasattr(c, "_log_tail")][0]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
fake = mock.Mock()
|
||||
fake.state_path = Path(directory) / "app-1.json"
|
||||
fake.name = "app-1"
|
||||
self.assertIsNone(owner._log_tail(fake)) # no log: nothing, no exception
|
||||
(Path(directory) / "app-1.server.log").write_text("loading\n\nmemory guard: 5.1 GiB free is under 6 GiB\nthe engine process ended: exit code 3\n", encoding="utf-8")
|
||||
tail = owner._log_tail(fake)
|
||||
self.assertIn("memory guard: 5.1 GiB free", tail)
|
||||
self.assertTrue(tail.endswith("exit code 3"))
|
||||
self.assertNotIn("loading", tail.split(" | ")[0] if tail.count(" | ") > 2 else "")
|
||||
|
||||
|
||||
class DeleteModelTests(unittest.TestCase):
|
||||
"""Deleting a downloaded model removes its own files and run config, never what another installed model still uses."""
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
base = Path(self.tmp.name)
|
||||
self.root = base / "install"
|
||||
self.root.mkdir()
|
||||
self.data = base / "Strata-data"
|
||||
spec = importlib.util.spec_from_file_location("strata_mcp_for_delete", ROOT / "tools" / "strata_mcp.py")
|
||||
self.mcp = importlib.util.module_from_spec(spec)
|
||||
with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(self.root)}):
|
||||
spec.loader.exec_module(self.mcp)
|
||||
self.s = self.mcp.Strata(self.root, ROOT)
|
||||
self.tools = self.mcp.Tools(self.s)
|
||||
|
||||
def make(path: Path, size: int):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"x" * size)
|
||||
return path
|
||||
self.make = make
|
||||
mtp = self.data / "mtp" / "rt"
|
||||
make(mtp / "experts.bin", 3000)
|
||||
shared_ple = make(self.data / "models" / "Q2_0" / "shard-2.gguf", 2000) # the same second shard in both models
|
||||
for tag, size in (("iq3_s", 10000), ("q2_0", 4000)):
|
||||
folder = self.data / "models" / tag
|
||||
first = make(folder / "shard-1.gguf", size)
|
||||
make(first.with_name(first.name + ".done"), 1)
|
||||
pack = self.data / "packs" / tag
|
||||
make(pack / "tokenizer" / "vocab.json", 500)
|
||||
(self.root / f"strata-{tag}.json").write_text(json.dumps({"exe": "component:strata-engine", "args": [
|
||||
"--pack", str(pack), "--native", str(first), "--ple-gguf", str(shared_ple), "--mtp", str(mtp), "--max-context", "32768"]}), encoding="utf-8")
|
||||
(self.root / f"strata-{tag}.log").write_text("log", encoding="utf-8")
|
||||
|
||||
def test_the_plan_names_what_goes_and_what_stays(self):
|
||||
plan = self.tools.strata_remove(model="iq3_s")["plan"]
|
||||
removed = {Path(x["path"]).name for x in plan["remove"]}
|
||||
kept = {Path(x["path"]).name for x in plan["keep"]}
|
||||
self.assertIn("shard-1.gguf", removed)
|
||||
self.assertIn("iq3_s", removed) # its pack folder
|
||||
self.assertIn("strata-iq3_s.json", removed)
|
||||
self.assertEqual(kept, {"shard-2.gguf", "rt"}) # the shared PLE shard and the shared MTP draft
|
||||
self.assertEqual(plan["bytes"], 10000 + 1 + 500 + 3 + (self.root / "strata-iq3_s.json").stat().st_size)
|
||||
|
||||
def test_confirm_deletes_only_that_model_and_the_other_still_has_everything(self):
|
||||
result = self.tools.strata_remove(model="iq3_s", confirm=True)
|
||||
self.assertEqual(result["failed"], [])
|
||||
self.assertFalse((self.data / "models" / "iq3_s").exists()) # its folder is gone with its file
|
||||
self.assertFalse((self.data / "packs" / "iq3_s").exists())
|
||||
self.assertFalse((self.root / "strata-iq3_s.json").exists())
|
||||
self.assertTrue((self.data / "models" / "Q2_0" / "shard-2.gguf").is_file())
|
||||
self.assertTrue((self.data / "mtp" / "rt" / "experts.bin").is_file())
|
||||
self.assertTrue((self.data / "models" / "q2_0" / "shard-1.gguf").is_file())
|
||||
self.assertTrue((self.data / "packs" / "q2_0" / "tokenizer" / "vocab.json").is_file())
|
||||
self.assertTrue((self.root / "strata-q2_0.json").is_file())
|
||||
|
||||
def test_the_last_model_takes_its_shared_files_with_it(self):
|
||||
self.tools.strata_remove(model="iq3_s", confirm=True)
|
||||
self.tools.strata_remove(model="q2_0", confirm=True)
|
||||
self.assertFalse((self.data / "mtp" / "rt").exists())
|
||||
self.assertFalse((self.data / "models" / "Q2_0" / "shard-2.gguf").exists())
|
||||
|
||||
def test_nothing_outside_strata_s_folders_is_touched_and_each_model_reports_its_own_disk_use(self):
|
||||
outside = Path(self.tmp.name) / "elsewhere" / "mine.gguf"
|
||||
self.make(outside, 777)
|
||||
cfg = self.root / "strata-q2_0.json"
|
||||
data = json.loads(cfg.read_text())
|
||||
data["args"] += ["--ple-gguf", str(outside)]
|
||||
cfg.write_text(json.dumps(data), encoding="utf-8")
|
||||
plan = self.tools.strata_remove(model="q2_0")["plan"]
|
||||
self.assertIn("mine.gguf", {Path(x["path"]).name for x in plan["keep"]})
|
||||
self.tools.strata_remove(model="q2_0", confirm=True)
|
||||
self.assertTrue(outside.is_file())
|
||||
described = self.s.describe_config(self.root / "strata-iq3_s.json")
|
||||
self.assertGreater(described["disk_bytes"], 10000)
|
||||
|
||||
|
||||
class LocalGgufInstallTests(unittest.TestCase):
|
||||
def test_a_plan_from_a_local_folder_adopts_the_files_and_needs_no_download_space(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / "install"
|
||||
root.mkdir()
|
||||
local = Path(tmp) / "mine"
|
||||
local.mkdir()
|
||||
spec = importlib.util.spec_from_file_location("strata_mcp_for_local", ROOT / "tools" / "strata_mcp.py")
|
||||
mcp = importlib.util.module_from_spec(spec)
|
||||
with mock.patch.dict(os.environ, {"STRATA_CONTROL_INSTALL": "1", "STRATA_INSTALL_DIR": str(root)}):
|
||||
spec.loader.exec_module(mcp)
|
||||
tools = mcp.Tools(mcp.Strata(root, ROOT))
|
||||
plan, args = tools.install_plan("qwen", "IQ3_S", 32768, "no", None, None, None, None, None, None, None, str(local))
|
||||
self.assertIn("--gguf-dir", args)
|
||||
self.assertEqual(args[args.index("--gguf-dir") + 1], str(local))
|
||||
self.assertLessEqual(plan["disk_needed_gb"], 9) # the 8 GB for preparing, not the download
|
||||
with self.assertRaises(mcp.ToolError):
|
||||
tools.install_plan("qwen", "IQ3_S", 32768, "no", None, None, None, None, None, None, None, str(local / "missing"))
|
||||
@@ -0,0 +1,101 @@
|
||||
r"""The Windows installer must never touch the user's data. The app lives in %LOCALAPPDATA%\Programs\Strata; %LOCALAPPDATA%\Strata
|
||||
holds engines, model run configs, tuning. A build that installed the app into the data folder is migrated by removing only its app
|
||||
files. Exercised with makensis on a temp layout (the template's own migration macro, extracted and run); skipped without NSIS."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TEMPLATE = ROOT / "apps" / "desktop" / "src-tauri" / "nsis" / "installer.nsi"
|
||||
MAKENSIS = Path(os.environ.get("LOCALAPPDATA", "")) / "tauri" / "NSIS" / "makensis.exe"
|
||||
DATA = ["components/engine/0.1.45/strata.exe", "install/strata-iq3_s.json", "procs/p.json", "runtime/r.json", "time-skip/t.json",
|
||||
"presets/p.json"]
|
||||
APP = ["strata-desktop.exe", "uninstall.exe", "host/server/index.mjs", "node/node.exe", "control/python/python.exe"]
|
||||
BS = "\\"
|
||||
|
||||
|
||||
def touch(base: Path, names):
|
||||
for name in names:
|
||||
path = base / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("x", encoding="utf-8")
|
||||
|
||||
|
||||
class TemplateTests(unittest.TestCase):
|
||||
text = TEMPLATE.read_text(encoding="utf-8")
|
||||
|
||||
def test_the_default_folder_is_programs_strata_and_the_data_folder_is_never_remembered_as_the_app(self):
|
||||
self.assertIn(r'StrCpy $INSTDIR "$LOCALAPPDATA\Programs\${PRODUCTNAME}"', self.text)
|
||||
self.assertIn(r'StrCmp $4 "$LOCALAPPDATA\${PRODUCTNAME}" restore_done 0', self.text)
|
||||
self.assertIn("StrIsUnder", self.text) # a remembered folder under Temp is ignored too
|
||||
|
||||
def test_the_uninstaller_removes_files_one_by_one_and_only_empty_folders(self):
|
||||
uninstall = self.text[self.text.index("Section Uninstall"):]
|
||||
self.assertNotRegex(uninstall, r'RMDir /r "\$INSTDIR"')
|
||||
self.assertNotIn(r'RmDir /r "$LOCALAPPDATA\${PRODUCTNAME}"', self.text)
|
||||
self.assertIn(r'RmDir /r "$LOCALAPPDATA\${BUNDLEID}"', self.text)
|
||||
|
||||
|
||||
@unittest.skipUnless(MAKENSIS.is_file(), "NSIS (the Tauri bundler's copy) is not installed here")
|
||||
class MigrationTests(unittest.TestCase):
|
||||
def run_nsis(self, body: str, work: Path):
|
||||
block = re.search(r"; STRATA-MIGRATE-BEGIN.*?; STRATA-MIGRATE-END", TEMPLATE.read_text(encoding="utf-8"), re.S).group(0)
|
||||
script = work / "t.nsi"
|
||||
script.write_text('Unicode true\nOutFile "t.exe"\nRequestExecutionLevel user\nSilentInstall silent\n' + block + "\nSection\n" + body + "\nSectionEnd\n", encoding="utf-8")
|
||||
done = subprocess.run([str(MAKENSIS), "/V1", str(script)], cwd=work, capture_output=True, text=True)
|
||||
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
|
||||
subprocess.run([str(work / "t.exe")], cwd=work, check=True, timeout=60)
|
||||
|
||||
def layout(self, base: Path) -> Path:
|
||||
old = base / "Strata"
|
||||
touch(old, DATA + APP)
|
||||
return old
|
||||
|
||||
def test_migration_removes_only_the_old_app_files_and_keeps_every_bit_of_data(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
old = self.layout(base)
|
||||
new = base / "Programs" / "Strata"
|
||||
self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{new}"', base)
|
||||
for name in DATA:
|
||||
self.assertTrue((old / name).is_file(), f"data kept: {name}")
|
||||
for name in APP:
|
||||
self.assertFalse((old / name).exists(), f"app file removed: {name}")
|
||||
for folder in ("host", "node", "control"):
|
||||
self.assertFalse((old / folder).exists())
|
||||
|
||||
def test_migration_does_nothing_when_old_and_new_are_the_same_or_there_is_no_old_app(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
old = self.layout(base)
|
||||
self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{old}" "{old}"', base)
|
||||
for name in DATA + APP:
|
||||
self.assertTrue((old / name).is_file(), name)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
touch(base / "Strata", DATA) # data only: no strata-desktop.exe
|
||||
self.run_nsis(f'!insertmacro StrataMigrateOldInstall "{base / "Strata"}" "{base / "Programs" / "Strata"}"', base)
|
||||
for name in DATA:
|
||||
self.assertTrue((base / "Strata" / name).is_file(), name)
|
||||
|
||||
def test_an_uninstall_of_the_template_kind_leaves_data_in_a_shared_folder(self):
|
||||
"""The uninstaller deletes named files and uses non-recursive RMDir: in a folder that also holds data (a legacy install) the
|
||||
data and so the folder stay."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
old = self.layout(base)
|
||||
lines = [f'Delete "{old}{BS}{n.replace("/", BS)}"' for n in APP]
|
||||
lines += [f'RMDir "{old}{BS}{d}"' for d in ("host" + BS + "server", "host", "node", "control" + BS + "python", "control")]
|
||||
lines += [f'RMDir "{old}"']
|
||||
self.run_nsis("\n".join(lines), base)
|
||||
for name in DATA:
|
||||
self.assertTrue((old / name).is_file(), name)
|
||||
self.assertFalse((old / "strata-desktop.exe").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -43,6 +43,9 @@ PROTOCOLS = ("2025-06-18", "2025-03-26", "2024-11-05") # the revisions this se
|
||||
VERSION = "0.1.0"
|
||||
WIN = os.name == "nt"
|
||||
DEFAULT_ROOT = Path(__file__).resolve().parent.parent
|
||||
# The desktop app runs this under Strata Control's Python (STRATA_CONTROL_INSTALL=1): the install runs on that Python, makes no
|
||||
# .venv and installs no package (setup.py's own CONTROL mode).
|
||||
CONTROL = os.environ.get("STRATA_CONTROL_INSTALL") == "1"
|
||||
DEFAULT_PORT = 8080
|
||||
STATE_DIR = ".strata-mcp" # in the Strata folder (git-ignored)
|
||||
|
||||
@@ -404,15 +407,18 @@ def system_folders() -> list[Path]:
|
||||
class Strata:
|
||||
"""One Strata folder: what is installed there, the PC, and the processes this server started."""
|
||||
|
||||
def __init__(self, root: Path | str = DEFAULT_ROOT):
|
||||
def __init__(self, root: Path | str = DEFAULT_ROOT, src: Path | str | None = None):
|
||||
self.root = Path(root).resolve()
|
||||
# where setup.py, tools/ and serve/ are (the app: inside Strata Control); `root` is where the installs live
|
||||
self.src = Path(src).resolve() if src else self.root
|
||||
self.state_dir = self.root / STATE_DIR
|
||||
self.lock = threading.Lock() # install / start / stop one at a time
|
||||
self.children: list[subprocess.Popen] = [] # reaped now and then (no zombies on POSIX)
|
||||
self._setup = None
|
||||
self._setup_tried = False
|
||||
self._hw_cache = None
|
||||
self.python_override: str | None = None # tests: the interpreter that runs setup / the server
|
||||
# tests: the interpreter that runs setup / the server. The app's Control runs the installer on its own Python.
|
||||
self.python_override: str | None = sys.executable if CONTROL else None
|
||||
self.health_timeout = 2.0
|
||||
|
||||
# ---- setup.py's own tables and logic
|
||||
@@ -422,7 +428,9 @@ class Strata:
|
||||
if not self._setup_tried:
|
||||
self._setup_tried = True
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.root / "setup.py")
|
||||
if str(self.src) not in sys.path:
|
||||
sys.path.insert(0, str(self.src)) # setup.py imports strata_control
|
||||
spec = importlib.util.spec_from_file_location("strata_setup_for_mcp", self.src / "setup.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
real = sys.stdout
|
||||
sys.stdout = sys.stderr # nothing it prints may reach the protocol stream
|
||||
@@ -528,8 +536,78 @@ class Strata:
|
||||
"low_ram": "--resident-experts" in a or "--mmap-experts" in a,
|
||||
"start_script": script.name if script.exists() else None,
|
||||
"ready": not missing and bool(cfg), "missing_files": missing[:3],
|
||||
"disk_gb": self.removal_plan(path)["gb"], "disk_bytes": self.removal_plan(path)["bytes"],
|
||||
"last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))}
|
||||
|
||||
# ---- what a model owns on disk (Delete, and the per-model disk usage in Storage)
|
||||
FILE_FLAGS = ("--native", "--ple-gguf", "--embd-gguf", "--native-dense-gguf")
|
||||
DIR_FLAGS = ("--pack", "--mtp")
|
||||
|
||||
def model_paths(self, cfg: dict) -> tuple[list, list]:
|
||||
"""(the GGUF files, the folders) a run config names: --native/--ple-gguf/... and --pack/--mtp, plus any other .gguf."""
|
||||
a = [x for x in (cfg.get("args") or []) if isinstance(x, str)]
|
||||
files = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.FILE_FLAGS]
|
||||
files += [Path(x) for x in a if x.lower().endswith(".gguf") and Path(x) not in files]
|
||||
dirs = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.DIR_FLAGS]
|
||||
return files, dirs
|
||||
|
||||
@staticmethod
|
||||
def tree_bytes(path: Path) -> int:
|
||||
if path.is_file():
|
||||
try:
|
||||
return path.stat().st_size
|
||||
except OSError:
|
||||
return 0
|
||||
total = 0
|
||||
for base, _d, names in os.walk(path):
|
||||
for n in names:
|
||||
try:
|
||||
total += os.stat(os.path.join(base, n)).st_size
|
||||
except OSError:
|
||||
pass
|
||||
return total
|
||||
|
||||
def removal_plan(self, config: Path) -> dict:
|
||||
"""What deleting this model removes and what it keeps. A file or folder another installed model's config still names
|
||||
(the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders."""
|
||||
cfg = self.read_config(config)
|
||||
files, dirs = self.model_paths(cfg)
|
||||
used_files, used_dirs = set(), set()
|
||||
for other in self.configs():
|
||||
if norm(other) == norm(config):
|
||||
continue
|
||||
f, d = self.model_paths(self.read_config(other))
|
||||
used_files |= {norm(x) for x in f}
|
||||
used_dirs |= {norm(x) for x in d}
|
||||
remove, keep = [], []
|
||||
|
||||
def shared(p: Path, is_dir: bool) -> bool:
|
||||
n = norm(p)
|
||||
if n in used_files or n in used_dirs or any(is_inside(u, n) for u in used_files | used_dirs) and is_dir:
|
||||
return True
|
||||
return any(is_inside(n, u) for u in used_dirs)
|
||||
|
||||
for p, is_dir in [(x, False) for x in files] + [(x, True) for x in dirs]:
|
||||
if not p.exists():
|
||||
continue
|
||||
if not self.allowed(p):
|
||||
keep.append({"path": str(p), "reason": "outside Strata's folders"})
|
||||
elif shared(p, is_dir):
|
||||
keep.append({"path": str(p), "reason": "another installed model still uses it"})
|
||||
else:
|
||||
remove.append({"path": str(p), "kind": "folder" if is_dir else "file", "bytes": self.tree_bytes(p)})
|
||||
if not is_dir:
|
||||
for extra in (p.with_name(p.name + ".done"), p.with_name(p.name + ".part")):
|
||||
if extra.exists():
|
||||
remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})
|
||||
tag = config.stem[len("strata-"):]
|
||||
for extra in (config, config.with_name(config.name + ".bak"), config.with_name(f"strata-{tag}.log"),
|
||||
self.root / f"run-{tag}.bat", self.root / f"run-{tag}.sh"):
|
||||
if extra.exists():
|
||||
remove.append({"path": str(extra), "kind": "file", "bytes": self.tree_bytes(extra)})
|
||||
total = sum(x["bytes"] for x in remove)
|
||||
return {"model": tag, "remove": remove, "keep": keep, "bytes": total, "gb": round(total / 1e9, 2)}
|
||||
|
||||
def find_config(self, model: str | None) -> Path:
|
||||
have = self.configs()
|
||||
if not have:
|
||||
@@ -839,6 +917,7 @@ class Strata:
|
||||
log_path = Path(j.get("log", ""))
|
||||
tail = read_tail(log_path, 400) if log_path.name else []
|
||||
prog = install_progress(tail)
|
||||
prog = combined_progress(prog, j)
|
||||
out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"),
|
||||
"log": str(log_path), **prog}
|
||||
if not running:
|
||||
@@ -854,6 +933,35 @@ class Strata:
|
||||
return out
|
||||
|
||||
|
||||
def combined_progress(prog: dict, job: dict) -> dict:
|
||||
"""One total for the whole model: the bytes of all its files (finished, partial and the one in flight, read from the
|
||||
model's folder) over the download size, instead of each file's own 0-100% (a two-file model went 70 GB -> 0 -> up
|
||||
again). Only while the download step runs; later steps are not a download."""
|
||||
folder, total = job.get("folder"), job.get("total_gb")
|
||||
step = str(prog.get("step") or "")
|
||||
if not folder or not total or not step.startswith("5/"):
|
||||
prog.pop("download", None)
|
||||
return prog
|
||||
done = 0
|
||||
try:
|
||||
for entry in os.scandir(folder):
|
||||
if entry.is_file() and (entry.name.endswith(".gguf") or entry.name.endswith(".part")):
|
||||
done += entry.stat().st_size
|
||||
except OSError:
|
||||
pass
|
||||
if not done: # nothing on disk yet: the log's own line is all there is
|
||||
return prog
|
||||
done_gb = min(done / 1e9, float(total))
|
||||
prog["download"] = {"file": "model files", "done_gb": round(done_gb, 3), "total_gb": float(total),
|
||||
"remaining_gb": round(max(0.0, float(total) - done_gb), 3),
|
||||
"percent": min(99, int(100 * done_gb / float(total))) if total else 0}
|
||||
# The parts of the whole job, for a progress bar that sums them (the job that fetches the engine adds its own part):
|
||||
# {kind, name, done_gb, total_gb, state}
|
||||
prog["parts"] = [{"kind": "model", "name": "Model files", "done_gb": prog["download"]["done_gb"],
|
||||
"total_gb": float(total), "state": "downloading"}]
|
||||
return prog
|
||||
|
||||
|
||||
def install_progress(lines: list[str]) -> dict:
|
||||
"""setup's progress from its output: the step, a download's percentage, a failure."""
|
||||
step, title, dl, err = None, None, None, None
|
||||
@@ -970,6 +1078,13 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list:
|
||||
"Read-only.",
|
||||
"inputSchema": {"type": "object", "additionalProperties": False, "properties": {}},
|
||||
"annotations": ro},
|
||||
{"name": "strata_remove", "title": "Delete an installed model",
|
||||
"description": "Delete an installed model's own files (its model GGUFs, its pack folder, its run config) and nothing "
|
||||
"another installed model still uses (a shared MTP draft or PLE file). Without confirm=true it only "
|
||||
"returns the plan (what would be removed and how big, what is kept). Stop the model first.",
|
||||
"inputSchema": {"type": "object", "additionalProperties": False, "required": ["model"],
|
||||
"properties": {"model": installed_model, "confirm": {"type": "boolean"}}},
|
||||
"annotations": {"readOnlyHint": False, "destructiveHint": True}},
|
||||
{"name": "strata_install", "title": "Install Strata",
|
||||
"description": "Install a Strata model on this PC by running Strata's setup non-interactively in the "
|
||||
"background (Python packages, the engine, a 58-111 GB model download, preparation, start "
|
||||
@@ -1008,6 +1123,9 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list:
|
||||
"Strata folder). Only the current data folder, a folder inside the Strata "
|
||||
"folder, or a new absolute path whose last folder is named Strata... "
|
||||
"(e.g. D:\\Strata-data) outside system folders"},
|
||||
"gguf_dir": {"type": "string", "maxLength": 260,
|
||||
"description": "a folder that already holds this model's GGUF files under their original names: setup "
|
||||
"checks them (size and SHA-256) and does not download them again"},
|
||||
"confirm": {"type": "boolean", "description": "true = really start the install (after the user agreed "
|
||||
"to the plan and the download size)"},
|
||||
"cancel": {"type": "boolean", "description": "true = stop the install in progress"}}},
|
||||
@@ -1149,6 +1267,39 @@ class Tools:
|
||||
"gpus": [{k: g.get(k) for k in ("index", "name", "vram_gb", "usable")}
|
||||
for g in hw.get("gpus", [])]}}
|
||||
|
||||
# ---- strata_remove
|
||||
def strata_remove(self, model=None, confirm=False) -> dict:
|
||||
s = self.s
|
||||
config = s.find_config(model)
|
||||
plan = s.removal_plan(config)
|
||||
if not confirm:
|
||||
return {"summary": f"Plan: delete {plan['model']} ({plan['gb']:.1f} GB). Nothing was done yet.", "plan": plan}
|
||||
with s.lock:
|
||||
job = s.install_job()
|
||||
if job and job["running"]:
|
||||
raise ToolError("an install is running: wait for it to finish or stop it first")
|
||||
tracked = s.tracked_server()
|
||||
if tracked and not tracked.get("ended") and tracked.get("model") == plan["model"]:
|
||||
raise ToolError("this model is running: stop it first")
|
||||
failed = []
|
||||
for item in sorted(plan["remove"], key=lambda x: (x["path"] == str(config), x["path"])):
|
||||
p = Path(item["path"])
|
||||
try:
|
||||
if p.is_dir():
|
||||
shutil.rmtree(p)
|
||||
else:
|
||||
p.unlink()
|
||||
except OSError as e:
|
||||
failed.append(f"{p.name}: {e}")
|
||||
files, dirs = s.model_paths(s.read_config(config)) if config.exists() else ([], [])
|
||||
for p in {x.parent for x in [Path(i["path"]) for i in plan["remove"]] if x.suffix == ".gguf"}:
|
||||
try:
|
||||
p.rmdir() # the model's own folder, when nothing else is in it
|
||||
except OSError:
|
||||
pass
|
||||
return {"summary": f"Deleted {plan['model']} ({plan['gb']:.1f} GB)" + (f"; could not remove {len(failed)} item(s)" if failed else ""),
|
||||
"plan": plan, "failed": failed}
|
||||
|
||||
# ---- strata_install
|
||||
def check_data_dir(self, raw: str) -> Path:
|
||||
s = self.s
|
||||
@@ -1177,7 +1328,8 @@ class Tools:
|
||||
return p
|
||||
|
||||
def strata_install(self, family=None, model=None, context=None, vision=None, kv=None, gpu=None, gpus=None,
|
||||
backend=None, low_ram=None, port=None, data_dir=None, confirm=False, cancel=False) -> dict:
|
||||
backend=None, low_ram=None, port=None, data_dir=None, confirm=False, cancel=False,
|
||||
gguf_dir=None) -> dict:
|
||||
s = self.s
|
||||
with s.lock:
|
||||
job = s.install_job()
|
||||
@@ -1208,7 +1360,7 @@ class Tools:
|
||||
"fix the problem above and call strata_install again with confirm=true (finished "
|
||||
"steps are skipped)"}
|
||||
plan, args = self.install_plan(family, model, context, vision, kv, gpu, gpus, backend, low_ram, port,
|
||||
data_dir)
|
||||
data_dir, gguf_dir)
|
||||
tracked = s.tracked_server()
|
||||
if tracked and not tracked.get("ended"):
|
||||
raise ToolError("Strata is running (started by strata_start): stop it first with strata_stop - setup "
|
||||
@@ -1222,7 +1374,7 @@ class Tools:
|
||||
raise ToolError(plan["disk_short"])
|
||||
return self.launch_install(plan, args)
|
||||
|
||||
def install_plan(self, family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir):
|
||||
def install_plan(self, family, model, context, vision, kv, gpu, gpus, backend, low_ram, port, data_dir, gguf_dir=None):
|
||||
s = self.s
|
||||
models, families, contexts, _src = s.tables()
|
||||
if gpu is not None and gpus is not None:
|
||||
@@ -1272,7 +1424,7 @@ class Tools:
|
||||
target = self.check_data_dir(data_dir) if data_dir else s.data_dir()
|
||||
tag = (families[family].get("tag", "") + model)
|
||||
have_dir = target / "models" / tag
|
||||
partly = have_dir.is_dir() and any(have_dir.glob("*.gguf*"))
|
||||
partly = (have_dir.is_dir() and any(have_dir.glob("*.gguf*"))) or bool(gguf_dir) # a local folder: nothing to download
|
||||
need = (8 if partly else models[model]["download_gb"] + 8) + (1 if vision in ("yes", "gpu", "cpu") else 0)
|
||||
free = s.disk_free(target)
|
||||
short = None
|
||||
@@ -1287,6 +1439,11 @@ class Tools:
|
||||
("--data-dir", str(target) if data_dir else None)):
|
||||
if v is not None:
|
||||
args += [flag, str(v)]
|
||||
if gguf_dir:
|
||||
local = Path(os.path.expandvars(gguf_dir)).expanduser()
|
||||
if not local.is_absolute() or not local.is_dir() or ".." in local.parts:
|
||||
raise ToolError("gguf_dir must be an existing absolute folder")
|
||||
args += ["--gguf-dir", str(local)]
|
||||
if backend in ("cuda", "hip"):
|
||||
args += ["--backend", backend]
|
||||
fit = None
|
||||
@@ -1297,7 +1454,8 @@ class Tools:
|
||||
installed = (s.root / f"strata-{tag.lower()}.json").exists()
|
||||
plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model,
|
||||
"context": context, "images": vision or "no", "download_gb": models[model]["download_gb"],
|
||||
"partly_downloaded": partly, "ram": fit, "data_folder": str(target), "disk_free_gb": free,
|
||||
"partly_downloaded": partly, "ram": fit, "data_folder": str(target), "model_folder": str(have_dir),
|
||||
"disk_free_gb": free,
|
||||
"disk_needed_gb": round(need), "disk_short": short, "already_installed": installed,
|
||||
"setup_command": ("START-HERE.bat " if WIN else "./setup.sh ") + " ".join(args),
|
||||
"takes": "about 20-90 minutes, mostly the download; the PC stays usable",
|
||||
@@ -1318,7 +1476,8 @@ class Tools:
|
||||
log_path = s.state_dir / "setup.log"
|
||||
with open(log_path, "a", encoding="utf-8") as f:
|
||||
f.write(f"\n===== strata-mcp: install {plan['title']} at {time.strftime('%Y-%m-%d %H:%M:%S')} =====\n")
|
||||
spec = {"job": job_id, "root": str(s.root), "python": s.run_python(), "base_python": sys.executable,
|
||||
spec = {"job": job_id, "root": str(s.root), "src": str(s.src), "control": CONTROL,
|
||||
"python": s.run_python(), "base_python": sys.executable,
|
||||
"create_venv": s.python_override is None and not s.venv_python().exists(),
|
||||
"args": args, "result": str(s.state_dir / "install-result.json")}
|
||||
spec_path = s.state_dir / "install-job.json"
|
||||
@@ -1333,7 +1492,8 @@ class Tools:
|
||||
if ident is None and p.poll() and s.state("install-result").get("job") != job_id:
|
||||
raise ToolError("setup did not start: " + " | ".join(read_tail(log_path, 5)))
|
||||
s.save_state("install", {"job": job_id, "pid": p.pid, "ident": ident, "log": str(log_path),
|
||||
"model": plan["model"], "family": plan["family"],
|
||||
"model": plan["model"], "family": plan["family"], "folder": plan.get("model_folder"),
|
||||
"total_gb": plan.get("download_gb"),
|
||||
"started": time.strftime("%Y-%m-%d %H:%M:%S"), "args": args})
|
||||
return {"summary": f"Install of {plan['title']} started in the background (about 20-90 minutes, mostly the "
|
||||
f"{plan['download_gb']:.0f} GB download). Call strata_install again to see the progress; "
|
||||
@@ -1712,6 +1872,7 @@ def install_job(spec_path: str) -> int:
|
||||
os.replace(tmp, result)
|
||||
|
||||
py = Path(spec["python"])
|
||||
src = Path(spec.get("src") or root)
|
||||
try:
|
||||
if spec.get("create_venv"):
|
||||
venv = root / ".venv"
|
||||
@@ -1727,10 +1888,18 @@ def install_job(spec_path: str) -> int:
|
||||
"once in a terminal", flush=True)
|
||||
record(exit_code=1, ended=time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
return 1
|
||||
cmd = [str(py), str(root / "setup.py"), *spec["args"]]
|
||||
cmd = [str(py), str(src / "setup.py"), *spec["args"]]
|
||||
print("strata-mcp: running " + " ".join(cmd), flush=True)
|
||||
env = dict(os.environ, PYTHONUNBUFFERED="1", PYTHONIOENCODING="utf-8")
|
||||
p = subprocess.Popen(cmd, cwd=str(root), stdin=subprocess.DEVNULL, env=env)
|
||||
if spec.get("control"): # the app: the installer's own mode, writing to `root`
|
||||
env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(root), PYTHONNOUSERSITE="1")
|
||||
for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV"):
|
||||
env.pop(key, None)
|
||||
# This job is the explicit install the user asked for (it downloads model files and the preparation sources). The
|
||||
# server that started it, and every start or serve, keep STRATA_NO_ACQUIRE; setup.py's CONTROL mode still runs
|
||||
# no pip, git, compiler or engine fetch.
|
||||
env.pop("STRATA_NO_ACQUIRE", None)
|
||||
p = subprocess.Popen(cmd, cwd=str(src if spec.get("control") else root), stdin=subprocess.DEVNULL, env=env)
|
||||
record(child_pid=p.pid, child_ident=proc_identity(p.pid))
|
||||
rc = p.wait()
|
||||
except Exception as e: # noqa: BLE001
|
||||
@@ -1745,6 +1914,7 @@ def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description="Strata's MCP server (stdio): install, start, check and stop Strata "
|
||||
"from an AI assistant. See docs/MCP_SERVER.md.")
|
||||
ap.add_argument("--root", help="the Strata folder (default: the one this file is in)")
|
||||
ap.add_argument("--src", help="where setup.py, tools/ and serve/ are, when that is not the Strata folder (the app)")
|
||||
ap.add_argument("--install-job", help=argparse.SUPPRESS)
|
||||
a = ap.parse_args(argv)
|
||||
if a.install_job:
|
||||
@@ -1753,12 +1923,13 @@ def main(argv=None) -> int:
|
||||
log("Python 3.10 or newer is needed")
|
||||
return 2
|
||||
root = Path(a.root).expanduser().resolve() if a.root else DEFAULT_ROOT
|
||||
if not (root / "setup.py").is_file() or not (root / "serve" / "server.py").is_file():
|
||||
log(f"{root} is not a Strata folder (no setup.py / serve/server.py)")
|
||||
src = Path(a.src).expanduser().resolve() if a.src else root
|
||||
if not (src / "setup.py").is_file() or not (src / "serve" / "server.py").is_file():
|
||||
log(f"{src} is not a Strata folder (no setup.py / serve/server.py)")
|
||||
return 2
|
||||
out = sys.stdout.buffer
|
||||
sys.stdout = sys.stderr # stray prints must never corrupt the protocol stream
|
||||
server = McpServer(Strata(root), out)
|
||||
server = McpServer(Strata(root, src), out)
|
||||
log(f"ready (Strata folder {root})")
|
||||
try:
|
||||
server.serve(sys.stdin.buffer)
|
||||
|
||||
@@ -233,7 +233,7 @@ class Protocol(FakeRoot):
|
||||
self.assertIn("tools", init["capabilities"])
|
||||
self.assertEqual(init["serverInfo"]["name"], "strata")
|
||||
names = [t["name"] for t in r[2]["result"]["tools"]]
|
||||
self.assertEqual(names, ["strata_status", "strata_models", "strata_install", "strata_start", "strata_stop",
|
||||
self.assertEqual(names, ["strata_status", "strata_models", "strata_remove", "strata_install", "strata_start", "strata_stop",
|
||||
"strata_logs", "strata_benchmark", "strata_connect_info"])
|
||||
for t in r[2]["result"]["tools"]:
|
||||
self.assertEqual(t["inputSchema"]["type"], "object")
|
||||
@@ -272,7 +272,7 @@ class Protocol(FakeRoot):
|
||||
timeout=60, env=dict(os.environ))
|
||||
lines = [json.loads(x) for x in p.stdout.splitlines()]
|
||||
self.assertEqual(sorted(m["id"] for m in lines), [1, 2, 3])
|
||||
self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 8)
|
||||
self.assertEqual(len(next(m for m in lines if m["id"] == 2)["result"]["tools"]), 9)
|
||||
self.assertIn("ready", p.stderr)
|
||||
|
||||
def test_not_a_strata_folder(self):
|
||||
|
||||