diff --git a/apps/desktop/scripts/first-run-ui.mjs b/apps/desktop/scripts/first-run-ui.mjs new file mode 100644 index 00000000..757905cd --- /dev/null +++ b/apps/desktop/scripts/first-run-ui.mjs @@ -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 ] [--node ] [--work ] [--shots ] + * + * 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); diff --git a/apps/desktop/scripts/installer-mockups.mjs b/apps/desktop/scripts/installer-mockups.mjs new file mode 100644 index 00000000..cc7a3c8f --- /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 ] + */ +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 = ''; +const folder = ''; + +const screens = { + welcome: theme => `
+

State of the art. At home.

Strata runs AI on your own computer.
Setting it up takes a few minutes.

+
${check}Private${check}Fast${check}Easy to use
+
Installs for you only. No administrator needed.
`, + where: theme => `
+

Where should Strata go?

This is the right place for most people.

+
${folder}
Your Strata folderC:\\Users\\Alex\\AppData\\Local\\Strata
+

About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.

+
`, + installing: theme => `
+

Installing Strata…

Copying the app and its engine room. You can keep working meanwhile.

+
+
62% · 190 / 310 MB
About 1 min left
+
Next: choose your first model inside Strata.
`, + done: theme => `
+

Strata is ready.

Open it to pick your first model. Strata downloads it for you and gets it ready.

+
A shortcut was added to your Start menu and desktop.
`, +}; + +const page = (name, theme) => `
Strata setup– ☐ ✕
+
${screens[name](theme)}
`; + +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/make-icons.mjs b/apps/desktop/scripts/make-icons.mjs new file mode 100644 index 00000000..411e4b97 --- /dev/null +++ b/apps/desktop/scripts/make-icons.mjs @@ -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 ] writes icon-.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 => ``).join(''); + return `${rects}`; +} + +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(`${svg(size)}`); + 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(',')); diff --git a/apps/desktop/scripts/make-installer-images.mjs b/apps/desktop/scripts/make-installer-images.mjs new file mode 100644 index 00000000..f12d6cc1 --- /dev/null +++ b/apps/desktop/scripts/make-installer-images.mjs @@ -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 ] [--preview ] + * + * 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: `
+
${lockup.replace(' +
+
State of
the art.
At home.
+
AI on your own computer.
Private. Fast. Easy.
+
+
` }, + header: { w: 150, h: 57, html: `
${lockup.replace('` }, +}; + +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, `${page.html}`); + 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')); diff --git a/apps/desktop/scripts/stage-control.py b/apps/desktop/scripts/stage-control.py index 33b00560..bf570076 100644 --- a/apps/desktop/scripts/stage-control.py +++ b/apps/desktop/scripts/stage-control.py @@ -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: diff --git a/apps/desktop/scripts/ui-flows.mjs b/apps/desktop/scripts/ui-flows.mjs new file mode 100644 index 00000000..87235e51 --- /dev/null +++ b/apps/desktop/scripts/ui-flows.mjs @@ -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 ] [--node ] [--shots ] [--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.', '', '', '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:). 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); diff --git a/apps/desktop/src-tauri/icons/128x128.png b/apps/desktop/src-tauri/icons/128x128.png index 63fb845f..432eaf48 100644 Binary files a/apps/desktop/src-tauri/icons/128x128.png and b/apps/desktop/src-tauri/icons/128x128.png differ diff --git a/apps/desktop/src-tauri/icons/128x128@2x.png b/apps/desktop/src-tauri/icons/128x128@2x.png index 3417d352..3bea2d8f 100644 Binary files a/apps/desktop/src-tauri/icons/128x128@2x.png and b/apps/desktop/src-tauri/icons/128x128@2x.png differ diff --git a/apps/desktop/src-tauri/icons/32x32.png b/apps/desktop/src-tauri/icons/32x32.png index a3b6ecba..c84b9465 100644 Binary files a/apps/desktop/src-tauri/icons/32x32.png and b/apps/desktop/src-tauri/icons/32x32.png differ diff --git a/apps/desktop/src-tauri/icons/64x64.png b/apps/desktop/src-tauri/icons/64x64.png index 6152d38a..c8c67a04 100644 Binary files a/apps/desktop/src-tauri/icons/64x64.png and b/apps/desktop/src-tauri/icons/64x64.png differ diff --git a/apps/desktop/src-tauri/icons/icon.ico b/apps/desktop/src-tauri/icons/icon.ico index a052e27f..e38a27ec 100644 Binary files a/apps/desktop/src-tauri/icons/icon.ico and b/apps/desktop/src-tauri/icons/icon.ico differ diff --git a/apps/desktop/src-tauri/icons/icon.png b/apps/desktop/src-tauri/icons/icon.png index 3b947060..da9c7603 100644 Binary files a/apps/desktop/src-tauri/icons/icon.png and b/apps/desktop/src-tauri/icons/icon.png differ diff --git a/apps/desktop/src-tauri/nsis/header.bmp b/apps/desktop/src-tauri/nsis/header.bmp new file mode 100644 index 00000000..efc77717 Binary files /dev/null and b/apps/desktop/src-tauri/nsis/header.bmp differ diff --git a/apps/desktop/src-tauri/nsis/installer.nsi b/apps/desktop/src-tauri/nsis/installer.nsi new file mode 100644 index 00000000..375d5238 --- /dev/null +++ b/apps/desktop/src-tauri/nsis/installer.nsi @@ -0,0 +1,1077 @@ +Unicode true +ManifestDPIAware true +; Add in `dpiAwareness` `PerMonitorV2` to manifest for Windows 10 1607+ (note this should not affect lower versions since they should be able to ignore this and pick up `dpiAware` `true` set by `ManifestDPIAware true`) +; Currently undocumented on NSIS's website but is in the Docs folder of source tree, see +; https://github.com/kichik/nsis/blob/5fc0b87b819a9eec006df4967d08e522ddd651c9/Docs/src/attributes.but#L286-L300 +; https://github.com/tauri-apps/tauri/pull/10106 +ManifestDPIAwareness PerMonitorV2 + +!if "{{compression}}" == "none" + SetCompress off +!else + ; Set the compression algorithm. We default to LZMA. + SetCompressor /SOLID "{{compression}}" +!endif + +; Keep above !include to stay ahead of any plugin command +; see https://github.com/tauri-apps/tauri/pull/15422#discussion_r3289239624 +{{#if signed_plugins_path}} +!addplugindir "{{signed_plugins_path}}" +{{/if}} + +!include MUI2.nsh +!include FileFunc.nsh +!include x64.nsh +!include WordFunc.nsh +!include "utils.nsh" +!include "FileAssociation.nsh" +!include "Win\COM.nsh" +!include "Win\Propkey.nsh" +!include "Win\RestartManager.nsh" +!include "StrFunc.nsh" +${StrCase} +${StrLoc} + +{{#if installer_hooks}} +!include "{{installer_hooks}}" +{{/if}} + +!define WEBVIEW2APPGUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" + +!define MANUFACTURER "{{manufacturer}}" +!define PRODUCTNAME "{{product_name}}" +!define VERSION "{{version}}" +!define VERSIONWITHBUILD "{{version_with_build}}" +!define HOMEPAGE "{{homepage}}" +!define INSTALLMODE "{{install_mode}}" +!define LICENSE "{{license}}" +!define INSTALLERICON "{{installer_icon}}" +!define SIDEBARIMAGE "{{sidebar_image}}" +!define HEADERIMAGE "{{header_image}}" +!define UNINSTALLERICON "{{uninstaller_icon}}" +!define UNINSTALLERHEADERIMAGE "{{uninstaller_header_image}}" +!define MAINBINARYNAME "{{main_binary_name}}" +!define MAINBINARYSRCPATH "{{main_binary_path}}" +!define BUNDLEID "{{bundle_id}}" +!define COPYRIGHT "{{copyright}}" +!define OUTFILE "{{out_file}}" +!define ARCH "{{arch}}" +!define ADDITIONALPLUGINSPATH "{{additional_plugins_path}}" +!define ALLOWDOWNGRADES "{{allow_downgrades}}" +!define DISPLAYLANGUAGESELECTOR "{{display_language_selector}}" +!define INSTALLWEBVIEW2MODE "{{install_webview2_mode}}" +!define WEBVIEW2INSTALLERARGS "{{webview2_installer_args}}" +!define WEBVIEW2BOOTSTRAPPERPATH "{{webview2_bootstrapper_path}}" +!define WEBVIEW2INSTALLERPATH "{{webview2_installer_path}}" +!define MINIMUMWEBVIEW2VERSION "{{minimum_webview2_version}}" +!define UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCTNAME}" +!define MANUKEY "Software\${MANUFACTURER}" +!define MANUPRODUCTKEY "${MANUKEY}\${PRODUCTNAME}" +!define UNINSTALLERSIGNCOMMAND "{{uninstaller_sign_cmd}}" +!define ESTIMATEDSIZE "{{estimated_size}}" +!define STARTMENUFOLDER "{{start_menu_folder}}" + +Var PassiveMode +Var UpdateMode +Var NoShortcutMode +Var WixMode +Var OldMainBinaryName + +Name "${PRODUCTNAME}" +BrandingText "${COPYRIGHT}" +OutFile "${OUTFILE}" + +; We don't actually use this value as default install path, +; it's just for nsis to append the product name folder in the directory selector +; https://nsis.sourceforge.io/Reference/InstallDir +!define PLACEHOLDER_INSTALL_DIR "placeholder\${PRODUCTNAME}" +InstallDir "${PLACEHOLDER_INSTALL_DIR}" + +VIProductVersion "${VERSIONWITHBUILD}" +VIAddVersionKey "ProductName" "${PRODUCTNAME}" +VIAddVersionKey "FileDescription" "${PRODUCTNAME}" +VIAddVersionKey "LegalCopyright" "${COPYRIGHT}" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" + +# additional plugins +!addplugindir "${ADDITIONALPLUGINSPATH}" + +; Uninstaller signing command +!if "${UNINSTALLERSIGNCOMMAND}" != "" + !uninstfinalize '${UNINSTALLERSIGNCOMMAND}' +!endif + +; Handle install mode, `perUser`, `perMachine` or `both` +!if "${INSTALLMODE}" == "perMachine" + RequestExecutionLevel admin +!endif + +!if "${INSTALLMODE}" == "currentUser" + RequestExecutionLevel user +!endif + +!if "${INSTALLMODE}" == "both" + !define MULTIUSER_MUI + !define MULTIUSER_INSTALLMODE_INSTDIR "${PRODUCTNAME}" + !define MULTIUSER_INSTALLMODE_COMMANDLINE + !if "${ARCH}" == "x64" + !define MULTIUSER_USE_PROGRAMFILES64 + !else if "${ARCH}" == "arm64" + !define MULTIUSER_USE_PROGRAMFILES64 + !endif + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_KEY "${UNINSTKEY}" + !define MULTIUSER_INSTALLMODE_DEFAULT_REGISTRY_VALUENAME "CurrentUser" + !define MULTIUSER_INSTALLMODEPAGE_SHOWUSERNAME + !define MULTIUSER_INSTALLMODE_FUNCTION RestorePreviousInstallLocation + !define MULTIUSER_EXECUTIONLEVEL Highest + !include MultiUser.nsh +!endif + +; Installer icon +!if "${INSTALLERICON}" != "" + !define MUI_ICON "${INSTALLERICON}" +!endif + +; Installer sidebar image +!if "${SIDEBARIMAGE}" != "" + !define MUI_WELCOMEFINISHPAGE_BITMAP "${SIDEBARIMAGE}" +!endif + +; Enable header images for installer and uninstaller pages when either image is configured. +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!else if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE +!endif + +; Installer header image +!if "${HEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_BITMAP "${HEADERIMAGE}" +!endif + +; Uninstaller header image +!if "${UNINSTALLERHEADERIMAGE}" != "" + !define MUI_HEADERIMAGE_UNBITMAP "${UNINSTALLERHEADERIMAGE}" +!endif + +; Uninstaller icon +!if "${UNINSTALLERICON}" != "" + !define MUI_UNICON "${UNINSTALLERICON}" +!endif + +; Define registry key to store installer language +!define MUI_LANGDLL_REGISTRY_ROOT "HKCU" +!define MUI_LANGDLL_REGISTRY_KEY "${MANUPRODUCTKEY}" +!define MUI_LANGDLL_REGISTRY_VALUENAME "Installer Language" + +; Strata's look and words: the app's light surface and ink, short copy, no directory page, straight on to the progress. +!define MUI_BGCOLOR "F9FAFB" +!define MUI_TEXTCOLOR "171B1E" +!define MUI_INSTFILESPAGE_PROGRESSBAR "smooth" +!define MUI_WELCOMEPAGE_TITLE "State of the art. At home." +!define MUI_WELCOMEPAGE_TEXT "Strata runs AI on your own computer.$\r$\n$\r$\nThis takes about a minute and needs no administrator. You choose your first model inside Strata." +!define MUI_FINISHPAGE_TITLE "Strata is ready." +!define MUI_FINISHPAGE_TEXT "Open it to pick your first model. Strata downloads it for you and gets it ready." +!define MUI_FINISHPAGE_RUN_TEXT "Open Strata" +!define MUI_PAGE_HEADER_TEXT "Installing Strata" +!define MUI_PAGE_HEADER_SUBTEXT "Copying the app. You can keep working meanwhile." +BrandingText "Strata" +ShowInstDetails nevershow + +; Installer pages, must be ordered as they appear +; 1. Welcome Page +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_WELCOME + +; 2. License Page (if defined) +!if "${LICENSE}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MUI_PAGE_LICENSE "${LICENSE}" +!endif + +; 3. Install mode (if it is set to `both`) +!if "${INSTALLMODE}" == "both" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !insertmacro MULTIUSER_PAGE_INSTALLMODE +!endif + +; 4. Custom page to ask user if he wants to reinstall/uninstall +; only if a previous installation was detected +Var ReinstallPageCheck +Page custom PageReinstall PageLeaveReinstall +Function PageReinstall + ; Uninstall previous WiX installation if exists. + ; + ; A WiX installer stores the installation info in registry + ; using a UUID and so we have to loop through all keys under + ; `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall` + ; and check if `DisplayName` and `Publisher` keys match ${PRODUCTNAME} and ${MANUFACTURER} + ; + ; This has a potential issue that there maybe another installation that matches + ; our ${PRODUCTNAME} and ${MANUFACTURER} but wasn't installed by our WiX installer, + ; however, this should be fine since the user will have to confirm the uninstallation + ; and they can chose to abort it if doesn't make sense. + StrCpy $0 0 + wix_loop: + EnumRegKey $1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" $0 + StrCmp $1 "" wix_loop_done ; Exit loop if there is no more keys to loop on + IntOp $0 $0 + 1 + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "DisplayName" + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "Publisher" + StrCmp "$R0$R1" "${PRODUCTNAME}${MANUFACTURER}" 0 wix_loop + ReadRegStr $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" "UninstallString" + ${StrCase} $R1 $R0 "L" + ${StrLoc} $R0 $R1 "msiexec" ">" + StrCmp $R0 0 0 wix_loop_done + StrCpy $WixMode 1 + StrCpy $R6 "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$1" + Goto compare_version + wix_loop_done: + + ; Check if there is an existing installation, if not, abort the reinstall page + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} "$R0$R1" == "" ${|} Abort ${|} + + ; Compare this installar version with the existing installation + ; and modify the messages presented to the user accordingly + compare_version: + StrCpy $R4 "$(older)" + ${If} $WixMode = 1 + ReadRegStr $R0 HKLM "$R6" "DisplayVersion" + ${Else} + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + ${EndIf} + ${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|} + + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; Reinstalling the same version + ${If} $R0 = 0 + StrCpy $R1 "$(alreadyInstalledLong)" + StrCpy $R2 "$(addOrReinstall)" + StrCpy $R3 "$(uninstallApp)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(chooseMaintenanceOption)" + ; Upgrading + ${ElseIf} $R0 = 1 + StrCpy $R1 "$(olderOrUnknownVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + StrCpy $R3 "$(dontUninstall)" + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ; Downgrading + ${ElseIf} $R0 = -1 + StrCpy $R1 "$(newerVersionInstalled)" + StrCpy $R2 "$(uninstallBeforeInstalling)" + !if "${ALLOWDOWNGRADES}" == "true" + StrCpy $R3 "$(dontUninstall)" + !else + StrCpy $R3 "$(dontUninstallDowngrade)" + !endif + !insertmacro MUI_HEADER_TEXT "$(alreadyInstalled)" "$(choowHowToInstall)" + ${Else} + Abort + ${EndIf} + + ; Skip showing the page if passive + ; + ; Note that we don't call this earlier at the beginning + ; of this function because we need to populate some variables + ; related to current installed version if detected and whether + ; we are downgrading or not. + ${If} $PassiveMode = 1 + Call PageLeaveReinstall + ${Else} + nsDialogs::Create 1018 + Pop $R4 + ${IfThen} $(^RTL) = 1 ${|} nsDialogs::SetRTL $(^RTL) ${|} + + ${NSD_CreateLabel} 0 0 100% 24u $R1 + Pop $R1 + + ${NSD_CreateRadioButton} 30u 50u -30u 8u $R2 + Pop $R2 + ${NSD_OnClick} $R2 PageReinstallUpdateSelection + + ${NSD_CreateRadioButton} 30u 70u -30u 8u $R3 + Pop $R3 + ; Disable this radio button if downgrading and downgrades are disabled + !if "${ALLOWDOWNGRADES}" == "false" + ${IfThen} $R0 = -1 ${|} EnableWindow $R3 0 ${|} + !endif + ${NSD_OnClick} $R3 PageReinstallUpdateSelection + + ; Check the first radio button if this the first time + ; we enter this page or if the second button wasn't + ; selected the last time we were on this page + ${If} $ReinstallPageCheck <> 2 + SendMessage $R2 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${Else} + SendMessage $R3 ${BM_SETCHECK} ${BST_CHECKED} 0 + ${EndIf} + + ${NSD_SetFocus} $R2 + nsDialogs::Show + ${EndIf} +FunctionEnd +Function PageReinstallUpdateSelection + ${NSD_GetState} $R2 $R1 + ${If} $R1 == ${BST_CHECKED} + StrCpy $ReinstallPageCheck 1 + ${Else} + StrCpy $ReinstallPageCheck 2 + ${EndIf} +FunctionEnd +Function PageLeaveReinstall + ${NSD_GetState} $R2 $R1 + + ; If migrating from Wix, always uninstall + ${If} $WixMode = 1 + Goto reinst_uninstall + ${EndIf} + + ; In update mode, always proceeds without uninstalling + ${If} $UpdateMode = 1 + Goto reinst_done + ${EndIf} + + ; $R0 holds whether same(0)/upgrading(1)/downgrading(-1) version + ; $R1 holds the radio buttons state: + ; 1 => first choice was selected + ; 0 => second choice was selected + ${If} $R0 = 0 ; Same version, proceed + ${If} $R1 = 1 ; User chose to add/reinstall + Goto reinst_done + ${Else} ; User chose to uninstall + Goto reinst_uninstall + ${EndIf} + ${ElseIf} $R0 = 1 ; Upgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${ElseIf} $R0 = -1 ; Downgrading + ${If} $R1 = 1 ; User chose to uninstall + Goto reinst_uninstall + ${Else} + Goto reinst_done ; User chose NOT to uninstall + ${EndIf} + ${EndIf} + + reinst_uninstall: + HideWindow + ClearErrors + + ${If} $WixMode = 1 + ReadRegStr $R1 HKLM "$R6" "UninstallString" + ExecWait '$R1' $0 + ${Else} + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + ReadRegStr $R1 SHCTX "${UNINSTKEY}" "UninstallString" + ${IfThen} $UpdateMode = 1 ${|} StrCpy $R1 "$R1 /UPDATE" ${|} ; append /UPDATE + ${IfThen} $PassiveMode = 1 ${|} StrCpy $R1 "$R1 /P" ${|} ; append /P + StrCpy $R1 "$R1 _?=$4" ; append uninstall directory + ExecWait '$R1' $0 + ${EndIf} + + BringToFront + + ${IfThen} ${Errors} ${|} StrCpy $0 2 ${|} ; ExecWait failed, set fake exit code + + ${If} $0 <> 0 + ${OrIf} ${FileExists} "$INSTDIR\${MAINBINARYNAME}.exe" + ; User cancelled wix uninstaller? return to select un/reinstall page + ${If} $WixMode = 1 + ${AndIf} $0 = 1602 + Abort + ${EndIf} + + ; User cancelled NSIS uninstaller? return to select un/reinstall page + ${If} $0 = 1 + Abort + ${EndIf} + + ; Other errors? show generic error message and return to select un/reinstall page + MessageBox MB_ICONEXCLAMATION "$(unableToUninstall)" + Abort + ${EndIf} + + ; The NSIS uninstaller was run in place (`_?=`), so it cannot delete itself + ; and the install directory, clean them up here once the uninstall succeeded + ; https://nsis.sourceforge.io/Docs/Chapter3.html#:~:text=path%20contains%20spaces.-,3.2.3%20Examples,-installer.exe%20/NCRC + ${If} $WixMode = 0 + ${AndIf} $4 != "" + Delete "$4\uninstall.exe" + RMDir "$4" + ${EndIf} + reinst_done: +FunctionEnd + +; 5. Choose install directory page +!define MUI_PAGE_CUSTOMFUNCTION_PRE Skip +!insertmacro MUI_PAGE_DIRECTORY + +; 6. Start menu shortcut page +Var AppStartMenuFolder +!if "${STARTMENUFOLDER}" != "" + !define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive + !define MUI_STARTMENUPAGE_DEFAULTFOLDER "${STARTMENUFOLDER}" +!else + !define MUI_PAGE_CUSTOMFUNCTION_PRE Skip +!endif +!insertmacro MUI_PAGE_STARTMENU Application $AppStartMenuFolder + +; 7. Installation page +!insertmacro MUI_PAGE_INSTFILES + +; 8. Finish page +; +; Don't auto jump to finish page after installation page, +; because the installation page has useful info that can be used debug any issues with the installer. +; (no NOAUTOCLOSE: welcome, progress, finish) +; Use show readme button in the finish page as a button create a desktop shortcut +!define MUI_FINISHPAGE_SHOWREADME +!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(createDesktop)" +!define MUI_FINISHPAGE_SHOWREADME_FUNCTION CreateOrUpdateDesktopShortcut +; Show run app after installation. +!define MUI_FINISHPAGE_RUN +!define MUI_FINISHPAGE_RUN_FUNCTION RunMainBinary +!define MUI_PAGE_CUSTOMFUNCTION_PRE SkipIfPassive +!insertmacro MUI_PAGE_FINISH + +Function RunMainBinary + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "" +FunctionEnd + +; Uninstaller Pages +; 1. Confirm uninstall page +Var DeleteAppDataCheckbox +Var DeleteAppDataCheckboxState +!define /ifndef WS_EX_LAYOUTRTL 0x00400000 +!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ConfirmShow +Function un.ConfirmShow ; Add add a `Delete app data` check box + ; $1 inner dialog HWND + ; $2 window DPI + ; $3 style + ; $4 x + ; $5 y + ; $6 width + ; $7 height + FindWindow $1 "#32770" "" $HWNDPARENT ; Find inner dialog + System::Call "user32::GetDpiForWindow(p r1) i .r2" + ${If} $(^RTL) = 1 + StrCpy $3 "${__NSD_CheckBox_EXSTYLE} | ${WS_EX_LAYOUTRTL}" + IntOp $4 50 * $2 + ${Else} + StrCpy $3 "${__NSD_CheckBox_EXSTYLE}" + IntOp $4 0 * $2 + ${EndIf} + IntOp $5 100 * $2 + IntOp $6 400 * $2 + IntOp $7 25 * $2 + IntOp $4 $4 / 96 + IntOp $5 $5 / 96 + IntOp $6 $6 / 96 + IntOp $7 $7 / 96 + System::Call 'user32::CreateWindowEx(i r3, w "${__NSD_CheckBox_CLASS}", w "$(deleteAppData)", i ${__NSD_CheckBox_STYLE}, i r4, i r5, i r6, i r7, p r1, i0, i0, i0) i .s' + Pop $DeleteAppDataCheckbox + SendMessage $HWNDPARENT ${WM_GETFONT} 0 0 $1 + SendMessage $DeleteAppDataCheckbox ${WM_SETFONT} $1 1 +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.ConfirmLeave +Function un.ConfirmLeave + SendMessage $DeleteAppDataCheckbox ${BM_GETCHECK} 0 0 $DeleteAppDataCheckboxState +FunctionEnd +!define MUI_PAGE_CUSTOMFUNCTION_PRE un.SkipIfPassive +!insertmacro MUI_UNPAGE_CONFIRM + +; 2. Uninstalling Page +!insertmacro MUI_UNPAGE_INSTFILES + +;Languages +{{#each languages}} +!insertmacro MUI_LANGUAGE "{{this}}" +{{/each}} +!insertmacro MUI_RESERVEFILE_LANGDLL +{{#each language_files}} + !include "{{this}}" +{{/each}} + +Function .onInit + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/NS" $NoShortcutMode + ${IfNot} ${Errors} + StrCpy $NoShortcutMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} + + !if "${DISPLAYLANGUAGESELECTOR}" == "true" + !insertmacro MUI_LANGDLL_DISPLAY + !endif + + !insertmacro SetContext + + ${If} $INSTDIR == "${PLACEHOLDER_INSTALL_DIR}" + ; Set default install location + !if "${INSTALLMODE}" == "perMachine" + ${If} ${RunningX64} + !if "${ARCH}" == "x64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else if "${ARCH}" == "arm64" + StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCTNAME}" + !else + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + !endif + ${Else} + StrCpy $INSTDIR "$PROGRAMFILES\${PRODUCTNAME}" + ${EndIf} + !else if "${INSTALLMODE}" == "currentUser" + StrCpy $INSTDIR "$LOCALAPPDATA\Programs\${PRODUCTNAME}" + !endif + + Call RestorePreviousInstallLocation + ${EndIf} + + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_INIT + !endif + + ; Abort downgrades if they are disabled, in the modes that skip the reinstall page choice: + ; silent, passive and update + !if "${ALLOWDOWNGRADES}" == "false" + ${If} ${Silent} + ${OrIf} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion" + nsis_tauri_utils::SemverCompare "${VERSION}" $R0 + Pop $R0 + ; If downgrading + ${If} $R0 = -1 + ${If} ${Silent} + System::Call 'kernel32::AttachConsole(i -1)i.r0' + ${If} $0 <> 0 + System::Call 'kernel32::GetStdHandle(i -11)i.r0' + System::call 'kernel32::SetConsoleTextAttribute(i r0, i 0x0004)' ; set red color + FileWrite $0 "$(silentDowngrades)" + ${EndIf} + ${Else} + MessageBox MB_ICONSTOP "$(silentDowngrades)" + ${EndIf} + Abort + ${EndIf} + ${EndIf} + !endif +FunctionEnd + +Section WebView2 + ; Check if Webview2 is already installed and skip this section + ${If} ${RunningX64} + ReadRegStr $4 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${Else} + ReadRegStr $4 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + ${If} $4 == "" + ReadRegStr $4 HKCU "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2APPGUID}" "pv" + ${EndIf} + + ${If} $4 == "" + ; Webview2 installation + ; + ; Skip if updating + ${If} $UpdateMode <> 1 + !if "${INSTALLWEBVIEW2MODE}" == "downloadBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + DetailPrint "$(webview2Downloading)" + NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Pop $0 + ${If} $0 == "success" + DetailPrint "$(webview2DownloadSuccess)" + ${Else} + DetailPrint "$(webview2DownloadError)" + Abort "$(webview2AbortError)" + ${EndIf} + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "embedBootstrapper" + Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe" + File "/oname=$TEMP\MicrosoftEdgeWebview2Setup.exe" "${WEBVIEW2BOOTSTRAPPERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebview2Setup.exe" + Goto install_webview2 + !endif + + !if "${INSTALLWEBVIEW2MODE}" == "offlineInstaller" + Delete "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + File "/oname=$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" "${WEBVIEW2INSTALLERPATH}" + DetailPrint "$(installingWebview2)" + StrCpy $6 "$TEMP\MicrosoftEdgeWebView2RuntimeInstaller.exe" + Goto install_webview2 + !endif + + Goto webview2_done + + install_webview2: + DetailPrint "$(installingWebview2)" + ; $6 holds the path to the webview2 installer + ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + DetailPrint "$(webview2InstallError)" + Abort "$(webview2AbortError)" + ${EndIf} + webview2_done: + ${EndIf} + ${Else} + !if "${MINIMUMWEBVIEW2VERSION}" != "" + ${VersionCompare} "${MINIMUMWEBVIEW2VERSION}" "$4" $R0 + ${If} $R0 = 1 + update_webview: + DetailPrint "$(installingWebview2)" + ${If} ${RunningX64} + ReadRegStr $R1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate" "path" + ${Else} + ReadRegStr $R1 HKLM "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 == "" + ReadRegStr $R1 HKCU "SOFTWARE\Microsoft\EdgeUpdate" "path" + ${EndIf} + ${If} $R1 != "" + ; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md + ; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath" + ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1 + ${If} $1 = 0 + DetailPrint "$(webview2InstallSuccess)" + ${Else} + MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview + Quit + ignore: + ${EndIf} + ${EndIf} + ${EndIf} + !endif + ${EndIf} +SectionEnd + +; STRATA-MIGRATE-BEGIN +; An earlier build installed the app into %LOCALAPPDATA%\Strata, the folder that also holds the user's data (components, install, +; procs, runtime, time-skip). Remove only the app files that build put there; everything else stays. +!macro StrataMigrateOldInstall OLDDIR NEWDIR + StrCmp "${OLDDIR}" "${NEWDIR}" +8 + IfFileExists "${OLDDIR}\strata-desktop.exe" 0 +7 + Delete "${OLDDIR}\strata-desktop.exe" + Delete "${OLDDIR}\uninstall.exe" + RMDir /r "${OLDDIR}\host" + RMDir /r "${OLDDIR}\node" + RMDir /r "${OLDDIR}\control" + RMDir "${OLDDIR}" +!macroend +; STRATA-MIGRATE-END + +Section Install + SetOutPath $INSTDIR + + !ifmacrodef NSIS_HOOK_PREINSTALL + !insertmacro NSIS_HOOK_PREINSTALL + !endif + + !insertmacro StrataMigrateOldInstall "$LOCALAPPDATA\${PRODUCTNAME}" "$INSTDIR" + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Copy main executable + File "${MAINBINARYSRCPATH}" + + ; Copy resources + {{#each resources_dirs}} + CreateDirectory "$INSTDIR\\{{this}}" + {{/each}} + {{#each resources}} + File /a "/oname={{this.[1]}}" "{{no-escape @key}}" + {{/each}} + + ; Copy external binaries + {{#each binaries}} + File /a "/oname={{this}}" "{{no-escape @key}}" + {{/each}} + + ; Create file associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_ASSOCIATE "{{ext}}" "{{or association.name ext}}" "{{association-description association.description ext}}" "$INSTDIR\${MAINBINARYNAME}.exe,0" "Open with ${PRODUCTNAME}" "$INSTDIR\${MAINBINARYNAME}.exe $\"%1$\"" + {{/each}} + {{/each}} + + ; Register deep links + {{#each deep_link_protocols as |protocol| ~}} + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "URL Protocol" "" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}" "" "URL:${BUNDLEID} protocol" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\DefaultIcon" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\",0" + WriteRegStr SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + {{/each}} + + ; Create uninstaller + WriteUninstaller "$INSTDIR\uninstall.exe" + + ; Save $INSTDIR in registry for future installations + WriteRegStr SHCTX "${MANUPRODUCTKEY}" "" $INSTDIR + + !if "${INSTALLMODE}" == "both" + ; Save install mode to be selected by default for the next installation such as updating + ; or when uninstalling + WriteRegStr SHCTX "${UNINSTKEY}" $MultiUser.InstallMode 1 + !endif + + ; Remove old main binary if it doesn't match new main binary name + ReadRegStr $OldMainBinaryName SHCTX "${UNINSTKEY}" "MainBinaryName" + ${If} $OldMainBinaryName != "" + ${AndIf} $OldMainBinaryName != "${MAINBINARYNAME}.exe" + Delete "$INSTDIR\$OldMainBinaryName" + ${EndIf} + + ; Save current MAINBINARYNAME for future updates + WriteRegStr SHCTX "${UNINSTKEY}" "MainBinaryName" "${MAINBINARYNAME}.exe" + + ; Registry information for add/remove programs + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayName" "${PRODUCTNAME}" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayIcon" "$\"$INSTDIR\${MAINBINARYNAME}.exe$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "DisplayVersion" "${VERSION}" + WriteRegStr SHCTX "${UNINSTKEY}" "Publisher" "${MANUFACTURER}" + WriteRegStr SHCTX "${UNINSTKEY}" "InstallLocation" "$\"$INSTDIR$\"" + WriteRegStr SHCTX "${UNINSTKEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\"" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoModify" "1" + WriteRegDWORD SHCTX "${UNINSTKEY}" "NoRepair" "1" + + ${GetSize} "$INSTDIR" "/M=uninstall.exe /S=0K /G=0" $0 $1 $2 + IntOp $0 $0 + ${ESTIMATEDSIZE} + IntFmt $0 "0x%08X" $0 + WriteRegDWORD SHCTX "${UNINSTKEY}" "EstimatedSize" "$0" + + !if "${HOMEPAGE}" != "" + WriteRegStr SHCTX "${UNINSTKEY}" "URLInfoAbout" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "URLUpdateInfo" "${HOMEPAGE}" + WriteRegStr SHCTX "${UNINSTKEY}" "HelpLink" "${HOMEPAGE}" + !endif + + ; Create start menu shortcut + !insertmacro MUI_STARTMENU_WRITE_BEGIN Application + Call CreateOrUpdateStartMenuShortcut + !insertmacro MUI_STARTMENU_WRITE_END + + ; Create desktop shortcut for silent and passive installers + ; because finish page will be skipped + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + Call CreateOrUpdateDesktopShortcut + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTINSTALL + !insertmacro NSIS_HOOK_POSTINSTALL + !endif + + ; Auto close this page for passive mode + ${If} $PassiveMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +Function .onInstSuccess + ; Check for `/R` flag only in silent and passive installers because + ; GUI installer has a toggle for the user to (re)start the app + ${If} $PassiveMode = 1 + ${OrIf} ${Silent} + ${GetOptions} $CMDLINE "/R" $R0 + ${IfNot} ${Errors} + ${GetOptions} $CMDLINE "/ARGS" $R0 + nsis_tauri_utils::RunAsUser "$INSTDIR\${MAINBINARYNAME}.exe" "$R0" + ${EndIf} + ${EndIf} +FunctionEnd + +Function un.onInit + !insertmacro SetContext + + !if "${INSTALLMODE}" == "both" + !insertmacro MULTIUSER_UNINIT + !endif + + !insertmacro MUI_UNGETLANGUAGE + + ${GetOptions} $CMDLINE "/P" $PassiveMode + ${IfNot} ${Errors} + StrCpy $PassiveMode 1 + ${EndIf} + + ${GetOptions} $CMDLINE "/UPDATE" $UpdateMode + ${IfNot} ${Errors} + StrCpy $UpdateMode 1 + ${EndIf} +FunctionEnd + +Section Uninstall + + !ifmacrodef NSIS_HOOK_PREUNINSTALL + !insertmacro NSIS_HOOK_PREUNINSTALL + !endif + + !insertmacro CheckIfAppIsRunning "$INSTDIR\${MAINBINARYNAME}.exe" "${PRODUCTNAME}" + + ; Delete the app directory and its content from disk + ; Copy main executable + Delete "$INSTDIR\${MAINBINARYNAME}.exe" + + ; Delete resources + {{#each resources}} + Delete "$INSTDIR\\{{this.[1]}}" + {{/each}} + + ; Delete external binaries + {{#each binaries}} + Delete "$INSTDIR\\{{this}}" + {{/each}} + + ; Delete app associations + {{#each file_associations as |association| ~}} + {{#each association.ext as |ext| ~}} + !insertmacro APP_UNASSOCIATE "{{ext}}" "{{or association.name ext}}" + {{/each}} + {{/each}} + + ; Delete deep links + {{#each deep_link_protocols as |protocol| ~}} + ReadRegStr $R7 SHCTX "Software\Classes\\{{protocol}}\shell\open\command" "" + ${If} $R7 == "$\"$INSTDIR\${MAINBINARYNAME}.exe$\" $\"%1$\"" + DeleteRegKey SHCTX "Software\Classes\\{{protocol}}" + ${EndIf} + {{/each}} + + + ; Delete uninstaller + Delete "$INSTDIR\uninstall.exe" + + {{#each resources_ancestors}} + RMDir /REBOOTOK "$INSTDIR\\{{this}}" + {{/each}} + RMDir "$INSTDIR" + + ; Remove shortcuts if not updating + ${If} $UpdateMode <> 1 + !insertmacro DeleteAppUserModelId + + ; Remove start menu shortcut + !insertmacro MUI_STARTMENU_GETFOLDER Application $AppStartMenuFolder + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + RMDir "$SMPROGRAMS\$AppStartMenuFolder" + ${EndIf} + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" + Delete "$SMPROGRAMS\${PRODUCTNAME}.lnk" + ${EndIf} + + ; Remove desktop shortcuts + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Pop $0 + ${If} $0 = 1 + !insertmacro UnpinShortcut "$DESKTOP\${PRODUCTNAME}.lnk" + Delete "$DESKTOP\${PRODUCTNAME}.lnk" + ${EndIf} + ${EndIf} + + ; Remove registry information for add/remove programs + !if "${INSTALLMODE}" == "both" + DeleteRegKey SHCTX "${UNINSTKEY}" + !else if "${INSTALLMODE}" == "perMachine" + DeleteRegKey HKLM "${UNINSTKEY}" + !else + DeleteRegKey HKCU "${UNINSTKEY}" + !endif + + ; Removes the Autostart entry for ${PRODUCTNAME} from the HKCU Run key if it exists. + ; This ensures the program does not launch automatically after uninstallation if it exists. + ; If it doesn't exist, it does nothing. + ; We do this when not updating (to preserve the registry value on updates) + ${If} $UpdateMode <> 1 + DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${PRODUCTNAME}" + ${EndIf} + + ; Delete app data if the checkbox is selected + ; and if not updating + ${If} $DeleteAppDataCheckboxState = 1 + ${AndIf} $UpdateMode <> 1 + ; Clear the install location $INSTDIR from registry + DeleteRegKey SHCTX "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty SHCTX "${MANUKEY}" + + ; Clear the install language from registry + DeleteRegValue HKCU "${MANUPRODUCTKEY}" "Installer Language" + DeleteRegKey /ifempty HKCU "${MANUPRODUCTKEY}" + DeleteRegKey /ifempty HKCU "${MANUKEY}" + + SetShellVarContext current + RmDir /r "$APPDATA\${BUNDLEID}" + RmDir /r "$LOCALAPPDATA\${BUNDLEID}" + ${EndIf} + + !ifmacrodef NSIS_HOOK_POSTUNINSTALL + !insertmacro NSIS_HOOK_POSTUNINSTALL + !endif + + ; Auto close if passive mode or updating + ${If} $PassiveMode = 1 + ${OrIf} $UpdateMode = 1 + SetAutoClose true + ${EndIf} +SectionEnd + +; StrIsUnder: Push path, Push folder, Call StrIsUnder, Pop result ("1" when path is the folder or inside it; case-insensitive, +; whole path segments only). +Function StrIsUnder + Exch $1 ; folder + Exch + Exch $0 ; path + Push $2 + Push $3 + StrCpy $R9 0 + StrCmp $1 "" under_done 0 + StrLen $2 $1 + StrCpy $3 $0 $2 + StrCmp $3 $1 0 under_done + StrCpy $3 $0 1 $2 + StrCmp $3 "" under_yes 0 + StrCmp $3 "\" under_yes under_done + under_yes: + StrCpy $R9 1 + under_done: + Pop $3 + Pop $2 + Pop $0 + Pop $1 + Push $R9 +FunctionEnd + +; Strata: the install folder remembered in the registry is only reused when it is a real place for an app. A location under the +; temp folders (a test install, a build machine's scratch run) is ignored and the default per-user folder is used instead. +Function RestorePreviousInstallLocation + ReadRegStr $4 SHCTX "${MANUPRODUCTKEY}" "" + StrCmp $4 "" restore_done 0 + ; %LOCALAPPDATA%\Strata holds the user's engines, model configs and tuning: never an app folder + StrCmp $4 "$LOCALAPPDATA\${PRODUCTNAME}" restore_done 0 + Push $4 + Push "$LOCALAPPDATA\Temp" + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + Push $4 + Push "$TEMP" + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + ReadEnvStr $6 TMP + Push $4 + Push $6 + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + ReadEnvStr $6 TEMP + Push $4 + Push $6 + Call StrIsUnder + Pop $5 + StrCmp $5 1 restore_done 0 + StrCpy $INSTDIR $4 + restore_done: +FunctionEnd + +Function Skip + Abort +FunctionEnd + +Function SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd +Function un.SkipIfPassive + ${IfThen} $PassiveMode = 1 ${|} Abort ${|} +FunctionEnd + +Function CreateOrUpdateStartMenuShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + StrCpy $R0 0 + + !insertmacro IsShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + !insertmacro IsShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + StrCpy $R0 1 + ${EndIf} + + ${If} $R0 = 1 + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + !if "${STARTMENUFOLDER}" != "" + CreateDirectory "$SMPROGRAMS\$AppStartMenuFolder" + CreateShortcut "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\$AppStartMenuFolder\${PRODUCTNAME}.lnk" + !else + CreateShortcut "$SMPROGRAMS\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$SMPROGRAMS\${PRODUCTNAME}.lnk" + !endif +FunctionEnd + +Function CreateOrUpdateDesktopShortcut + ; We used to use product name as MAINBINARYNAME + ; migrate old shortcuts to target the new MAINBINARYNAME + !insertmacro IsShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\$OldMainBinaryName" + Pop $0 + ${If} $0 = 1 + !insertmacro SetShortcutTarget "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + Return + ${EndIf} + + ; Skip creating shortcut if in update mode or no shortcut mode + ; but always create if migrating from wix + ${If} $WixMode = 0 + ${If} $UpdateMode = 1 + ${OrIf} $NoShortcutMode = 1 + Return + ${EndIf} + ${EndIf} + + CreateShortcut "$DESKTOP\${PRODUCTNAME}.lnk" "$INSTDIR\${MAINBINARYNAME}.exe" + !insertmacro SetLnkAppUserModelId "$DESKTOP\${PRODUCTNAME}.lnk" +FunctionEnd diff --git a/apps/desktop/src-tauri/nsis/sidebar.bmp b/apps/desktop/src-tauri/nsis/sidebar.bmp new file mode 100644 index 00000000..9d936c6c Binary files /dev/null and b/apps/desktop/src-tauri/nsis/sidebar.bmp differ diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 864e065d..03a80fb8 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -239,6 +239,22 @@ fn pick_port() -> Result { Ok(port) } +/// The port the app prefers. The window's origin is `http://127.0.0.1:`, 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 { + 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 { } 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); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d7edc14f..314272d6 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -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" diff --git a/apps/host/index.html b/apps/host/index.html index 437d8143..7f7aae75 100644 --- a/apps/host/index.html +++ b/apps/host/index.html @@ -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'; } diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index e0d30064..3f328e67 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -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); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 25cf4d8c..1c378f00 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -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; diff --git a/apps/host/server/inference.mjs b/apps/host/server/inference.mjs index 1c2fbde1..c3735863 100644 --- a/apps/host/server/inference.mjs +++ b/apps/host/server/inference.mjs @@ -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; diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 9bc183e1..e655345d 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -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)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}; } diff --git a/apps/host/server/native-resources.mjs b/apps/host/server/native-resources.mjs index fb5ace4e..eda84f7f 100644 --- a/apps/host/server/native-resources.mjs +++ b/apps/host/server/native-resources.mjs @@ -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 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 : null)} {tr(preferences ? setPreferences(null)}> - {tr(preferences === 'mode' ? <>{tr(modes.map((option, index) => ))} : <>
{tr(apiModel?.name ?? loaded?.family ?? 'No model loaded')}

