Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
first-run feedback 2: plain words for failures with Details, parts-based download progress, reading size reaches all conversation text, tuning pop-up fits its error, headless UI flows, installer mock-ups
Niko12215df75b1d4d2a
diff --git a/apps/desktop/scripts/installer-mockups.mjs b/apps/desktop/scripts/installer-mockups.mjsnew file mode 100644index 000000000..cc7a3c8f2--- /dev/null+++ b/apps/desktop/scripts/installer-mockups.mjs@@ -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'));diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjsnew file mode 100644index 000000000..a25fb40cd--- /dev/null+++ b/apps/desktop/scripts/ui-flows.mjs@@ -0,0 +1,353 @@+#!/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,theme').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+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_status': return {'summary': 'fake', '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')]}+ 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+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)+print('READY 4096 stop', 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+ for ch in os.environ.get('FAKE_REPLY', 'a'):+ print('T %d' % ord(ch), flush=True)+ print('DONE 1 1 1.0 1.0 length 0 0 0', 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, 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 = 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 }, ...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)');+ check(page.problems.length === 0, 'no page error', page.problems.join('; '));+});++// ------------------------------------------------------------------------------------------------ tune + reading size+await scenario('tune', { installed: true, env: { 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(() => {});+ const sizes = [];+ for (const px of [12, 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 });+ 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; })));+ 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] === 16 && sizes[2][1] === 22 && sizes[0][2] === 12 && sizes[2][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('ArrowLeft');+ 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('; '));+});++// ------------------------------------------------------------------------------------------------ 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) && /memory guard: 5\.1 GiB/.test(details), 'Details holds the code and the last engine line', 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;+});++// ------------------------------------------------------------------------------------------------ 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);diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjsindex 515c95fd3..a71519ca0 100644--- a/apps/host/server/native-control.mjs+++ b/apps/host/server/native-control.mjs@@ -42,11 +42,9 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},spfunction sourceText(){try{return readFileSync(join(packaged?control.control.dir:preferences.repo,'serve/server.py'),'utf8');}catch{return '';}}function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));}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` says nothing a person can act on. The usual cause is the PC running low on memory- (the engine's own guard, or the OS); say that, what to try, and the last thing the engine wrote. */- function humanStartError(error){const text=String(error?.message??error),tail=error?.output?.log_tail;- if(!/server_exited|exited|memory|killed|oom/i.test(text)&&!/memory|alloc|guard|killed/i.test(tail??''))return text;- return `The engine stopped before it was ready, most likely because the PC ran low on memory. Close other programs and try again, choose “Leave 20% for my work”, or turn on the low-RAM option so part of the model is read from the SSD instead of kept in memory.${tail?` Last engine message: ${tail}`:''}`;}+ /* 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;}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 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;}diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsxindex 1e71c64c6..4bbe713e6 100644--- a/apps/host/src/components/GuidedSetup.tsx+++ b/apps/host/src/components/GuidedSetup.tsx@@ -12,7 +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 { useDownloadEta } from '../lib/download-eta';+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))@@ -142,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(() => {diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsxindex 2501f5ca2..3de86f6ce 100644--- a/apps/host/src/components/NativeModels.tsx+++ b/apps/host/src/components/NativeModels.tsx@@ -2,7 +2,8 @@ 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 { useDownloadEta } from '../lib/download-eta';+import { installProgress, useDownloadEta } from '../lib/download-eta';+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';@@ -86,11 +87,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEnginereturn; 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)}@@ -111,7 +112,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine}export function NativeProgress({ job }: {job: NativeJob;-}) { const download = job.result?.install?.download; 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 {+}) { 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) {@@ -119,4 +120,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' ? <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' ? (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)}%{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></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' ? (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)}%{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>; }diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsxindex 7b4c27f34..b7b3da7dd 100644--- a/apps/host/src/components/ui.tsx+++ b/apps/host/src/components/ui.tsx@@ -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; }diff --git a/apps/host/src/lib/download-eta.ts b/apps/host/src/lib/download-eta.tsindex 6cb466700..64b5c556f 100644--- a/apps/host/src/lib/download-eta.ts+++ b/apps/host/src/lib/download-eta.ts@@ -13,8 +13,11 @@ export function etaMinutes(samples: { at: number; done: number }[], remainingGb:export function etaLabel(minutes: number | null): string {if (minutes === null) return '';- if (minutes >= 90) { const h = Math.floor(minutes / 60), m = minutes % 60; return `${tr('About')} ${h} ${tr('h')}${m ? ` ${m} ${tr('min')}` : ''} ${tr('left')}`; }- return `${tr('About')} ${minutes} ${tr('min left')}`;+ 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. */@@ -34,3 +37,19 @@ export function useDownloadEta(download: { done_gb?: number; remaining_gb?: numb}, [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;+}diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.tsindex b4fb4df8a..fbdd66e22 100644--- a/apps/host/src/lib/native.ts+++ b/apps/host/src/lib/native.ts@@ -4,7 +4,7 @@ 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}}let state:NativeState|null=null,timer:ReturnType<typeof setInterval>|null=null,reading:Promise<void>|null=null;diff --git a/apps/host/src/lib/plain-errors.ts b/apps/host/src/lib/plain-errors.tsnew file mode 100644index 000000000..23f30561c--- /dev/null+++ b/apps/host/src/lib/plain-errors.ts@@ -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 };+}diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.tsindex 24901631d..18703366e 100644--- a/apps/host/src/lib/store.ts+++ b/apps/host/src/lib/store.ts@@ -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';@@ -1341,7 +1342,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 => {@@ -1368,7 +1369,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,diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex 0c48de2e8..5ade6d0d9 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -2568,5 +2568,27 @@"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."}diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex 7ce504b5e..de1c65cd1 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -2568,5 +2568,27 @@"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."}diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex 9ebba966d..9be5f93db 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -2568,5 +2568,27 @@"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."}diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex 0a8afb22c..7a9adc0f3 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -2568,5 +2568,27 @@"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": "もう一度お試しください。それでも解決しない場合は「詳細」を開き、サポートに問い合わせる際に共有してください。"}diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex b5f365650..5f683a473 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -2568,5 +2568,27 @@"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": "다시 시도하세요. 계속되면 “세부 정보”를 열어 도움을 요청할 때 함께 알려 주세요."}diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex 41853a9da..8b5e61804 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -2568,5 +2568,27 @@"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."}diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex af2300360..466e49084 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -2568,5 +2568,27 @@"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": "Повторите попытку. Если проблема остаётся, откройте «Подробности» и приложите их, когда будете обращаться за помощью."}diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex 83e2e3e56..724688022 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -2568,5 +2568,27 @@"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": "请重试。如果问题持续出现,请展开“详情”,并在求助时一并提供。"}diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.cssindex b00cdf8cd..b37f74af0 100644--- a/apps/host/src/styles/app.css+++ b/apps/host/src/styles/app.css@@ -6993,3 +6993,15 @@ 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, 16px) * .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, 16px) * .8125); }+.st-msg--assistant .st-collapse__body { font-size: calc(var(--st-content-fs, 16px) * .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); }diff --git a/apps/host/src/styles/onboarding.css b/apps/host/src/styles/onboarding.cssindex cc88ad030..84e885c61 100644--- a/apps/host/src/styles/onboarding.css+++ b/apps/host/src/styles/onboarding.css@@ -242,3 +242,4 @@@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}diff --git a/apps/host/tests/download-eta.test.mjs b/apps/host/tests/download-eta.test.mjsnew file mode 100644index 000000000..70ee005ba--- /dev/null+++ b/apps/host/tests/download-eta.test.mjs@@ -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);+});diff --git a/apps/host/tests/packaged-control.test.mjs b/apps/host/tests/packaged-control.test.mjsindex 579907d58..f6ce53ccc 100644--- a/apps/host/tests/packaged-control.test.mjs+++ b/apps/host/tests/packaged-control.test.mjs@@ -296,18 +296,13 @@ test('packaged: the catalog offers no picture reading (app installs have none),} finally { await f.native.close(); f.cleanup(); }});-test('packaged: an engine that stops while loading is explained in words, with the engine\'s last line', async () => {+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);- const control = f.native;- // the fixture's Control starts fine; make start fail the way Control reports a dead enginef.failStart({ message: 'server_exited', output: { log_tail: 'memory guard: 5.1 GiB free is under the 6 GiB limit' } });- const job = await finish(control, control.operation('load', { model: 'iq2_xs' }).id);+ const job = await finish(f.native, f.native.operation('load', { model: 'iq2_xs' }).id);assert.equal(job.state, 'error');- assert.match(job.error, /ran low on memory/);- assert.match(job.error, /Leave 20% for my work/);- assert.match(job.error, /memory guard: 5\.1 GiB free/);- assert.doesNotMatch(job.error, /^server_exited$/);+ assert.match(job.error, /^server_exited: memory guard: 5\.1 GiB free/);} finally { await f.native.close(); f.cleanup(); }});diff --git a/apps/host/tests/plain-errors.test.mjs b/apps/host/tests/plain-errors.test.mjsnew file mode 100644index 000000000..fbb9c840f--- /dev/null+++ b/apps/host/tests/plain-errors.test.mjs@@ -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');+});diff --git a/strata_control/runtime.py b/strata_control/runtime.pyindex 1f4774518..5ec301a92 100644--- a/strata_control/runtime.py+++ b/strata_control/runtime.py@@ -798,15 +798,18 @@ class Host:self.last_error = result["error"]def _log_tail(self, limit: int = 4096) -> str | None:- """The last line the server wrote (a failed start is explained by it), or None. Bounded read, never raises."""+ """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.strip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()]+ lines = [x.rstrip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()]except OSError:return None- return lines[-1][:300] if lines else 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 Nonedef _status(self) -> dict:child = self.childdiff --git a/tests/desktop/test_control_install.py b/tests/desktop/test_control_install.pyindex c8449cc8d..d1650f066 100644--- a/tests/desktop/test_control_install.py+++ b/tests/desktop/test_control_install.py@@ -255,3 +255,20 @@ class InstallerServerTests(unittest.TestCase):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 "")diff --git a/tools/strata_mcp.py b/tools/strata_mcp.pyindex 8abd108a7..64fc3e29f 100644--- a/tools/strata_mcp.py+++ b/tools/strata_mcp.py@@ -885,6 +885,10 @@ def combined_progress(prog: dict, job: dict) -> dict: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