okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
6.7 KiB109 linesraw
1/**
2 * UI preview only (STRATA_UI_PREVIEW=1): several installed engines for Settings > Engine and an engine update for About, kept in memory.
3 * The demo host refuses mutations and simulates the hardware, so this answers the same routes the real host has (/api/engines, /api/engines/use,
4 * /api/engines/remove, /api/updates/check, the update-engine job) with believable behaviour: switching changes what is in use, the engine in use
5 * cannot be deleted, a switch while a model is loaded answers with the same plain sentence, an update makes the new engine the one in use.
6 * Nothing here touches a disk or a process.
7 */
8const GB = 1e9;
9
10function engine(family, version, bytes, extra = {}) {
11  const backend = extra.backend ?? 'cuda';
12  const variant = extra.variant ?? (backend === 'cuda' ? 'cuda13' : '');
13  const folder = `${version}-windows-x86_64-${backend}${variant ? `-${variant}` : ''}`;
14  return { family, folder, version, backend, platform: 'windows-x86_64', variant, bytes, signed: true, fits: true, why_not: null, why_code: null, why_args: [],
15    active: false, newest: false, pinned: false, running: false, can_use: true, can_delete: true, delete_blocked: null, blocked_code: null,
16    build_id: `preview-${version}`, path: `C:\\Users\\you\\AppData\\Local\\Strata\\components\\engine\\${folder}`, ...extra };
17}
18
19export function createEnginePreview(native) {
20  const qwen = [engine('qwen', '0.1.55', 1.02 * GB), engine('qwen', '0.1.54', 0.98 * GB), engine('qwen', '0.1.50', 0.91 * GB),
21    engine('qwen', '0.1.49', 0.88 * GB, { backend: 'hip', fits: false, why_not: 'x', why_code: 'gpu_make' })];
22  const groups = () => [{ family: 'qwen', title: 'Qwen and other models', engines: qwen }];
23  const latest = '0.1.56';
24  let checked = false;
25  const jobs = [];
26
27  function settle(list, activeFolder) {
28    const fitting = list.filter(e => e.fits);
29    const newest = fitting.reduce((a, b) => (a && a.version.localeCompare(b.version, undefined, { numeric: true }) >= 0 ? a : b), null);
30    for (const e of list) {
31      e.active = e.folder === activeFolder;
32      e.newest = e === newest;
33      e.can_use = e.fits && !e.active;
34      e.can_delete = !e.active;
35      e.blocked_code = e.active ? 'active' : null;
36      e.delete_blocked = e.active ? 'This is the engine in use. Switch to another one first.' : null;
37    }
38  }
39  const activeOf = list => list.find(e => e.active)?.folder;
40  settle(qwen, qwen[0].folder);
41  const syncVersion = () => { native.installed = { ...(native.installed ?? {}), engine: { version: qwen.find(e => e.active)?.version ?? null } }; };
42  syncVersion();
43  native.capabilities = { ...(native.capabilities ?? {}), componentUpdates: true };
44
45  const total = () => qwen.reduce((sum, e) => sum + e.bytes, 0);
46  const loaded = () => (native.instances ?? []).some(i => i.status === 'ready' || i.status === 'loading');
47
48  return {
49    /** True when the request was answered here. */
50    async handle(path, method, body, json) {
51      if (path === '/api/engines' && method === 'GET') return json({ available: true, families: groups(), total_bytes: total(), serving: loaded() }), true;
52      if ((path === '/api/engines/use' || path === '/api/engines/remove') && method === 'POST') {
53        const list = qwen;
54        const row = list.find(e => e.folder === body.folder);
55        if (!row) return json({ error: 'That engine is already gone. The list has been refreshed.' }, 400), true;
56        await new Promise(r => setTimeout(r, 700));
57        if (path.endsWith('/use')) {
58          if (loaded()) return json({ error: 'A model is running, so nothing was changed. Unload the model in Models, then try again.' }, 409), true;
59          if (!row.fits) return json({ error: "This engine can't run on this computer, so nothing was changed." }, 400), true;
60          settle(list, row.folder);
61          if (body.family === 'qwen') syncVersion();
62          return json({ ok: true, status: 'switched', to: row.version }), true;
63        }
64        if (row.active) return json({ error: 'This is the engine in use. Switch to another one first, then delete it.' }, 400), true;
65        list.splice(list.indexOf(row), 1);
66        settle(list, activeOf(list));
67        return json({ ok: true, status: 'deleted', version: row.version, freed_bytes: row.bytes }), true;
68      }
69      // The demo host refuses every change; unloading the demo model is allowed so the switch can be tried after the "a model is running" answer.
70      const unload = /^\/api\/native\/instances\/([^/]+)\/unload$/.exec(path);
71      if (unload && method === 'POST') {
72        native.instances = (native.instances ?? []).filter(i => i.id !== unload[1]);
73        if (native.defaultId === unload[1]) native.defaultId = native.instances[0]?.id ?? null;
74        return json(native), true;
75      }
76      if (path === '/api/updates/check' && method === 'GET') {
77        checked = true;
78        const inUse = qwen.find(e => e.active)?.version ?? null;
79        const newer = inUse && inUse.localeCompare(latest, undefined, { numeric: true }) < 0 && !qwen.some(e => e.version === latest);
80        return json({
81          checkedAt: new Date().toISOString(),
82          strata: { installedVersion: '0.2.9', status: 'current', message: 'Strata is up to date.', canInstall: false },
83          engine: newer ? { installedVersion: inUse, latestVersion: latest, status: 'available', message: 'A new engine is available (1,030 MB).', canInstall: true }
84            : { installedVersion: inUse, status: 'current', message: 'The engine is up to date.', canInstall: false },
85        }), true;
86      }
87      if (path === '/api/native/operations' && method === 'POST' && body.kind === 'update-engine') {
88        if (loaded()) return json({ error: 'Unload native models before changing engine files.' }, 400), true;
89        const job = { id: `preview-update-${jobs.length}`, kind: 'update-engine', state: 'running', startedAt: new Date().toISOString(), summary: 'Downloading: 12%', error: null,
90          result: { install: { step: 'Downloading: 12%', download: { file: `engine ${latest}`, percent: 12 } } } };
91        jobs.push(job);
92        native.jobs.push(job);
93        const step = (delay, fn) => setTimeout(fn, delay).unref();
94        step(1500, () => { job.summary = 'Downloading: 64%'; job.result.install.download.percent = 64; });
95        step(3000, () => { job.summary = 'Making sure it works…'; job.result = null; });
96        step(4500, () => {
97          for (const e of qwen) e.active = false;
98          qwen.unshift(engine('qwen', latest, 1.03 * GB));
99          settle(qwen, qwen[0].folder);
100          syncVersion();
101          Object.assign(job, { state: 'done', summary: 'The engine is updated and ready.', result: { results: [{ component: 'engine', status: 'updated' }] } });
102        });
103        return json(job), true;
104      }
105      return false;
106    },
107    get checked() { return checked; },
108  };
109}