{tr("Reasoning effort")}

{tr(efforts.map(option => ))})} + {tr(preferences === 'mode' ? <>{tr(modes.map((option, index) => ))} : <>
{tr(apiModel?.name ?? loaded?.family ?? 'No model loaded')}

{tr("Reasoning effort")}

{tr(efforts.map(option => ))}

{tr("Thinking budget")}

{tr(THINKING_BUDGETS.map(([value, label]) => ))})}
: null)} setUrlOpen(false)} actions={<> setUrlOpen(false)}>{tr("Cancel")} { diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index bd0777b8..4bbe713e 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -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['onboarding']>; function radioKeys(event: KeyboardEvent) { 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
@@ -183,7 +185,7 @@ export function GuidedSetup() { :
{tr("Connect your Strata installation")} void skip(false, 'Engine')}>{tr("Connect engine")}
)}
: step === 3 ?
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
- {tr(preparing ?
{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}% of this file` : 'Getting files ready…')}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} + {tr(preparing ?
{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}
{tr(progress ? : )}
{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…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} {tr("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
:
diff --git a/apps/host/src/components/NativeDelete.tsx b/apps/host/src/components/NativeDelete.tsx new file mode 100644 index 00000000..07e9ba62 --- /dev/null +++ b/apps/host/src/components/NativeDelete.tsx @@ -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('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 {tr("Keep version")} void remove()}>{tr(pending ? 'Working…' : 'Delete version')}}> +

{tr(label)}{tr(gb ? ` · ${sizeGb(gb)}` : '')}

+ {tr(entry ?

{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.' : '')}

:

{tr("This version is no longer downloaded.")}

)} + {tr(error ? : null)} +
; +} diff --git a/apps/host/src/components/NativeLocalModel.tsx b/apps/host/src/components/NativeLocalModel.tsx new file mode 100644 index 00000000..f2d05aaa --- /dev/null +++ b/apps/host/src/components/NativeLocalModel.tsx @@ -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(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('/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('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 {tr("Strata optimized models")}}> +
+
+

{tr("Use a local GGUF…")}

+

{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.")}

+ +
void check('')}>{tr("Choose folder")} void check(typed)}>{tr(pending && !jobId ? 'Checking…' : 'Check files')}
+
+ {tr(checked ?
{tr(usable ? <> +

{tr(family ? family.title : 'Model found')}

+

{tr(version ? catalogVersionLabel(version) : selection?.model ?? '')} · {tr(selection?.model ?? '')}

+

{tr("{0} files · {1}", [checked.preview.file_count, sizeGb(checked.preview.total_bytes / 1024 ** 3)])}

+
void prepare()}>{tr(pending ? 'Checking…' : 'Prepare and load')}
+ : <> +

{tr(found!.message)}

+

{tr(found!.next)}

+ {tr(checked.preview.issues.length ?
{tr("Details")}
{checked.preview.issues.join(String.fromCharCode(10))}
: null)} + )}
: null)} + {tr(active ? : job?.state === 'error' ? : job?.state === 'done' ?

{tr(job.summary)}

: null)} + {tr(error ? : null)} +
+ +
+
; +} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index fdc6a953..07625d16 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -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([]), [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 | null>(null), [benchmark, setBenchmark] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); const presetPending = useRef(false); + const [deleting, setDeleting] = useState(null); const families = nativeCatalogModels(native?.catalog?.families ?? []); const expertSection = useRef(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'); }}/> setManage(true)}>{tr("Manage models")}
: null)}
- {tr(native?.instances.length && expert ?

{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}

{tr(native.instances.map(i =>
{tr(i.label)}{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' : '')}{tr(i.error ? {tr(i.error)} : null)}{tr(expert && multiple && native.defaultId !== i.id ? void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")} : null)} void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}
))}
: null)} + {tr(native?.instances.length && expert ?

{tr(native.instances.length === 1 ? 'Loaded model' : 'Loaded models')}

{tr(native.instances.map(i =>
{tr(i.label)}{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' : '')}{tr(i.error ? {tr(plainFailureText(i.error).message)} : null)}{tr(expert && multiple && native.defaultId !== i.id ? void perform(() => nativeAction(`instances/${i.id}/default`))}>{tr("Use in chat")} : null)} void perform(() => nativeAction(`instances/${i.id}/unload`))}>{tr("Unload")}
))}
: null)}
{tr(selectedFamily && !selectedSize ? <>

{tr("This model needs a newer engine.")}

{tr("Update your engine or import a local GGUF for this model.")}

{ setSettingsSection('Engine'); go('settings'); }}>{tr("Update engine")}{tr("Use a local GGUF\u2026")} : null)}{tr(!selectedFamily ? <>

{tr("Set up Strata")}

{tr("Connect your local installation to choose an optimized model.")}

{ setSettingsSection('Engine'); go('settings'); })}>{tr("Connect engine")}{tr(native?.error ?

{tr(native.error)}

: null)}{tr("Other local models")} : null)} {tr(selectedSize ? <>{tr(expert && vision !== 'no' ? setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("Optional")}{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}{tr(expert && vision !== 'no' ? ({ value: String(n), label: `${n / 1024}K` }))} onChange={n => setContext(Number(n))}/>
: null)} @@ -91,18 +106,32 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(active ? : null)} {tr(job?.state === 'error' ? void load()}/> : null)} {tr(error ? : null)} -
{tr(onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> i.status === 'ready') || !!active} onClick={() => setBenchmark(true)}>{tr("Tune model")} void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
+
{tr(loadedSelected ? <> void perform(() => nativeAction(`instances/${loadedSelected.id}/unload`))}>{tr("Unload")}{tr(onReady ? {tr("Start chatting")} : {tr("Ready")})} : onReady && native?.instances.some(i => i.status === 'ready') ? {tr("Start chatting")} : <> void load()}>{tr(pending ? 'Checking…' : installed?.ready ? 'Load model' : 'Download & load')})}
!pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr("Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")}

{tr(plan?.plan?.disk_short ? : null)}

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
- setManage(false)} actions={ setManage(false)}>{tr("Done")}}>

{tr(selectedFamily?.title)}

{tr(selectedFamily?.sizes.map(v => ))}
{tr("Version")}{tr("Download")}{tr("Status")}
{tr(catalogVersionLabel(v))}{tr(v.model)} · {tr(v.about)}{tr(v.download_gb.toFixed(1))}{tr(" GB")}{tr(native?.instances.some(i => i.model === v.id) ? 'Loaded' : v.installed ? 'Downloaded' : 'Available')} { setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === v.id ? 'Selected' : 'Use version')}
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF\u2026")}

{tr("Choose a version, then load it from Models. Shared native files are kept together in Storage.")}

- setBenchmark(false)}/> + setDeleting(null)}/> + setManage(false)} actions={ setManage(false)}>{tr("Done")}}>
+ {tr(downloaded.length ?
{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
+ {tr(v ? `${catalogVersionLabel(v)}` : m.model_name ?? m.model)}{tr(v ? v.model : m.model)}{tr(m.diskGb ? ` · ${sizeGb(m.diskGb)}` : '')} + {tr(loaded ? 'Loaded' : 'Downloaded')} + { if (v) setSize(v.id); setManage(false); }}>{tr(selectedSize?.id === m.model ? 'Selected' : 'Use version')} setDeleting(m.model)}>{tr("Delete")} +
; }))}
:

{tr("No downloaded models")}

)} +
{ setManage(false); (onImport ?? onOtherModels)(); }}>{tr("Use a local GGUF…")}
+
; } +/** 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

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ? void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')} : null)}

{tr(job.kind === 'install' ? (job.result?.install?.step ?? 'Downloading and preparing model files…') : job.summary)}

{tr(download ? <>

{tr(download.file)} · {tr(download.percent ?? 0)}%

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? installStepLabel(job.result?.install?.step) : job.summary)}

{tr(download ? <>

{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` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(detailsText ?
{detailsText}
: null)}
{tr(error ? : null)}
; } diff --git a/apps/host/src/components/NativeOperations.tsx b/apps/host/src/components/NativeOperations.tsx index 1857b747..f058becc 100644 --- a/apps/host/src/components/NativeOperations.tsx +++ b/apps/host/src/components/NativeOperations.tsx @@ -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

