okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
58.6 KiB721 linesraw
1#!/usr/bin/env node
2/**
3 * Headless UI flows of the installed app against a packaged host with a FAKE installer and a FAKE engine (nothing is
4 * downloaded, no real engine runs; the real Control starts the fake engine through the owner runtime):
5 *
6 *   node apps/desktop/scripts/ui-flows.mjs [--control <staged control>] [--node <node.exe>] [--shots <dir>] [--only download,models,tune,fail,theme]
7 *
8 *   download  the onboarding download: ONE combined bar over both files, an ETA in minutes left of Stop, Finish later closes the
9 *             pop-up with the download still running, the Models screen shows the same progress, Stop stops it
10 *   models    an installed model is the one Models selects and loads, without a download pop-up
11 *   tune      the tuning step offers no picture reading, tunes, writes a RAM budget for "leave 20%", opens chat; reading size
12 *   fail      an engine that stops while loading: the error is in words and the pop-up does not scroll
13 *   theme     the app follows the system light/dark setting
14 * Per-user folders are all under a scratch folder. Exit 1 if a check fails.
15 */
16import { spawn, spawnSync } from 'node:child_process';
17import { createHash } from 'node:crypto';
18import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, symlinkSync, writeFileSync } from 'node:fs';
19import { createServer } from 'node:net';
20import { tmpdir } from 'node:os';
21import { dirname, join, resolve } from 'node:path';
22import { fileURLToPath, pathToFileURL } from 'node:url';
23
24const 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), []));
25const here = dirname(fileURLToPath(import.meta.url));
26const repoHost = resolve(here, '../../host');
27const staged = resolve(here, '../src-tauri/resources');
28const stagedControl = resolve(args.control ?? join(staged, 'control'));
29const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node'));
30const work = mkdtempSync(join(tmpdir(), 'strata-ui-flows-'));
31const shots = resolve(args.shots ?? join(work, 'shots'));
32mkdirSync(shots, { recursive: true });
33const only = new Set(String(args.only ?? 'download,models,profile,ui2,ui2d,tune,fail,delete,theme,restart,perf,polish,stop,latest').split(','));
34const isWin = process.platform === 'win32';
35const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core'));
36const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync);
37const delay = ms => new Promise(r => setTimeout(r, ms));
38const sha = buf => createHash('sha256').update(buf).digest('hex');
39const 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; };
40let failed = false;
41const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok  ' : 'FAIL'} ${label}${detail ? '  ' + detail : ''}`); if (!ok) failed = true; };
42
43// ------------------------------------------------------------------ the app folder: the real Control with a fake installer
44const control = join(work, 'control');
45mkdirSync(control, { recursive: true });
46for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) symlinkSync(join(stagedControl, name), join(control, name), 'junction');
47for (const name of ['strata.py', 'VERSION', 'BUNDLE.json', 'requirements.txt']) copyFileSync(join(stagedControl, name), join(control, name));
48cpSync(join(stagedControl, 'tools'), join(control, 'tools'), { recursive: true });
49const python = isWin ? join(control, 'python', 'python.exe') : join(control, 'python', 'bin', 'python3');
50
51const FAKE_INSTALLER = String.raw`
52import json, os, sys, time
53from pathlib import Path
54ROOT = Path(sys.argv[sys.argv.index('--root') + 1]) if '--root' in sys.argv else Path('.')
55STATE = Path(os.environ['FAKE_STATE']); STATE.mkdir(parents=True, exist_ok=True)
56RATE = float(os.environ.get('FAKE_RATE_GB_S', '0.5'))
57def size(model, gb, ram, mid):
58    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}
59CATALOG = {'summary': 'fake', 'families': [{'family': 'qwen', 'title': 'Qwen3.8-Flash-Next', 'about': 'x', 'experimental': False, 'images': True, 'sizes': [
60    size('Q2_0', 66.4, 48, 'q2_0'), size('IQ3_XXS', 75.8, 60, 'iq3_xxs'), size('IQ3_S', 83.6, 62, 'iq3_s')]}],
61    'contexts': [8192, 32768, 65536], 'recommendation': {'family': 'qwen', 'model': 'IQ3_XXS', 'title': 'Qwen3.8-Flash-Next IQ3_XXS', 'context': 32768}, 'context_note': ''}
62HARDWARE = {'ram_gb': 63.1, 'cpu': {'name': 'cpu', 'cores': 12}, 'gpus': [{'index': 0, 'name': 'NVIDIA GeForce RTX 5070', 'vram_gb': 11.9, 'usable': True}]}
63TOTAL = 83.6
64def job():
65    f = STATE / 'job.json'
66    if not f.exists(): return None
67    j = json.loads(f.read_text())
68    if j.get('cancelled'):
69        return {'running': False, 'exit_code': 1, 'error': 'stopped', 'result': 'failed'}
70    done = min(TOTAL, RATE * (time.time() - j['start']))
71    return {'running': True, 'step': '5/7: downloading Qwen3.8-Flash-Next IQ3_S', 'model': 'IQ3_S',
72            'download': {'file': 'model files', 'done_gb': round(done, 3), 'total_gb': TOTAL, 'remaining_gb': round(TOTAL - done, 3), 'percent': int(100 * done / TOTAL)}}
73def call(name, a):
74    if name == 'strata_models': return CATALOG
75    if name == 'strata_remove':
76        cfg = ROOT / ('strata-%s.json' % a['model'])
77        if a.get('confirm') and cfg.exists(): cfg.unlink()
78        return {'summary': 'Deleted', 'plan': {'gb': 83.6}, 'failed': []}
79    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': []}
80    if name == 'strata_install':
81        if a.get('cancel'):
82            f = STATE / 'job.json'
83            if f.exists(): j = json.loads(f.read_text()); j['cancelled'] = True; f.write_text(json.dumps(j))
84            return {'summary': 'stopped', 'install': job()}
85        if a.get('confirm'):
86            (STATE / 'job.json').write_text(json.dumps({'start': time.time()}))
87            return {'summary': 'started', 'plan': {'download_gb': TOTAL}, 'install': job()}
88        if not a: return {'summary': 'progress', 'install': job()}
89        return {'summary': 'Plan', 'plan': {'title': 'Qwen3.8-Flash-Next IQ3_S', 'download_gb': TOTAL, 'disk_short': None}}
90    raise Exception('unknown tool ' + name)
91for line in sys.stdin:
92    line = line.strip()
93    if not line: continue
94    m = json.loads(line)
95    if 'id' not in m: continue
96    method = m.get('method')
97    if method == 'initialize': res = {'protocolVersion': '2024-11-05'}
98    elif method == 'tools/list': res = {'tools': [{'name': n} for n in ('strata_models', 'strata_status', 'strata_install', 'strata_remove')]}
99    else:
100        p = m['params']
101        res = {'structuredContent': call(p['name'], p.get('arguments') or {})}
102    sys.stdout.write(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': res}) + '\n'); sys.stdout.flush()
103`;
104writeFileSync(join(control, 'tools', 'strata_mcp.py'), FAKE_INSTALLER);
105
106const FAKE_ENGINE = `import os, sys, json, time
107from pathlib import Path
108if os.environ.get('FAKE_ENGINE_FAIL'):
109    print('memory guard: 5.1 GiB of RAM free is under the 6 GiB limit (limit 63.1 GiB)', flush=True)
110    sys.exit(3)
111ctx = '4096'
112if '--max-context' in sys.argv: ctx = sys.argv[sys.argv.index('--max-context') + 1]
113print('READY %s stop' % ctx, flush=True)
114for line in sys.stdin:
115    if line.strip() == 'QUIT': break
116    if line.startswith(('GEN ', 'BGEN ')):
117        slot = int(line.split()[1]) if line.startswith('BGEN ') else None
118        t0 = time.time(); n = 0
119        for ch in os.environ.get('FAKE_REPLY', 'a'):
120            print('T %d' % ord(ch), flush=True); n += 1
121            if os.environ.get('FAKE_TOKEN_DELAY'): time.sleep(float(os.environ['FAKE_TOKEN_DELAY']))
122        print('DONE %d 12 300.0 %.1f length 0 0 0' % (n, max(1.0, (time.time() - t0) * 1000)), flush=True)
123        if slot is not None: print(f'BADM {slot} 0', flush=True)
124`;
125
126// one scenario = one fresh host with its own per-user folders
127async function scenario(name, { installed = false, env = {} } = {}, body) {
128  if (!only.has(name)) return;
129  console.log(`--- ${name}`);
130  const dir = join(work, name);
131  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') };
132  for (const d of [dirs.home, dirs.appdata, dirs.local, dirs.components, dirs.install, dirs.state, join(dir, 'models')]) mkdirSync(d, { recursive: true });
133  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 };
134  delete baseEnv.STRATA_API_KEY; delete baseEnv.STRATA_INSTALL_DIR;
135  if (installed) {
136    const platform = isWin ? 'windows-x86_64' : 'linux-x86_64';
137    const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`);
138    mkdirSync(folder, { recursive: true });
139    writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE);
140    const entry = isWin ? 'engine.cmd' : 'engine';
141    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`);
142    const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; });
143    writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files }));
144    const tok = join(dirs.install, 'tokenizer');
145    mkdirSync(tok, { recursive: true });
146    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`;
147    const made = spawnSync(python, ['-c', script, tok], { cwd: control, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' });
148    if (made.status !== 0) throw new Error('tokenizer fixture: ' + made.stderr);
149    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' }));
150  }
151  const port = env.FIXED_PORT ? Number(env.FIXED_PORT) : await freePort(), base = `http://127.0.0.1:${port}`;
152  const host = spawn(nodeExe, [join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
153    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()) } });
154  let log = ''; host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; });
155  const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; };
156  const browser = await chromium.launch({ executablePath: CHROME, headless: true });
157  try {
158    let up = false;
159    for (let i = 0; i < 200 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(150); } }
160    check(up, `${name}: the packaged host starts`);
161    await api('/api/native?refresh=1');
162    await body({ base, api, browser, dirs, shot: (page, n) => page.screenshot({ path: join(shots, `${name}-${n}.png`) }), log: () => log });
163  } catch (error) {
164    check(false, `${name}: the flow`, String(error?.stack ?? error).slice(0, 700) + '\n' + log.slice(-600));
165  } finally {
166    await browser.close().catch(() => {});
167    host.kill(); await new Promise(r => host.once('exit', r));
168  }
169}
170const newPage = async (browser, base, options = {}) => {
171  const context = await browser.newContext({ viewport: { width: 1400, height: 950 }, ...(process.env.SCHEME ? { colorScheme: process.env.SCHEME } : {}), ...options });
172  const page = await context.newPage();
173  const problems = [];
174  page.on('pageerror', e => problems.push(e.message));
175  page.problems = problems;
176  await page.goto(base, { waitUntil: 'domcontentloaded' });
177  return page;
178};
179const clickText = async (page, re, timeout = 30000) => { const b = page.getByRole('button', { name: re }).first(); await b.waitFor({ timeout }); await b.click(); };
180const noScroll = async page => page.evaluate(() => {
181  const root = document.querySelector('.guided-onboarding');
182  const bad = [];
183  for (let el = document.querySelector('.onboard-tune-stage, .onboard-prepare-stage, .onboard-model-stage') ?? root; el && el !== document.body; el = el.parentElement) {
184    const style = getComputedStyle(el);
185    if (/(auto|scroll)/.test(style.overflowY) && el.scrollHeight > el.clientHeight + 1) bad.push(`${el.className || el.tagName}: ${el.scrollHeight} > ${el.clientHeight}`);
186  }
187  return bad;
188});
189
190// ------------------------------------------------------------------------------------------------ download
191await scenario('download', {}, async ({ base, api, browser, shot }) => {
192  const page = await newPage(browser, base);
193  await clickText(page, /get started/i);
194  await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
195  await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
196  await clickText(page, /^Continue/);
197  await clickText(page, /Download model/i, 60000);
198  await page.locator('.onboard-progress progress').waitFor({ timeout: 30000 });
199  // ONE bar: sample the percent while it runs, it only goes up
200  const samples = [];
201  let eta = '';
202  for (let i = 0; i < 40 && !eta; i++) {
203    const state = (await api('/api/native')).body;
204    const d = state.jobs.at(-1)?.result?.install?.download;
205    if (d) samples.push(d.done_gb);
206    eta = (await page.locator('.onboard-progress-actions span').first().textContent({ timeout: 1000 }).catch(() => '')) ?? '';
207    await delay(1000);
208  }
209  await shot(page, '1-wizard-progress');
210  check(/About \d+ (min left|h)/.test(eta), 'the wizard shows about how many minutes are left', eta.trim());
211  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; });
212  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(' '));
213  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(', '));
214  const meta = await page.locator('.onboard-progress-meta span').first().textContent();
215  check(/GB/.test(meta ?? '') && /83\.6/.test(meta ?? ''), 'the bar says done / total over the whole model', meta);
216  // close the pop-up while it downloads
217  await clickText(page, /Finish later/i);
218  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
219  await page.getByText(/Preparing your model/i).waitFor({ timeout: 15000 }).catch(() => {});
220  await delay(1500);
221  await shot(page, '2-models-progress');
222  await page.locator('.native-progress').first().screenshot({ path: join(shots, 'download-3-models-progress-card.png') }).catch(() => {});
223  check(await page.locator('.guided-onboarding').count() === 0, 'the setup pop-up closed');
224  check(await page.getByText(/Preparing your model/i).count() > 0, 'the Models screen shows the running download');
225  const still = (await api('/api/native')).body.jobs.at(-1);
226  check(still?.state === 'running', 'the download keeps running in the background', still?.state);
227  const modelsEta = await page.locator('.native-progress .onboard-progress-actions span').first().textContent({ timeout: 15000 }).catch(() => '');
228  check(/About \d+ (min left|h)/.test(modelsEta ?? ''), 'the Models screen shows the time left too', (modelsEta ?? '').trim());
229  await clickText(page, /^Stop$/);
230  await delay(2500);
231  check((await api('/api/native')).body.jobs.at(-1)?.state !== 'running', 'Stop stops it');
232  check(page.problems.length === 0, 'no page error', page.problems.join('; '));
233});
234
235// ------------------------------------------------------------------------------------------------ models
236await scenario('models', { installed: true }, async ({ base, api, browser, shot }) => {
237  const page = await newPage(browser, base);
238  await clickText(page, /Go straight to the app/i);
239  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
240  await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
241  await delay(1500);
242  await shot(page, '1-models');
243  await page.locator('.version-trigger').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))); });
244  const summary = await page.locator('.version-trigger').first().textContent({ timeout: 5000 }).catch(() => '');
245  // the Models tab fits the first view: nothing to scroll while no list is open and Expert mode is closed
246  if (await page.getByRole('button', { name: /^Close expert mode$/ }).count()) { await page.getByRole('button', { name: /^Close expert mode$/ }).click(); await delay(500); }
247  await shot(page, '1b-models-one-view');
248  const overflow = await page.evaluate(() => { const el = document.querySelector('.main__body'); return el ? el.scrollHeight - el.clientHeight : 0; });
249  check(overflow <= 2, 'the Models tab fits the first view without scrolling', String(overflow) + ' px over');
250  check(await page.locator('.family-switch').count() === 1, 'the model family switch is in the navbar');
251  check(await page.locator('h1').filter({ hasText: /^Model$/ }).count() === 0, 'and the navbar does not say "Model"');
252  check(/IQ3_S|High quality/.test(summary ?? ''), 'Models selects the model that is on this PC, not the recommendation', (summary ?? '').replace(/\s+/g, ' ').trim());
253  check(!/IQ3_XXS|Balanced/.test(summary ?? ''), 'the recommendation (IQ3_XXS) is not what is selected');
254  const load = page.getByRole('button', { name: /^Load model$/ }).first();
255  await load.click();
256  await delay(1200);
257  check(await page.getByRole('dialog').filter({ hasText: /Download and prepare/i }).count() === 0, 'loading an installed model opens no download pop-up');
258  let ready = false;
259  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); }
260  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'); }
261  check(ready, 'the model loads (a fake engine under the real Control)');
262  await page.reload({ waitUntil: 'domcontentloaded' });
263  await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 }).catch(() => {});
264  await shot(page, '3-models-loaded');
265  check(await page.getByRole('button', { name: /^Unload$/ }).count() > 0, 'after a reload the Models screen shows the model as loaded, with Unload');
266  check(await page.getByRole('button', { name: /^Load model$/ }).count() === 0, 'and no longer offers Load model');
267  await page.getByRole('button', { name: /^Unload$/ }).first().click();
268  let gone = false;
269  for (let i = 0; i < 40 && !gone; i++) { gone = (await api('/api/native')).body.instances.length === 0; await delay(500); }
270  check(gone, 'Unload stops the engine');
271  await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 15000 }).catch(() => {});
272  check(await page.getByRole('button', { name: /^Load model$/ }).count() > 0, 'and Load model is back');
273  check(page.problems.length === 0, 'no page error', page.problems.join('; '));
274});
275
276// ------------------------------------------------------------------------------------------------ the profile used, the popover, the pop-up
277await scenario('profile', { installed: true }, async ({ base, api, browser, shot }) => {
278  const page = await newPage(browser, base);
279  await clickText(page, /Go straight to the app/i);
280  await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
281  await delay(1500);
282  const work = () => page.getByRole('button', { name: /Leave 20% for my work/ }).first();
283  const full = () => page.getByRole('button', { name: /Full performance/ }).first();
284  await work().click();
285  check(await work().getAttribute('aria-pressed') === 'true', 'Leave 20% is chosen before loading');
286  await page.getByRole('button', { name: /^Load model$/ }).first().click();
287  let ready = false;
288  for (let i = 0; i < 90 && !ready; i++) { const s = (await api('/api/native')).body; ready = s.instances.some(x => x.status === 'ready'); await delay(500); }
289  check(ready, 'the model loads');
290  const inst = (await api('/api/native')).body.instances.find(x => x.status === 'ready');
291  check(inst?.resourceProfile === 'work', 'the running model reports the profile it was started with', String(inst?.resourceProfile));
292  await delay(1500);
293  check(await work().getAttribute('aria-pressed') === 'true' && await full().getAttribute('aria-pressed') === 'false', 'after the load the page still shows Leave 20%, not Full performance');
294  await page.reload({ waitUntil: 'domcontentloaded' });
295  await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 });
296  await delay(1000);
297  check(await work().getAttribute('aria-pressed') === 'true', 'and after a reload it is still the profile in use');
298  await shot(page, '1-profile-used');
299  // the reasoning popover names the loaded model
300  await page.evaluate(() => { location.hash = '#/chat'; });
301  const effort = page.getByRole('button', { name: /^Reasoning effort/ }).first();
302  await effort.waitFor({ timeout: 30000 });
303  await effort.click();
304  const header = await page.locator('.reasoning-menu-model strong').first().textContent({ timeout: 10000 });
305  check(header && !/No model loaded/i.test(header), 'the Reasoning popover names the loaded model, not "No model loaded"', String(header));
306  await shot(page, '2-reasoning-popover');
307  await page.keyboard.press('Escape');
308  // an installed model asked for with other settings: the pop-up never speaks of downloading
309  await page.evaluate(() => { location.hash = '#/models'; });
310  await page.getByRole('button', { name: /^Unload$/ }).first().waitFor({ timeout: 30000 });
311  await page.getByRole('button', { name: /^Unload$/ }).first().click();
312  await page.getByRole('button', { name: /^Load model$/ }).first().waitFor({ timeout: 30000 });
313  await page.getByRole('combobox', { name: 'Conversation context' }).first().click();
314  const options = page.getByRole('option');
315  const pick = (await options.allTextContents()).findIndex(t => /^8K$/.test(t.trim()));
316  if (pick >= 0) await options.nth(pick).click();
317  await page.getByRole('button', { name: /^Load model$|^Checking/ }).first().click();
318  const dialog = page.getByRole('dialog').first();
319  await dialog.waitFor({ timeout: 15000 }).catch(() => {});
320  const text = (await dialog.textContent().catch(() => '')) ?? '';
321  await shot(page, '3-apply-dialog');
322  if (text) {
323    check(!/Download and prepare|Download . load|approximately|[0-9] GB/i.test(text), 'for a downloaded model the pop-up has no download wording or size', text.replace(/\s+/g, ' ').slice(0, 600));
324    check(/Apply/.test(text), 'it says what happens: apply settings and load');
325  } else console.log('info  the settings were the saved ones, so loading needed no pop-up at all');
326  check(page.problems.length === 0, 'no page error', page.problems.join('; '));
327});
328
329// ------------------------------------------------------------------------------------------------ version list, This computer, Tune, a task
330for (const scheme of ['light', 'dark']) await scenario(scheme === 'light' ? 'ui2' : 'ui2d', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: 'I am thinking about it. </think> ' + 'Here is the answer, word by word. '.repeat(12), STRATA_TUNE_NO_QUIET_CHECK: '1' } }, async ({ base, api, browser, shot }) => {
331  const page = await newPage(browser, base, { colorScheme: scheme });
332  await clickText(page, /Go straight to the app/i);
333  await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
334  await delay(1500);
335  // the version list: Recommended (the fixed four), then folded groups, one line per model
336  console.log('info  triggers', await page.locator('.version-trigger').count(), await page.getByRole('button', { name: 'Model version' }).count());
337  await page.locator('.version-trigger').first().click();
338  await delay(300);
339  console.log('info  expanded after click', await page.locator('.version-trigger').first().getAttribute('aria-expanded'));
340  await delay(800); await shot(page, `0-after-click-${scheme}`);
341  console.log('info  menu', await page.evaluate(() => { const m = document.querySelector('.version-menu'); const t = document.querySelector('.version-trigger'); return JSON.stringify({ menu: m ? m.getBoundingClientRect() : null, parent: m ? [m.parentElement.className, getComputedStyle(m.parentElement).display, getComputedStyle(m.parentElement).visibility, m.parentElement.style.cssText.slice(0, 120)] : null, expanded: t?.getAttribute('aria-expanded'), roles: [...document.querySelectorAll('[role=menu]')].length }); }));
342  await page.locator('.version-menu').waitFor({ timeout: 10000 });
343  const heads = await page.locator('.version-head span:first-child, .version-group__head').allTextContents();
344  const names = await page.locator('.version-menu > .version-row .version-row__name strong').allTextContents();
345  console.log('info  version list', JSON.stringify(heads.map(t => t.replace(/\s+/g, ' ').trim())), JSON.stringify(names));
346  check(heads[0]?.trim() === 'Recommended', `${scheme}: the list starts with Recommended`);
347  check(names.length >= 1 && names.length <= 4, `${scheme}: Recommended shows only the picks this catalog has (at most the fixed four)`, names.join(' | '));
348  check(heads.some(t => /Swift models|GSQ-RCO models|Gyro models|NVFP4 models|Unsloth models/.test(t)), `${scheme}: the other models are in folded groups`);
349  check(heads.at(-1)?.includes('Use your own GGUF'), `${scheme}: the last row is Use your own GGUF`);
350  const tall = await page.locator('.version-row').evaluateAll(els => els.filter(e => e.getBoundingClientRect().height > 44).length);
351  check(tall === 0, `${scheme}: every model is one line`, String(tall));
352  await shot(page, `1-versions-${scheme}`);
353  await page.keyboard.press('Escape');
354  // This computer
355  const pc = page.locator('.pc-card');
356  await pc.waitFor({ timeout: 10000 });
357  const pcText = ((await pc.textContent()) ?? '').replace(/\s+/g, ' ');
358  check(/This computer/.test(pcText) && /(Fits fully in memory|read from the SSD)/.test(pcText), `${scheme}: This computer says in one line whether it fits`, pcText.slice(0, 200));
359  check(await pc.locator('.pc-meter').count() >= 1, `${scheme}: it shows the memory bars`);
360  check(await pc.locator('.chip, .st-pill, [class*="badge"]').count() === 0, `${scheme}: no chips or badges in it`);
361  await shot(page, `2-computer-${scheme}`);
362  // Tune: five steps, a live speed, a result card
363  await page.getByRole('button', { name: /^Tune model$/ }).first().click({ timeout: 10000 });
364  await delay(1500); await shot(page, `2b-tune-dialog-${scheme}`);
365  // The fake engine has no other setting worth trying, so its tune passes through "trying" too fast to be seen. The page is shown the progress a
366  // real tune reports (Control's status file: stage, speeds) for the running view; the start, the result and every other call are real.
367  let fakePhase = 'run';
368  await page.route('**/api/native*', async route => {
369    const response = await route.fetch(); let json = null;
370    try { json = await response.json(); } catch { return route.fulfill({ response }); }
371    for (const job of json?.jobs ?? []) if (job.kind === 'autotune' && fakePhase === 'done') { job.state = 'done'; job.progress = null; job.result = { outcome: 'improved', gain_pct: 18, base: { decode_tok_s: 41.2 }, chosen: { decode_tok_s: 48.6 }, preset: { id: 'fast', name: 'Fast · 64K' }, answers: { class: 'exact', fields: [] } }; } else if (job.kind === 'autotune' && job.state === 'running') job.progress = { stage: 'rounds', text: null, minutesLeft: 9, runsDone: 3, runsPlanned: 6, elapsedS: 300, step: 'Trying: more experts kept in memory (round 1 of 2)', speeds: [{ label: 'base', tok_s: 41.2 }, { label: 'Fewer helper threads', tok_s: 40.1 }, { label: 'More experts kept in memory', tok_s: 46.8 }] };
372    return route.fulfill({ response, json });
373  });
374  await page.getByRole('button', { name: /Start tuning|Tune again/ }).first().click({ timeout: 15000 });
375  await page.locator('.tune-step').first().waitFor({ timeout: 60000 });
376  check(await page.locator('.tune-step').count() === 5, `${scheme}: the tuner shows its five steps`);
377  let sawRun = false, sawSpeed = false;
378  for (let i = 0; i < 400; i++) {
379    const done = await page.locator('.tune-result, .tune-progress').count();
380    if (i % 4 === 0) { const jobs = (await api('/api/native')).body?.jobs ?? []; const j = jobs.find(x => x.kind === 'autotune'); if (j) console.log('info  tune job', j.state, JSON.stringify(j.progress ?? null).slice(0, 300)); }
381    if (await page.locator('.tune-step[data-s=run]').count()) sawRun = true;
382    const big = await page.locator('.tune-live__big').first().textContent().catch(() => '');
383    if (/[0-9]/.test(big ?? '')) sawSpeed = true;
384    if (sawRun && sawSpeed) { await delay(700); await shot(page, `3-tune-running-${scheme}`); break; }
385    if (done) break;
386    await delay(600);
387  }
388  check(sawRun, `${scheme}: a step is shown as running`);
389  check(sawSpeed, `${scheme}: the live speed shows a number while it runs`);
390  if (sawSpeed) { fakePhase = 'done'; await page.locator('.tune-outcome').waitFor({ timeout: 15000 }).catch(() => {}); check(/18% faster/.test((await page.locator('.tune-outcome__body h3').textContent().catch(() => '')) ?? ''), `${scheme}: the result card shows the gain as its headline`); check(/Fast/.test((await page.locator('.tune-outcome__facts').textContent().catch(() => '')) ?? ''), `${scheme}: and what it was saved as`); }
391  await shot(page, `4-tune-result-${scheme}`);
392  await page.getByRole('button', { name: /^Close$/ }).first().click({ timeout: 10000 }).catch(() => {});
393  // a task: the opened task is skimmable, with pause / delete / Edit / Run now
394  const made = await api('/api/tasks', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ title: 'Open Downloads folder', prompt: 'Open my Downloads folder and tell me what is new.', frequency: 'weekdays', at: '08:00', weekday: 1, timeZone: 'Europe/Ljubljana', mode: 'manual', enabled: true }) });
395  const id = made.body?.id ?? made.body?.task?.id;
396  check(!!id, `${scheme}: a task is created`, JSON.stringify(made.body).slice(0, 120));
397  await page.evaluate(i => { location.hash = '#/tasks/' + i; }, id);
398  await page.getByRole('button', { name: /^Edit$/ }).first().waitFor({ timeout: 15000 });
399  console.log('info  header buttons', await page.getByRole('button', { name: /^Pause / }).count(), await page.getByRole('button', { name: /^Delete / }).count(), await page.getByRole('button', { name: /Run now/ }).count(), JSON.stringify(await page.locator('.task-header-actions button').evaluateAll(b => b.map(x => (x.getAttribute('aria-label') ?? x.textContent ?? '').trim()))));
400  check(await page.getByRole('button', { name: /^Pause / }).count() === 1 && await page.getByRole('button', { name: /^Delete / }).count() >= 1 && await page.getByRole('button', { name: /Run now/ }).count() >= 1, `${scheme}: pause, delete, Edit and Run now are in the header`);
401  check(await page.locator('.main__back').count() === 0 && await page.locator('.main__title-line .task-state').count() === 0, `${scheme}: nothing sits on the left of an opened task's navbar`);
402  const factsText = ((await page.locator('.task-facts').textContent()) ?? '').replace(/\s+/g, ' ');
403  check(/Weekdays/.test(factsText) && /Schedule/i.test(factsText) && /Last result/i.test(factsText), `${scheme}: schedule, what it may do and the last result are at the top`, factsText.slice(0, 160));
404  await shot(page, `5-task-${scheme}`);
405  await page.getByRole('button', { name: /^Pause / }).first().click();
406  await page.getByRole('button', { name: /^Resume / }).first().waitFor({ timeout: 10000 });
407  check(true, `${scheme}: Pause becomes Resume`);
408  check(page.problems.length === 0, `${scheme}: no page error`, page.problems.join('; '));
409});
410
411// ------------------------------------------------------------------------------------------------ tune + reading size
412await scenario('tune', { installed: true, env: { FAKE_TOKEN_DELAY: '0.02', FAKE_REPLY: ['I am thinking about it.', '</think>', '', 'Here is a list:', '', '- one', '- two', '', '## Heading', '', 'Some `code` and **bold** text.', '', '| a | b |', '|---|---|', '| 1 | 2 |', '', '```', 'code line', '```', ''].join(String.fromCharCode(10)) } }, async ({ base, api, browser, dirs, shot }) => {
413  const page = await newPage(browser, base);
414  await clickText(page, /get started/i);
415  await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
416  await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
417  await clickText(page, /^Continue/);
418  await page.getByText(/Leave 20% for my work/i).waitFor({ timeout: 30000 });
419  await delay(800);
420  await shot(page, '1-tune-step');
421  check(await page.getByText(/Read pictures when this model loads/i).count() === 0, 'the tuning step offers no picture reading for an app install');
422  await clickText(page, /Tune & start chatting/i);
423  let done = false, job = null;
424  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); }
425  check(job?.state === 'done', 'tuning finishes without a vision error', job?.error ?? job?.state);
426  const cfg = JSON.parse(readFileSync(join(dirs.install, 'strata-iq3_s.json'), 'utf8'));
427  check(cfg.args.includes('--resident-budget-gib'), '"leave 20%" wrote a RAM budget for the experts', cfg.args.join(' '));
428  const gib = Number(cfg.args[cfg.args.indexOf('--resident-budget-gib') + 1]);
429  check(gib + 10 <= 63.1 * 0.8, 'the budget keeps the model within 80% of the PC RAM', `${gib} GiB`);
430  // chat + reading size
431  await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 60000 });
432  await page.getByRole('textbox', { name: /Message Strata/i }).fill('hello');
433  await page.keyboard.press('Enter');
434  await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 60000 });
435  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)));
436  await page.waitForFunction(() => !document.querySelector('.st-msg--assistant .caret'), null, { timeout: 90000 }).catch(() => {});
437  // the chat's telemetry chips: speed and context
438  const chips = page.locator('.telemetry__chip');
439  const chipTexts = await chips.allInnerTexts();
440  console.log('info  chips', JSON.stringify(chipTexts));
441  let speedText = '', contextText = '';
442  for (let i = 0; i < await chips.count(); i++) {
443    await chips.nth(i).click();
444    await delay(400);
445    const pop = await page.locator('.telepop').last().innerText().catch(() => '');
446    if (/tok\/s|speed/i.test(pop) && !speedText) speedText = pop;
447    if (/context/i.test(pop) && !contextText) contextText = pop;
448    await page.keyboard.press('Escape');
449  }
450  const tps = Number(speedText.match(/([\d.]+)\s*tok(?:ens)?\/s/)?.[1] ?? NaN);
451  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));
452  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));
453  const sizes = [];
454  for (const px of [12, 14, 16, 22]) {
455    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);
456    await page.reload({ waitUntil: 'domcontentloaded' });
457    await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
458    await page.screenshot({ path: join(shots, `tune-3-chat-${px}px.png`) });
459    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]; }));
460  }
461  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; })));
462  // which visible text does NOT follow the reading size? (same elements at 12 and 22)
463  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);
464    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; }); };
465  const a = await survey(12), b = await survey(22);
466  // a fresh app (nothing saved) uses 14 px
467  await page.evaluate(() => localStorage.removeItem('strata.prefs.v2'));
468  await page.reload({ waitUntil: 'domcontentloaded' });
469  await page.locator('.st-msg--assistant .st-bubble').first().waitFor({ timeout: 30000 });
470  check(await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble')).fontSize) === '14px', 'the default reading size is 14 px');
471  const fixed = Object.keys(a).filter(k => k in b && a[k] === b[k]);
472  console.log('info  text that does not follow the reading size:', JSON.stringify(fixed.map(k => k + '=' + a[k])));
473  await shot(page, '2-chat-22px');
474  console.log('info  sizes', JSON.stringify(sizes), JSON.stringify(await page.locator('.st-msg--assistant .st-bubble').first().innerHTML()).slice(0, 400));
475  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));
476  // the slider itself
477  await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
478  const slider = page.getByLabel('Reading text size');
479  if (await slider.count()) {
480    await slider.first().focus();
481    for (let i = 0; i < 4; i++) await page.keyboard.press('ArrowRight');
482    await delay(500);
483    const now = await page.evaluate(() => getComputedStyle(document.querySelector('.st-msg--assistant .st-bubble') ?? document.body).fontSize);
484    check(parseFloat(now) === 18, 'moving the slider changes the conversation text at once', now);
485    const box = await slider.first().boundingBox();
486    await page.mouse.click(box.x + box.width * 0.9, box.y + box.height / 2);
487    await delay(400);
488    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]);
489    check(parseFloat(dragged[0]) >= 20 && parseFloat(dragged[2]) >= 20, 'clicking the slider with the mouse changes it too, and it is saved', dragged.join(' '));
490  } else console.log('info  the settings slider was not reachable by hash here; the stored size was checked above');
491  check(page.problems.length === 0, 'no page error', page.problems.join('; '));
492});
493
494// ------------------------------------------------------------------------------------------------ delete
495await scenario('delete', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
496  const page = await newPage(browser, base);
497  await clickText(page, /Go straight to the app/i);
498  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
499  await page.getByRole('button', { name: /^Load model$/ }).first().click();
500  let ready = false;
501  for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
502  check(ready, 'a model is loaded');
503  await clickText(page, /Manage models/i);
504  await page.getByRole('button', { name: /^Delete$/ }).first().click();
505  await delay(600);
506  await shot(page, '1-delete-confirm');
507  const dialog = await page.getByRole('dialog').last().innerText();
508  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, 600));
509  check(/running model will be unloaded/i.test(dialog), 'and says the loaded model is unloaded first');
510  await page.getByRole('button', { name: /^Delete version$/ }).click();
511  let state = null;
512  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); }
513  check(state.instances.length === 0, 'the loaded model was unloaded');
514  check(!existsSync(join(dirs.install, 'strata-iq3_s.json')), 'the installer removed the run config of the model');
515  check(!state.installed?.models?.some(m => m.model === 'iq3_s'), 'the model is no longer listed as downloaded');
516  await shot(page, '2-after-delete');
517});
518
519// ------------------------------------------------------------------------------------------------ perf
520await scenario('perf', { installed: true }, async ({ base, api, browser, shot }) => {
521  const page = await newPage(browser, base);
522  await clickText(page, /Go straight to the app/i);
523  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
524  await page.getByRole('button', { name: /^Load model$/ }).first().click();
525  let ready = false;
526  for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
527  check(ready, 'a model is loaded');
528  await delay(2500);
529  const requests = [];
530  const started = new Map();
531  page.on('request', r => started.set(r, Date.now()));
532  page.on('requestfinished', r => requests.push([r.url().replace(base, '').slice(0, 60), Date.now() - (started.get(r) ?? Date.now())]));
533  await page.evaluate(() => { window.__long = []; new PerformanceObserver(l => { for (const e of l.getEntries()) window.__long.push(Math.round(e.duration)); }).observe({ entryTypes: ['longtask'] }); });
534  const t0 = Date.now();
535  await page.evaluate(() => { location.hash = '#/chat'; });
536  await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
537  const open = Date.now() - t0;
538  await delay(1500);
539  const long = await page.evaluate(() => window.__long);
540  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);
541  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');
542});
543
544// ------------------------------------------------------------------------------------------------ polish
545await scenario('polish', { installed: true }, async ({ base, api, browser, dirs, shot }) => {
546  const page = await newPage(browser, base);
547  await clickText(page, /Go straight to the app/i);
548  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
549  await page.getByText(/Conversation context/i).first().waitFor({ timeout: 30000 });
550  check(await page.getByRole('button', { name: /^Tune model$/ }).count() === 1, 'the Models tab has the Tune model button (the real tuner, not the old short benchmark)');
551  await clickText(page, /Manage models/i);
552  await delay(500);
553  const rows = await page.locator('.native-manage-row').count();
554  check(rows === 1, 'Manage models lists only the downloaded model, not the catalog', rows + ' row(s)');
555  await shot(page, '1-manage-models');
556  await page.getByRole('button', { name: /^Done$/ }).click();
557  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); });
558  await page.getByText(/Folder with the GGUF files/i).first().waitFor({ timeout: 15000 }).catch(() => {});
559  await shot(page, '2-local-gguf');
560  check(await page.getByText(/Folder with the GGUF files/i).count() > 0, 'the local GGUF page opens in the same design as Models');
561  await page.getByPlaceholder(/Full path to the folder/i).fill(join(dirs.install, 'does-not-exist'));
562  await page.getByRole('button', { name: /^Check files$/ }).click();
563  await delay(3000);
564  check(await page.locator('.error-notice').count() > 0, 'a folder that cannot be used says so in words');
565  await shot(page, '2b-local-gguf-problem');
566  await page.evaluate(() => { location.hash = '#/chat?settings=1'; });
567  await delay(1500);
568  const text = await page.locator('body').innerText();
569  check(!/Contrast/.test(text), 'Settings has no Contrast option');
570  check(!/View request log/.test(text), 'and no "View request log" button');
571  await page.getByText(/^Engine$/).first().click().catch(() => {});
572  await delay(1500);
573  await shot(page, '3-settings-engine');
574  const engine = await page.locator('body').innerText();
575  check(/Update component/.test(engine) && /Diagnostics/.test(engine), 'Settings > Engine has Update component and Diagnostics');
576  check(!/Performance|Model settings|Calibrate|Engine installation/.test(engine), 'and nothing else');
577  await page.getByRole('button', { name: /^View logs$/ }).click();      // the logs open in a pop-up that holds Save logs
578  await page.getByRole('button', { name: /^Save logs$/ }).click();
579  await page.getByText(/Saved to/).first().waitFor({ timeout: 15000 }).catch(() => {});
580  const savedText = await page.getByText(/Saved to/).first().innerText().catch(() => '');
581  const savedPath = savedText.replace(/^Saved to\s*/, '').trim();
582  check(!!savedPath && existsSync(savedPath), 'Save logs writes a file to Downloads and says where', savedPath);
583  await shot(page, '4-logs-saved');
584  await page.evaluate(() => { location.hash = '#/monitor'; });
585  await delay(6000);
586  await shot(page, '5-monitor');
587  const mon = await page.locator('body').innerText();
588  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, ' '));
589});
590
591// ------------------------------------------------------------------------------------------------ stop
592await scenario('stop', { installed: true, env: { FAKE_TOKEN_DELAY: '0.1', FAKE_REPLY: 'thinking '.repeat(30) } }, async ({ base, api, browser, shot }) => {
593  const page = await newPage(browser, base);
594  await clickText(page, /Go straight to the app/i);
595  await page.waitForURL(/#\/models/, { timeout: 15000 }).catch(() => {});
596  await page.getByRole('button', { name: /^Load model$/ }).first().click();
597  let ready = false;
598  for (let i = 0; i < 90 && !ready; i++) { ready = (await api('/api/native')).body.instances.some(x => x.status === 'ready'); await delay(1000); }
599  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'); }
600  check(ready, 'a model is loaded');
601  await page.evaluate(() => { location.hash = '#/chat'; });
602  const box = page.getByRole('textbox', { name: /Message Strata/i });
603  await box.waitFor({ timeout: 30000 });
604  await box.fill('hello');
605  await page.keyboard.press('Enter');
606  await page.locator('.typing').first().waitFor({ timeout: 30000 });
607  await delay(1500);
608  await page.getByRole('button', { name: /^Stop/i }).first().click().catch(async () => { await page.keyboard.press('Escape'); });
609  await delay(4000);
610  const dots = await page.locator('.typing').count();
611  await shot(page, '1-after-stop');
612  check(dots === 0, 'after Stop in the middle of thinking the three dots are gone', dots + ' left');
613});
614
615// ------------------------------------------------------------------------------------------------ latest
616await scenario('latest', {}, async ({ base, browser, shot }) => {
617  const page = await newPage(browser, base);
618  const now = Date.now();
619  await page.evaluate(async now => {
620    const messages = [];
621    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 }); }
622    await fetch('/api/chats/s_latest', { method: 'PUT', headers: { 'x-strata-client': 'ui' }, body: JSON.stringify({ id: 's_latest', title: 'long', updatedAt: now, createdAt: now, messages }) });
623    localStorage.setItem('strata.active-session.v1', 's_latest');
624  }, now);
625  await page.reload({ waitUntil: 'domcontentloaded' });
626  await delay(1500);
627  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); }
628  await page.goto(base + '/#/chat', { waitUntil: 'domcontentloaded' });
629  await page.getByRole('textbox', { name: /Message Strata/i }).waitFor({ timeout: 30000 });
630  await delay(800);
631  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))); });
632  await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 3000; });
633  await delay(600);
634  await page.mouse.wheel(0, -400);
635  await delay(600);
636  await page.locator('.main__body.chat').first().evaluate(el => { el.scrollTop = 0; });
637  await delay(800);
638  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) }; });
639  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 }; })));
640  await shot(page, '1-latest-button');
641  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));
642});
643
644// ------------------------------------------------------------------------------------------------ fail
645await scenario('fail', { installed: true, env: { FAKE_ENGINE_FAIL: '1' } }, async ({ base, api, browser, shot }) => {
646  const page = await newPage(browser, base);
647  await clickText(page, /get started/i);
648  await page.getByText(/Choose a version/i).waitFor({ timeout: 30000 });
649  await page.locator('[role=radio]').filter({ hasText: 'IQ3_S' }).first().click();
650  await clickText(page, /^Continue/);
651  await clickText(page, /Tune & start chatting/i, 30000);
652  await page.getByText(/ran low on memory/i).first().waitFor({ timeout: 120000 });
653  await delay(1000);
654  await shot(page, '1-tune-error');
655  const text = await page.locator('.guided-onboarding').innerText();
656  check(/ran low on memory/.test(text), 'the error says in words that the PC ran low on memory');
657  check(/Leave 20% for my work/.test(text) && /low-RAM/.test(text), 'and what to try');
658  check(!/server_exited|memory guard/.test(text), 'no code or log line in the main text');
659  check(!/vision files/i.test(text), 'no picture-reading error');
660  const bad = await noScroll(page);
661  check(bad.length === 0, 'the tuning pop-up does not scroll when an error shows', bad.join('; '));
662  await page.locator('.error-notice summary').first().click();
663  await delay(500);
664  await shot(page, '2-tune-error-details');
665  const details = await page.locator('.error-notice pre').first().innerText();
666  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));
667  const badOpen = await noScroll(page);
668  check(badOpen.length === 0, 'and the pop-up still does not scroll with Details open', badOpen.join('; '));
669  await page.setViewportSize({ width: 1280, height: 700 });
670  await delay(600);
671  const small = await noScroll(page);
672  check(small.length === 0, 'nor in a small window (1280x700), Details open', small.join('; '));
673  await shot(page, '3-tune-error-small-window');
674  void api;
675});
676
677// ------------------------------------------------------------------------------------------------ restart
678// The app keeps its theme, text size, language and chat list in the browser's storage, which belongs to the window's origin
679// (127.0.0.1:<port>). The shell now uses the same port every launch: stop the host, start it again on that port, reopen the
680// window with the same browser profile, and everything is still there.
681if (only.has('restart')) {
682  console.log('--- restart');
683  const fixed = await freePort();
684  const profile = join(work, 'browser-profile');
685  const run = async (body) => scenario('restart', { env: { FIXED_PORT: String(fixed) } }, async ctx => {
686    const context = await chromium.launchPersistentContext(profile, { executablePath: CHROME, headless: true, viewport: { width: 1200, height: 800 } });
687    try { await body(context, ctx); } finally { await context.close(); }
688  });
689  only.add('restart');
690  await run(async (context, { base }) => {
691    const page = context.pages()[0] ?? await context.newPage();
692    await page.goto(base, { waitUntil: 'domcontentloaded' });
693    await page.evaluate(() => { localStorage.setItem('strata.prefs.v2', JSON.stringify({ theme: 'dark', contentFontSize: 19, language: 'de' })); return fetch('/api/chats/chat-1', { method: 'PUT', headers: { 'x-strata-client': 'ui' }, body: JSON.stringify({ id: 'chat-1', title: 'My chat', messages: [], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }) }); });
694  });
695  await run(async (context, { base }) => {
696    const page = context.pages()[0] ?? await context.newPage();
697    await page.goto(base, { waitUntil: 'domcontentloaded' });
698    const saved = await page.evaluate(async () => ({ prefs: JSON.parse(localStorage.getItem('strata.prefs.v2') || '{}'), chats: JSON.stringify(await (await fetch('/api/chats', { headers: { 'x-strata-client': 'ui' } })).json()), theme: document.documentElement.dataset.theme }));
699    check(saved.prefs.contentFontSize === 19 && saved.prefs.language === 'de', 'text size and language survive a restart on the same port', JSON.stringify(saved.prefs));
700    check(saved.theme === 'dark', 'the theme survives too', saved.theme);
701    check(/My chat/.test(saved.chats ?? ''), 'and the chat list', saved.chats);
702  });
703}
704
705// ------------------------------------------------------------------------------------------------ theme
706await scenario('theme', {}, async ({ base, browser, shot }) => {
707  for (const scheme of ['dark', 'light']) {
708    const page = await newPage(browser, base, { colorScheme: scheme });
709    await delay(1500);
710    const theme = await page.evaluate(() => document.documentElement.dataset.theme);
711    check(theme === scheme, `a fresh app follows the system (${scheme})`, theme);
712    await shot(page, `1-${scheme}`);
713    await page.context().close();
714  }
715});
716
717// the junctions into the staged Control go first (rmdir on a junction removes only the link)
718for (const name of ['python', 'strata_control', 'strata_cli', 'serve']) { try { rmdirSync(join(control, name)); } catch { /* already gone */ } }
719try { rmSync(work, { recursive: true, force: true, maxRetries: 3 }); } catch (e) { console.log('info  scratch folder left behind:', work); }
720console.log(`shots in ${shots}`);
721process.exit(failed ? 1 : 0);