okami.mom/strata

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

Niko1221Merge f-027-app2: master switches in the app and Terminal settings03d709820

main
10.2 KiB143 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { spawn } from 'node:child_process';
4import { mkdtemp, rm } from 'node:fs/promises';
5import { tmpdir } from 'node:os';
6import { join } from 'node:path';
7import { createServer } from 'node:net';
8import { fileURLToPath } from 'node:url';
9import { EventEmitter } from 'node:events';
10import { createAppUi, openInBrowser, startOpener, APP_UPDATE_UNAVAILABLE, BROWSER_UPDATE_MESSAGE } from '../server/app-ui.mjs';
11import { checkComponentUpdates } from '../server/updates.mjs';
12
13const root = fileURLToPath(new URL('..', import.meta.url));
14const delay = ms => new Promise(r => setTimeout(r, ms));
15/** Wait until `done()` is true, polling every 10 ms for up to `ms` (a busy PC can hold a timer back by far more than a fixed 20 ms sleep). */
16const until = async (done, ms = 5000) => { const end = Date.now() + ms; while (!done() && Date.now() < end) await delay(10); return done(); };
17const bridgeEnv = { STRATA_SHELL_BRIDGE: 'http://127.0.0.1:5555', STRATA_SHELL_TOKEN: 'a'.repeat(32) };
18
19test('a host nobody started has no window mode, no Quit and no updater', () => {
20  const ui = createAppUi({ env: {} });
21  assert.deepEqual(ui.state(), { mode: null, reason: null, canQuit: false, appUpdate: 'unavailable' });
22  assert.equal(ui.updater, null);
23  assert.equal(ui.quit().ok, false);
24});
25
26test('window mode: no Quit entry (closing the window ends everything), the updater waits for the window process', async () => {
27  const ui = createAppUi({ env: { STRATA_UI_MODE: 'window' } });
28  assert.equal(ui.state().canQuit, false);
29  assert.equal(ui.state().appUpdate, 'available');
30  assert.equal(ui.quit().status, 409);
31  await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE);
32  ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'b'.repeat(32) });
33  assert.ok(ui.updater);
34  assert.throws(() => ui.setBridge({ url: 'http://example.com:1', token: 'b'.repeat(32) }), /not a bridge/);
35  assert.throws(() => ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'short' }), /not a bridge/);
36});
37
38test('browser mode (chosen): Quit works once and the app updater says why it is not available', async () => {
39  let stopped = 0;
40  const ui = createAppUi({ env: { STRATA_UI_MODE: 'browser' }, shutdown: () => { stopped++; } });
41  assert.deepEqual(ui.state(), { mode: 'browser', reason: 'chosen', canQuit: true, appUpdate: 'unavailable' });
42  assert.equal(ui.updater.unavailable, BROWSER_UPDATE_MESSAGE);
43  await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE && error.message === BROWSER_UPDATE_MESSAGE);
44  assert.equal(ui.quit().status, 202);
45  assert.ok(await until(() => stopped >= 1), 'the shutdown callback ran');
46  await delay(50);   // and only once
47  assert.equal(stopped, 1);
48});
49
50test('the shell moves a window host to a browser tab: opens the page, sends the notice, drops the window updater', async () => {
51  const opened = [], notices = [];
52  const ui = createAppUi({ env: { STRATA_UI_MODE: 'window' }, open: async url => { opened.push(url); return true; }, notify: async text => { notices.push(text); } });
53  ui.setBridge({ url: 'http://127.0.0.1:6001', token: 'b'.repeat(32) });
54  const out = await ui.switchToBrowser({ url: 'http://127.0.0.1:47831/', notice: 'Strata opened in your browser because the app window couldn\'t start on this computer.' });
55  assert.deepEqual(out, { mode: 'browser', reason: 'window-failed', opened: true });
56  assert.deepEqual(opened, ['http://127.0.0.1:47831/']);
57  assert.equal(notices.length, 1);
58  assert.equal(ui.state().canQuit, true);
59  await assert.rejects(ui.updater.check(), error => error.code === APP_UPDATE_UNAVAILABLE);
60  // no browser could be opened: the shell is told, it prints the address
61  const none = createAppUi({ env: { STRATA_UI_MODE: 'window' }, open: async () => false, notify: async () => false });
62  assert.equal((await none.switchToBrowser({ url: 'http://127.0.0.1:1/' })).opened, false);
63});
64
65test('openers are tried in order until one takes the address', async () => {
66  const tried = [];
67  const ok = await openInBrowser('http://127.0.0.1:1/', { openers: [['xdg-open'], ['gio', 'open'], ['firefox']], start: async (cmd, args) => { tried.push([cmd, ...args].join(' ')); return cmd === 'gio'; } });
68  assert.equal(ok, true);
69  assert.deepEqual(tried, ['xdg-open http://127.0.0.1:1/', 'gio open http://127.0.0.1:1/']);
70  assert.equal(await openInBrowser('x', { openers: [['a'], ['b']], start: async () => false }), false);
71});
72
73test('an opener that is missing or fails fast is a failure; one still running is a success', async () => {
74  const fake = behaviour => () => { const child = new EventEmitter(); child.unref = () => {}; queueMicrotask(() => behaviour(child)); return child; };
75  assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('error', new Error('ENOENT'))) }), false);
76  assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('exit', 3)) }), false);
77  assert.equal(await startOpener('x', [], { env: {}, settleMs: 200, spawnProcess: fake(c => c.emit('exit', 0)) }), true);
78  assert.equal(await startOpener('x', [], { env: {}, settleMs: 50, spawnProcess: fake(() => {}) }), true);
79});
80
81test('update check in browser mode: the app part says it cannot be done here, engine/component updates stay possible', async () => {
82  const control = { version: '0.1.0', updateCheck: async () => ({ app: { status: 'available', offered: '0.2.0', notes: 'Faster.' }, engine: { status: 'current', installed: { version: '1' } }, control: { status: 'current' } }) };
83  const browser = createAppUi({ env: { STRATA_UI_MODE: 'browser' } });
84  const inBrowser = await checkComponentUpdates({ control, appUpdater: browser.updater, appVersion: '0.1.0' });
85  assert.equal(inBrowser.strata.status, 'available');
86  assert.equal(inBrowser.strata.canInstall, false);
87  assert.match(inBrowser.strata.message, /can't be updated in browser mode/);
88  // the same check with the window's updater in place offers the update as before
89  const windowed = createAppUi({ env: { STRATA_UI_MODE: 'window', ...bridgeEnv }, createUpdater: ({ env }) => env.STRATA_SHELL_BRIDGE ? { check: async () => ({ available: true, version: '0.2.0', notes: 'Faster.' }), install: async () => {} } : null });
90  const inWindow = await checkComponentUpdates({ control, appUpdater: windowed.updater, appVersion: '0.1.0' });
91  assert.equal(inWindow.strata.canInstall, true);
92  assert.doesNotMatch(inWindow.strata.message, /browser mode/);
93});
94
95async function freePort() { 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; }
96
97async function startHost(extraEnv) {
98  const home = await mkdtemp(join(tmpdir(), 'strata-host-appui-'));
99  const port = await freePort();
100  const host = spawn(process.execPath, ['server/index.mjs'], {
101    cwd: root, stdio: 'ignore',
102    env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_NO_ACQUIRE: '1', STRATA_NO_BUNDLED_ENGINE: '1', ...extraEnv },
103  });
104  let up = false;
105  for (let i = 0; i < 150 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }
106  assert.ok(up, 'the host answers');
107  const exited = new Promise(resolve => host.on('exit', code => resolve(code)));
108  return { port, host, exited, home, base: `http://127.0.0.1:${port}` };
109}
110
111test('browser-mode host over HTTP: mode, Quit needs the client header, then the host stops cleanly and only listens on 127.0.0.1', async () => {
112  const { port, host, exited, home, base } = await startHost({ STRATA_UI_MODE: 'browser' });
113  try {
114    const mode = await (await fetch(`${base}/api/app/mode`)).json();
115    assert.equal(mode.mode, 'browser'); assert.equal(mode.canQuit, true);
116    // a plain POST (what a web page could send without asking first) is refused, and so is a page from another site
117    assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST' })).status, 403);
118    assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui', origin: 'https://example.com' } })).status, 403);
119    // the shell's own routes need the secret
120    assert.equal((await fetch(`${base}/api/control/ui`, { method: 'POST', body: '{}' })).status, 403);
121    // it is listening on the loopback address only
122    const { networkInterfaces } = await import('node:os');
123    const other = Object.values(networkInterfaces()).flat().find(i => i && !i.internal && i.family === 'IPv4');
124    if (other) await assert.rejects(fetch(`http://${other.address}:${port}/api/health`, { signal: AbortSignal.timeout(2000) }));
125    assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui' } })).status, 202);
126    assert.equal(await Promise.race([exited, delay(30000).then(() => 'still running')]), 0);
127  } finally { host.kill(); await rm(home, { recursive: true, force: true }); }
128});
129
130test('window-mode host over HTTP: Quit is refused; the shell (with its secret) registers the bridge and can move the host to browser mode', async () => {
131  const secret = 'c'.repeat(64);
132  const { host, home, base } = await startHost({ STRATA_UI_MODE: 'window', STRATA_SHUTDOWN_TOKEN: secret, STRATA_OPENER: 'record' });
133  try {
134    assert.equal((await fetch(`${base}/api/app/quit`, { method: 'POST', headers: { 'x-strata-client': 'ui' } })).status, 409);
135    const as = (body, token = secret) => fetch(`${base}/api/control/ui`, { method: 'POST', headers: { 'x-strata-shutdown': token, 'content-type': 'application/json' }, body: JSON.stringify(body) });
136    assert.equal((await as({}, 'd'.repeat(64))).status, 403);
137    assert.equal((await as({ bridge: { url: 'http://evil.example:1', token: 'e'.repeat(32) } })).status, 400);
138    assert.equal((await as({ bridge: { url: 'http://127.0.0.1:9', token: 'e'.repeat(32) } })).status, 200);
139    const moved = await (await as({ mode: 'browser', reason: 'window-failed', open: false })).json();
140    assert.equal(moved.mode, 'browser');
141    assert.equal((await (await fetch(`${base}/api/app/mode`)).json()).reason, 'window-failed');
142  } finally { host.kill(); await rm(home, { recursive: true, force: true }); }
143});