{tr("Engine installation")}

{tr(native?.available ? 'Connected' : 'Setup needed')}

{tr("Your local Strata installation handles optimized models, companion files and engine updates.")}

{tr("Installation folder")}
void connect()}>{tr(pending ? 'Connecting…' : 'Connect installation')} void refreshNative(true)}>{tr("Check again")}{tr("Get Strata")}
{tr(native?.error ?

{tr(native.error)}

:

{tr(native?.summary)}

)}
- {tr(installed.length ?

{tr("Model settings & tools")}

setLanguage(value as typeof prefs.language)}/> }, { section: 'Reading & focus', label: 'Font', hint: 'Choose an installed font for the interface and conversations.', control: }, { section: 'General', label: 'Keyboard shortcuts', hint: 'Set the key combinations that feel natural to you.', aliases: 'command keys hotkeys', control: setShortcuts(true)}>{tr("Edit shortcuts")} }, - { section: 'Reading & focus', label: 'Appearance', hint: 'Light is the default. System follows your computer.', aliases: 'theme light dark system automatic', control: }, { section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: }, { section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: }, { section: 'Reading & focus', label: 'Motion', hint: 'Reduced motion also disables smooth scrolling.', aliases: 'animation system full reduced', control: }, - { section: 'Reading & focus', label: 'Contrast', hint: 'Increase text and boundary contrast.', aliases: 'accessibility standard increased', control: