diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59f246d9..4fe11415 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,14 +44,23 @@ jobs: - name: The cockpit page survives losing its server (headless browser, a cockpit of its own) run: | # The browser checks in dashboard/tests/*.mjs ran nowhere (found in review, - # 2026-09-24). This one and the touch check below own what they drive: a dry-run + # 2026-09-24). This one and the three below own what they drive: a dry-run # cockpit on loopback with a key of its own, a PATH whose box commands answer - # nothing and no network, and a browser that resolves no name. The other five - # drive the live cockpit of a box and stay manual; they are parsed here so they - # do not rot. + # nothing and no network, and a browser that resolves no name. The other three + # drive the live cockpit of a box and stay manual; they are parsed here. Parsing + # is not running: the update banner check called functions the redesign of + # 2026-09-30 renamed and failed 7 of 9 since, parsed green, and the monkey check + # found a page that read '…' for good with no text engine (both 2026-10-02): + # they own their cockpit now and run below. for f in dashboard/tests/*.mjs; do node --check "$f"; done node dashboard/tests/resilience-check.mjs + - name: The cockpit says when a newer version exists (headless browser, a cockpit of its own) + run: node dashboard/tests/update-banner-check.mjs + + - name: The cockpit survives a click storm on every view (headless browser, a cockpit of its own) + run: node dashboard/tests/monkey-check.mjs + - name: The cockpit page works under a finger (headless browser, real taps, a cockpit of its own) run: | # Every browser check switched views with element.click() from script, which diff --git a/dashboard/tests/monkey-check.mjs b/dashboard/tests/monkey-check.mjs index 7c07041e..95f18a07 100644 --- a/dashboard/tests/monkey-check.mjs +++ b/dashboard/tests/monkey-check.mjs @@ -3,22 +3,86 @@ // server. It refuses to run against a cockpit that is not in dry run, so nothing it // clicks can ever touch the real serving stack. // -// COCKPIT_DRY_RUN=1 COCKPIT_PORT=30091 COCKPIT_CONFIG_DIR=/tmp/x python3 dashboard/cockpit.py & -// node dashboard/tests/monkey-check.mjs [http://127.0.0.1:30091] +// node dashboard/tests/monkey-check.mjs // +// It OWNS its cockpit, like resilience-check.mjs: a dry-run instance on loopback with a key +// of its own, its engine, proxy and image lane on a closed port, its update check off and a +// PATH whose box commands answer nothing, so it runs in CI. To drive a dry-run cockpit you +// started yourself instead (one that reads the box's units, say), name it and its key: +// +// COCKPIT_KEY_FILE=/tmp/x/api-key node dashboard/tests/monkey-check.mjs http://127.0.0.1:30095 +// +// (COCKPIT_BASE works for the address too.) +// The invocation this used to give, COCKPIT_PORT=30091, is the port a box's own cockpit +// gives its agent relay, and it ran nowhere to be noticed (found 2026-10-02). // Exit code 0 = every check passed. Any failure prints the check that failed. import { spawn } from 'node:child_process'; -import { readFileSync, writeFileSync } from 'node:fs'; +import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, chmodSync, existsSync, rmSync } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import net from 'node:net'; -const BASE = process.argv[2] || process.env.COCKPIT_BASE || 'http://127.0.0.1:30091'; -const KEYFILE = process.env.COCKPIT_KEY_FILE || `${process.env.HOME}/.config/qwen38/api-key`; -const SHOT = process.env.COCKPIT_SHOT || '/tmp/cockpit-monkey.png'; +const HERE = dirname(fileURLToPath(import.meta.url)); +const CHROME = process.env.CHROME || ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', + '/snap/bin/chromium'].find(existsSync); const checks = []; const ok = (name, cond, detail = '') => { checks.push({ name, ok: !!cond, detail: String(detail).slice(0, 200) }); }; const sleep = ms => new Promise(r => setTimeout(r, ms)); +const root = mkdtempSync(join(tmpdir(), 'cockpit-monkey-')); +let server = null, chrome = null; +// process.exit() skips every finally: an early exit (the cockpit never healthy, the login +// refused, no browser) left the cockpit this spawned running on a port nobody owned. The +// exit signals what is still alive, the browser with SIGKILL so it writes no profile back. +process.on('exit', () => { + try { if (chrome && chrome.exitCode === null && chrome.signalCode === null) chrome.kill('SIGKILL'); } catch { /* gone */ } + try { if (server && server.exitCode === null && server.signalCode === null) process.kill(-server.pid, 'SIGTERM'); } catch { /* gone */ } + rmSync(root, { recursive: true, force: true }); +}); +process.on('SIGINT', () => process.exit(130)); +const SHOT = process.env.COCKPIT_SHOT || join(tmpdir(), 'cockpit-monkey.png'); +let BASE = process.argv[2] || process.env.COCKPIT_BASE || ''; +let key; +if (BASE) { + key = readFileSync(process.env.COCKPIT_KEY_FILE || `${process.env.HOME}/.config/qwen38/api-key`, 'utf8').trim(); +} else { + const cfgDir = join(root, 'config'), fence = join(root, 'bin'); + mkdirSync(cfgDir); mkdirSync(fence); + key = randomBytes(24).toString('hex'); + writeFileSync(join(cfgDir, 'api-key'), key + '\n', { mode: 0o600 }); + for (const cmd of ['docker', 'systemctl', 'journalctl', 'nvidia-smi', 'sudo', 'git', 'curl', 'tailscale', 'opencode']) { + writeFileSync(join(fence, cmd), '#!/bin/sh\nexit 1\n'); chmodSync(join(fence, cmd), 0o755); + } + const port = await new Promise(res => { const srv = net.createServer(); srv.listen(0, '127.0.0.1', () => { const p = srv.address().port; srv.close(() => res(p)); }); }); + BASE = `http://127.0.0.1:${port}`; + const CLOSED = 'http://127.0.0.1:1'; + server = spawn('python3', [join(HERE, '..', 'cockpit.py')], { + env: { ...process.env, COCKPIT_DRY_RUN: '1', COCKPIT_PORT: String(port), COCKPIT_CONFIG_DIR: cfgDir, + COCKPIT_BIND: '127.0.0.1', COCKPIT_AGENT_PORT: '0', COCKPIT_AUTOHEAL: '0', COCKPIT_AUTOFIT: '0', + COCKPIT_UPDATE_CHECK: '0', COCKPIT_ENGINE: CLOSED, COCKPIT_PROXY: CLOSED, COCKPIT_IMAGE: CLOSED, + HOME: root, PATH: `${fence}:${process.env.PATH}` }, + stdio: ['ignore', 'ignore', 'ignore'], detached: true, + }); + const t0 = Date.now(); + for (;;) { + try { const r = await fetch(`${BASE}/api/health`, { signal: AbortSignal.timeout(1500) }); if (r.ok) break; } catch { /* booting */ } + if (Date.now() - t0 > 25000) { console.error('the cockpit did not come up'); process.exit(2); } + await sleep(400); + } +} +const stopAll = async () => { + const gone = child => (!child || child.exitCode !== null || child.signalCode !== null) ? null + : Promise.race([new Promise(r => child.once('exit', r)), sleep(5000)]); + const browser = gone(chrome); + try { if (chrome) chrome.kill('SIGTERM'); } catch { /* gone */ } + await browser; + const cockpit = gone(server); + if (server) { try { process.kill(-server.pid, 'SIGTERM'); } catch { try { server.kill('SIGTERM'); } catch { /* gone */ } } } + await cockpit; +}; // ── session (server side: nothing is typed into the login form) ─────────────── -const key = readFileSync(KEYFILE, 'utf8').trim(); const jar = []; async function api(path, init = {}) { const r = await fetch(BASE + path, { ...init, headers: { ...(init.headers || {}), cookie: jar.join('; ') } }); @@ -26,7 +90,7 @@ async function api(path, init = {}) { return r; } const login = await api('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key }) }); -if (!login.ok) { console.error(`login failed: HTTP ${login.status}`); process.exit(2); } +if (!login.ok) { console.error(`login failed: HTTP ${login.status}`); await stopAll(); process.exit(2); } const cookie = jar.join('; ').match(/cockpit=([^;]+)/)?.[1]; const state0 = await (await api('/api/state')).json(); @@ -34,20 +98,28 @@ const cfg = (state0.config || {}).data || {}; if (cfg.dry_run !== true) { console.error(`REFUSING to run: ${BASE} is not in dry run (config.dry_run=${cfg.dry_run}).`); console.error('Start a second cockpit with COCKPIT_DRY_RUN=1 on another port and point this test at it.'); - process.exit(3); + await stopAll(); process.exit(3); } -// ── browser ────────────────────────────────────────────────────────────────── -const chrome = spawn('/snap/bin/chromium', ['--headless=new', '--remote-debugging-port=0', '--no-first-run', - '--disable-gpu', '--hide-scrollbars', '--window-size=1500,1000', 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] }); -const wsUrl = await new Promise((res, rej) => { - let buf = ''; chrome.stderr.on('data', d => { buf += d; const m = buf.match(/DevTools listening on (ws:\S+)/); if (m) res(m[1]); }); - setTimeout(() => rej(new Error('no devtools url: ' + buf.slice(-300))), 20000); -}); -const ws = new WebSocket(wsUrl); await new Promise(r => { ws.onopen = r; }); +// ── browser, over a pipe (no network, no name resolved but the page's own address) ── +if (!CHROME) { console.error('no browser: set CHROME to a Chromium or Chrome binary'); await stopAll(); process.exit(2); } +chrome = spawn(CHROME, ['--headless=new', '--remote-debugging-pipe', '--no-first-run', '--disable-gpu', + '--no-sandbox', `--user-data-dir=${join(root, 'chrome')}`, '--hide-scrollbars', '--window-size=1500,1000', + '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-extensions', + '--disable-default-apps', '--no-default-browser-check', '--disable-domain-reliability', '--no-pings', + '--disable-client-side-phishing-detection', '--disable-features=OptimizationHints,Translate,MediaRouter', + '--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1', 'about:blank'], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] }); let id = 0; const pending = new Map(); let events = []; -ws.onmessage = e => { const m = JSON.parse(e.data); if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } else if (m.method) events.push(m); }; -const send = (method, params = {}, sessionId) => new Promise(r => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params, sessionId })); }); +let inbox = ''; +chrome.stdio[4].on('data', d => { + inbox += d.toString(); + let cut; + while ((cut = inbox.indexOf('\0')) >= 0) { + const m = JSON.parse(inbox.slice(0, cut)); inbox = inbox.slice(cut + 1); + if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } else if (m.method) events.push(m); + } +}); +const send = (method, params = {}, sessionId) => new Promise(r => { const i = ++id; pending.set(i, r); chrome.stdio[3].write(JSON.stringify({ id: i, method, params, sessionId }) + '\0'); }); const { result: { targetId } } = await send('Target.createTarget', { url: 'about:blank' }); const { result: { sessionId } } = await send('Target.attachToTarget', { targetId, flatten: true }); await send('Network.enable', {}, sessionId); await send('Runtime.enable', {}, sessionId); await send('Page.enable', {}, sessionId); @@ -232,6 +304,7 @@ for (const v of VIEWS) { await evalJs(`showView('${v}')`); await sleep(250); ok('no horizontal scrolling at 390 px on any view', hs.length === 0, hs.join(', ')); ok('the menu button opens the rail as a drawer', await evalJs("(document.getElementById('menubtn').click(), document.body.classList.contains('railopen'))")); await send('Emulation.clearDeviceMetricsOverride', {}, sessionId); +await sleep(400); // the drawer's slide (0.3 s) ends: the screenshot caught the rail mid-way ok('no exception at phone width', jsErrors().length === 0, jsErrors().join(' | ')); // ── 10. server side: idle at the end, no collector in error ─────────────────── @@ -244,7 +317,7 @@ ok('no collector is in error at the end', const shot = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }, sessionId); writeFileSync(SHOT, Buffer.from(shot.result.data, 'base64')); -ws.close(); chrome.kill('SIGTERM'); +await stopAll(); const failed = checks.filter(c => !c.ok); for (const c of checks) console.log(` ${c.ok ? 'ok ' : 'FAIL'} ${c.name}${c.ok || !c.detail ? '' : ' <- ' + c.detail}`); diff --git a/dashboard/tests/resilience-check.mjs b/dashboard/tests/resilience-check.mjs index 276ef072..8341d1dd 100644 --- a/dashboard/tests/resilience-check.mjs +++ b/dashboard/tests/resilience-check.mjs @@ -31,7 +31,15 @@ const sleep = ms => new Promise(r => setTimeout(r, ms)); const freePort = () => new Promise(res => { const srv = net.createServer(); srv.listen(0, '127.0.0.1', () => { const p = srv.address().port; srv.close(() => res(p)); }); }); const root = mkdtempSync(join(tmpdir(), 'cockpit-resilience-')); -process.on('exit', () => rmSync(root, { recursive: true, force: true })); +let server = null, chrome = null; +// process.exit() skips every finally: an early exit (the cockpit never healthy, the login +// refused, no browser) left the cockpit this spawned running on a port nobody owned. The +// exit signals what is still alive, the browser with SIGKILL so it writes no profile back. +process.on('exit', () => { + try { if (chrome && chrome.exitCode === null && chrome.signalCode === null) chrome.kill('SIGKILL'); } catch { /* gone */ } + try { if (server && server.exitCode === null && server.signalCode === null) process.kill(-server.pid, 'SIGTERM'); } catch { /* gone */ } + rmSync(root, { recursive: true, force: true }); +}); process.on('SIGINT', () => process.exit(130)); const cfgDir = join(root, 'config'); const fence = join(root, 'bin'); @@ -45,7 +53,6 @@ const PORT = await freePort(); const BASE = `http://127.0.0.1:${PORT}`; const CLOSED = 'http://127.0.0.1:1'; -let server = null; function startServer() { server = spawn('python3', [COCKPIT], { env: { ...process.env, COCKPIT_DRY_RUN: '1', COCKPIT_PORT: String(PORT), COCKPIT_CONFIG_DIR: cfgDir, @@ -71,7 +78,6 @@ function stopServer() { server = null; } -let chrome = null; try { startServer(); if (!await waitHealth(true)) { console.error('the spawned cockpit never became healthy'); process.exit(2); } diff --git a/dashboard/tests/touch-check.mjs b/dashboard/tests/touch-check.mjs index 06ab220e..2cbca846 100644 --- a/dashboard/tests/touch-check.mjs +++ b/dashboard/tests/touch-check.mjs @@ -53,7 +53,15 @@ const PHONES = [ const DESKTOP = { name: 'laptop', w: 1366, h: 768, dpr: 1 }; const root = mkdtempSync(join(tmpdir(), 'cockpit-touch-')); -process.on('exit', () => rmSync(root, { recursive: true, force: true })); +let server = null, chrome = null; +// process.exit() skips every finally: an early exit (the cockpit never healthy, the login +// refused, no browser) left the cockpit this spawned running on a port nobody owned. The +// exit signals what is still alive, the browser with SIGKILL so it writes no profile back. +process.on('exit', () => { + try { if (chrome && chrome.exitCode === null && chrome.signalCode === null) chrome.kill('SIGKILL'); } catch { /* gone */ } + try { if (server && server.exitCode === null && server.signalCode === null) process.kill(-server.pid, 'SIGTERM'); } catch { /* gone */ } + rmSync(root, { recursive: true, force: true }); +}); process.on('SIGINT', () => process.exit(130)); const cfgDir = join(root, 'config'); const fence = join(root, 'bin'); @@ -67,7 +75,6 @@ const PORT = await freePort(); const BASE = `http://127.0.0.1:${PORT}`; const CLOSED = 'http://127.0.0.1:1'; -let server = null, chrome = null; const gone = child => (!child || child.exitCode !== null || child.signalCode !== null) ? null : Promise.race([new Promise(r => child.once('exit', r)), sleep(5000)]); try { diff --git a/dashboard/tests/update-banner-check.mjs b/dashboard/tests/update-banner-check.mjs index c0da8541..62554907 100644 --- a/dashboard/tests/update-banner-check.mjs +++ b/dashboard/tests/update-banner-check.mjs @@ -1,55 +1,147 @@ // Does the cockpit actually TELL you a newer version exists? The check behind it is -// server-side and unit-tested; what a browser has to prove is that the banner appears -// when the box is behind, names the command, disappears when it is not, and that the -// Setup line reads correctly offline and when the check is switched off. -// Usage: COCKPIT_BASE=http://127.0.0.1:30090 node dashboard/tests/update-banner-check.mjs +// server-side and unit-tested; what a browser has to prove is that the banner appears when +// the box is behind, names the command, disappears when it is not, that a cockpit running +// older code than its files says so with the file and the remedy, and that the Setup line +// reads correctly behind, offline and with the check switched off. +// +// node dashboard/tests/update-banner-check.mjs +// +// It OWNS its cockpit, like resilience-check.mjs: a dry-run instance on loopback with a key +// of its own, its engine, proxy and image lane on a closed port, its own update check off, +// and a PATH whose box commands answer nothing. Each state is put into the page and read +// back in one evaluation, so the page's own stream cannot draw over it in between. It used +// to drive a live cockpit by functions the redesign of 2026-09-30 renamed (banners(), +// rUpdate(), #upd), so 7 of its 9 checks failed on every cockpit since, and it ran nowhere +// to say so (found 2026-10-02). import { spawn } from 'node:child_process'; -import { readFileSync } from 'node:fs'; -const BASE = process.env.COCKPIT_BASE || "http://127.0.0.1:30090"; -const key = readFileSync(`${process.env.HOME}/.config/qwen38/api-key`, 'utf8').trim(); -const login = await fetch(`${BASE}/api/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key }) }); -const cookie = (login.headers.get('set-cookie') || '').match(/cockpit=([^;]+)/)?.[1]; -if (!cookie) { console.log('login echoue', login.status); process.exit(2); } -const chrome = spawn('/snap/bin/chromium', ['--headless=new', '--remote-debugging-port=0', '--no-first-run', '--disable-gpu', '--hide-scrollbars', '--window-size=1440,1400', 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] }); -const wsUrl = await new Promise((res, rej) => { let buf = ''; chrome.stderr.on('data', d => { buf += d; const m = buf.match(/DevTools listening on (ws:\S+)/); if (m) res(m[1]); }); setTimeout(() => rej(new Error('pas d url devtools')), 20000); }); -const ws = new WebSocket(wsUrl); await new Promise(r => ws.onopen = r); -let id = 0; const pending = new Map(); -ws.onmessage = e => { const m = JSON.parse(e.data); if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } }; -const send = (method, params = {}, sessionId) => new Promise(r => { const i = ++id; pending.set(i, r); ws.send(JSON.stringify({ id: i, method, params, sessionId })); }); -const { result: { targetId } } = await send('Target.createTarget', { url: 'about:blank' }); -const { result: { sessionId } } = await send('Target.attachToTarget', { targetId, flatten: true }); -await send('Network.enable', {}, sessionId); await send('Runtime.enable', {}, sessionId); await send('Page.enable', {}, sessionId); -await send('Network.setCookie', { name: 'cockpit', value: cookie, url: BASE, httpOnly: true, sameSite: 'Strict' }, sessionId); -await send('Page.navigate', { url: BASE + '/' }, sessionId); -await new Promise(r => setTimeout(r, 7000)); -const js = async expression => (await send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)).result?.result?.value; -const strip = () => js("[...document.querySelectorAll('#banners .banner')].map(e=>e.textContent).join(' | ')"); +import { mkdtempSync, mkdirSync, writeFileSync, chmodSync, existsSync, rmSync } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import net from 'node:net'; +const HERE = dirname(fileURLToPath(import.meta.url)); +const COCKPIT = join(HERE, '..', 'cockpit.py'); +const CHROME = process.env.CHROME || ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', + '/snap/bin/chromium'].find(existsSync); +const checks = []; +const ok = (name, cond, detail = '') => { checks.push({ name, ok: !!cond, detail: String(detail).slice(0, 180) }); }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const freePort = () => new Promise(res => { const srv = net.createServer(); srv.listen(0, '127.0.0.1', () => { const p = srv.address().port; srv.close(() => res(p)); }); }); +const root = mkdtempSync(join(tmpdir(), 'cockpit-update-banner-')); +let server = null, chrome = null; +// process.exit() skips every finally: an early exit (the cockpit never healthy, the login +// refused, no browser) left the cockpit this spawned running on a port nobody owned. The +// exit signals what is still alive, the browser with SIGKILL so it writes no profile back. +process.on('exit', () => { + try { if (chrome && chrome.exitCode === null && chrome.signalCode === null) chrome.kill('SIGKILL'); } catch { /* gone */ } + try { if (server && server.exitCode === null && server.signalCode === null) process.kill(-server.pid, 'SIGTERM'); } catch { /* gone */ } + rmSync(root, { recursive: true, force: true }); +}); +process.on('SIGINT', () => process.exit(130)); +const cfgDir = join(root, 'config'); +const fence = join(root, 'bin'); +mkdirSync(cfgDir); mkdirSync(fence); +const key = randomBytes(24).toString('hex'); +writeFileSync(join(cfgDir, 'api-key'), key + '\n', { mode: 0o600 }); +for (const cmd of ['docker', 'systemctl', 'journalctl', 'nvidia-smi', 'sudo', 'git', 'curl', 'tailscale', 'opencode']) { + writeFileSync(join(fence, cmd), '#!/bin/sh\nexit 1\n'); chmodSync(join(fence, cmd), 0o755); +} +const PORT = await freePort(); +const BASE = `http://127.0.0.1:${PORT}`; +const CLOSED = 'http://127.0.0.1:1'; +server = spawn('python3', [COCKPIT], { + env: { ...process.env, COCKPIT_DRY_RUN: '1', COCKPIT_PORT: String(PORT), COCKPIT_CONFIG_DIR: cfgDir, + COCKPIT_BIND: '127.0.0.1', COCKPIT_AGENT_PORT: '0', COCKPIT_AUTOHEAL: '0', COCKPIT_AUTOFIT: '0', + COCKPIT_UPDATE_CHECK: '0', COCKPIT_ENGINE: CLOSED, COCKPIT_PROXY: CLOSED, COCKPIT_IMAGE: CLOSED, + HOME: root, PATH: `${fence}:${process.env.PATH}` }, + stdio: ['ignore', 'ignore', 'ignore'], detached: true, +}); +try { + const t0 = Date.now(); + for (;;) { + try { const r = await fetch(`${BASE}/api/health`, { signal: AbortSignal.timeout(1500) }); if (r.ok) break; } catch { /* booting */ } + if (Date.now() - t0 > 25000) { console.error('the cockpit did not come up'); process.exit(2); } + await sleep(400); + } + const login = await fetch(`${BASE}/api/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ key }) }); + const cookie = (login.headers.get('set-cookie') || '').match(/cockpit=([^;]+)/)?.[1]; + if (!cookie) { console.error(`login failed: HTTP ${login.status}`); process.exit(2); } + if (!CHROME) { console.error('no browser: set CHROME to a Chromium or Chrome binary'); process.exit(2); } + chrome = spawn(CHROME, ['--headless=new', '--remote-debugging-pipe', '--no-first-run', '--disable-gpu', + '--no-sandbox', `--user-data-dir=${join(root, 'chrome')}`, '--hide-scrollbars', '--window-size=1400,900', + '--disable-background-networking', '--disable-component-update', '--disable-sync', '--disable-extensions', + '--disable-default-apps', '--no-default-browser-check', '--disable-domain-reliability', '--no-pings', + '--disable-client-side-phishing-detection', '--disable-features=OptimizationHints,Translate,MediaRouter', + '--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1', 'about:blank'], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] }); + let id = 0; const pending = new Map(); let events = []; + let inbox = ''; + chrome.stdio[4].on('data', d => { + inbox += d.toString(); + let cut; + while ((cut = inbox.indexOf('\0')) >= 0) { + const m = JSON.parse(inbox.slice(0, cut)); inbox = inbox.slice(cut + 1); + if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } else if (m.method) events.push(m); + } + }); + const send = (method, params = {}, sessionId) => new Promise(r => { const i = ++id; pending.set(i, r); chrome.stdio[3].write(JSON.stringify({ id: i, method, params, sessionId }) + '\0'); }); + const { result: { targetId } } = await send('Target.createTarget', { url: 'about:blank' }); + const { result: { sessionId } } = await send('Target.attachToTarget', { targetId, flatten: true }); + await send('Runtime.enable', {}, sessionId); await send('Page.enable', {}, sessionId); await send('Network.enable', {}, sessionId); + await send('Network.setCookie', { name: 'cockpit', value: cookie, url: BASE, httpOnly: true, sameSite: 'Strict' }, sessionId); + const evalJs = async expression => { + const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId); + if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || 'eval threw'); + return r.result.result.value; + }; + const waitFor = async (expression, ms = 20000) => { + const t0 = Date.now(); + for (;;) { + try { if (await evalJs(expression)) return true; } catch { /* navigating */ } + if (Date.now() - t0 > ms) return false; + await sleep(300); + } + }; + const jsErrors = () => events.filter(m => m.method === 'Runtime.exceptionThrown').map(m => m.params.exceptionDetails?.exception?.description || m.params.exceptionDetails?.text || 'exception'); + await send('Page.navigate', { url: BASE + '/' }, sessionId); + ok('the page is live', await waitFor("document.getElementById('conn-lbl').textContent === 'live'"), + await evalJs("document.getElementById('conn-lbl').textContent")); + // one evaluation per state: set it, draw, read + const banners = upd => evalJs(`(() => { F.update = ${JSON.stringify(upd)}; renderBanners(lastState || {}, lastErrors || {}); + return [...document.querySelectorAll('#banners .banner')].map(e => e.textContent).join(' | '); })()`); + const setupLine = upd => evalJs(`(() => { (HANDLERS.update || []).forEach(f => f(${JSON.stringify(upd)})); + return document.getElementById('rp-upd').textContent; })()`); -let ok = 0, ko = 0; -const check = (name, cond, extra='') => { (cond ? ok++ : ko++); console.log(` [${cond?' ok ':'FAIL'}] ${name}${extra?' '+extra:''}`); }; + let s = await banners({ installed: 'v1.15.1', latest: 'v1.15.1', behind: false }); + ok('up to date: no update banner', !/is out; this box runs/.test(s), s); + s = await banners({ installed: 'v1.15.0', latest: 'v1.99.0', behind: true }); + ok('behind: the banner names both versions', /Version v1\.99\.0 is out; this box runs v1\.15\.0/.test(s), s); + ok('and gives the command', /git pull && \.\/install\.sh/.test(s), s); + s = await banners({ installed: 'v1.15.1', stale_code: ['static/js/base.js'] }); + ok('older code than its files: the banner says so', /runs older code than the files on disk/.test(s), s); + ok('and names the file and the remedy', /static\/js\/base\.js/.test(s) && /systemctl restart qwen38-dashboard/.test(s), s); + s = await banners({ installed: 'v1.15.1', latest: 'v1.15.1', behind: false }); + ok('up to date again: the banner goes', !/is out; this box runs/.test(s) && !/older code/.test(s), s); + let line = await setupLine({ installed: 'v1.15.0', latest: 'v1.99.0', behind: true }); + ok('Setup line, behind', /v1\.15\.0/.test(line) && /v1\.99\.0 is out/.test(line), line); + line = await setupLine({ installed: 'v1.15.1', latest: null }); + ok('Setup line, offline', /unknown/.test(line), line); + line = await setupLine({ installed: 'v1.15.1', checked: false }); + ok('Setup line, check switched off', /check is off/.test(line), line); + ok('no exception', jsErrors().length === 0, jsErrors().join(' | ')); +} finally { + const gone = child => (!child || child.exitCode !== null || child.signalCode !== null) ? null + : Promise.race([new Promise(r => child.once('exit', r)), sleep(5000)]); + const browser = gone(chrome); + try { if (chrome) chrome.kill('SIGTERM'); } catch { /* gone */ } + await browser; + const cockpit = gone(server); + try { process.kill(-server.pid, 'SIGTERM'); } catch { try { server.kill('SIGTERM'); } catch { /* gone */ } } + await cockpit; +} -check('a jour: aucun bandeau de mise a jour', !/is out; this box runs/.test(await strip() || '')); -await js("F.update={installed:'v1.15.0',latest:'v1.99.0',behind:true}; banners(lastState||{}, lastErrors||{});"); -let s = await strip() || ''; -check('en retard: le bandeau apparait', /Version v1\.99\.0 is out; this box runs v1\.15\.0/.test(s)); -check('il donne la commande', /git pull && \.\/install\.sh/.test(s)); -await js("F.update={installed:'v1.15.1',stale_code:['static/js/base.js']}; banners(lastState||{}, lastErrors||{});"); -s = await strip() || ''; -check('code perime: le bandeau apparait', /running older code than the files on disk/.test(s)); -check('il nomme le fichier et le remede', /static\/app\.js/.test(s) && /systemctl restart qwen38-dashboard/.test(s)); -await js("F.update={installed:'v1.15.1',latest:'v1.15.1',behind:false}; banners(lastState||{}, lastErrors||{});"); -check('a jour a nouveau: le bandeau disparait', !/is out; this box runs/.test(await strip() || '')); - -await js("rUpdate({installed:'v1.15.0',latest:'v1.99.0',behind:true})"); -let line = await js("document.getElementById('upd').textContent"); -check('ligne Setup, en retard', /v1\.15\.0/.test(line) && /v1\.99\.0 is out/.test(line), JSON.stringify(line)); -await js("rUpdate({installed:'v1.15.1',latest:null})"); -line = await js("document.getElementById('upd').textContent"); -check('ligne Setup, hors ligne', /unknown/.test(line), JSON.stringify(line)); -await js("rUpdate({installed:'v1.15.1',checked:false})"); -line = await js("document.getElementById('upd').textContent"); -check('ligne Setup, desactive', /check off/.test(line), JSON.stringify(line)); - -console.log(`\n${ok} verifications passees, ${ko} echouees`); -ws.close(); chrome.kill('SIGTERM'); -process.exit(ko ? 1 : 0); +const failed = checks.filter(c => !c.ok); +for (const c of checks) console.log(` ${c.ok ? 'ok ' : 'FAIL'} ${c.name}${c.ok || !c.detail ? '' : ' <- ' + c.detail}`); +console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`); +process.exit(failed.length ? 1 : 0);