Upstream/e2e/flows.js
jvanvik 3c23c51902 Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e
Built:
- Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds).
- End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x).
- Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in.
- e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English.

Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented).
NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-12 00:58:12 +02:00

911 lines
66 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/*
* Feature flows for the e2e (run through e2e/run.js): units, movements + reports, alliance + messages, trade, end game, Norwegian,
* PWA, reconnect and the polling fallback. Every flow drives the real UI in real Chromium against the in-process server and, where
* the UI is not the point, seeds what a long game would have built (buildings, units) straight into the DB, like the push suite.
*
* How a check can fail (so it cannot pass by accident): each check asserts something the page could not show before the action
* (the "before" state is asserted too), reads the database where the UI could lie, and the flows that depend on an acceleration
* (hurryMovement / hurryEvents) assert that it was needed (the countdown was on screen first).
*/
const L = require('./lib.js');
const { check, group, sleep, PROFILES, noErrors, tapper, openFromMore, hurryMovement, hurryEvents, latestMovement, R } = L;
const DAY = 24 * 3600 * 1000;
const uniq = () => String(Date.now() % 1e6) + Math.floor(Math.random() * 90 + 10);
const COUNTDOWN = /\d+:\d\d|\d+\s?[smh]\b/; // 0:07, 12 s, 3 min ...
// Two players next to each other in a slow world: attacker has units, no beginner protection on either side.
function armedPair(S, nameA, nameB, units) {
return Promise.all([S.signup(nameA), S.signup(nameB)]).then(([a, b]) => {
const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId);
L.placeTown(S, b.townId, aT.x + 4, aT.y + 1);
S.db.run('UPDATE operators SET protection_until = 0');
L.setBuildings(S, a.townId, { core_router: 10, ops_lab: 6, noc: 5, rack_hall: 6, battery_bank: 6 });
for (const k of ['f13', 'f14', 'f15', 'f16']) S.db.run('UPDATE buildings SET level = 8 WHERE town_id = ? AND key = ?', a.townId, k);
S.db.run('UPDATE towns SET battery = 900, footprint = 100 WHERE id = ?', a.townId);
L.giveUnits(S, a.townId, units || { script_crew: 40, port_scanner: 6 });
return { a, b, aT, bT: S.db.get('SELECT * FROM towns WHERE id = ?', b.townId) };
});
}
// Navigate with the bottom bar (real clicks) to one of the five bar screens.
async function goBar(page, id, touch) {
await tapper(page, touch)('#nav [data-screen="' + id + '"]');
await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 });
}
const sheetClosed = (page) => page.waitForSelector('.sheet', { state: 'detached', timeout: 5000 });
const text = (page, sel) => page.innerText(sel).then((t) => t.replace(/\s+/g, ' ').trim());
const navBadge = (page, id) => page.evaluate((i) => { const b = document.querySelector('#nav [data-screen="' + i + '"] .nav-badge'); return b && !b.hidden ? b.textContent.trim() : ''; }, id);
// ---- Norwegian sweep of pages that already hold real data (reports, alliance, offers, sites): used at the end of several suites.
async function nbScan(p, where, attrs) {
await sleep(450);
const r = await p.evaluate(nbLeaks, { attrs: attrs !== false });
return r.raw.length || r.english.length ? where + ': raw keys ' + JSON.stringify(r.raw.slice(0, 5)) + ' English ' + JSON.stringify(r.english.slice(0, 5)) : null;
}
// Visit a screen in Norwegian and scan it, then run each [name, fn] step (open a sheet, switch a tab...) and scan again.
async function nbVisit(p, id, steps) {
await p.evaluate((i) => App.go(i), id);
await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])');
await sleep(500);
const out = [];
const r0 = await nbScan(p, id); if (r0) out.push(r0);
for (const [name, fn] of steps || []) { await fn(); const r = await nbScan(p, id + ' > ' + name); if (r) out.push(r); }
return out;
}
// Switch to Norwegian the way a player keeps it: the choice is stored and the page is reloaded, so every screen renders fresh in nb.
// (Switching live on screens that were already drawn is covered, for visible text, by the Norwegian suite.)
async function nbOn(p) {
await p.evaluate(() => App.setLang('nb'));
await p.reload();
await p.waitForSelector('#nav:not([hidden])', { timeout: 15000 });
await p.waitForFunction(() => document.documentElement.lang === 'nb');
}
// ================================================================== 5. units
async function suiteUnits(browser, S, U) {
group('5. units: train through the UI, queue + countdown, completion, home and stationed lists');
const { a, b } = U;
const P = await L.openSignedIn(browser, S, a, PROFILES.desktop);
const { page } = P;
// The attacker's POP already has seeded crews (home list is never empty), so use the POP with fewer: a third player trains from scratch.
const c = await S.signup('Trainer' + uniq());
L.setBuildings(S, c.townId, { noc: 3, ops_lab: 3 });
S.db.run('UPDATE towns SET battery = 900, footprint = 100 WHERE id = ?', c.townId);
await P.ctx.close();
const Q = await L.openSignedIn(browser, S, c, PROFILES.desktop, '#/units');
const q = Q.page;
const before = {};
await check('units screen: empty home list, trainable rows from the server, nothing queued', async () => {
await q.waitForSelector('[data-screen="units"]:not([hidden]) .mil-train[data-unit="script_crew"]');
before.home = await text(q, '[data-screen="units"] .col:first-child .empty');
if (!/./.test(before.home)) return 'no empty-state text for the home list';
if (await q.locator('li.batch').count()) return 'a batch is queued before anything was trained';
if (await q.locator('.mil-train.locked').count() < 3) return 'expected the high-tier units to be locked for a fresh POP';
if (await q.locator('.mil-train[data-unit="script_crew"].locked').count()) return 'script_crew is locked although Ops lab 3 is built';
});
await check('train 2 script crews: sheet previews cost and time, queue shows the batch with a countdown', async () => {
await q.click('.mil-train[data-unit="script_crew"]');
await q.waitForSelector('.sheet .mil-num');
await q.fill('.sheet .mil-num', '2');
const costs = await text(q, '.sheet .costs');
if (!/160/.test(costs)) return 'cost preview did not scale to 2 units: ' + costs; // 2 x 80 fiber
const btnOff = await q.$eval('.sheet .btn.primary', (b) => b.disabled);
if (btnOff) return 'train button disabled although the POP can afford 2';
await q.click('.sheet .btn.primary');
await sheetClosed(q);
await q.waitForSelector('li.batch', { timeout: 5000 });
const row = await text(q, 'li.batch');
if (!/× 2/.test(row)) return 'queue row misses the count: ' + row;
if (!COUNTDOWN.test(row)) return 'queue row shows no countdown: ' + row;
const ev = S.db.get("SELECT payload FROM events WHERE type = 'trainDone' AND status = 'pending' AND town_id = ?", c.townId);
if (!ev) return 'the server has no pending trainDone event';
const pill = await text(q, '[data-screen="units"] .card:has(li.batch) .card-head .pill');
if (pill !== '1') return 'queue count pill is ' + pill;
});
await check('the batch completes (event moved up): queue empties, units appear in the home list', async () => {
hurryEvents(S, 'trainDone', c.townId, 2000);
await q.waitForFunction(() => !document.querySelector('li.batch'), null, { timeout: 15000 });
await q.waitForSelector('[data-screen="units"] li.unit', { timeout: 8000 });
const row = await text(q, '[data-screen="units"] li.unit');
if (!/× 2/.test(row)) return 'home list shows ' + row;
const n = S.db.get("SELECT count FROM town_units WHERE town_id = ? AND unit = 'script_crew'", c.townId);
if (!n || n.count !== 2) return 'database has ' + JSON.stringify(n);
if (await q.locator('[data-screen="units"] .col:first-child .empty').count()) return 'the home list still shows its empty-state text';
});
await check('a failed train is explained: not enough resources keeps the button disabled', async () => {
S.db.run('UPDATE towns SET fiber = 5, res_at = ? WHERE id = ?', Date.now(), c.townId);
await q.evaluate(() => App.refreshTown());
await q.click('.mil-train[data-unit="script_crew"]');
await q.waitForSelector('.sheet .btn.primary');
await q.waitForFunction(() => { const b = document.querySelector('.sheet .btn.primary'); const r = document.querySelector('.sheet .reason'); return b && b.disabled && r && !r.hidden && r.textContent.trim().length > 3; }, null, { timeout: 4000 });
await q.keyboard.press('Escape');
});
await check('stationed units: reinforcements hosted here are listed, "send home" removes them and starts a return', async () => {
const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId);
S.db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?)', c.townId, b.townId, 'soc_analyst', 7);
await q.evaluate(() => App.refreshTown());
await q.waitForFunction(() => /7/.test((document.querySelector('[data-screen="units"]') || {}).innerText || '') && !!document.querySelector('[data-screen="units"] .mil-group'), null, { timeout: 5000 });
const grp = await text(q, '[data-screen="units"] .mil-group');
if (!/soc/i.test(grp) && !/analyst/i.test(grp)) return 'group does not name the unit: ' + grp;
if (!new RegExp(b.name).test(grp)) return 'group does not name the owner: ' + grp;
await q.click('[data-screen="units"] .mil-group .btn');
await q.waitForFunction(() => !document.querySelector('[data-screen="units"] .mil-group'), null, { timeout: 6000 });
const left = S.db.get('SELECT COUNT(*) AS n FROM stationed WHERE host_town_id = ?', c.townId).n;
if (left !== 0) return 'stationed row still in the database';
const ret = S.db.get("SELECT * FROM movements WHERE type = 'return' AND to_town_id = ? ORDER BY id DESC LIMIT 1", b.townId);
if (!ret) return 'no return movement for the owner';
void aT;
});
await check('units page: no console errors', async () => noErrors(Q));
await Q.ctx.close();
}
// ================================================================== 6. movements + reports
async function suiteMovements(browser, S, U) {
group('6. movements and reports: scan + raid through the send dialog, outgoing list, arrival, report, incoming banner');
const { a, b, bT } = U;
const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/movements', { keepLang: true });
const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true });
const ap = A.page, bp = B.page;
const label = (p, type) => p.evaluate((t) => App.mil.typeLabel(t), type);
async function sendThroughDialog(type, wantUnit, count) {
await ap.click('[data-screen="movements"] .head-actions .btn.primary'); // Send
await ap.waitForSelector('.sheet .send-coords');
await ap.fill('.sheet input[aria-label="x"]', String(bT.x));
await ap.fill('.sheet input[aria-label="y"]', String(bT.y));
await ap.click('.sheet .send-coords .btn'); // Look up
await ap.waitForSelector('.sheet .send-target .pill-row');
const tgt = await text(ap, '.sheet .send-target');
if (!tgt.includes(bT.name)) throw new Error('target card does not show the defender POP: ' + tgt);
const lbl = await label(ap, type);
await ap.click('.sheet .seg-btn:has-text("' + lbl + '")');
await ap.waitForFunction((l) => [...document.querySelectorAll('.sheet .seg-btn')].some((x) => x.textContent.trim() === l && x.getAttribute('aria-pressed') === 'true'), lbl, { timeout: 3000 });
const pick = ap.locator('.sheet .mil-pick', { hasText: wantUnit });
if (!(await pick.count())) throw new Error('no unit picker for ' + wantUnit);
if (await ap.locator('.sheet .send-preview').count()) throw new Error('a preview is shown before any unit is picked');
await pick.locator('input[type=number]').fill(String(count || 1));
await ap.waitForSelector('.sheet .send-preview', { timeout: 3000 });
const prev = await text(ap, '.sheet .send-preview');
if (!/\d/.test(prev)) throw new Error('no preview numbers: ' + prev);
if (await ap.$eval('.sheet .send-foot .btn.primary', (x) => x.disabled)) throw new Error('send button disabled: ' + (await text(ap, '.sheet .send-warn')));
await ap.click('.sheet .send-foot .btn.primary');
await sheetClosed(ap);
}
const stat = { raidId: 0, scanId: 0 };
await check('defender: no banner, Moves badge empty before anything is sent', async () => {
await bp.waitForFunction(() => window.App && App.ws && App.ws.open, null, { timeout: 10000 });
const vis = await bp.evaluate(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; });
if (vis) return 'banner visible before any send';
if (await navBadge(bp, 'movements')) return 'badge visible before any send';
});
await check('attacker: scan through the send dialog shows up in the outgoing list with a countdown and a recall button', async () => {
await sendThroughDialog('scan', 'Port scanner', 3);
await ap.waitForSelector('[data-screen="movements"] li.out.type-scan', { timeout: 6000 });
const row = await text(ap, '[data-screen="movements"] li.out.type-scan');
if (!row.includes(bT.name)) return 'row does not name the target: ' + row;
if (!COUNTDOWN.test(row)) return 'no countdown in ' + row;
if (!(await ap.locator('li.out.type-scan .mil-recall').count())) return 'no recall button in the first 90 s';
const mv = latestMovement(S, a.operatorId, 'scan');
if (!mv) return 'no scan movement in the database';
stat.scanId = mv.id;
});
await check('attacker: raid through the send dialog, 20 crews, outgoing list has both legs', async () => {
await sendThroughDialog('raid', 'Script', 20);
await ap.waitForSelector('[data-screen="movements"] li.out.type-raid', { timeout: 6000 });
const n = await ap.locator('[data-screen="movements"] li.out').count();
if (n !== 2) return 'expected 2 outgoing rows, got ' + n;
const mv = latestMovement(S, a.operatorId, 'raid');
if (!mv) return 'no raid movement in the database';
stat.raidId = mv.id;
const units = JSON.parse(mv.units);
if (!(units.script_crew > 0)) return 'raid has no crews: ' + mv.units;
});
await check('defender: incoming banner (2 movements, hidden type) and Moves badge by push, no reload', async () => {
await bp.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }, null, { timeout: 6000, polling: 100 });
const banner = await text(bp, '.mil-banner');
if (!banner.includes('Alice') && !banner.includes(a.name)) return 'banner does not name the attacker: ' + banner;
if (!/2/.test(banner)) return 'banner does not count 2 incoming: ' + banner;
if (/raid|scan/i.test(banner)) return 'banner leaks the movement type: ' + banner;
await bp.waitForFunction(() => { const b = document.querySelector('#nav [data-screen="movements"] .nav-badge'); return b && !b.hidden && b.textContent.trim() === '2'; }, null, { timeout: 4000 });
});
await check('defender: Moves screen lists the incoming movements in red with origin and ETA, type unknown', async () => {
await goBar(bp, 'movements');
await bp.waitForSelector('[data-screen="movements"] li.incoming');
const n = await bp.locator('[data-screen="movements"] li.incoming').count();
if (n !== 2) return 'expected 2 incoming rows, got ' + n;
const row = await text(bp, '[data-screen="movements"] li.incoming');
if (!row.includes(a.name)) return 'incoming row does not name the attacker: ' + row;
if (/script|scanner/i.test(row)) return 'incoming row leaks the units: ' + row;
});
await check('both movements arrive: banner goes away, reports unread on both sides (More badge)', async () => {
hurryMovement(S, stat.scanId, 2000);
hurryMovement(S, stat.raidId, 2600);
await bp.waitForFunction(() => App.mil && App.mil.reportsUnread > 0, null, { timeout: 15000, polling: 100 });
await ap.waitForFunction(() => App.mil && App.mil.reportsUnread >= 2, null, { timeout: 15000, polling: 100 });
await bp.waitForFunction(() => !document.querySelector('[data-screen="movements"] li.incoming'), null, { timeout: 6000 });
if (!(await navBadge(ap, 'more'))) return 'attacker More badge is empty with unread reports';
});
await check('attacker: Reports screen lists the scan and the raid, unread; opening the raid shows verdict, units and loot', async () => {
await openFromMore(ap, false, 'reports', 'Reports');
await ap.waitForSelector('[data-screen="reports"] button.alert.rep');
const n = await ap.locator('[data-screen="reports"] button.alert.rep').count();
if (n < 2) return 'expected >= 2 reports, got ' + n;
const unread = await ap.locator('[data-screen="reports"] button.alert.rep.new').count();
if (unread !== n) return unread + ' of ' + n + ' reports are marked new';
const raidBtn = ap.locator('[data-screen="reports"] button.alert.rep', { hasText: bT.name }).filter({ hasText: /Raid|Phishing/i });
if (!(await raidBtn.count())) return 'no raid report row naming ' + bT.name + ': ' + (await text(ap, '[data-screen="reports"] ul.alert-list'));
await raidBtn.first().click();
await ap.waitForSelector('.sheet .rep-verdict', { timeout: 5000 });
const body = await text(ap, '.sheet .rep-detail');
if (!body.includes(bT.name)) return 'report does not name the target POP: ' + body;
if (!/script/i.test(body)) return 'report lists no crews: ' + body;
await ap.keyboard.press('Escape');
await ap.waitForFunction((len) => document.querySelectorAll('[data-screen="reports"] button.alert.rep.new').length < len, n, { timeout: 5000 });
const row = S.db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NOT NULL', a.userId);
if (!row || row.n !== 1) return 'server read flags after opening exactly one report: ' + JSON.stringify(row);
});
await check('attacker: scan report opens from the list and says what it found', async () => {
const scanBtn = ap.locator('[data-screen="reports"] button.alert.rep', { hasText: /scan/i }).first();
if (!(await scanBtn.count())) return 'no scan row';
await scanBtn.click();
await ap.waitForSelector('.sheet .rep-verdict', { timeout: 5000 });
const body = await text(ap, '.sheet .rep-detail');
if (!body.includes(bT.name)) return 'scan report does not name ' + bT.name + ': ' + body;
await ap.keyboard.press('Escape');
});
await check('defender: the raid report is in the Reports screen from the defender side', async () => {
await openFromMore(bp, false, 'reports', 'Reports');
await bp.waitForSelector('[data-screen="reports"] button.alert.rep');
const row = await text(bp, '[data-screen="reports"] button.alert.rep');
if (!/Raid|Phishing/i.test(row)) return 'defender sees ' + row;
await bp.click('[data-screen="reports"] button.alert.rep');
await bp.waitForSelector('.sheet .rep-verdict');
const body = await text(bp, '.sheet .rep-detail');
if (!/defender/i.test(body)) return 'detail does not tell the defender role: ' + body;
await bp.keyboard.press('Escape');
});
await check('Norwegian, with data on screen: reports list + raid and scan report sheets, movements, units, alerts (attacker) and the defender report: no raw keys, no English', async () => {
const out = [];
const openRows = (p, n) => async () => { for (let i = 0; i < n; i++) { const rows = p.locator('[data-screen="reports"] button.alert.rep'); await rows.nth(i).click(); await p.waitForSelector('.sheet .rep-verdict'); const r = await nbScan(p, 'report sheet ' + i); if (r) out.push(r); await p.keyboard.press('Escape'); await sheetClosed(p); } };
await nbOn(ap); await nbOn(bp);
out.push(...await nbVisit(ap, 'reports', [['all report sheets', openRows(ap, 2)]]));
out.push(...await nbVisit(ap, 'movements'));
out.push(...await nbVisit(ap, 'units'));
out.push(...await nbVisit(ap, 'alerts'));
out.push(...await nbVisit(bp, 'reports', [['defender report sheet', openRows(bp, 1)]]));
out.push(...await nbVisit(bp, 'alerts'));
return out.length ? out.join('\n') : true;
});
await check('movements pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; });
await A.ctx.close(); await B.ctx.close();
}
// ================================================================== reconnect + polling fallback
// Wraps WebSocket so the test can see every socket the client opens, close one from the "network", and refuse new ones for a while.
const WS_SPY = () => {
const Native = window.WebSocket;
window.__socks = []; window.__wsBlock = false;
window.WebSocket = class extends Native { constructor(...a) { if (window.__wsBlock) throw new Error('ws blocked by e2e'); super(...a); window.__socks.push(this); } };
};
const WS_OFF = () => { window.WebSocket = undefined; }; // a browser or proxy without WebSocket: only the REST poll is left
const bannerShown = (p) => p.evaluate(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; });
const bannerWait = (p, ms) => p.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }, null, { timeout: ms, polling: 100 });
async function suiteReconnect(browser, S) {
group('7. reconnect: the socket dies mid-session, the client reconnects, catches up what it missed, push works again');
const { a, b } = await armedPair(S, 'Carol' + uniq(), 'Dave' + uniq(), { script_crew: 60 });
const P = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { init: WS_SPY });
const p = P.page;
const raid = (n) => S.api('/movements', 'POST', { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: n }, confirmEndProtection: true }, a.token);
let n0 = 0;
await check('socket is open, the page holds exactly one', async () => {
await p.waitForFunction(() => App.ws && App.ws.open, null, { timeout: 10000 });
n0 = await p.evaluate(() => window.__socks.length);
if (n0 !== 1) return 'expected 1 socket, saw ' + n0;
});
await check('connection drops (socket closed, new ones refused): client notices and is not open', async () => {
await p.evaluate(() => { window.__wsBlock = true; window.__socks[window.__socks.length - 1].close(); });
await p.waitForFunction(() => App.ws && !App.ws.open, null, { timeout: 5000 });
if (await bannerShown(p)) return 'banner before any raid';
});
await check('a raid launched during the gap is not shown yet (nothing can reach the page), the page stays usable', async () => {
await raid(20);
await sleep(2500);
if (await bannerShown(p)) return 'banner appeared while the socket was down (and the REST poll is 45 s away): the test would not prove the catch-up';
await p.click('#nav [data-screen="map"]'); // still usable offline
await p.waitForSelector('[data-screen="map"]:not([hidden]) .map-canvas');
await p.click('#nav [data-screen="pop"]');
await p.waitForSelector('.town-name');
});
await check('network back: client reconnects with a NEW socket and catches up (banner for the missed raid) without a reload', async () => {
await p.evaluate(() => { window.__noReload = 'still-here'; window.__wsBlock = false; });
await p.waitForFunction(() => App.ws && App.ws.open, null, { timeout: 25000 });
const n1 = await p.evaluate(() => window.__socks.length);
if (n1 <= n0) return 'no new socket was opened (' + n0 + ' -> ' + n1 + ')';
await bannerWait(p, 6000);
const banner = await text(p, '.mil-banner');
if (!banner.includes(a.name)) return 'banner does not name the attacker: ' + banner;
});
await check('after the reconnect a NEW raid shows by push (<= 6 s, socket open, no reload): the new socket really delivers', async () => {
await sleep(1500); // let the on-ready refetch settle: the next banner change must be push
const before = await text(p, '.mil-banner');
await raid(10);
await p.waitForFunction((b0) => { const el = document.querySelector('.mil-banner'); return el && !el.hidden && el.innerText.replace(/\s+/g, ' ').trim() !== b0; }, before, { timeout: 6000, polling: 100 });
if (!(await p.evaluate(() => App.ws.open))) return 'socket not open: it came from polling';
if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page was reloaded';
const banner = await text(p, '.mil-banner');
if (!/2/.test(banner)) return 'banner does not count both raids: ' + banner;
});
await check('reconnect page: no console errors', async () => noErrors(P));
await P.ctx.close();
}
// Slow: no WebSocket at all. The incoming raid must still show up through the REST poll (45 s gap, 15 s tick).
async function suiteSlow(browser) {
group('9. (slow) push fallback: WebSocket unavailable, the incoming raid still appears by polling');
const S = await L.bootServer({ speed: 1 });
try {
const { a, b } = await armedPair(S, 'Erin' + uniq(), 'Finn' + uniq(), { script_crew: 40 });
const P = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { init: WS_OFF });
const p = P.page;
let sentAt = 0;
await check('page runs without any WebSocket: client reports not open', async () => {
await sleep(1200);
if (await p.evaluate(() => !!(App.ws && App.ws.open))) return 'a socket is open although WebSocket was removed';
if (await bannerShown(p)) return 'banner before any raid';
await p.evaluate(() => { window.__noReload = 'still-here'; });
});
await check('raid is sent; the banner is NOT shown within 8 s (no push), then appears by polling within 75 s, same page', async () => {
sentAt = Date.now();
await S.api('/movements', 'POST', { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 }, confirmEndProtection: true }, a.token);
await sleep(8000);
if (await bannerShown(p)) return 'banner appeared within 8 s: that is not the polling path';
await bannerWait(p, 75000);
const ms = Date.now() - sentAt;
if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page was reloaded';
if (await p.evaluate(() => !!App.ws.open)) return 'socket opened';
console.log(' (banner by polling after ' + Math.round(ms / 1000) + ' s)');
});
await check('fallback page: no console errors', async () => noErrors(P));
await P.ctx.close();
} finally { await S.close(); }
}
// ================================================================== 8. alliance + messages
async function suiteAlliance(browser, S) {
group('10. alliance: found, invite, accept, a message to the alliance, read on the other page (badge, feed)');
const a = await S.signup('Ally' + uniq()), b = await S.signup('Beau' + uniq());
for (const u of [a, b]) L.setBuildings(S, u.townId, { peering_office: 1 });
const tag = 'T' + uniq().slice(-3), name = 'Blue Team ' + uniq();
const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/pop', { keepLang: true });
const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true });
const ap = A.page, bp = B.page;
await check('not in an alliance yet: the screen offers founding, the create button is disabled until name and tag are valid', async () => {
await openFromMore(ap, false, 'alliance', 'Alliance');
await ap.waitForSelector('#soc-name');
if (!(await ap.$eval('.soc-card .btn.primary.wide', (x) => x.disabled))) return 'create enabled with empty fields';
await ap.fill('#soc-name', name); await ap.fill('#soc-tag', tag);
if (await ap.$eval('.soc-card .btn.primary.wide', (x) => x.disabled)) return 'create still disabled with valid fields';
});
await check('found it: overview shows the name, tag, you as leader and 1 member; the server agrees', async () => {
await ap.click('.soc-card .btn.primary.wide');
await ap.waitForSelector('.soc-head .soc-name');
const head = await text(ap, '.soc-head');
if (!head.includes(name) || !head.includes('[' + tag + ']')) return 'head: ' + head;
const row = S.db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE operator_id = ?', a.operatorId);
if (!row || row.n !== 1) return 'server has no membership row for the founder';
});
await check('invite the other player by name from the Members tab: pending list shows them', async () => {
await ap.click('.soc-tabs [data-tab="members"]');
await ap.waitForSelector('.soc-inline input');
await ap.fill('.soc-inline input', b.name);
await ap.click('.soc-inline .btn.primary');
await ap.waitForFunction((n) => [...document.querySelectorAll('.soc-content .soc-item')].some((x) => x.innerText.includes(n)), b.name, { timeout: 5000 });
});
await check('invitee: the invitation is on the Alliance screen; accepting makes them a member (2 of N)', async () => {
await openFromMore(bp, false, 'alliance', 'Alliance');
await bp.waitForSelector('.soc-invite');
const inv = await text(bp, '.soc-invite');
if (!inv.includes(name)) return 'invite card: ' + inv;
await bp.click('.soc-invite .btn.primary');
await bp.waitForSelector('.soc-head .soc-name');
const head = await text(bp, '.soc-head');
if (!head.includes(name) || !/2/.test(head)) return 'head after joining: ' + head;
await bp.click('.soc-tabs [data-tab="members"]');
await bp.waitForFunction((n) => document.querySelectorAll('.soc-member').length === 2 && document.body.innerText.includes(n), a.name, { timeout: 5000 });
});
const msg = 'Hold the line ' + uniq();
let moreBefore = 0;
await check('before: the invitee has no unread message (the More badge may carry alerts, it must not carry messages)', async () => {
await bp.click('#nav [data-screen="pop"]');
await bp.waitForSelector('.town-name');
await sleep(1200); // the unread poll runs at session start
const unread = await bp.evaluate(() => App.state.unreadMsgs || 0);
if (unread !== 0) return 'unread messages before any was sent: ' + unread;
moreBefore = Number(await navBadge(bp, 'more')) || 0;
});
await check('leader writes to the alliance (Messages > Alliance tab > composer)', async () => {
await openFromMore(ap, false, 'messages', 'Messages');
await ap.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]');
await ap.waitForSelector('[data-screen="messages"] .soc-composer textarea');
await ap.fill('[data-screen="messages"] .soc-composer textarea', msg);
await ap.click('[data-screen="messages"] .soc-composer .btn.primary');
await ap.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg, { timeout: 5000 });
});
await check('invitee page (no reload): unread badge appears on More within 6 s (push hint)', async () => {
await bp.waitForFunction((n0) => { const b = document.querySelector('#nav [data-screen="more"] .nav-badge'); return App.state.unreadMsgs === 1 && b && !b.hidden && Number(b.textContent) > n0; }, moreBefore, { timeout: 6000, polling: 100 });
});
await check('invitee: Messages screen shows the broadcast as unread in the Alliance feed with the sender; reading clears the badge', async () => {
await openFromMore(bp, false, 'messages', 'Messages');
await bp.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]');
await bp.waitForSelector('[data-screen="messages"] .soc-feed');
const row = await text(bp, '[data-screen="messages"] .soc-feed');
if (!row.includes(msg)) return 'feed row: ' + row;
if (!row.includes(a.name)) return 'feed row does not name the sender: ' + row;
const wasUnread = await bp.locator('[data-screen="messages"] .soc-feed.unread').count();
if (!wasUnread) return 'the broadcast is not marked unread';
await bp.click('[data-screen="messages"] .soc-tabs [data-tab="inbox"]');
await bp.click('[data-screen="messages"] .soc-toolbar .btn'); // mark all read
await bp.waitForFunction((n0) => { const b = document.querySelector('#nav [data-screen="more"] .nav-badge'); return App.state.unreadMsgs === 0; }, moreBefore, { timeout: 6000 });
const left = S.db.get('SELECT COUNT(*) AS n FROM message_recipients WHERE operator_id = ? AND read_at IS NULL', b.operatorId).n;
if (left !== 0) return left + ' unread rows left on the server';
});
await check('invitee sits on the Alliance feed: a second broadcast appears live (push), unread, without pressing refresh', async () => {
await bp.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]');
await bp.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg, { timeout: 4000 });
const msg2 = 'Second wave ' + uniq();
await S.api('/messages', 'POST', { text: msg2, toAlliance: true }, a.token);
await bp.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg2, { timeout: 6000, polling: 100 });
await bp.waitForFunction(() => App.state.unreadMsgs === 1, null, { timeout: 4000 });
});
await check('Norwegian, as alliance members: alliance overview / members / diplomacy, messages tabs: no raw keys, no English', async () => {
const out = [];
const tab = (p, id) => async () => { await p.click('.soc-tabs [data-tab="' + id + '"]'); };
const mtab = (p, id) => async () => { await p.click('[data-screen="messages"] .soc-tabs [data-tab="' + id + '"]'); };
for (const p of [ap, bp]) {
await nbOn(p);
out.push(...await nbVisit(p, 'alliance', [['members', tab(p, 'members')], ['diplomacy', tab(p, 'diplomacy')]]));
out.push(...await nbVisit(p, 'messages', [['alliance', mtab(p, 'alliance')], ['sent', mtab(p, 'sent')], ['blocked', mtab(p, 'blocked')], ['inbox', mtab(p, 'inbox')]]));
}
return out.length ? out.join('\n') : true;
});
await check('alliance pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; });
await A.ctx.close(); await B.ctx.close();
}
// ================================================================== 9. trade
async function suiteTrade(browser, S) {
group('11. trade: post an offer, take it from a second user, both see it complete');
const a = await S.signup('Tara' + uniq()), b = await S.signup('Tom' + uniq());
const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId);
L.placeTown(S, b.townId, aT.x + 3, aT.y + 1);
for (const u of [a, b]) { L.setBuildings(S, u.townId, { internet_exchange: 3, rack_hall: 6 }); S.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000, res_at = ? WHERE id = ?', Date.now(), u.townId); }
const stock = (u) => S.db.get('SELECT fiber, hardware FROM towns WHERE id = ?', u.townId);
// accept refuses a taker whose Rack hall is projected full at arrival (no_room_for_goods); this world is fast, so switch the taker's fields off
S.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", b.townId);
const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/pop', { keepLang: true });
const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true });
const ap = A.page, bp = B.page;
const before = { a: null, b: null };
await check('poster: Exchange > New offer, default terms (give 100 fiber, want 100 hardware) are valid, post enabled', async () => {
before.a = stock(a); before.b = stock(b);
await openFromMore(ap, false, 'trade', 'Trade');
await ap.click('[data-screen="trade"] .trd-tabs [data-tab="new"]');
await ap.waitForSelector('.trd-form .btn.primary');
await ap.waitForFunction(() => { const x = document.querySelector('.trd-form .btn.primary'); return x && !x.disabled; }, null, { timeout: 6000 });
const msgs = await text(ap, '.trd-msgs');
if (msgs) return 'validation messages shown: ' + msgs;
});
await check('post it: lands on "mine" with an open offer and a countdown; the escrow left the POP', async () => {
await ap.click('.trd-form .btn.primary');
await ap.waitForSelector('li.trd-offer[data-status="open"]');
const row = await text(ap, 'li.trd-offer[data-status="open"]');
if (!/100/.test(row)) return 'offer row: ' + row;
const off = S.db.get("SELECT * FROM trade_offers WHERE status = 'open'");
if (!off) return 'no open offer in the database';
const now = stock(a);
if (!(now.fiber < before.a.fiber - 20)) return 'fiber was not escrowed: ' + before.a.fiber + ' -> ' + now.fiber;
});
await check('taker: the offer is listed on the Offers tab with who posted it; Take opens the POP picker with a preselected POP', async () => {
await openFromMore(bp, false, 'trade', 'Trade');
await bp.waitForSelector('[data-screen="trade"] li.trd-offer', { timeout: 8000 });
const row = await text(bp, '[data-screen="trade"] li.trd-offer');
if (!row.includes(a.name)) return 'offer row does not name the poster: ' + row;
await bp.click('[data-screen="trade"] li.trd-offer .btn.primary');
await bp.waitForSelector('.trd-accept .trd-pop input:checked');
});
await check('accept it: sheet closes, the offer leaves the Offers list, the taker POP dispatches its 100 hardware', async () => {
await bp.click('.trd-accept .send-foot .btn.primary');
await sheetClosed(bp);
await bp.waitForFunction(() => !document.querySelector('[data-screen="trade"] li.trd-offer'), null, { timeout: 8000 });
const leg = S.db.get("SELECT cargo FROM movements WHERE owner_id = ? AND type = 'transport' AND status = 'out'", b.operatorId);
if (!leg || JSON.parse(leg.cargo).hardware !== 100) return 'the taker has no 100 hardware leg in flight: ' + (leg && leg.cargo);
});
await check('both transports land (the 10 minute minimum latency is moved up): both POPs hold the swapped goods, the offer is completed', async () => {
const legs = S.db.all("SELECT id FROM movements WHERE type = 'transport' AND status = 'out'");
if (legs.length !== 2) return 'expected 2 transport legs in flight, found ' + legs.length;
if (S.db.get("SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1").status !== 'accepted') return 'offer is not in the accepted state while the goods are in flight';
legs.forEach((m, i) => hurryMovement(S, m.id, 1500 + i * 400));
for (let i = 0; i < 40; i++) { const o = S.db.get('SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1'); if (o && o.status === 'completed') break; await sleep(250); }
const o = S.db.get('SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1');
if (!o || o.status !== 'completed') return 'offer status ' + (o && o.status);
const na = stock(a), nb = stock(b);
if (!(na.hardware > before.a.hardware + 80)) return 'poster hardware ' + before.a.hardware + ' -> ' + na.hardware;
if (!(nb.fiber > before.b.fiber + 80)) return 'taker fiber ' + before.b.fiber + ' -> ' + nb.fiber;
});
await check('poster sees it complete: "mine" tab status completed, an alert for it, no open offers left', async () => {
await ap.click('#nav [data-screen="pop"]');
await openFromMore(ap, false, 'trade', 'Trade');
await ap.click('[data-screen="trade"] .trd-tabs [data-tab="mine"]');
await ap.waitForSelector('li.trd-offer[data-status="completed"]', { timeout: 8000 });
if (await ap.locator('li.trd-offer[data-status="open"]').count()) return 'an open offer is still listed';
await openFromMore(ap, false, 'alerts', 'Alerts');
await ap.waitForFunction(() => /complet|settled|fullf/i.test(document.querySelector('[data-screen="alerts"]').innerText), null, { timeout: 6000 });
});
await check('taker sees it complete too: "mine" tab shows their side as completed', async () => {
await bp.click('#nav [data-screen="pop"]');
await openFromMore(bp, false, 'trade', 'Trade');
await bp.click('[data-screen="trade"] .trd-tabs [data-tab="mine"]');
await bp.waitForSelector('li.trd-offer[data-status="completed"]', { timeout: 8000 });
const row = await text(bp, 'li.trd-offer[data-status="completed"]');
if (!/100/.test(row)) return 'taker row: ' + row;
});
await check('Norwegian, with offers on screen: every Trade tab on both pages, the alerts feed: no raw keys, no English', async () => {
const out = [];
for (const p of [ap, bp]) {
await nbOn(p);
const tab = (id) => async () => { await p.click('[data-screen="trade"] .trd-tabs [data-tab="' + id + '"]'); };
out.push(...await nbVisit(p, 'trade', [['new', tab('new')], ['mine', tab('mine')], ['send', tab('send')], ['offers', tab('offers')]]));
out.push(...await nbVisit(p, 'alerts'));
}
return out.length ? out.join('\n') : true;
});
await check('trade pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; });
await A.ctx.close(); await B.ctx.close();
}
// ================================================================== 12. end game
async function suiteEndgame(browser) {
group('12. end game: world screen before and after the landing sites open, site list, a shipment to a held site');
const speed = 4000;
const S = await L.bootServer({ speed });
try {
const g = await S.signup('Gina' + uniq()), h = await S.signup('Hank' + uniq());
const sites = R.backboneSites(S.world.seed, S.world.map_radius);
L.placeTown(S, g.townId, sites[0].x - 4, sites[0].y);
L.setBuildings(S, g.townId, { peering_office: 1, internet_exchange: 2, rack_hall: 8, core_router: 5 });
S.db.run('UPDATE towns SET fiber = 3000, hardware = 3000, capital = 3000, res_at = ? WHERE id = ?', Date.now(), g.townId);
S.db.run('UPDATE operators SET protection_until = 0');
const al = await S.api('/alliances', 'POST', { name: 'Gold Backbone', tag: 'GOLD' }, g.token);
const P = await L.openSignedIn(browser, S, g, PROFILES.desktop, '#/pop', { keepLang: true });
const Q = await L.openSignedIn(browser, S, h, PROFILES.phone, '#/pop');
const p = P.page;
await check('before day 100: banner counts down to the landing sites, the how-it-works card is shown, no sites listed', async () => {
await openFromMore(p, false, 'world', 'Backbone');
await p.waitForSelector('.wld-banner');
const banner = await text(p, '.wld-banner');
if (!/appear in/i.test(banner)) return 'banner: ' + banner;
if (!(await p.locator('.wld-how li').count())) return 'no how-it-works card while running';
if (await p.locator('li.wld-site').count()) return 'sites listed before they exist';
if (await p.locator('.wld-banner.open').count()) return 'open banner before day 100';
});
await check('the world moves to day 100.5 (start date backdated, sites created like the first touch does): banner flips to open with 7 sites', async () => {
S.db.run('UPDATE worlds SET start_at = ? WHERE id = ?', Date.now() - Math.round(100.5 * DAY / speed), S.world.id);
const st = await S.api('/worlds/' + S.world.id + '/status', 'GET', undefined, g.token);
if (st.phase !== 'backbone_open' || st.sites.length !== 7) return 'server says phase ' + st.phase + ' with ' + st.sites.length + ' sites';
const rows = require('../server/endgame').ensureSites(S.db, S.db.get('SELECT * FROM worlds WHERE id = ?', S.world.id), Date.now()); // what the first scan or attack does
if (rows.length !== 7) return 'ensureSites made ' + rows.length + ' rows';
S.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, taken_at = ? WHERE world_id = ? AND idx = 0', al.allianceId, g.operatorId, Date.now(), S.world.id);
await p.click('[data-screen="world"] .page-head .icon-btn'); // refresh
await p.waitForSelector('.wld-banner.open', { timeout: 6000 });
const n = await p.locator('li.wld-site').count();
if (n !== 7) return 'expected 7 site cards, got ' + n;
const banner = await text(p, '.wld-banner.open');
if (!/open/i.test(banner)) return 'banner: ' + banner;
});
await check('site list: site 1 is held by [GOLD] and marked as yours with a Manage button; the six others are incumbent with a scan/attack button', async () => {
const mine = await text(p, 'li.wld-site.mine');
if (!mine.includes('GOLD') || !/Landing site 1/.test(mine)) return 'site 1 card: ' + mine;
if (!(await p.locator('li.wld-site.mine .btn.primary', { hasText: 'Manage' }).count())) return 'no Manage button on the held site';
const others = await p.locator('li.wld-site:not(.mine)').count();
if (others !== 6) return 'expected 6 other sites, got ' + others;
const incumbents = await p.locator('li.wld-site:not(.mine) .pill.dim').count();
if (incumbents !== 6) return 'expected 6 incumbent pills, got ' + incumbents;
if (!(await p.locator('li.wld-site:not(.mine) .btn.primary', { hasText: 'Scan or attack' }).count())) return 'no scan/attack button';
});
await check('another player (phone, no alliance) sees the same phase and the sites, and no Manage button', async () => {
await openFromMore(Q.page, true, 'world', 'Backbone');
await Q.page.waitForSelector('.wld-banner.open', { timeout: 6000 });
if ((await Q.page.locator('li.wld-site').count()) !== 7) return 'not 7 sites';
if (await Q.page.locator('.btn', { hasText: 'Manage' }).count()) return 'a non-member is offered Manage';
const holder = await text(Q.page, 'li.wld-site:first-child');
if (!holder.includes('GOLD')) return 'site 1 holder not shown: ' + holder;
});
await check('Manage opens the site sheet: level, stock (empty), the next level cost and the ship section', async () => {
await p.click('li.wld-site.mine .btn.primary');
await p.waitForSelector('.wld-manage .wld-sec');
const body = await text(p, '.wld-manage');
if (!/Ship resources/i.test(body)) return 'no ship section: ' + body.slice(0, 200);
if (!(await p.locator('.wld-manage .mil-pick').count())) return 'no cargo pickers';
});
let shipId = 0;
await check('ship 300 fiber from the POP: toast, a site shipment appears on Moves, the POP stock drops', async () => {
const stockNow = () => p.evaluate(async () => { await App.refreshTown(); return App.resourcesNow().amounts.fiber; });
const f0 = await stockNow();
await p.locator('.wld-manage .mil-pick', { hasText: 'Fiber' }).locator('input[type=number]').fill('300');
const goLabel = await p.evaluate(() => App.t('wld.ship.go'));
const go = p.locator('.wld-manage .btn.primary', { hasText: new RegExp('^\\s*' + goLabel + '\\s*$') });
if (await go.evaluate((x) => x.disabled)) return 'ship button disabled';
await go.click();
await p.waitForFunction(() => /on its way/i.test(document.getElementById('toasts').innerText), null, { timeout: 5000 });
const mv = S.db.get("SELECT * FROM movements WHERE owner_id = ? AND type = 'transport' AND status = 'out' ORDER BY id DESC LIMIT 1", g.operatorId);
if (!mv) return 'no transport movement';
shipId = mv.id;
if (JSON.parse(mv.cargo).fiber !== 300) return 'cargo ' + mv.cargo;
const f1 = await stockNow();
if (!(f1 < f0 - 150)) return 'fiber on screen ' + f0 + ' -> ' + f1;
await p.keyboard.press('Escape');
await p.evaluate(() => App.go('movements'));
await p.waitForSelector('[data-screen="movements"] li.out');
const row = await text(p, '[data-screen="movements"] li.out');
if (!/landing site/i.test(row)) return 'moves row does not mark the site shipment: ' + row;
});
await check('the shipment lands (10 minute minimum latency moved up): the site stockpile holds 300 fiber, the sheet shows it, the ledger names the shipper', async () => {
hurryMovement(S, shipId, 1500);
for (let i = 0; i < 40; i++) { if (S.db.get('SELECT fiber FROM landing_sites WHERE world_id = ? AND idx = 0', S.world.id).fiber === 300) break; await sleep(250); }
const f = S.db.get('SELECT fiber FROM landing_sites WHERE world_id = ? AND idx = 0', S.world.id).fiber;
if (f !== 300) return 'site stockpile has ' + f + ' fiber';
await p.evaluate(() => App.go('world'));
await p.waitForSelector('li.wld-site.mine .btn.primary');
await p.click('li.wld-site.mine .btn.primary');
await p.waitForFunction(() => /300/.test(document.querySelector('.wld-manage') ? document.querySelector('.wld-manage').innerText : ''), null, { timeout: 5000 });
const body = await text(p, '.wld-manage');
if (!body.includes(g.name)) return 'ledger does not name ' + g.name + ': ' + body.slice(-300);
await p.keyboard.press('Escape');
});
await check('Norwegian, with 7 sites on screen: world screen, the Manage sheet (ship, ledger) and the scan/attack dialog: no raw keys, no English', async () => {
const out = [];
await nbOn(p);
await p.evaluate(() => App.go('world'));
await p.waitForSelector('li.wld-site.mine .btn.primary');
out.push(...await nbVisit(p, 'world', [
['manage sheet', async () => { await p.click('li.wld-site.mine .btn.primary'); await p.waitForSelector('.wld-manage .wld-sec'); }],
['closed', async () => { await p.keyboard.press('Escape'); await sheetClosed(p); }],
['scan or attack dialog', async () => { await p.click('li.wld-site:not(.mine) .btn.primary >> nth=0'); await p.waitForSelector('.sheet .send-target .pill-row'); }],
]));
await p.keyboard.press('Escape');
return out.length ? out.join('\n') : true;
});
await check('end game pages: no console errors', async () => { const r = noErrors(P); return r === true ? noErrors(Q) : r; });
await P.ctx.close(); await Q.ctx.close();
} finally { await S.close(); }
}
// ================================================================== 13. Norwegian
// Runs in the page. Finds (1) raw i18n keys on screen ("pop.build", "err.x": what t() returns for a key nobody defined) and (2) English
// leftovers: a visible string equal to the English text of a key whose Norwegian text is different. Both tables come from a snapshot taken
// before the test touched anything, so a deleted nb key is still known to be an nb key.
function nbLeaks(opts) {
if (!window.__I18N0) window.__I18N0 = JSON.parse(JSON.stringify(UpstreamI18n.strings));
const withAttrs = !opts || opts.attrs !== false;
const snap = window.__I18N0;
const en = snap.en, nb = snap.nb;
const nbValues = new Set(Object.values(nb));
const prefixes = Object.keys(en).map((k) => k.split('.')[0]).filter((v, i, a) => a.indexOf(v) === i);
const rawRe = new RegExp('(?:^|[^A-Za-z0-9_.])((?:' + prefixes.join('|') + ')\\.[A-Za-z][A-Za-z0-9_]*(?:\\.[A-Za-z0-9_]+)*)', 'g');
const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const exact = new Map(), tpl = [];
for (const k of Object.keys(en)) {
const e = en[k];
if (nb[k] === undefined || nb[k] === e || nbValues.has(e) || !/[A-Za-z]{3}/.test(e)) continue;
if (/\{\w+\}/.test(e)) { const body = esc(e).replace(/\\\{\w+\\\}/g, '.+?').replace(/\{\w+\}/g, '.+?'); if (body.replace(/\.\+\?/g, '').replace(/\\./g, '.').trim().length >= 4) tpl.push({ k, re: new RegExp('^' + body + '$') }); } else exact.set(e, k);
}
const visible = (el) => { for (let n = el; n && n !== document.body; n = n.parentElement) { if (n.hidden || (n.getAttribute && n.getAttribute('aria-hidden') === 'true' && n.tagName !== 'SPAN')) return false; } return el.getClientRects().length > 0; };
const raw = [], english = [];
const seen = new Set();
const test = (txt, where) => {
txt = txt.replace(/\s+/g, ' ').trim();
if (!txt || seen.has(where + txt)) return;
seen.add(where + txt);
let m; rawRe.lastIndex = 0;
while ((m = rawRe.exec(txt))) raw.push(m[1] + ' in "' + txt.slice(0, 60) + '"');
if (exact.has(txt)) english.push(exact.get(txt) + ' = "' + txt + '"');
else for (const t of tpl) if (t.re.test(txt)) { english.push(t.k + ' ~ "' + txt.slice(0, 70) + '"'); break; }
};
for (const root of document.querySelectorAll('#app, #sheet-root')) {
const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
for (let n = w.nextNode(); n; n = w.nextNode()) if (n.parentElement && visible(n.parentElement) && !n.parentElement.closest('script, style, [data-user]')) test(n.nodeValue, 'text');
if (withAttrs) for (const el of root.querySelectorAll('[aria-label], [placeholder], [title]')) if (visible(el)) for (const a of ['aria-label', 'placeholder', 'title']) if (el.getAttribute(a)) test(el.getAttribute(a), a);
}
test(document.title, 'title');
return { raw: [...new Set(raw)], english: [...new Set(english)] };
}
async function suiteNorwegian(browser, S) {
group('13. Norwegian: switch in Settings, main screens and dialogs have no raw keys and no English leftovers');
const u = await S.signup('Nora' + uniq());
const P = await L.openSignedIn(browser, S, u, PROFILES.desktop, '#/pop', { keepLang: true });
const p = P.page;
const leaks = () => p.evaluate(nbLeaks);
const report = (r) => (r.raw.length || r.english.length ? 'raw keys: ' + JSON.stringify(r.raw.slice(0, 6)) + ' English leftovers: ' + JSON.stringify(r.english.slice(0, 6)) : true);
await check('calibration: in English the detector reports many "English leftovers" on the real POP screen (so it does see the UI text), and nav says Map', async () => {
await p.evaluate(() => { window.__I18N0 = JSON.parse(JSON.stringify(UpstreamI18n.strings)); });
if ((await p.evaluate(() => document.documentElement.lang)) !== 'en') return 'page does not start in English';
const kart = await text(p, '#nav [data-screen="map"]');
if (kart !== 'Map') return 'nav label is ' + kart;
await p.waitForSelector('.tile[data-key="f1"]');
const r = await leaks();
if (r.english.length < 8) return 'the detector found only ' + r.english.length + ' English strings on the English POP screen: ' + JSON.stringify(r.english);
});
await check('no multi-word Norwegian string is a verbatim copy of its English text (the detector cannot see a copy-pasted untranslated string, this does)', async () => {
const same = await p.evaluate(() => { const en = window.__I18N0.en, nb = window.__I18N0.nb; return Object.keys(en).filter((k) => en[k] === nb[k] && /[A-Za-z]{3,}\s+[A-Za-z]{2,}/.test(en[k])); });
if (same.length) return same.length + ' strings are identical in nb and en: ' + same.slice(0, 8).join(', ');
});
const screens = ['pop', 'map', 'units', 'movements', 'reports', 'alerts', 'rankings', 'alliance', 'messages', 'trade', 'world', 'settings'];
// Part A: the player visits every screen in English (each is drawn once), then switches language live in Settings.
// Static labels built once in render() would stay English; only visible text is compared here (stale aria-labels are reported, not failed).
for (const id of screens) await check('(setup) English screen ' + id + ' is drawn', async () => { await p.evaluate((i) => App.go(i), id); await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])'); await sleep(250); });
await check('Settings > language: tap Norsk; html lang, nav labels and the stored choice switch at once, no reload', async () => {
await p.evaluate(() => { window.__noReload = 'still-here'; });
await openFromMore(p, false, 'settings', 'Settings');
const label = await p.evaluate(() => App.t('settings.lang.nb'));
await p.click('[data-screen="settings"] .seg-btn:has-text("' + label + '")');
await p.waitForFunction(() => document.documentElement.lang === 'nb', null, { timeout: 3000 });
const nav = await p.$$eval('#nav .nav-lbl', (els) => els.map((e) => e.textContent.trim()));
const want = await p.evaluate(() => ['nav.pop', 'nav.map', 'nav.units', 'nav.movements', 'nav.more'].map((k) => window.__I18N0.nb[k]));
if (JSON.stringify(nav) !== JSON.stringify(want)) return 'nav ' + JSON.stringify(nav) + ' != ' + JSON.stringify(want);
const stored = await p.evaluate(() => localStorage.getItem('upstream.lang'));
if (stored !== 'nb') return 'stored language ' + stored;
if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page reloaded';
});
await check('nav is fully Norwegian: no label equals its English text unless both languages spell it the same (POP)', async () => {
const bad = await p.evaluate(() => { const en = window.__I18N0.en, nb = window.__I18N0.nb; const out = []; for (const b of document.querySelectorAll('#nav .nav-btn')) { const t = b.querySelector('.nav-lbl').textContent.trim(); const k = Object.keys(en).find((x) => /^nav\./.test(x) && nb[x] === t); if (!k) out.push('"' + t + '" is no nb nav label'); } return out; });
if (bad.length) return bad.join('; ');
await p.click('#nav [data-screen="more"]');
await p.waitForSelector('.more-list .row-btn');
const rows = await p.$$eval('.more-list .row-title', (els) => els.map((e) => e.textContent.trim()));
const en = await p.evaluate(() => window.__I18N0.en), nbt = await p.evaluate(() => window.__I18N0.nb);
const enRows = rows.filter((r) => Object.keys(en).some((k) => /^nav\./.test(k) && en[k] === r && nbt[k] !== r));
await p.keyboard.press('Escape');
if (enRows.length) return 'More list has English rows: ' + enRows.join(', ');
if (rows.length < 6) return 'More list has only ' + rows.length + ' rows';
});
await check('detector self-test: a planted raw key and an English string on the live page are both reported; planted nb gap is reported', async () => {
await p.evaluate(() => { const d = document.createElement('div'); d.id = 'plant'; d.innerHTML = '<p>pop.build.nothing</p><p>Region map</p><p>err.not_enough_resources</p>'; document.getElementById('view').appendChild(d); });
const r = await leaks();
await p.evaluate(() => document.getElementById('plant').remove());
if (!r.raw.some((x) => /pop\.build\.nothing/.test(x)) || !r.raw.some((x) => /err\.not_enough_resources/.test(x))) return 'raw keys not found: ' + JSON.stringify(r);
if (!r.english.some((x) => /Region map/.test(x))) return 'English leftover not found: ' + JSON.stringify(r);
await p.evaluate(() => { const nb = UpstreamI18n.strings.nb; window.__nbGap = nb['screen.alerts']; delete nb['screen.alerts']; App.go('alerts'); });
await p.waitForSelector('[data-screen="alerts"]:not([hidden])');
await sleep(500);
const r2 = await leaks();
await p.evaluate(() => { UpstreamI18n.strings.nb['screen.alerts'] = window.__nbGap; });
if (!r2.english.some((x) => /screen\.alerts/.test(x) || /Alerts/.test(x))) return 'a deleted nb string was not reported: ' + JSON.stringify(r2);
});
const visitAll = async (id, attrs) => {
await p.evaluate((i) => App.go(i), id);
await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 });
await sleep(id === 'map' ? 1200 : 600);
if (id !== 'map' && (await p.evaluate((i) => document.querySelector('[data-screen="' + i + '"]').innerText.trim().length, id)) < 5) return 'screen is empty';
if (attrs === false) { const withAttrs = await p.evaluate(nbLeaks, { attrs: true }); for (const x of withAttrs.english) staleAttrs.add(id + ': ' + x); }
return report(await p.evaluate(nbLeaks, { attrs }));
};
const staleAttrs = new Set();
// Part A (continued): every screen was drawn in English before the live switch above; now each is shown and scanned.
for (const id of screens) await check('nb, switched live: screen ' + id + ' shows no raw keys and no English text', async () => visitAll(id, false));
// Part B: reload (the choice is stored): every screen renders fresh in Norwegian, text and aria-labels / placeholders / titles
await check('reload keeps Norwegian; nav in nb', async () => {
if (staleAttrs.size) console.log(' (known gap, not a failure: ' + staleAttrs.size + ' English aria-label/title strings stay on screens drawn before a live switch, e.g. ' + [...staleAttrs].slice(0, 3).join(' | ') + ')');
await p.reload();
await p.waitForSelector('#nav:not([hidden])', { timeout: 15000 });
if ((await text(p, '#nav [data-screen="map"]')) !== 'Kart') return 'nav label after reload: ' + (await text(p, '#nav [data-screen="map"]'));
});
for (const id of screens) await check('nb, fresh render: screen ' + id + ' shows no raw keys, no English text, no English aria-labels', async () => visitAll(id, true));
await check('nb dialogs: build sheet, locked-unit train sheet (dynamic err.* text), send dialog with greyed types', async () => {
const out = [];
await p.evaluate(() => App.go('pop')); await p.waitForSelector('.tile[data-key="f1"]');
await p.click('.tile[data-key="f1"]'); await p.waitForSelector('.sheet .btn.primary');
out.push(['build sheet', report(await leaks())]);
await p.keyboard.press('Escape'); await sheetClosed(p);
await p.evaluate(() => App.go('units')); await p.waitForSelector('.mil-train.locked');
await p.click('.mil-train.locked >> nth=0'); await p.waitForSelector('.sheet .reason:not([hidden])');
out.push(['train sheet', report(await leaks())]);
const reason = await text(p, '.sheet .reason');
const nbReason = await p.evaluate(() => window.__I18N0.nb['err.requirements_not_met']);
if (!reason.startsWith(nbReason)) return 'locked unit reason is "' + reason + '", expected it to start with "' + nbReason + '"';
await p.keyboard.press('Escape'); await sheetClosed(p);
await p.evaluate(() => App.go('movements')); await p.waitForSelector('[data-screen="movements"] .head-actions .btn.primary');
await p.click('[data-screen="movements"] .head-actions .btn.primary'); await p.waitForSelector('.sheet .chips .chip-btn');
await p.click('.sheet .chips .chip-btn >> nth=0'); await p.waitForSelector('.sheet .send-why, .sheet .seg-btn');
await sleep(500);
out.push(['send dialog', report(await leaks())]);
await p.keyboard.press('Escape'); await sheetClosed(p);
const bad = out.filter(([, r]) => r !== true).map(([n, r]) => n + ': ' + r);
if (bad.length) return bad.join('\n');
});
await check('switching back to English restores English labels', async () => {
await p.evaluate(() => App.setLang('en'));
if ((await text(p, '#nav [data-screen="map"]')) !== 'Map') return 'English did not come back';
if ((await p.evaluate(() => document.documentElement.lang)) !== 'en') return 'html lang stayed nb';
});
await check('nb pages: no console errors', async () => noErrors(P));
await P.ctx.close();
}
// ================================================================== 14. PWA
async function suitePwa(browser, S) {
group('14. PWA: manifest, icons, start_url, install hints');
const get = async (url) => { const r = await fetch(url); return { status: r.status, type: r.headers.get('content-type') || '', buf: Buffer.from(await r.arrayBuffer()), cc: r.headers.get('cache-control') || '' }; };
const html = await (await fetch(S.base + '/')).text();
let manifest = null, mUrl = '';
await check('index links the manifest; it is served 200 as application/manifest+json and parses', async () => {
const m = /<link rel="manifest" href="([^"]+)"/.exec(html);
if (!m) return 'no <link rel="manifest">';
mUrl = new URL(m[1], S.base + '/').href;
const r = await get(mUrl);
if (r.status !== 200) return 'status ' + r.status;
if (!/^application\/manifest\+json/.test(r.type)) return 'content-type ' + r.type;
manifest = JSON.parse(r.buf.toString('utf8'));
});
await check('manifest: standalone display, name, short_name, theme + background colours, start_url inside scope and serving the app', async () => {
if (manifest.display !== 'standalone') return 'display ' + manifest.display;
if (!manifest.name || !manifest.short_name) return 'name / short_name missing';
for (const k of ['theme_color', 'background_color']) if (!/^#[0-9a-f]{6}$/i.test(manifest[k] || '')) return k + ' is ' + manifest[k];
const start = new URL(manifest.start_url, mUrl), scope = new URL(manifest.scope || '.', mUrl);
if (start.origin !== new URL(S.base).origin) return 'start_url leaves the origin: ' + start.href;
if (!start.pathname.startsWith(scope.pathname)) return 'start_url ' + start.pathname + ' is outside scope ' + scope.pathname;
const r = await get(start.href);
if (r.status !== 200 || !/text\/html/.test(r.type)) return 'start_url answers ' + r.status + ' ' + r.type;
if (!/id="app"/.test(r.buf.toString('utf8'))) return 'start_url does not serve the app shell';
const tc = /<meta name="theme-color" content="([^"]+)"/.exec(html);
if (!tc || tc[1].toLowerCase() !== manifest.theme_color.toLowerCase()) return 'meta theme-color ' + (tc && tc[1]) + ' != manifest ' + manifest.theme_color;
});
await check('icons: 192 and 512 PNG exist (any), a maskable 512 exists, every src resolves 200 with an image type, PNG sizes match the declared sizes', async () => {
const icons = manifest.icons || [];
const png = (sz, purpose) => icons.find((i) => i.sizes === sz && i.type === 'image/png' && (i.purpose || 'any').split(' ').includes(purpose));
if (!png('192x192', 'any')) return 'no 192 png (any)';
if (!png('512x512', 'any')) return 'no 512 png (any)';
if (!png('512x512', 'maskable')) return 'no maskable 512 png';
for (const i of icons) {
const r = await get(new URL(i.src, mUrl).href);
if (r.status !== 200) return i.src + ' -> ' + r.status;
if (!/^image\//.test(r.type)) return i.src + ' content-type ' + r.type;
if (r.type.includes('png')) {
if (r.buf.readUInt32BE(0) !== 0x89504e47) return i.src + ' is not a PNG';
const w = r.buf.readUInt32BE(16), h = r.buf.readUInt32BE(20);
if (i.sizes !== w + 'x' + h) return i.src + ' declares ' + i.sizes + ' but is ' + w + 'x' + h;
}
}
const touch = /<link rel="apple-touch-icon" href="([^"]+)"/.exec(html);
if (!touch) return 'no apple-touch-icon';
const r = await get(new URL(touch[1], S.base + '/').href);
if (r.status !== 200 || !/image\/png/.test(r.type)) return 'apple-touch-icon ' + r.status + ' ' + r.type;
});
await check('in the browser: the manifest link resolves, the page declares itself installable-ready (viewport-fit, mobile-web-app-capable), no service worker', async () => {
const P = await L.newPage(browser, PROFILES.phone);
await P.page.goto(S.base + '/');
await P.page.waitForSelector('.auth-form');
const info = await P.page.evaluate(async () => {
const link = document.querySelector('link[rel=manifest]');
const r = await fetch(link.href);
const regs = navigator.serviceWorker ? (await navigator.serviceWorker.getRegistrations()).length : -1;
return { href: link.href, ok: r.ok, type: r.headers.get('content-type'), viewport: document.querySelector('meta[name=viewport]').content, capable: !!document.querySelector('meta[name=mobile-web-app-capable]'), regs };
});
await P.ctx.close();
if (!info.ok || !/manifest\+json/.test(info.type)) return 'manifest fetched from the page: ' + JSON.stringify(info);
if (!/viewport-fit=cover/.test(info.viewport)) return 'viewport ' + info.viewport;
if (!info.capable) return 'no mobile-web-app-capable meta';
if (info.regs > 0) return 'a service worker is registered (NEXT says there is none)';
return noErrors(P);
});
}
module.exports = { suiteUnits, suiteMovements, suiteReconnect, suiteSlow, suiteAlliance, suiteTrade, suiteEndgame, suiteNorwegian, suitePwa, armedPair, goBar, text, navBadge, sheetClosed, uniq, DAY, COUNTDOWN };