Merge remote-tracking branch 'upstream/main' into noc-window
# Conflicts: # CHANGELOG.md # src/game/99-loop.js # tests/harness.js
This commit is contained in:
commit
f9d24699c1
83 changed files with 3845 additions and 1031 deletions
90
tests/agent-api.test.js
Normal file
90
tests/agent-api.test.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// The agent facade (src/agent/, window.TUBES) and where it lives: in the development page only. It does nothing until
|
||||
// a tool calls it, listens to toast() only during a call, and the page players get carries none of it.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const page = require('../scripts/lib/page');
|
||||
|
||||
// Names the agent files define at the top level: none may appear in the page players get.
|
||||
const AGENT_NAMES = ['TUBES', 'API_CMD', 'API_DOMAINS', 'API_RELAY', 'apiCall', 'apiDispatch', 'apiSchema', 'apiAgentStart'];
|
||||
|
||||
test('the facade is inert until called, and listens to the game only during a call', () => {
|
||||
const a = load({ agent: true });
|
||||
assert.equal(a.ev('toast.name'), 'toast', 'loading the page leaves toast() alone');
|
||||
assert.equal(a.ev('spend.name'), 'spend', 'and spend()');
|
||||
assert.equal(a.ev('API_TOASTS.depth'), 0);
|
||||
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(TUBES.tools)')).sort(), ['act', 'actions', 'advance', 'catalog', 'city', 'classes', 'click', 'clock', 'find',
|
||||
'hot_spots', 'network', 'open_link', 'panel', 'peering_check', 'results', 'schema', 'screen', 'since', 'state', 'status', 'traceroute', 'ui'].sort());
|
||||
// Before a game there is a contract to read, and nothing else.
|
||||
assert.ok(a.ev("TUBES.call('schema',{section:'commands'}).buildPop"));
|
||||
assert.throws(() => a.ev("TUBES.call('status',{})"), /No game is running/);
|
||||
assert.throws(() => a.ev("TUBES.call('eval',{})"), /No tool "eval"/);
|
||||
a.ev('ACT.start({});S.cash=1e6;compute()');
|
||||
// A call hears what the game says while it runs, and gives toast() back after, also when it fails.
|
||||
const r = a.ev("TUBES.call('act',{action:'buyTransit',args:{city:'fra',net:'cog',tier:1}})");
|
||||
assert.equal(r.outcome, 'applied');
|
||||
assert.ok(r.toasts.some((t) => /Cogentle/.test(t)), 'the game\'s own words');
|
||||
assert.equal(a.ev('toast.name'), 'toast');
|
||||
assert.throws(() => a.ev("TUBES.call('act',{action:'buildPop',args:{city:'atlantis'}})"), /not a cityId/);
|
||||
assert.equal(a.ev('toast.name+spend.name+API_TOASTS.depth'), 'toastspend0', 'a failing call restores both');
|
||||
// A toast outside a call is the game's alone.
|
||||
a.ev("toast('hello','good')");
|
||||
assert.equal(a.ev('API_TOASTS.list.length'), 0);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('headless and the player\'s tab share one contract; only the tab holds the dice back and names its owner', () => {
|
||||
const a = load({ agent: true });
|
||||
a.ev('ACT.start({});S.nextFail=S.day+30;compute()');
|
||||
const here = a.ev("TUBES.call('schema',{})"), there = a.ev("TUBES.call('schema',{},{relay:true})");
|
||||
for (const k of ['commands', 'view', 'drafts', 'denied', 'domains', 'results']) assert.deepEqual(here[k], there[k], k);
|
||||
assert.equal(here.mode.backend, 'headless');
|
||||
assert.equal(there.mode.backend, 'browser');
|
||||
assert.ok(there.session.startScn.refused && !here.session.startScn.refused, 'starting a scenario is the player\'s in their tab');
|
||||
assert.equal(a.ev("TUBES.call('state',{path:'nextFail'})"), a.ev('S.nextFail'), 'headless reads everything');
|
||||
assert.equal(a.ev("TUBES.call('state',{path:'nextFail'},{relay:true})"), null, 'the tab holds it back');
|
||||
assert.equal(a.ev("'rng' in TUBES.call('state',{},{relay:true})"), false);
|
||||
assert.equal(a.ev("TUBES.call('state',{path:'cash'},{relay:true})"), a.ev('S.cash'));
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('the page players get has no agent code; the development page has it', () => {
|
||||
const ship = page.assemble().html, dev = page.assemble({ dev: true }).html;
|
||||
assert.ok(!ship.includes('@include-dev'), 'the marker line is dropped whole');
|
||||
for (const n of AGENT_NAMES) {
|
||||
assert.ok(!new RegExp(`\\b${n}\\b`).test(ship), `${n} is not in the page players get`);
|
||||
assert.ok(new RegExp(`\\b${n}\\b`).test(dev), `${n} is in the development page`);
|
||||
}
|
||||
// The agent files are pasted in where the marker is, after the game, inside the same script.
|
||||
const at = dev.indexOf('/* ================= AGENT API: argument domains');
|
||||
assert.ok(at > dev.indexOf('/* ================= LOOP ================='), 'after the game');
|
||||
assert.ok(at < dev.lastIndexOf('</script>'), 'inside the game\'s script');
|
||||
assert.equal(page.shipped().html.match(/\bTUBES\b/), null, 'nor in the shipped page, labels compiled');
|
||||
// The players' page is the game alone: no facade, and it boots and plays.
|
||||
const p = load();
|
||||
assert.equal(p.ev('typeof TUBES+typeof apiCall+typeof API_CMD'), 'undefinedundefinedundefined');
|
||||
assert.equal(p.ev('JSON.stringify(HOOKS)+UI.clockLocked'), '{}false', 'no hooks, and the clock is the player\'s');
|
||||
p.ev("ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<5;i++)dayTick()");
|
||||
assert.ok(p.ev('R.served') > 0);
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
test('an @include-dev line only expands in the development page', () => {
|
||||
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-dev-include-'));
|
||||
try {
|
||||
fs.mkdirSync(path.join(src, 'a'));
|
||||
fs.mkdirSync(path.join(src, 'b'));
|
||||
fs.writeFileSync(path.join(src, 'a', '10-a.js'), 'const A=1;\n');
|
||||
fs.writeFileSync(path.join(src, 'b', '10-b.js'), 'const B=2;\n');
|
||||
fs.writeFileSync(path.join(src, 'index.html'), '<script>\n<!-- @include a -->\n<!-- @include-dev b -->\n</script>\n');
|
||||
const ship = page.assemble({ src }), dev = page.assemble({ src, dev: true });
|
||||
assert.equal(ship.html, '<script>\nconst A=1;\n</script>\n');
|
||||
assert.equal(dev.html, '<script>\nconst A=1;\nconst B=2;\n</script>\n');
|
||||
// Error lines still map to their files in both.
|
||||
assert.deepEqual(page.locate(dev.map, 3), { file: 'b/10-b.js', line: 1 });
|
||||
assert.deepEqual(page.locate(ship.map, 3), { file: 'index.html (shell)', line: 3 });
|
||||
} finally { fs.rmSync(src, { recursive: true, force: true }); }
|
||||
});
|
||||
528
tests/agent-relay.test.js
Normal file
528
tests/agent-relay.test.js
Normal file
|
|
@ -0,0 +1,528 @@
|
|||
// The agent relay (scripts/agent/relay.js): a WebSocket router between the game page (src/agent/80-relay.js, agent
|
||||
// mode in Settings) and tool clients. This drives the whole chain with a real page: the harness loads the game
|
||||
// in jsdom, the page's own client dials the relay (a test opts in with __AGENT_RELAY_TEST__ and points it at the
|
||||
// relay's port, because under __TUBES_TEST__ nothing dials on its own), and a raw WebSocket tool client, the relay
|
||||
// client (scripts/lib/relay-client.js) and the MCP server in browser mode (scripts/mcp.js --browser) take turns driving
|
||||
// it. No token anywhere: whatever can connect to the port may drive the game, by design.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const http = require('node:http');
|
||||
const WebSocket = require('ws');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const { createRelay } = require('../scripts/agent/relay');
|
||||
const { createRelaySession } = require('../scripts/lib/relay-client');
|
||||
const SERVER = path.join(ROOT, 'scripts', 'mcp.js');
|
||||
const PORT = 8799 + (process.pid % 500); // dodge a busy port across suites
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-relay-'));
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// The relay in-process, riding a real http.Server (the same createRelay the servers host): no child to leak, and
|
||||
// 'listening' means the first dial cannot race the bind.
|
||||
function startRelay(port = PORT) {
|
||||
const srv = http.createServer((req, res) => { res.writeHead(404); res.end(); });
|
||||
const relay = createRelay({ server: srv });
|
||||
return {
|
||||
relay, srv,
|
||||
listening: () => new Promise((res, rej) => { srv.once('error', rej); srv.listen(port, '127.0.0.1', res); }),
|
||||
close: () => new Promise((r) => { relay.close(); srv.close(() => r()); }),
|
||||
};
|
||||
}
|
||||
|
||||
// The game page: jsdom via the harness, agent mode on (opts.ms: the clock, 0 for the agent's). The page's own client
|
||||
// connects to this relay's host:port as the page. The harness origin matches the relay host, so the page's WebSocket
|
||||
// Origin is same-origin (the relay refuses a foreign one; a Node tool sends none).
|
||||
function page(opts = {}) {
|
||||
const a = load({ url: `http://127.0.0.1:${opts.port ?? PORT}/`, seed: opts.seed ?? 5, storage: { 'sot-agent': JSON.stringify({ on: true, ms: opts.ms ?? 60000 }) }, agent: true });
|
||||
dial(a, opts.port);
|
||||
return a;
|
||||
}
|
||||
const dial = (a, port = PORT) => a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:'+${port};apiAgentSync()`);
|
||||
// Kill the page's dial and retry timer before a test ends, or its backoff keeps the process alive.
|
||||
const stop = (...ps) => { for (const a of ps) if (a) a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)"); };
|
||||
|
||||
// A raw tool client, the way the MCP server speaks to the relay. `headers` fakes a browser's Origin (which Node's ws
|
||||
// does not send) for the cross-site test.
|
||||
function toolClient(port = PORT, headers) {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/agent`, headers ? { headers } : undefined);
|
||||
const calls = new Map();
|
||||
let seq = 0;
|
||||
const events = [];
|
||||
ws.on('message', (d) => {
|
||||
const m = JSON.parse(String(d));
|
||||
if (m.kind === 'presence') { events.push(m); return; }
|
||||
if (m.kind === 'result' && calls.has(m.id)) { calls.get(m.id)(m); calls.delete(m.id); }
|
||||
});
|
||||
return {
|
||||
ws, events,
|
||||
open: () => new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); }),
|
||||
auth: (role = 'tool') => ws.send(JSON.stringify({ kind: 'auth', role })),
|
||||
call: (tool, args) => new Promise((res) => { // a timeout, never a hang
|
||||
const id = 'c' + (++seq);
|
||||
const t = setTimeout(() => { calls.delete(id); res({ error: `no answer for ${tool} (the page went silent?)` }); }, 20000);
|
||||
calls.set(id, (m) => { clearTimeout(t); res(m); });
|
||||
ws.send(JSON.stringify({ kind: 'call', id, tool, args: args || {} }));
|
||||
}),
|
||||
close: () => { try { ws.close(); } catch {} },
|
||||
};
|
||||
}
|
||||
async function tool() { const t = toolClient(); await t.open(); t.auth('tool'); await wait(150); return t; }
|
||||
|
||||
async function withRelay(fn) {
|
||||
const r = startRelay();
|
||||
await r.listening();
|
||||
try { return await fn(r); } finally { await r.close(); }
|
||||
}
|
||||
|
||||
// The MCP server over stdio, as a client runs it.
|
||||
function mcp(argv, onErr) {
|
||||
const child = spawn(process.execPath, [SERVER, ...argv], { stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
let buf = '', id = 0, err = '';
|
||||
const waiting = new Map();
|
||||
child.stderr.on('data', (d) => { err += d; if (onErr) onErr(String(d)); });
|
||||
child.stdout.on('data', (d) => {
|
||||
buf += d;
|
||||
let i;
|
||||
while ((i = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, i); buf = buf.slice(i + 1);
|
||||
let m; try { m = JSON.parse(line); } catch { continue; }
|
||||
if (m.id !== undefined && waiting.has(m.id)) { waiting.get(m.id)(m); waiting.delete(m.id); }
|
||||
}
|
||||
});
|
||||
const send = (o) => new Promise((res) => { const k = ++id; waiting.set(k, res); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: k, ...o }) + '\n'); });
|
||||
return {
|
||||
child, send, stderr: () => err,
|
||||
init: async () => { const r = await send({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } } });
|
||||
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); return r; },
|
||||
call: async (name, args) => (await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result,
|
||||
json: async (name, args) => JSON.parse((await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result.content[0].text),
|
||||
kill: async () => { child.kill('SIGTERM'); await wait(200); child.kill('SIGKILL'); },
|
||||
};
|
||||
}
|
||||
|
||||
test('the relay binds loopback, gates on the role, and never needs a token', () => withRelay(async () => {
|
||||
const silent = toolClient();
|
||||
await silent.open();
|
||||
assert.equal(await new Promise((res) => silent.ws.on('close', (code) => res(code))), 4003, 'a client that never states a role is closed');
|
||||
const bogus = toolClient();
|
||||
await bogus.open();
|
||||
bogus.auth('hacker');
|
||||
assert.equal(await new Promise((res) => bogus.ws.on('close', (code) => res(code))), 4001, 'a role that is neither page nor tool is refused');
|
||||
const t = await tool();
|
||||
assert.deepEqual(t.events.map((e) => e.page), [false], 'a fresh tool sees no page');
|
||||
const r = await t.call('state', { path: 'cash' });
|
||||
assert.match(r.error, /no game page connected/i);
|
||||
t.close();
|
||||
}));
|
||||
|
||||
test('a live page answers tool calls through the relay, from a fixed list of tools', () => withRelay(async () => {
|
||||
const t = await tool();
|
||||
const a = page();
|
||||
try {
|
||||
a.ev("ACT.start({});S.cash=500000;compute()");
|
||||
await wait(600);
|
||||
assert.ok(t.events.some((e) => e.page === true), 'the tools see the page join');
|
||||
const q = await t.call('act', { action: 'buildPop', args: { city: 'ams' }, dryRun: true });
|
||||
assert.equal(q.value.outcome, 'quote');
|
||||
assert.equal(q.value.quote.setup, 20000);
|
||||
assert.equal(a.ev('S.pops.ams'), undefined, 'nothing was dispatched in the page');
|
||||
const r = await t.call('act', { action: 'buildPop', args: { city: 'ams' } });
|
||||
assert.equal(r.value.outcome, 'applied');
|
||||
assert.equal(r.value.charged, 20000);
|
||||
assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, 'the page really changed');
|
||||
assert.equal(r.dayBefore, 0);
|
||||
assert.equal((await t.call('state', { path: 'cash' })).value, 480000);
|
||||
assert.equal((await t.call('status')).value.pops.length, 2);
|
||||
const nope = await t.call('act', { action: 'speed', args: { v: 0 } });
|
||||
assert.match(nope.error, /not available here/);
|
||||
// Unknown tools never reach the facade: its fixed list is the whole vocabulary.
|
||||
const hack = await t.call('eval', { code: 'S.cash=1e9' });
|
||||
assert.match(hack.error, /no tool "eval"/);
|
||||
assert.equal(a.ev('S.cash'), 480000);
|
||||
assert.equal(a.ev('API_TOASTS.depth===0&&API_TOASTS.real===null&&toast.name'), 'toast', 'toast() is the game\'s own again after every call');
|
||||
} finally { stop(a); t.close(); }
|
||||
}));
|
||||
|
||||
test('in the player\'s tab the player owns the game, their windows, their settings and the dice', () => withRelay(async () => {
|
||||
const t = await tool();
|
||||
const a = page({ ms: 0 });
|
||||
try {
|
||||
a.ev("ACT.start({});S.cash=1e7;S.nextFail=S.day+40;S.nextEvent=S.day+50;compute()");
|
||||
await wait(500);
|
||||
// The dice stay hidden, whole or by path, and the schema says so.
|
||||
const st = (await t.call('state')).value;
|
||||
for (const k of ['rng', 'nextFail', 'nextEvent']) assert.ok(!(k in st), `${k} is held back`);
|
||||
assert.equal((await t.call('state', { path: 'nextFail' })).value, null);
|
||||
assert.equal(st.cash, 1e7, 'the board itself is all there');
|
||||
const mode = (await t.call('schema', { section: 'mode' })).value;
|
||||
assert.equal(mode.backend, 'browser');
|
||||
assert.equal(mode.clock, 'agent');
|
||||
assert.ok(mode.withheld.nextFail);
|
||||
assert.ok((await t.call('schema', { section: 'state' })).value.rng.withheld);
|
||||
// Starting, loading or leaving a game is the player's.
|
||||
for (const [action, args] of [['startScn', { id: a.ev('SCN[0].id') }], ['pzStart', { id: a.ev('PZ[0].id') }], ['startWeekly', {}]]) {
|
||||
const r = await t.call('act', { action, args });
|
||||
assert.match(r.error || '', /the player's/, action);
|
||||
}
|
||||
assert.equal(a.ev('S.mode'), 'normal');
|
||||
// So are their settings, agent mode's own switch included: it is no game action, so no tool can find or press it.
|
||||
assert.match((await t.call('act', { action: 'prefSet', args: { v: 'pauseFurious:0' } })).error, /not available here/);
|
||||
assert.match((await t.call('act', { action: 'agentSet', args: {} })).error, /no action/);
|
||||
assert.equal(a.ev('API_AGENT_PREFS.on'), true);
|
||||
// A window the player opened by hand stays theirs: the agent plays behind it, and never closes or replaces it.
|
||||
a.ev("(()=>{const b=document.createElement('button');b.dataset.act='settings';document.body.appendChild(b);b.click();b.remove();})()");
|
||||
assert.equal(a.ev("$('modal').hidden"), false, 'the player has a window open');
|
||||
assert.equal(a.ev('API_MODAL.hand'), true, 'marked as theirs');
|
||||
const html = a.ev("$('modalCard').innerHTML");
|
||||
const sc = (await t.call('screen')).value;
|
||||
assert.equal(sc.where, 'modal');
|
||||
assert.ok(sc.playerWindow, 'the screen says whose it is');
|
||||
assert.equal(sc.question, false, 'and that it is no question');
|
||||
const b = await t.call('act', { action: 'buildPop', args: { city: 'ams' } });
|
||||
assert.equal(b.value.outcome, 'applied', 'the agent plays on behind it');
|
||||
const v = await t.call('act', { action: 'opsOpen' });
|
||||
assert.equal(v.value.screen.where, 'modal');
|
||||
assert.match(v.value.screen.note || '', /shown to you and closed again/, 'its own sheet is shown, then the player\'s window comes back');
|
||||
await t.call('act', { action: 'closeModal' });
|
||||
assert.equal(a.ev("$('modal').hidden"), false, 'closeModal does not close the player\'s window');
|
||||
assert.equal(a.ev("$('modalCard').innerHTML"), html, 'nor change it');
|
||||
await t.call('screen', { where: 'modal' });
|
||||
const c = await t.call('click', { button: 0 });
|
||||
assert.match(c.error || '', /theirs to press/);
|
||||
assert.match((await t.call('open_link', { from: 'fra', to: 'nyc' })).error || '', /would replace it/);
|
||||
// Days run behind it (the agent's clock here), and it is still there after.
|
||||
const adv = await t.call('advance', { days: 3 });
|
||||
assert.equal(adv.value.daysRun, 3);
|
||||
assert.equal(a.ev('S.day'), 3);
|
||||
assert.equal(a.ev("$('modalCard').innerHTML"), html);
|
||||
} finally { stop(a); t.close(); }
|
||||
}));
|
||||
|
||||
test('the agent\'s clock moves only with advance; a running clock only with time, and wait reads it', () => withRelay(async () => {
|
||||
const t = await tool();
|
||||
const a = page({ ms: 0 });
|
||||
try {
|
||||
a.ev("ACT.start({});S.cash=1e7;compute()");
|
||||
await wait(500);
|
||||
assert.equal(a.ev('UI.speed'), 0, 'a tool is connected, but the agent\'s clock stands still');
|
||||
a.ev('last=performance.now();for(let i=1;i<=20;i++)frame(last+i*250)');
|
||||
assert.equal(a.ev('S.day'), 0, 'the loop runs no days');
|
||||
const adv = await t.call('advance', { days: 20 });
|
||||
assert.equal(adv.value.daysRun, 20, 'advance runs them, where the player sees them');
|
||||
assert.equal(a.ev('S.day'), 20);
|
||||
assert.match((await t.call('clock')).value.mode, /agent/);
|
||||
// The player switches to a pace: the clock runs by itself, and advance is refused.
|
||||
a.ev("apiAgentSet('ms',30000)");
|
||||
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000'), 'a pace, and a tool connected: it runs, a day per 30 s');
|
||||
assert.match((await t.call('advance', { days: 1 })).error, /use wait/);
|
||||
const c = (await t.call('clock')).value;
|
||||
assert.equal(c.mode, 'realtime');
|
||||
assert.equal(c.running, true);
|
||||
// The page's own loop moves days at the pace (the test plays the browser's frames, 2 s of them per day).
|
||||
a.ev('API_AGENT_PREFS.ms=2000;apiAgentSync()');
|
||||
a.ev('last=performance.now()');
|
||||
const frames = setInterval(() => a.ev('frame(performance.now())'), 20);
|
||||
try {
|
||||
const { createBrowserSession } = require('../scripts/lib/mcp-browser');
|
||||
const { TOOLS } = require('../scripts/lib/mcp-game');
|
||||
const s = createBrowserSession({ port: PORT });
|
||||
const w = await TOOLS.find((x) => x.name === 'wait').run(s, { days: 1, maxSeconds: 10 });
|
||||
assert.ok(w.daysRun >= 1, `wait returns once a day has passed (${JSON.stringify(w)})`);
|
||||
assert.equal(w.stoppedBecause, null);
|
||||
await s.close();
|
||||
} finally { clearInterval(frames); }
|
||||
} finally { stop(a); t.close(); }
|
||||
}));
|
||||
|
||||
test('the page client reconnects after the relay restarts, and stops when the player switches agent mode off', () => withRelay(async (r) => {
|
||||
const t = await tool();
|
||||
const a = page();
|
||||
try {
|
||||
a.ev("ACT.start({});S.cash=500000;compute()");
|
||||
await wait(500);
|
||||
assert.ok(t.events.some((e) => e.page === true));
|
||||
await r.close();
|
||||
await wait(300);
|
||||
a.ev("apiAgentSet('on',false)");
|
||||
const r2 = startRelay();
|
||||
await r2.listening();
|
||||
try {
|
||||
await wait(1200); // past the first backoff retry
|
||||
assert.equal(a.ev('API_RELAY.on'), false, 'the client is off');
|
||||
a.ev("apiAgentSet('on',true)");
|
||||
await wait(1200);
|
||||
const t2 = await tool();
|
||||
await wait(300);
|
||||
assert.ok(t2.events.some((e) => e.page === true), 'the page reconnected after the relay came back');
|
||||
assert.equal((await t2.call('state', { path: 'cash' })).value, 500000, 'and answers calls again');
|
||||
t2.close();
|
||||
} finally { stop(a); await r2.close(); }
|
||||
} finally { stop(a); t.close(); }
|
||||
}));
|
||||
|
||||
test('a paced clock holds while no tool is connected, and runs when one arrives', () => withRelay(async () => {
|
||||
const a = page({ seed: 5 });
|
||||
try {
|
||||
a.ev("ACT.start({});S.nextFail=S.day+99;S.nextEvent=S.day+99;compute()");
|
||||
await wait(500);
|
||||
assert.equal(a.ev('UI.speed'), 0, 'no tool connected: the clock holds');
|
||||
assert.equal(a.ev('UI.clockLocked'), true, 'agent mode stays on');
|
||||
a.ev('last=performance.now();frame(last);frame(last+250);frame(last+500)');
|
||||
assert.equal(a.ev('S.day'), 0, 'no day ran');
|
||||
const t = await tool();
|
||||
await wait(300);
|
||||
assert.ok(a.ev('UI.speed') > 0, 'a tool connecting runs it');
|
||||
t.close();
|
||||
await wait(400);
|
||||
assert.equal(a.ev('UI.speed'), 0, 'the tool leaving holds it again');
|
||||
a.ev('S.uiSpeed=4;gameResume()');
|
||||
assert.equal(a.ev('UI.speed'), 0, 'gameResume holds with no tool connected');
|
||||
const t2 = await tool();
|
||||
await wait(300);
|
||||
assert.ok(a.ev('UI.speed') > 0, 'and a tool arriving runs it again');
|
||||
// An unrelated preference change does not drop the connection or hold the clock.
|
||||
a.ev('window.__w0=API_RELAY.ws');
|
||||
a.ev("ACT.prefSet({v:'pauseFurious:0'})");
|
||||
a.ev("apiAgentSet('ms',300000)");
|
||||
assert.equal(a.ev('API_RELAY.ws===window.__w0'), true, 'the same socket survived both');
|
||||
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/300000'), 'the clock never held for them, and runs at the new pace');
|
||||
t2.close();
|
||||
} finally { stop(a); }
|
||||
}));
|
||||
|
||||
test('a second page replaces the first: one game per relay, the newest tab wins', () => withRelay(async () => {
|
||||
const a = page({ seed: 5 });
|
||||
a.ev("ACT.start({});S.cash=111000;compute()");
|
||||
const b = page({ seed: 6 });
|
||||
b.ev("ACT.start({});S.cash=222000;compute()");
|
||||
await wait(700);
|
||||
const t = await tool();
|
||||
try {
|
||||
assert.equal((await t.call('state', { path: 'cash' })).value, 222000, 'the newest page answers');
|
||||
} finally { stop(a, b); t.close(); }
|
||||
}));
|
||||
|
||||
test('the MCP server drives the player\'s page in browser mode, over stdio', () => withRelay(async () => {
|
||||
const a = page({ seed: 9, ms: 0 });
|
||||
a.ev("ACT.start({});S.cash=1000000;compute()");
|
||||
await wait(500);
|
||||
const m = mcp(['--browser', '--relay-host', 'localhost', '--relay-port', String(PORT)]);
|
||||
try {
|
||||
const init = await m.init();
|
||||
assert.match(init.result.instructions, /player's own browser tab/);
|
||||
const list = (await m.send({ method: 'tools/list' })).result.tools.map((x) => x.name);
|
||||
for (const n of ['status', 'act', 'schema', 'state', 'advance', 'wait', 'screen', 'click']) assert.ok(list.includes(n), n);
|
||||
for (const n of ['new_game', 'load_save', 'export_save']) assert.ok(!list.includes(n), `${n} is the headless session's`);
|
||||
const mode = await m.json('schema', { section: 'mode' });
|
||||
assert.equal(mode.backend, 'browser');
|
||||
assert.equal(mode.transport, 'relay');
|
||||
assert.equal(mode.relay, `ws://localhost:${PORT}/agent`, 'the mode says which relay: host, port and path');
|
||||
assert.equal(await m.json('state', { path: 'cash' }), 1000000);
|
||||
const r = await m.json('act', { action: 'buildPop', args: { city: 'ams' } });
|
||||
assert.equal(r.outcome, 'applied');
|
||||
assert.equal(r.charged, 20000);
|
||||
assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, "the player's page really changed");
|
||||
assert.equal((await m.json('advance', { days: 2 })).daysRun, 2);
|
||||
assert.ok((await m.json('actions')).includes('buildLink(a,b,tier,cable?,route?,premiumCrossing?)'));
|
||||
const no = await m.call('act', { action: 'startScn', args: { id: a.ev('SCN[0].id') } });
|
||||
assert.equal(no.isError, true);
|
||||
assert.match(no.content[0].text, /the player's/);
|
||||
} finally { stop(a); await m.kill(); }
|
||||
}));
|
||||
|
||||
test('a game page older than the code stops the server rather than mislead', () => withRelay(async () => {
|
||||
const a = page({ seed: 3 });
|
||||
a.ev("ACT.start({});compute()");
|
||||
// A stale tab whose commands keep their names but change shape: only a deep compare of the sections catches it.
|
||||
a.ev('const __c=TUBES.call;TUBES.call=(t,x,c)=>{const v=__c(t,x,c);if(t==="schema"&&!x.section)v.commands.buildPop.args=[{name:"city",required:true}];return v;};');
|
||||
await wait(400);
|
||||
const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '8000']);
|
||||
try {
|
||||
const init = await m.init();
|
||||
assert.ok(init.result.serverInfo, 'the handshake is answered at once');
|
||||
const code = await new Promise((r) => m.child.on('exit', (c2) => r(c2)));
|
||||
assert.equal(code, 1, 'the server exits with an error');
|
||||
assert.match(m.stderr(), /disagrees with the code on disk \(commands\)/);
|
||||
assert.match(m.stderr(), /reload the page/);
|
||||
} finally { stop(a); await m.kill(); }
|
||||
}));
|
||||
|
||||
test('the MCP server answers the handshake at once and waits for the game page', () => withRelay(async () => {
|
||||
const gone = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '1200']);
|
||||
const code = await new Promise((r) => gone.child.on('exit', (c2) => r(c2)));
|
||||
assert.equal(code, 1, 'exits 1 without a page');
|
||||
assert.match(gone.stderr(), /waiting for the game page/);
|
||||
assert.match(gone.stderr(), /no game page answered/);
|
||||
assert.match(gone.stderr(), /Settings → Agent API/);
|
||||
assert.doesNotMatch(gone.stderr(), /TypeError/);
|
||||
const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '20000']);
|
||||
let a = null;
|
||||
try {
|
||||
const t0 = Date.now();
|
||||
await m.init();
|
||||
assert.ok(Date.now() - t0 < 3000, 'initialize does not wait for a browser tab');
|
||||
const early = await m.call('status');
|
||||
assert.equal(early.isError, true, 'a tool before the page arrives is an error, not a hang');
|
||||
await wait(300);
|
||||
assert.match(m.stderr(), /waiting for the game page/);
|
||||
a = page({ seed: 4 });
|
||||
a.ev("ACT.start({});S.cash=444000;compute()");
|
||||
await wait(2500);
|
||||
assert.match(m.stderr(), /ready/, 'the server proceeded once the page answered');
|
||||
assert.equal(await m.json('state', { path: 'cash' }), 444000, 'and drives the late page');
|
||||
} finally { stop(a); await m.kill(); }
|
||||
}));
|
||||
|
||||
const free = () => new Promise((res, rej) => { const s = http.createServer(); s.on('error', rej); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); });
|
||||
|
||||
test('dev.js binds loopback and parses --port; the page dials its own host', async () => {
|
||||
const port = await free();
|
||||
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'dev.js'), '--port', String(port)], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let serr = '';
|
||||
child.stderr.on('data', (d) => { serr += d; });
|
||||
let a = null;
|
||||
try {
|
||||
await wait(700);
|
||||
assert.match(serr, new RegExp(`agent relay on ws://127\\.0\\.0\\.1:${port}/agent`), 'dev.js binds loopback and honours --port');
|
||||
const t = toolClient(port);
|
||||
await t.open(); t.auth('tool'); await wait(150);
|
||||
assert.ok(t.events.some((e) => e.page === false), 'the relay answers on 127.0.0.1');
|
||||
t.close();
|
||||
a = load({ url: `http://127.0.0.1:${port}/`, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true }) } });
|
||||
assert.equal(a.ev('API_RELAY.on'), false, 'under __TUBES_TEST__ nothing dials on its own');
|
||||
a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='';apiAgentSync()`);
|
||||
assert.equal(a.ev('API_RELAY.on'), true);
|
||||
assert.equal(a.ev('apiRelayUrl()'), `ws://127.0.0.1:${port}/agent`, 'its own host and port, the relay path');
|
||||
} finally {
|
||||
stop(a);
|
||||
child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL');
|
||||
}
|
||||
});
|
||||
|
||||
test('calls neither page nor relay can answer resolve as errors, not hangs', async () => {
|
||||
const r = startRelay();
|
||||
await r.listening();
|
||||
const pages = [];
|
||||
try {
|
||||
const t = await tool();
|
||||
const a = page();
|
||||
pages.push(a);
|
||||
a.ev('ACT.start({});S.cash=500000;compute()');
|
||||
await wait(400);
|
||||
// The page dies with a call in flight; it is silenced first, so the call is provably pending when it closes.
|
||||
a.ev('API_RELAY.ws.onmessage=()=>{}');
|
||||
const p = t.call('act', { action: 'buildPop', args: { city: 'ams' } });
|
||||
await wait(100);
|
||||
a.ev('API_RELAY.ws.close(1000)');
|
||||
assert.match((await p).error || '', /disconnected before answering/i);
|
||||
stop(a);
|
||||
t.close();
|
||||
// The relay dies under a call in flight: the client answers on its own behalf, at once.
|
||||
const b = page({ seed: 12 });
|
||||
pages.push(b);
|
||||
b.ev('ACT.start({});S.cash=222000;compute()');
|
||||
await wait(400);
|
||||
b.ev('API_RELAY.ws.onmessage=()=>{}');
|
||||
const s = createRelaySession({ host: '127.0.0.1', port: PORT });
|
||||
const p2 = s.call('state', { path: 'cash' });
|
||||
await wait(150);
|
||||
await r.close();
|
||||
assert.match((await p2).refused || '', /connection closed/i);
|
||||
await s.close();
|
||||
} finally {
|
||||
for (const pg of pages) stop(pg);
|
||||
await r.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('a page that hangs on a call answers within --call-ms, not minutes later', () => withRelay(async () => {
|
||||
const a = page({ seed: 4 });
|
||||
try {
|
||||
a.ev('ACT.start({});compute()');
|
||||
await wait(400);
|
||||
a.ev('API_RELAY.ws.onmessage=()=>{}'); // connected, alive, and never answering
|
||||
const s = createRelaySession({ host: '127.0.0.1', port: PORT, callMs: 300 });
|
||||
const t0 = Date.now();
|
||||
const r = await s.call('state', { path: 'cash' });
|
||||
assert.match(r.refused || '', /no answer from the game page in 0\.3 s/);
|
||||
assert.ok(Date.now() - t0 < 2000, 'the configured timeout, not the default');
|
||||
assert.equal(createRelaySession({}).config.callMs, 30000, 'the default is 30 s');
|
||||
await s.close();
|
||||
} finally { stop(a); }
|
||||
}));
|
||||
|
||||
test('the relay refuses a cross-site Origin and takes a same-origin page or a token-less tool', () => withRelay(async () => {
|
||||
const evil = toolClient(PORT, { Origin: 'http://evil.example' });
|
||||
await evil.open();
|
||||
assert.equal(await new Promise((res) => evil.ws.on('close', (code) => res(code))), 4004, 'refused before any role is granted');
|
||||
// DNS rebinding: evil.example re-pointed at 127.0.0.1 is "same-origin" with itself, but the Host is a name.
|
||||
const rebound = toolClient(PORT, { Host: `evil.example:${PORT}`, Origin: `http://evil.example:${PORT}` });
|
||||
await rebound.open();
|
||||
assert.equal(await new Promise((res) => rebound.ws.on('close', (code) => res(code))), 4004, 'a rebound DNS name is refused');
|
||||
const named = toolClient(PORT, { Host: `evil.example:${PORT}` });
|
||||
await named.open();
|
||||
assert.equal(await new Promise((res) => named.ws.on('close', (code) => res(code))), 4004, 'with or without an Origin');
|
||||
const same = toolClient(PORT, { Origin: `http://127.0.0.1:${PORT}` });
|
||||
await same.open();
|
||||
same.auth('page');
|
||||
await wait(150);
|
||||
const t = await tool();
|
||||
await wait(100);
|
||||
assert.ok(same.events.some((e) => e.tools === 1), 'the same-origin page connects and sees the tool');
|
||||
t.close(); same.close();
|
||||
}));
|
||||
|
||||
// Spawns a server script and resolves with the address its relay banner reports (server.address()).
|
||||
function bannerOf(argv) {
|
||||
const child = spawn(process.execPath, argv, { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let serr = '';
|
||||
return new Promise((res) => {
|
||||
const done = (v) => { clearTimeout(t); child.kill('SIGKILL'); res(v); };
|
||||
const t = setTimeout(() => done({ addr: null, serr }), 5000);
|
||||
child.stderr.on('data', (d) => { serr += d; const m = /agent relay on ws:\/\/(\S+)\/agent/.exec(serr); if (m) done({ addr: m[1], serr }); });
|
||||
});
|
||||
}
|
||||
|
||||
test('dev.js: a bare --host binds loopback, never every interface; binding wider is the operator\'s choice, and said', async () => {
|
||||
const p1 = await free();
|
||||
const dev = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '--port', String(p1)]);
|
||||
assert.equal(dev.addr, `127.0.0.1:${p1}`, `the socket is bound to loopback (${dev.serr})`);
|
||||
const p2 = await free();
|
||||
const wide = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '0.0.0.0', '--port', String(p2)]);
|
||||
assert.equal(wide.addr, `0.0.0.0:${p2}`, 'the banner is the real socket, not the flag echoed back');
|
||||
assert.match(wide.serr, /bound to 0\.0\.0\.0, so anything that can reach this address can drive/);
|
||||
});
|
||||
|
||||
test('browser mode over HTTP: a client connects to the server, the server to the player\'s page', () => withRelay(async () => {
|
||||
const a = page({ seed: 11, ms: 0 });
|
||||
a.ev("ACT.start({});S.cash=555000;compute()");
|
||||
await wait(400);
|
||||
const child = spawn(process.execPath, [SERVER, '--browser', '--relay-port', String(PORT), '--http', '127.0.0.1:0'], { stdio: ['ignore', 'ignore', 'pipe'] });
|
||||
let err = '';
|
||||
try {
|
||||
const port = await new Promise((res, rej) => {
|
||||
child.stderr.on('data', (d) => { err += d; const m = /on http:\/\/127\.0\.0\.1:(\d+)\/mcp/.exec(err); if (m) res(+m[1]); });
|
||||
child.on('exit', () => rej(new Error(err)));
|
||||
});
|
||||
const post = (body) => new Promise((res, rej) => {
|
||||
const data = JSON.stringify({ jsonrpc: '2.0', id: 1, ...body });
|
||||
const req = http.request({ host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data) } }, (r) => {
|
||||
let t = ''; r.setEncoding('utf8'); r.on('data', (d) => { t += d; });
|
||||
r.on('end', () => { const line = t.split('\n').find((l) => l.startsWith('data: ')); res(JSON.parse(line ? line.slice(6) : t)); });
|
||||
});
|
||||
req.on('error', rej); req.end(data);
|
||||
});
|
||||
const init = await post({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } });
|
||||
assert.match(init.result.instructions, /player's own browser tab/);
|
||||
const r = await post({ method: 'tools/call', params: { name: 'state', arguments: { path: 'cash' } } });
|
||||
assert.equal(JSON.parse(r.result.content[0].text), 555000, 'the player\'s game, through HTTP and the relay');
|
||||
const no = await post({ method: 'tools/call', params: { name: 'new_game', arguments: {} } });
|
||||
assert.ok(no.error || (no.result && no.result.isError), 'no new_game in the player\'s tab');
|
||||
} finally { stop(a); child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL'); }
|
||||
}));
|
||||
166
tests/agent-settings.test.js
Normal file
166
tests/agent-settings.test.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// Agent mode in the player's tab (src/agent/75-mode.js, 85-ticker.js): its own switch and clock in Settings, kept
|
||||
// apart from the game's preferences; the gate that keeps it off the public site; the speed the save remembers across
|
||||
// it; the badge that stands in for the speed buttons; and the clock that keeps running where frames do not.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const prefs = (ms = 60000, on = true) => ({ 'sot-agent': JSON.stringify({ on, ms }) });
|
||||
const agent = (o = {}) => load({ agent: true, storage: prefs(o.ms), ...o });
|
||||
// Press one of agent mode's own Settings buttons, as the player does.
|
||||
const press = (a, v) => a.ev(`(()=>{ACT.settings({});const b=document.querySelector('[data-agent-set="${v}"]');b.click();return true;})()`);
|
||||
|
||||
test('the clock buttons set the pace, or give the clock to the agent, and are remembered', () => {
|
||||
const a = agent();
|
||||
a.ev('ACT.start({});S.cash=1e9;compute()');
|
||||
for (const m of [30000, 60000, 120000, 300000]) {
|
||||
press(a, `ms:${m}`);
|
||||
assert.equal(a.ev('apiAgentMs()'), m, `the ${m} ms button sets the pace`);
|
||||
assert.equal(JSON.parse(a.ev(`localStorage.getItem('sot-agent')`)).ms, m, 'in agent mode\'s own storage');
|
||||
assert.ok(a.ev(`document.querySelector('[data-agent-set="ms:${m}"]').classList.contains('pink')`), 'and shows as picked');
|
||||
}
|
||||
// 0: the agent's clock. It stands still: no speed, and the loop never runs a day by itself.
|
||||
press(a, 'ms:0');
|
||||
assert.equal(a.ev('apiAgentMs()'), 0);
|
||||
assert.equal(a.ev('UI.speed'), 0, 'the agent\'s clock stands still');
|
||||
a.ev('last=performance.now();for(let i=1;i<=40;i++)frame(last+i*250)');
|
||||
assert.equal(a.ev('S.day'), 0, 'no day passes on its own');
|
||||
assert.match(a.ev('settingsHtml()'), /The agent moves it/);
|
||||
// Junk is ignored, never coerced.
|
||||
a.ev("apiAgentSet('ms','nope');apiAgentSet('ms',true);apiAgentSet('ms',12345);apiAgentSet('nope',1)");
|
||||
assert.equal(a.ev('apiAgentMs()'), 0);
|
||||
// Its buttons are agent mode's own, not game actions: no tool finds them on a screen.
|
||||
assert.equal(a.ev(`document.querySelectorAll('#modal [data-agent-set][data-act]').length`), 0);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('the game\'s preferences stay exactly as they are', () => {
|
||||
const a = agent();
|
||||
assert.deepEqual(Object.keys(a.ev('PREF_DEF')).sort(), ['pauseFurious', 'pauseIncident', 'quiet', 'warnUnhappy']);
|
||||
a.ev("ACT.prefSet({v:'pauseFurious:0'})");
|
||||
assert.equal(a.ev('PREFS.pauseFurious'), false);
|
||||
a.ev("ACT.prefSet({v:'agent:1'})");
|
||||
assert.equal(a.ev("'agent' in PREFS"), false, 'prefSet knows nothing of agent mode');
|
||||
assert.equal(a.ev(`localStorage.getItem('sot-prefs')`), JSON.stringify({ pauseFurious: false }));
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('agent mode only exists where a relay can be reached', () => {
|
||||
const a = agent();
|
||||
assert.equal(a.ev('API_AGENT_OK'), true);
|
||||
assert.match(a.ev('settingsHtml()'), /Agent API/, 'the Settings sheet has the section');
|
||||
// Plain http to an address: yes, wherever the operator bound the dev server. https (the public site cannot even
|
||||
// open ws:// from its pages), and DNS names (the relay refuses them): no.
|
||||
const gate = (p, h) => a.ev(`apiAgentLocal(${JSON.stringify(p)},${JSON.stringify(h)})`);
|
||||
for (const h of ['127.0.0.1', 'localhost', 'tubes.localhost', '10.0.0.4', '192.168.1.5', '203.0.113.7', '[::1]']) assert.equal(gate('http:', h), true, h);
|
||||
assert.equal(gate('https:', 'seriesoftub.es'), false, 'the public site has no relay behind it');
|
||||
assert.equal(gate('http:', 'seriesoftub.es'), false);
|
||||
assert.equal(gate('http:', 'example.com'), false);
|
||||
assert.equal(gate('file:', ''), false);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('on the public site there is no agent mode, even with the preference set by hand', () => {
|
||||
const a = load({ url: 'https://seriesoftub.es/', agent: true, storage: prefs() });
|
||||
a.ev('ACT.start({});S.cash=1e9;compute()');
|
||||
assert.equal(a.ev('API_AGENT_OK'), false);
|
||||
assert.doesNotMatch(a.ev('settingsHtml()'), /Agent API/, 'no section in Settings');
|
||||
assert.equal(a.ev('UI.clockLocked'), false, 'the clock is the player\'s');
|
||||
assert.equal(a.ev('API_RELAY.on'), false, 'nothing dials');
|
||||
a.ev('ACT.speed({v:2})');
|
||||
assert.equal(a.ev('UI.speed'), 2, 'the speed buttons work');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('agent mode remembers the speed the player left the game at, not the agent\'s', () => {
|
||||
const a = agent({ storage: prefs(60000, false) }); // agent mode off: the player is playing
|
||||
a.ev('ACT.start({});S.cash=1e9;ACT.speed({v:2});compute();save(true)');
|
||||
assert.equal(a.ev('S.uiSpeed'), 2, 'the save carries the player speed');
|
||||
press(a, 'on:1');
|
||||
assert.equal(a.ev('UI.clockLocked'), true);
|
||||
assert.equal(a.ev('UI.speed'), 0, 'no tool is connected, so the clock holds');
|
||||
for (const x of ['ACT.speed({v:4})', 'ACT.phonePlay()', 'ACT.phoneSpeed()', "dispatchEvent(new KeyboardEvent('keydown',{code:'Space',key:' '}))"]) {
|
||||
a.ev(x);
|
||||
assert.equal(a.ev('UI.speed'), 0, `${x} does nothing while an agent drives`);
|
||||
}
|
||||
assert.equal(a.ev('autoPause()'), false, 'nothing pauses a locked clock either');
|
||||
a.ev('S.day=5;save(true)');
|
||||
assert.equal(a.ev('S.uiSpeed'), 2, 'save() never stores the locked speed in its place');
|
||||
a.ev('S.uiSpeed=4;gameResume()');
|
||||
assert.equal(a.ev('UI.speed'), 0, 'resuming a game keeps the lock');
|
||||
a.ev('S.uiSpeed=2');
|
||||
press(a, 'on:0');
|
||||
assert.equal(a.ev('UI.clockLocked'), false);
|
||||
assert.equal(a.ev('UI.speed'), 2, 'switching off restores the speed the player left the game at');
|
||||
a.ev('ACT.speed({v:4})');
|
||||
assert.equal(a.ev('UI.speed'), 4, 'and the speed buttons are back');
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('a paced clock runs behind an open window and in a hidden tab, and leaves the rest to the frame', () => {
|
||||
const a = agent({ ms: 30000 });
|
||||
a.ev('ACT.start({});S.cash=1e9;S.nextFail=S.day+999;S.nextEvent=S.day+999;compute()');
|
||||
// As if a tool were connected: the pace runs.
|
||||
a.ev('API_RELAY.on=true;apiRelayPresence(1)');
|
||||
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000'));
|
||||
// Visible, no window: the frame runs the days, the ticker none.
|
||||
a.ev('API_TICKER.last=0;apiAgentTick(1000);for(let t=1250;t<=31000;t+=250)apiAgentTick(t)');
|
||||
assert.equal(a.ev('S.day'), 0, 'the ticker leaves a visible, open map to the frame');
|
||||
a.ev('last=0;for(let t=250;t<=30250;t+=250)frame(t)');
|
||||
assert.equal(a.ev('S.day'), 1, 'which runs a day in 30 s');
|
||||
// A window open: the frame stops, the ticker goes on.
|
||||
a.ev('ACT.settings({})');
|
||||
a.ev('last=40000;for(let t=40250;t<=70000;t+=250)frame(t)');
|
||||
assert.equal(a.ev('S.day'), 1, 'no days in the frame behind a window');
|
||||
a.ev('API_TICKER.last=0;apiAgentTick(70000);for(let t=70250;t<=100250;t+=250)apiAgentTick(t)');
|
||||
assert.equal(a.ev('S.day'), 2, 'the ticker runs the day behind it');
|
||||
a.ev('closeModal()');
|
||||
// A hidden tab: frames stop altogether, the ticker goes on.
|
||||
a.ev("Object.defineProperty(document,'visibilityState',{value:'hidden',configurable:true})");
|
||||
a.ev('API_TICKER.last=0;apiAgentTick(200000);for(let t=200250;t<=230250;t+=250)apiAgentTick(t)');
|
||||
assert.equal(a.ev('S.day'), 3, 'and in a hidden tab');
|
||||
// Off: the ticker does nothing at all.
|
||||
a.ev("apiAgentSet('on',false)");
|
||||
a.ev('API_TICKER.last=0;apiAgentTick(300000);for(let t=300250;t<=400000;t+=250)apiAgentTick(t)');
|
||||
assert.equal(a.ev('S.day'), 3);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('phones show the agent pace in the tab bar, where the speed button was', () => {
|
||||
const a = agent();
|
||||
a.ev('ACT.start({});S.cash=1e9;compute();window.innerWidth=360;window.innerHeight=740;renderTabbar()');
|
||||
const pace = () => a.ev(`(()=>{const b=document.querySelector('#tabbar button.pace');return b?{dis:b.disabled,ic:b.querySelector('.ic').textContent}:null;})()`);
|
||||
assert.equal(a.ev('isPhone()'), true);
|
||||
assert.deepEqual({ ...pace() }, { dis: true, ic: '1 min' }, 'the locked speed button reads the pace');
|
||||
assert.equal(a.ev(`document.querySelector('#tabbar button.play').disabled`), true, 'and play/pause is locked');
|
||||
assert.equal(a.ev(`document.querySelectorAll('#tabbar [data-act="phonePlay"],#tabbar [data-act="phoneSpeed"]').length`), 0);
|
||||
a.ev("apiAgentSet('ms',30000);renderTabbar()");
|
||||
assert.equal(pace().ic, '30 s', 'and follows the pace the player picks');
|
||||
a.ev("apiAgentSet('ms',0);renderTabbar()");
|
||||
assert.equal(pace().ic, '🤖', 'the agent\'s clock has a badge of its own');
|
||||
// The desktop and tablet HUD badge says the same, in place of the speed buttons.
|
||||
a.ev('renderHUD()');
|
||||
assert.equal(a.ev("$('spPace').hidden"), false);
|
||||
assert.equal(a.ev("$('sp1').hidden"), true);
|
||||
assert.equal(a.ev("$('spPace').textContent"), 'Agent\'s clock');
|
||||
a.ev("apiAgentSet('ms',30000);renderHUD()");
|
||||
assert.match(a.ev("$('spPace').textContent"), /30 s per simulated day/);
|
||||
// Agent mode off: the ordinary buttons are back, and the badge goes.
|
||||
a.ev("apiAgentSet('on',false);renderTabbar();renderHUD()");
|
||||
assert.equal(pace(), null);
|
||||
assert.match(a.ev(`document.querySelector('#tabbar [data-act="phoneSpeed"] .ic').textContent`), /×$/);
|
||||
assert.equal(a.ev("$('spPace').hidden"), true);
|
||||
assert.equal(a.ev("$('sp1').hidden"), false);
|
||||
assert.deepEqual(a.errors, []);
|
||||
});
|
||||
|
||||
test('the Settings sheet\'s agent section is complete in every language, on a phone too', () => {
|
||||
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
|
||||
const a = load({ agent: true, storage: prefs(), ...(lang === 'en' ? {} : { lang }) });
|
||||
a.ev('ACT.start({});window.innerWidth=360;window.innerHeight=740;ACT.settings({})');
|
||||
const html = a.ev("$('modalCard').innerHTML");
|
||||
assert.ok(html.includes('data-agent-set="ms:0"') && html.includes('data-agent-set="ms:300000"'), `${lang}: every clock button is there`);
|
||||
assert.doesNotMatch(a.ev("$('modalCard').textContent"), /settings\./, `${lang}: no label shows untranslated`);
|
||||
assert.deepEqual(a.errors, [], lang);
|
||||
}
|
||||
});
|
||||
24
tests/big-numbers.test.js
Normal file
24
tests/big-numbers.test.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('money and bandwidth keep a readable unit past a billion dollars and a petabit', () => {
|
||||
const { ev, errors } = load();
|
||||
const f = x => ev(x);
|
||||
assert.equal(f('fmt$(1.5e6)'), '$1.50M');
|
||||
assert.equal(f('fmt$(250e6)'), '$250.0M');
|
||||
assert.equal(f('fmt$(999.97e6)'), '$1.00B');
|
||||
assert.equal(f('fmt$(1.2e9)'), '$1.20B');
|
||||
assert.equal(f('fmt$(-12.5e9)'), '-$12.5B');
|
||||
assert.equal(f('fmt$(120e9)'), '$120.0B');
|
||||
assert.equal(f('fmtG(2500)'), '2.50 Tbps');
|
||||
assert.equal(f('fmtG(999000)'), '999.0 Tbps');
|
||||
assert.equal(f('fmtG(999990)'), '1.00 Pbps');
|
||||
assert.equal(f('fmtG(12e6)'), '12.0 Pbps');
|
||||
// The map's fiber labels and the NOC graph axes use the short form.
|
||||
assert.equal(f('fmtCap(334000)'), '334T');
|
||||
assert.equal(f('fmtCap(1024000)'), '1P');
|
||||
assert.equal(f('fmtCap(3152700)'), '3.2P');
|
||||
assert.equal(f('fmtCap(400)'), '400G');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -46,10 +46,28 @@ test('src: partials follow the layout rules (docs/adr/0002-one-page-assembled-at
|
|||
const src = path.join(root, 'src');
|
||||
for (const f of listFiles(src)) {
|
||||
if (f === 'index.html' || f === 'i18n/en.js') continue;
|
||||
assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|game\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/ or game/`);
|
||||
assert.match(f, /^(styles\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.css|(game|agent)\/(\d\d-[a-z0-9-]+\/)*\d\d-[a-z0-9-]+\.js)$/, `${f}: name it NN-lower-case under styles/, game/ or agent/`);
|
||||
}
|
||||
for (const dev of [false, true]) {
|
||||
const { html, map } = assemble({ dev });
|
||||
assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})');
|
||||
assert.equal((html.match(/<script>/g) || []).length, 2, 'the language loader and the game: one inline game script');
|
||||
assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial');
|
||||
}
|
||||
});
|
||||
|
||||
test('src: the game never names the agent code, which only the development page has (docs/adr/0004-dev-only-code.md)', () => {
|
||||
// Everything src/agent/ defines at the top level is named api…, API_… (or is window.TUBES), so one pattern finds any
|
||||
// use of it elsewhere: such code would work in development and break in the page players get.
|
||||
const { listFiles } = require('../scripts/lib/page');
|
||||
const src = path.join(root, 'src'), read = (f) => fs.readFileSync(path.join(src, f), 'utf8'), AGENT = /\b(api[A-Z]\w*|API_[A-Z0-9_]+|TUBES)\b/;
|
||||
let n = 0;
|
||||
for (const f of listFiles(path.join(src, 'agent'))) {
|
||||
for (const m of read('agent/' + f).matchAll(/^(?:const|let|var|function|async function)\s+([A-Za-z_$][\w$]*)/gm)) { n++; assert.match(m[1], AGENT, `src/agent/${f}: top-level ${m[1]} is named api… or API_…`); }
|
||||
}
|
||||
assert.ok(n > 30, `found the agent's top-level names (${n})`);
|
||||
for (const f of listFiles(src).filter((f) => !f.startsWith('agent/'))) {
|
||||
const m = read(f).match(AGENT);
|
||||
assert.equal(m, null, `src/${f} names ${m && m[0]}, which only the development page defines`);
|
||||
}
|
||||
const { html, map } = assemble();
|
||||
assert.equal((html.match(/^const ACT=\{$/gm) || []).length, 1, 'ACT is declared once; other action files use Object.assign(ACT,{…})');
|
||||
assert.equal((html.match(/<script>/g) || []).length, 2, 'the language loader and the game: one inline game script');
|
||||
assert.ok(map.length > 50 && map.every((m) => m.to >= m.from), 'the line map covers every partial');
|
||||
});
|
||||
|
|
|
|||
52
tests/de-kicks-price-cap.test.js
Normal file
52
tests/de-kicks-price-cap.test.js
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = "ACT.start({});S.cash=1e12;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:1});S.dk=S.dk||dkState();S.dk.m.fra=2";
|
||||
|
||||
test('DE-Kicks harmonisation raises the price for years, then stops at a ceiling', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
assert.equal(ev("S.ixp.fra"), 1, 'joined the DE-Kicks exchange');
|
||||
const base = ev("PORT[1].ix*ixMul('fra')");
|
||||
ev("for(let d=1;d<=360*10;d++)dkTick(d)");
|
||||
const tenYears = ev("dkMult('fra')");
|
||||
assert.ok(tenYears > 2 && tenYears <= ev("DK_MAX"), 'it still climbs at first');
|
||||
ev("for(let d=360*10;d<=360*70;d++)dkTick(d)");
|
||||
assert.equal(ev("dkMult('fra')"), ev("DK_MAX"), 'sixty more years stay at the ceiling');
|
||||
assert.equal(ev("ixPortMo('fra',1)"), Math.round(base * ev("DK_MAX")), 'so the port costs a few times list, never a hundred');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a save that already ran away reads as the ceiling, and a capped price stops announcing rises', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.dk.m.fra=40");
|
||||
assert.equal(ev("dkMult('fra')"), ev("DK_MAX"));
|
||||
ev("S.inc=[];S.dk.add.fra=[]");
|
||||
const day = ev("(()=>{for(let d=1;d<400;d++)if((d+hstr('fra')%90)%365===0)return d;})()");
|
||||
ev(`Math.random=()=>0.9;toast=(...a)=>{(window.__t=window.__t||[]).push(a[0])};dkTick(${day})`);
|
||||
assert.equal(ev("(window.__t||[]).filter(t=>/harmonised/i.test(t)).length"), 0, 'no "prices up" toast at the ceiling');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('loading a save clamps a runaway DE-Kicks price and the quote it remembers, so rejoining is not quoted at 40× list', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.dk.m.fra=40;S.dk.lastQ={fra:{m:40,h:3,until:S.day+365}};S.dk.m.mad='x';S=sanitize(S)||S");
|
||||
assert.equal(ev("S.dk.m.fra"), ev("DK_MAX"));
|
||||
assert.equal(ev("S.dk.lastQ.fra.m"), ev("DK_MAX"));
|
||||
assert.equal(ev("'mad' in S.dk.m"), false, 'junk is dropped');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a rise clipped by the ceiling announces only what the bill shows', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.dk.m.fra=3.9;S.dk.add.fra=[1,2,3]");
|
||||
const day = ev("(()=>{for(let d=1;d<400;d++)if((d+hstr('fra')%90)%365===0)return d;})()");
|
||||
ev(`Math.random=()=>0.9;toast=(...a)=>{(window.__t=window.__t||[]).push(a[0])};dkTick(${day})`);
|
||||
const t = ev("(window.__t||[]).find(t=>/harmonised/i.test(t))||''");
|
||||
assert.match(t, /\b3\s?%/, `a 3% rise, not 14%: ${t}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1,17 +1,21 @@
|
|||
// Loads the game page in jsdom with the animation loop disabled, so tests can drive the simulation
|
||||
// directly through the game's globals (ACT, S, R, dayTick…). The page is assembled from src/ once per
|
||||
// test process (scripts/lib/page.js), so tests always run what is in src/, never a stale build.
|
||||
// It is the page players get; {agent: true} loads the development page instead, with the agent facade
|
||||
// (src/agent/) the MCP server drives. Only the tests of that facade ask for it, so core code that leans on
|
||||
// it fails here rather than in production.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { JSDOM, VirtualConsole } = require('jsdom');
|
||||
const { assemble } = require('../scripts/lib/page');
|
||||
|
||||
let PAGE = null;
|
||||
const page = () => PAGE || (PAGE = assemble().html);
|
||||
const PAGE = {};
|
||||
const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html);
|
||||
|
||||
// opts.file: a built or older page to load instead (the perf bench, the release build test).
|
||||
// opts.agent: the development page, with src/agent/.
|
||||
function load(opts = {}) {
|
||||
const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page();
|
||||
const html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent);
|
||||
const errors = [];
|
||||
const vc = new VirtualConsole();
|
||||
vc.on('jsdomError', (e) => {
|
||||
|
|
@ -19,6 +23,9 @@ function load(opts = {}) {
|
|||
if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message);
|
||||
});
|
||||
const dom = new JSDOM(html, {
|
||||
// opts.url: the origin the page is "served" from. Tests that dial the agent relay pass the relay's own host, so
|
||||
// the page's WebSocket Origin matches (the relay refuses a cross-site one); everything else stays on a made-up
|
||||
// https origin nothing can reach.
|
||||
url: opts.url || 'https://tests.invalid/',
|
||||
runScripts: 'dangerously',
|
||||
pretendToBeVisual: true,
|
||||
|
|
|
|||
208
tests/intern-ports.test.js
Normal file
208
tests/intern-ports.test.js
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// The intern's "Keep peering headroom" order: PNI and IX ports above a multiple of today's traffic. One port at a POP with
|
||||
// several routers gets a second in a LAG; anything else moves up a port size. Same setup as the other standing-order tests:
|
||||
// a small network, a hired intern, no cash floor, no fat fingers (Change Freeze).
|
||||
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
|
||||
"ACT.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
|
||||
function game(t, extra = '') {
|
||||
const h = load();
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev(BASE);
|
||||
if (extra) h.ev(extra);
|
||||
return h;
|
||||
}
|
||||
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
|
||||
// Hiring recomputes, which would wipe the traffic a case stages: hire first, then stage.
|
||||
function hired(t, extra) { const h = game(t); hire(h.ev); h.ev(extra); return h; }
|
||||
const on = (ev, p = { x: 1.5 }, cap) => ev(`S.ops.on.ports=true;S.ops.p.ports=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.ports=${cap};`}`);
|
||||
const shift = ev => ev('opsDay(S.day)');
|
||||
const cash = ev => ev('S.cash');
|
||||
// A 10G PNI with a small network at Frankfurt, carrying `use` Gbps today. PNIs are up the moment they are ordered, so the
|
||||
// outcome does not wait on a lead time.
|
||||
const pni = (tier, use, n = 1) => `S.rules.pnis='instant';S.pni.push({id:'p1',city:'fra',net:'drz',tier:${tier},n:${n},ready:0});compute();R.usePni.p1=${use}`;
|
||||
const ix = (tier, use) => `S.rules.pnis='instant';ACT.buyIx({city:'fra',tier:${tier},signed:true});compute();R.useIx.fra=${use}`;
|
||||
const PNIS = "JSON.stringify(S.pni.map(p=>[p.net,p.tier,p.n||1,!!p.up]))";
|
||||
const IXP = "JSON.stringify([S.ixp.fra,(S.ixn||{}).fra||1])";
|
||||
// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same.
|
||||
function twins(t, extra, manual, pick, x = 1.5) {
|
||||
const A = game(t), B = game(t);
|
||||
hire(A.ev); hire(B.ev);
|
||||
A.ev(extra); B.ev(extra);
|
||||
on(A.ev, { x });
|
||||
const a0 = cash(A.ev); shift(A.ev); const a1 = cash(A.ev);
|
||||
const b0 = cash(B.ev); B.ev(manual); const b1 = cash(B.ev);
|
||||
assert.ok(a0 - a1 > 0, 'the order did some paid work');
|
||||
assert.equal(a0 - a1, b0 - b1, 'the shift cost exactly what the clicks cost');
|
||||
assert.equal(A.ev(pick), B.ev(pick), 'and left the network the same');
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
return A;
|
||||
}
|
||||
|
||||
test('a hot PNI at a one-router POP moves up a port size, exactly as the click would', t => {
|
||||
const A = twins(t, pni(0, 9), "ACT.pni({city:'fra',net:'drz',tier:1})", PNIS);
|
||||
assert.equal(A.ev('S.pni[0].tier'), 1);
|
||||
assert.equal(A.ev('S.pni[0].n||1'), 1, 'one port, not a LAG');
|
||||
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up a peering port in Frankfurt 10G→100G/);
|
||||
});
|
||||
|
||||
test('a single PNI port at a POP with several routers gets a second port in a LAG', t => {
|
||||
const A = twins(t, pni(0, 9) + ";S.pops.fra.routers=2;compute();R.usePni.p1=9", "ACT.lagP({id:'p1',d:1})", PNIS);
|
||||
assert.equal(A.ev('S.pni[0].tier'), 0, 'same size');
|
||||
assert.equal(A.ev('S.pni[0].n'), 2);
|
||||
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up a peering port in Frankfurt \+1×10G/);
|
||||
});
|
||||
|
||||
test('a PNI that is already a LAG moves up a port size, whatever the routers', t => {
|
||||
const A = twins(t, pni(0, 15, 2) + ";S.pops.fra.routers=2;compute();R.usePni.p1=15", "ACT.pni({city:'fra',net:'drz',tier:1})", PNIS);
|
||||
assert.equal(A.ev('S.pni[0].tier'), 1);
|
||||
assert.equal(A.ev('S.pni[0].n'), 2, 'the LAG keeps its members');
|
||||
});
|
||||
|
||||
test('the same two rules for an IX port', t => {
|
||||
const up = twins(t, ix(0, 9), "ACT.buyIx({city:'fra',tier:1})", IXP);
|
||||
assert.equal(up.ev(IXP), '[1,1]', 'one router: a bigger port');
|
||||
assert.match(up.ev('opsEntry(S.ops.log[0])'), /topped up a peering port in Frankfurt 10G→100G/);
|
||||
const lag = twins(t, ix(0, 9) + ";S.pops.fra.routers=2;compute();R.useIx.fra=9", "ACT.lagIx({city:'fra',d:1})", IXP);
|
||||
assert.equal(lag.ev(IXP), '[0,2]', 'several routers: a second port in a LAG');
|
||||
const big = twins(t, ix(0, 15) + ";S.ixn={fra:2};S.pops.fra.routers=2;compute();R.useIx.fra=15", "ACT.buyIx({city:'fra',tier:1})", IXP);
|
||||
assert.equal(big.ev(IXP), '[1,2]', 'a LAG moves up as a whole');
|
||||
});
|
||||
|
||||
test('it picks the smallest port that gives the headroom, and the biggest the router takes when none does', t => {
|
||||
// 99G of traffic at 1.5× needs about 149G: 100G is too small, 400G fits.
|
||||
const A = twins(t, pni(1, 99) + ";R.usePni.p1=99", "ACT.pni({city:'fra',net:'drz',tier:2})", PNIS);
|
||||
assert.equal(A.ev('S.pni[0].tier'), 2);
|
||||
// A router that tops out at 100G cannot take a bigger port: another member of the LAG instead.
|
||||
const B = twins(t, "S.pops.fra.rgen=0;" + pni(1, 95), "ACT.lagP({id:'p1',d:1})", PNIS);
|
||||
assert.equal(B.ev('S.pni[0].tier'), 1);
|
||||
assert.equal(B.ev('S.pni[0].n'), 2);
|
||||
// 380G of traffic at 3× needs 1140G: the next size up (800G) is still too small, so it skips to 1.6T in one order.
|
||||
const C = twins(t, "S.pops.fra.rgen=3;" + pni(2, 380), "ACT.pni({city:'fra',net:'drz',tier:4})", PNIS, 3);
|
||||
assert.equal(C.ev('S.pni[0].tier'), 4);
|
||||
});
|
||||
|
||||
test('it leaves ports with their headroom alone, and does nothing when switched off', t => {
|
||||
const { ev, errors } = hired(t, pni(1, 20) + ";" + ix(0, 5));
|
||||
on(ev);
|
||||
const s0 = ev(`${PNIS}+${IXP}`), c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev(`${PNIS}+${IXP}`), s0);
|
||||
assert.equal(cash(ev), c0);
|
||||
assert.equal(ev('S.ops.log[0].r.length'), 0, 'a quiet shift');
|
||||
ev('R.usePni.p1=95;R.useIx.fra=9;S.ops.on.ports=false');
|
||||
shift(ev);
|
||||
assert.equal(cash(ev), c0, 'off: hot ports stay as they are');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a PNI augment on order is waited for, not ordered twice', t => {
|
||||
const { ev, errors } = hired(t, "S.rules.pnis='wait';S.pni.push({id:'p1',city:'fra',net:'drz',tier:0,ready:0});compute();R.usePni.p1=9");
|
||||
on(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pni[0].up&&S.pni[0].up.tier'), 1, 'the augment is ordered');
|
||||
assert.equal(ev('S.pni[0].tier'), 0, 'and lands later');
|
||||
const c1 = cash(ev), up = ev('JSON.stringify(S.pni[0].up)');
|
||||
ev('R.usePni.p1=9'); shift(ev);
|
||||
assert.equal(cash(ev), c1, 'a second shift buys nothing');
|
||||
assert.equal(ev('JSON.stringify(S.pni[0].up)'), up);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the router ports an augment on order will take are not promised twice', t => {
|
||||
// A hot 100G PNI, a hot 10G PNI and a hot IX port, two routers, one free port: the hottest gets its second member and nobody else can have a port.
|
||||
const { ev, errors } = hired(t, "S.rules.pnis='wait';S.pops.fra.routers=2;S.transit.push({id:'fill',city:'fra',net:'ntt',tier:1,n:43,down:0},{id:'fill2',city:'fra',net:'ntt',tier:0,n:6,down:0});ACT.buyIx({city:'fra',tier:0,signed:true});" +
|
||||
"S.pni.push({id:'p1',city:'fra',net:'drz',tier:1,ready:0},{id:'p2',city:'fra',net:'vdp',tier:0,ready:0});compute();R.usePni.p1=95;R.usePni.p2=9;R.useIx.fra=9");
|
||||
on(ev);
|
||||
assert.equal(ev("portsMax('fra')-portsUsed('fra')"), 1);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pni[0].up&&S.pni[0].up.n'), 2, 'the hotter PNI is the one that gets the port');
|
||||
assert.ok(!ev('S.pni[1].up'), 'the 10G one gets neither a member nor a bigger port');
|
||||
assert.equal(ev(IXP), '[0,1]', 'and neither does the exchange port');
|
||||
assert.ok(ev("portsUsed('fra')+S.pni.reduce((a,p)=>a+(p.up?Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):0),0)") <= ev("portsMax('fra')"), 'and the POP is not over-booked');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('it keeps to the monthly budget, the cash floor and the per-POP switch', t => {
|
||||
const { ev, errors } = hired(t, pni(0, 9));
|
||||
on(ev, { x: 1.5 }, 10000);
|
||||
ev('S.ops.spent.ports=9000');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pni[0].tier'), 0, 'over the budget: left alone');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Keep peering headroom/);
|
||||
ev('S.ops.spent.ports=0;S.ops.floor=1e8');
|
||||
ev('R.usePni.p1=9'); shift(ev);
|
||||
assert.equal(ev('S.pni[0].tier'), 0, 'under the cash floor: left alone');
|
||||
ev("S.ops.floor=0;ACT.opsPop({k:'ports',city:'fra'});closeModal();R.usePni.p1=9");
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pni[0].tier'), 0, 'switched off at this POP');
|
||||
ev("ACT.opsPop({k:'ports',city:'fra'});closeModal();R.usePni.p1=9");
|
||||
shift(ev);
|
||||
assert.equal(ev('S.pni[0].tier'), 1, 'and on again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('it waits out a flood instead of buying ports for it', t => {
|
||||
const { ev, errors } = hired(t, pni(0, 9));
|
||||
on(ev);
|
||||
ev("S.ev.ddos={id:'a',city:'fra',tgt:'bb:fra',vec:'http',gbps:20,start:S.day,until:S.day+3};compute();R.usePni.p1=9");
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(cash(ev), c0);
|
||||
assert.equal(ev('S.pni[0].tier'), 0);
|
||||
ev("S.ev.ddos=null;compute();R.usePni.p1=9"); shift(ev);
|
||||
assert.equal(ev('S.pni[0].tier'), 1, 'the day after, it gets on with it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the monthly bill the intern reports includes IX ports', t => {
|
||||
const { ev, errors } = hired(t, ix(0, 9));
|
||||
on(ev);
|
||||
const m0 = ev('opsMoNow()');
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ixp.fra'), 1);
|
||||
assert.equal(ev('opsMoNow()') - m0, ev('ixPortMo("fra",1)-ixPortMo("fra",0)'));
|
||||
assert.equal(ev('S.ops.log[0].mo'), ev('opsMoNow()') - m0, 'and the log says so');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an old save has the order off, and a new save keeps its dials', t => {
|
||||
const { ev, errors } = game(t);
|
||||
hire(ev); on(ev, { x: 2 }, 250000);
|
||||
ev("S.ops.skip.fra=['ports'];save();S=migrate(JSON.parse(slotRaw(UI.slot)))");
|
||||
assert.equal(ev("S.ops.on.ports&&S.ops.p.ports.x===2&&S.ops.cap.ports===250000&&S.ops.skip.fra[0]==='ports'"), true);
|
||||
ev("delete S.ops.on.ports;delete S.ops.p.ports;delete S.ops.cap.ports;delete S.ops.spent.ports;S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.ops.on.ports'), false, 'an intern hired before the order existed does not start doing it');
|
||||
assert.equal(ev('opsP("ports","x")'), 1.5);
|
||||
assert.equal(ev('S.ops.spent.ports'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a LACP fault or a building down does not buy a bigger IX port: the order counts what the port is', t => {
|
||||
const { ev, errors } = hired(t, ix(1, 70) + ";S.ixn={fra:2};S.pops.fra.routers=2;S.ev.ixlacp={fra:{until:S.day+2,f:0.5}};compute();R.useIx.fra=70");
|
||||
assert.ok(ev("ixCap('fra')") < 1.5 * 70, 'the fault leaves less than the headroom for a day or two');
|
||||
on(ev);
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev(IXP), '[1,2]', 'the 2×100G LAG stays as it is');
|
||||
assert.equal(cash(ev), c0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a remote IX port moves up to 100G at most, and the log names the exchange', t => {
|
||||
const { ev, errors } = hired(t, "S.rules.pnis='instant';S.links.push({id:'remote',a:'fra',b:'ams',kind:'vxc',prov:FABS.find(f=>f.cities.includes('fra')&&f.cities.includes('ams')).id,vt:1,km:kmBetween('fra','ams'),sub:false,mo:0,cut:0,day:0});" +
|
||||
"ACT.buyIx({city:'ams',tier:0,signed:true});compute();R.useIx.ams=9");
|
||||
assert.equal(ev("isRemote('ams')"), true, 'no POP in Amsterdam: a remote port');
|
||||
on(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ixp.ams'), 1, '10G → 100G');
|
||||
assert.match(ev('opsEntry(S.ops.log[0])'), new RegExp(ev("ixName('ams')") + '|Amsterdam'));
|
||||
ev('compute();R.useIx.ams=70');
|
||||
const c0 = cash(ev);
|
||||
shift(ev);
|
||||
assert.equal(ev('S.ixp.ams'), 1, 'a remote port stops at 100G, and there is no LAG without a POP');
|
||||
assert.equal(cash(ev), c0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
64
tests/ix-downgrade.test.js
Normal file
64
tests/ix-downgrade.test.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = "ACT.start({});S.cash=1e8;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})";
|
||||
|
||||
test('an exchange port steps down one size at a time, and stops at the smallest', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("ACT.buyIx({city:'fra',tier:1,signed:1})");
|
||||
assert.equal(ev("S.ixp.fra"), 1, 'joined at 100G');
|
||||
assert.ok(ev("ixPortMo('fra',0)") < ev("ixPortMo('fra',1)"));
|
||||
assert.match(ev("ixSection('fra')"), /Downgrade 10G/, 'one button, naming the next size down');
|
||||
const cash = ev("S.cash");
|
||||
ev("ACT.downIx({city:'fra'})");
|
||||
assert.equal(ev("S.ixp.fra"), 0, 'down to 10G');
|
||||
assert.ok(ev("S.cash") >= cash - 1e6, 'a downgrade costs nothing up front');
|
||||
assert.doesNotMatch(ev("ixSection('fra')"), /Downgrade/, 'nothing below the smallest port');
|
||||
ev("ACT.downIx({city:'fra'})");
|
||||
assert.equal(ev("S.ixp.fra"), 0, 'the smallest port stays');
|
||||
ev("ACT.downIx({city:'ams'})");
|
||||
assert.equal(ev("S.ixp.ams"), undefined, 'a port you do not have stays that way');
|
||||
ev("compute()");
|
||||
assert.ok(ev("ixCap('fra')") <= 10 * ev("(S.ixn||{}).fra||1"), 'capacity follows the smaller port');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a transit port steps down one size at a time, with a button naming the next size down', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'cog',tier:2})");
|
||||
const id = ev("S.transit.find(t=>t.net==='cog'&&t.city==='fra').id");
|
||||
assert.equal(ev("S.transit.find(t=>t.id==='" + id + "').tier"), 2);
|
||||
ev("UI.tab='up'");
|
||||
assert.match(ev("cityPanel('fra')"), /Downgrade 100G/, 'one button, naming the next size down');
|
||||
ev(`ACT.downT({id:'${id}'})`);
|
||||
assert.equal(ev(`S.transit.find(t=>t.id==='${id}').tier`), 1, 'down one size');
|
||||
ev(`ACT.downT({id:'${id}'})`);
|
||||
assert.equal(ev(`S.transit.find(t=>t.id==='${id}').tier`), 0, 'and one more');
|
||||
ev(`ACT.downT({id:'${id}'})`);
|
||||
assert.equal(ev(`S.transit.find(t=>t.id==='${id}').tier`), 0, 'the smallest port stays');
|
||||
ev("ACT.downT({id:'nope'})");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a PNI steps down one size at a time, but not while an augment is on order', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev("S.pops.fra.rgen=3;S.pni.push({id:'pt1',net:'cog',city:'fra',tier:2});UI.tab='peer';compute()");
|
||||
assert.match(ev("cityPanel('fra')"), /Downgrade 100G/, 'one button, naming the next size down');
|
||||
ev("ACT.downP({id:'pt1'})");
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='pt1').tier"), 1, 'down one size');
|
||||
ev("S.pni.find(p=>p.id==='pt1').up={tier:1,n:2,ready:S.day+30};ACT.downP({id:'pt1'})");
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='pt1').tier"), 1, 'an augment on order blocks it');
|
||||
ev("S.pni.find(p=>p.id==='pt1').up=null;ACT.downP({id:'pt1'})");
|
||||
assert.equal(ev("pniMin('cog')"), 1, 'Cogentle, a Tier 1, sells no 10G PNIs');
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='pt1').tier"), 1, 'so its PNI stops at 100G');
|
||||
assert.doesNotMatch(ev("cityPanel('fra')"), /Downgrade 10G/, 'and offers no 10G step');
|
||||
ev("S.pni.push({id:'pt2',net:'cmc',city:'fra',tier:0});ACT.downP({id:'pt2'})");
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='pt2').tier"), 0, 'the smallest port stays');
|
||||
ev("S.pni.find(p=>p.id==='pt1').tier=1;S.pni.find(p=>p.id==='pt1').ready=S.day+9;ACT.downP({id:'pt1'})");
|
||||
assert.equal(ev("S.pni.find(p=>p.id==='pt1').tier"), 1, 'a PNI that is not up yet stays');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
39
tests/latency-offers.test.js
Normal file
39
tests/latency-offers.test.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// #273: a latency offer only asks for a ceiling something you can build meets. Pevek–Anadyr is 635 km apart as the
|
||||
// crow flies, but only a 1,717 km sea route joins them, so a 4.3 ms ceiling can never be met.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// Spawn many mars offers from a network at Pevek and Anadyr only: most are between the two.
|
||||
const marsOnly = "eval('('+spawnOffer.toString().replace('const t=pick(types)',\"const t='mars'\")+')')";
|
||||
const spawn = (ev, n) => ev(`(()=>{S.offers=[];const f=${marsOnly};for(let i=0;i<${n};i++)f();return JSON.stringify(S.offers.map(o=>[o.city,o.city2,o.latMax]));})()`);
|
||||
const start = (ev, cities) => ev(`ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;S.pops={};for(const c of ${JSON.stringify(cities)})S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};compute()`);
|
||||
|
||||
test('#273 no latency offer between Pevek and Anadyr: no buildable path meets the straight-line ceiling', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, ['pvs', 'dyr']);
|
||||
assert.ok(ev('lvl()') >= 13, 'mars offers are unlocked');
|
||||
assert.equal(ev("latMaxOf('pvs','dyr')"), 4.3);
|
||||
const pair = o => [o[0], o[1]].sort().join('-') === 'dyr-pvs';
|
||||
const offers = JSON.parse(spawn(ev, 60));
|
||||
assert.ok(offers.length > 0, 'mars offers still spawn');
|
||||
assert.deepEqual(offers.filter(pair), [], 'but none asks for 4.3 ms between Pevek and Anadyr');
|
||||
assert.ok(!(ev("latFloor('pvs','dyr')") <= 4.3), 'nothing on the map gets there in 4.3 ms');
|
||||
// Even with the player's own Low latency cable, 7.7 ms is the best there is.
|
||||
ev("S.links.push({id:'own1',a:'pvs',b:'dyr',kind:'df',own:true,sub:true,seaDesign:'express',sys:'roadm',ch:[],km:1717,cable:null,mo:1,trench:'own:own1',cut:0,day:0,ready:0,pairs:1});compute()");
|
||||
assert.ok(ev("bestLat('pvs','dyr')") > 4.3);
|
||||
assert.deepEqual(JSON.parse(spawn(ev, 60)).filter(pair), []);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#273 latency offers still come where a build meets the ceiling', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev, ['lon', 'nyc']);
|
||||
const offers = JSON.parse(spawn(ev, 60));
|
||||
assert.ok(offers.length > 0, 'London–New York has latency offers');
|
||||
for (const [a, b, max] of offers) assert.ok(ev(`latFloor('${a}','${b}')`) <= max, `${a}–${b} within ${max} ms is buildable`);
|
||||
// The floor is what bestLat() would read on the links it describes: a wave on the fastest London–New York cable.
|
||||
const f = ev("latFloor('lon','nyc')"), c = ev("Math.min(...cablesFor('lon','nyc').map(c=>c.km*Math.min(0.9,CAB[c.cid].lat||1)))/200+0.05");
|
||||
assert.ok(Math.abs(f - c) < 1e-9);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
// The MCP server's act tool (scripts/lib/mcp-commands.js, scripts/lib/mcp-page.js): typed, checked commands with
|
||||
// The MCP server's act tool (the page's agent facade, src/agent/): typed, checked commands with
|
||||
// outcomes and quotes, the raw reads (schema, catalog, state, results, ui), and screens beyond the side panel.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
|
@ -28,7 +28,7 @@ test('every action in the game is in exactly one class, so a new one forces a de
|
|||
assert.deepEqual(JSON.parse(acts).filter((x) => !all.includes(x)), [], 'every action is classified');
|
||||
assert.deepEqual(all.filter((x) => !JSON.parse(acts).includes(x)), [], 'every classified action exists');
|
||||
// Every argument domain resolves, and the tools' fixed vocabularies are the game's.
|
||||
const bad = ev(`(()=>{const {API_CMD,API_VIEW,API_SESSION,API_DOMAINS,API_TABLES,API_MADE}=window.__mcpCmds,out=[];
|
||||
const bad = ev(`(()=>{const out=[];
|
||||
for(const [n,s] of Object.entries({...API_CMD,...API_VIEW,...API_SESSION}))
|
||||
for(const [nm,d] of (s.args||[])) if(!['string','boolean','integer'].includes(d)&&!API_DOMAINS[d]) out.push(n+'.'+nm+': no domain '+d);
|
||||
for(const [n,d] of Object.entries(API_DOMAINS)) if(d.table&&!API_TABLES[d.table]&&!(d.table in API_MADE)) out.push('domain '+n+': no table '+d.table);
|
||||
|
|
@ -273,7 +273,7 @@ test('everything an action needs can be read: loan offers, conference keys, reci
|
|||
assert.equal(T('state', { path: 'no.such.path' }), null);
|
||||
assert.ok('pending' in T('ui') && !('hover' in T('ui')), 'the view state, without render scratch');
|
||||
assert.throws(() => T('schema', { section: 'nope' }), /No section/);
|
||||
assert.deepEqual(Object.keys(T('schema')).sort(), ['clock', 'commands', 'denied', 'domains', 'drafts', 'results', 'session', 'state', 'view']);
|
||||
assert.deepEqual(Object.keys(T('schema')).sort(), ['clock', 'commands', 'denied', 'domains', 'drafts', 'mode', 'results', 'session', 'state', 'view']);
|
||||
const a = T('actions');
|
||||
for (const x of ['buildLink(a,b,tier,cable?,route?,premiumCrossing?)', 'orderDf(a,b,source,system)', 'teDeploy(script)', 'renameGo(name)', 'rtbh(id?)', 'startScn(id)', 'dfSrc(v)']) assert.ok(a.includes(x), x);
|
||||
assert.deepEqual(s.errors(), []);
|
||||
|
|
|
|||
166
tests/mcp-http.test.js
Normal file
166
tests/mcp-http.test.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// The MCP server over HTTP (scripts/mcp.js --http): the same tools as stdio through the SDK's Streamable HTTP
|
||||
// handler, with the Host and Origin checked on every request, an optional bearer token, and files confined.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
const { createSession } = require('../scripts/lib/mcp-game');
|
||||
const { serverFactory, createHttpServer, serial, parseListen, allowedHosts, MCP_PATH } = require('../scripts/mcp');
|
||||
|
||||
const INIT = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } };
|
||||
|
||||
// One server on a free loopback port for the length of fn.
|
||||
async function withServer(opts, fn) {
|
||||
const session = createSession({ saveDir: opts.saveDir === undefined ? null : opts.saveDir });
|
||||
const server = createHttpServer(serverFactory(session), { host: '127.0.0.1', allow: opts.allow, token: opts.token });
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
try { await fn(base); } finally { await new Promise((r) => server.close(r)); }
|
||||
}
|
||||
|
||||
// A JSON-RPC message as an MCP client posts it; the answer may come as JSON or as one SSE event. node:http, not fetch,
|
||||
// because fetch will not send a Host header of the caller's choosing.
|
||||
let seq = 0;
|
||||
function post(base, pathname, payload, headers = {}) {
|
||||
const u = new URL(base), data = payload === undefined ? '' : JSON.stringify(payload);
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = http.request({ host: u.hostname, port: u.port, path: pathname, method: 'POST',
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data), ...headers } }, (res) => {
|
||||
let text = '';
|
||||
res.setEncoding('utf8');
|
||||
res.on('data', (d) => { text += d; });
|
||||
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text }));
|
||||
});
|
||||
req.on('error', reject);
|
||||
req.end(data);
|
||||
});
|
||||
}
|
||||
async function rpc(base, method, params, headers = {}) {
|
||||
const res = await post(base, MCP_PATH, { jsonrpc: '2.0', id: ++seq, method, params }, headers);
|
||||
let body = null;
|
||||
if (/event-stream/.test(res.headers['content-type'] || '')) {
|
||||
const data = res.text.split('\n').filter((l) => l.startsWith('data: ')).map((l) => JSON.parse(l.slice(6)));
|
||||
body = data.find((d) => d.id !== undefined) || null;
|
||||
} else if (res.text) body = JSON.parse(res.text);
|
||||
return { status: res.status, headers: res.headers, body };
|
||||
}
|
||||
const call = async (base, name, args = {}, headers) => {
|
||||
const r = await rpc(base, 'tools/call', { name, arguments: args }, headers);
|
||||
const c = r.body && r.body.result;
|
||||
return { ...r, isError: !!(c && c.isError), text: c ? c.content[0].text : null, json: c && !c.isError ? JSON.parse(c.content[0].text) : null };
|
||||
};
|
||||
|
||||
test('HTTP: initialize, list the tools and play, as over stdio', () => withServer({}, async (base) => {
|
||||
const init = await rpc(base, 'initialize', INIT);
|
||||
assert.equal(init.status, 200);
|
||||
assert.equal(init.body.result.protocolVersion, '2025-06-18');
|
||||
assert.equal(init.body.result.serverInfo.name, 'seriesoftubes');
|
||||
assert.match(init.body.result.instructions, /Time moves only with advance/);
|
||||
const list = await rpc(base, 'tools/list', {});
|
||||
assert.ok(list.body.result.tools.length >= 22);
|
||||
assert.deepEqual(list.body.result.tools.find((t) => t.name === 'network').inputSchema.required, ['network'], 'the schemas as written');
|
||||
const st = await call(base, 'status');
|
||||
assert.equal(st.json.home, 'Frankfurt');
|
||||
await call(base, 'act', { action: 'launchBB', args: { city: 'fra' } });
|
||||
const a = await call(base, 'advance', { days: 3 });
|
||||
assert.equal(a.json.daysRun, 3);
|
||||
assert.equal((await call(base, 'status')).json.day, 3, 'one game, kept between requests');
|
||||
// Arguments are checked against the tool's schema before the game sees them; the game's own errors stay its own.
|
||||
const extra = await call(base, 'status', { nope: 1 });
|
||||
assert.ok(extra.isError && /additional properties/.test(extra.text));
|
||||
const bad = await call(base, 'network', { network: 'no such thing at all' });
|
||||
assert.ok(bad.isError && /No network matches/.test(bad.text));
|
||||
assert.equal((await rpc(base, 'tools/call', { name: 'nope', arguments: {} })).body.error.code, -32602);
|
||||
assert.equal((await post(base, '/elsewhere', {})).status, 404);
|
||||
}));
|
||||
|
||||
test('HTTP: a Host this machine does not answer to, or a web page\'s Origin, is refused', () => withServer({ allow: ['tubes.lan'] }, async (base) => {
|
||||
const port = new URL(base).port;
|
||||
// DNS rebinding: a name someone else's DNS points at 127.0.0.1.
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { host: `evil.example:${port}` })).status, 403);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { host: `tubes.lan:${port}` })).status, 200, 'unless the operator allowed it');
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { host: `localhost:${port}` })).status, 200);
|
||||
// A website open in a browser on this machine.
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { origin: 'https://evil.example' })).status, 403);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { origin: 'null' })).status, 403);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { origin: 'http://localhost:6274' })).status, 200, 'a local browser-based client may');
|
||||
}));
|
||||
|
||||
test('HTTP: with a token, every request must carry it', () => withServer({ token: 's3cret-token' }, async (base) => {
|
||||
const none = await rpc(base, 'tools/list', {});
|
||||
assert.equal(none.status, 401);
|
||||
assert.match(none.headers['www-authenticate'], /^Bearer/);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { authorization: 'Bearer wrong' })).status, 401);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { authorization: 'Basic czNjcmV0LXRva2Vu' })).status, 401);
|
||||
assert.equal((await rpc(base, 'tools/list', {}, { authorization: 'Bearer s3cret-token' })).status, 200);
|
||||
}));
|
||||
|
||||
test('HTTP: saves as JSON only, unless --save-dir, and then nowhere outside it', async () => {
|
||||
await withServer({}, async (base) => {
|
||||
for (const [tool, args] of [['load_save', { path: '/etc/hosts' }], ['export_save', { path: path.join(os.tmpdir(), 'x.json') }]]) {
|
||||
const r = await call(base, tool, args);
|
||||
assert.ok(r.isError && /JSON only/.test(r.text), `${tool} refuses a path`);
|
||||
}
|
||||
const out = await call(base, 'export_save');
|
||||
assert.equal(out.json.app, 'series-of-tubes');
|
||||
const back = await call(base, 'load_save', { json: JSON.stringify(out.json) });
|
||||
assert.equal(back.json.home, 'Frankfurt');
|
||||
});
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-saves-')), dir = fs.realpathSync(root);
|
||||
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-outside-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(outside, 'secret.json'), '{"secret":1}');
|
||||
fs.symlinkSync(path.join(outside, 'secret.json'), path.join(dir, 'link.json'));
|
||||
fs.symlinkSync(outside, path.join(dir, 'out'));
|
||||
await withServer({ saveDir: dir }, async (base) => {
|
||||
const w = await call(base, 'export_save', { path: 'mine.json' });
|
||||
assert.equal(w.json.wrote, path.join(dir, 'mine.json'));
|
||||
assert.equal((await call(base, 'load_save', { path: 'mine.json' })).json.home, 'Frankfurt');
|
||||
for (const [tool, p, why] of [['load_save', '../' + path.basename(outside) + '/secret.json', /outside/], ['load_save', '/etc/hosts', /outside|no such file/],
|
||||
['load_save', 'link.json', /outside/], ['load_save', 'out/secret.json', /outside/], ['export_save', 'out/x.json', /outside/],
|
||||
['export_save', 'link.json', /symbolic link|outside/], ['export_save', '../escape.json', /outside/]]) {
|
||||
const r = await call(base, tool, { path: p });
|
||||
assert.ok(r.isError && why.test(r.text), `${tool} ${p}: ${r.text}`);
|
||||
}
|
||||
assert.equal(fs.readFileSync(path.join(outside, 'secret.json'), 'utf8'), '{"secret":1}', 'nothing outside was touched');
|
||||
assert.ok(!fs.existsSync(path.join(os.tmpdir(), 'escape.json')));
|
||||
});
|
||||
} finally { fs.rmSync(root, { recursive: true, force: true }); fs.rmSync(outside, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('calls run one at a time, in the order they came', async () => {
|
||||
const q = serial(), log = [];
|
||||
const slow = (n, ms) => q(async () => { log.push(`start ${n}`); await new Promise((r) => setTimeout(r, ms)); log.push(`end ${n}`); return n; });
|
||||
const failing = q(async () => { log.push('start bad'); throw new Error('bad'); });
|
||||
const r = await Promise.allSettled([slow(1, 30), failing, slow(2, 1)]);
|
||||
assert.deepEqual(log, ['start bad', 'start 1', 'end 1', 'start 2', 'end 2']);
|
||||
assert.deepEqual(r.map((x) => x.status), ['fulfilled', 'rejected', 'fulfilled'], 'a failed call does not stop the queue');
|
||||
});
|
||||
|
||||
test('--http: where it listens, which Host names it answers to, and what it says about it', async () => {
|
||||
assert.deepEqual(parseListen('7777'), { host: '127.0.0.1', port: 7777 });
|
||||
assert.deepEqual(parseListen('0.0.0.0:7777'), { host: '0.0.0.0', port: 7777 });
|
||||
assert.deepEqual(parseListen('[::1]:7777'), { host: '::1', port: 7777 });
|
||||
assert.throws(() => parseListen(true), /HOST:\]PORT/);
|
||||
assert.throws(() => parseListen('localhost'), /HOST:\]PORT/);
|
||||
const loop = allowedHosts('127.0.0.1');
|
||||
assert.ok(loop.includes('localhost') && loop.includes('127.0.0.1') && !loop.includes('0.0.0.0'));
|
||||
const all = allowedHosts('0.0.0.0');
|
||||
assert.ok(all.includes('127.0.0.1'), 'bound to every address: every address of this machine');
|
||||
// The server itself, bound beyond loopback without a token: it runs, and says so loudly.
|
||||
const child = spawn(process.execPath, [path.join(__dirname, '..', 'scripts', 'mcp.js'), '--http', '0.0.0.0:0'], { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, SOT_MCP_TOKEN: '' } });
|
||||
try {
|
||||
let err = '';
|
||||
await new Promise((res, rej) => { child.stderr.on('data', (d) => { err += d; if (/WARNING/.test(err) && /JSON only|--save-dir/.test(err)) res(); }); child.on('exit', () => rej(new Error(err))); });
|
||||
assert.match(err, /MCP server .* on http:\/\/.*:\d+\/mcp/);
|
||||
assert.match(err, /WARNING: bound to 0\.0\.0\.0, beyond this machine, without a token/);
|
||||
} finally { child.kill(); }
|
||||
const bad = spawn(process.execPath, [path.join(__dirname, '..', 'scripts', 'mcp.js'), '--save-dir', os.tmpdir()], { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let msg = '';
|
||||
bad.stderr.on('data', (d) => { msg += d; });
|
||||
assert.equal(await new Promise((r) => bad.on('exit', r)), 1);
|
||||
assert.match(msg, /--save-dir is an --http option/);
|
||||
});
|
||||
83
tests/mcp-parity.test.js
Normal file
83
tests/mcp-parity.test.js
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
// One MCP session, two places: the same scripted moves through the headless server's own page and through the agent
|
||||
// relay into a page in a "browser" (a jsdom page connected to an in-process relay, the player's clock set to the
|
||||
// agent's) must give the same outcomes, the same money and the same game. The facade is one piece of code; this checks
|
||||
// that the transport, the async days and the player's rules change nothing a tool would see in a plain game.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const { load } = require('./harness');
|
||||
const { createRelay } = require('../scripts/agent/relay');
|
||||
const { createSession, TOOLS } = require('../scripts/lib/mcp-game');
|
||||
const { createBrowserSession } = require('../scripts/lib/mcp-browser');
|
||||
|
||||
const PORT = 9399 + (process.pid % 400);
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const HEADLESS_JS = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'mcp-headless.js'), 'utf8');
|
||||
|
||||
const SCRIPT = [
|
||||
['status'],
|
||||
['act', { action: 'launchBB', args: { city: 'fra' } }],
|
||||
['act', { action: 'buyTransit', args: { city: 'fra', net: 'cog', tier: 1 } }],
|
||||
['act', { action: 'buildLink', args: { a: 'fra', b: 'ams', tier: 1 } }],
|
||||
['act', { action: 'buildPop', args: { city: 'ams' } }],
|
||||
['act', { action: 'buyTransit', args: { city: 'fra', net: 'nope', tier: 1 } }],
|
||||
['act', { action: 'pni', args: { city: 'fra', net: 'lvl', tier: 1 }, dryRun: true }],
|
||||
['act', { action: 'buyIx', args: { city: 'fra', tier: 1 } }],
|
||||
['act', { action: 'buildPop', args: { city: 'par' } }],
|
||||
['act', { action: 'dkAccept' }],
|
||||
['advance', { days: 30 }],
|
||||
['status'],
|
||||
['hot_spots', { limit: 3 }],
|
||||
['network', { network: 'ggl' }],
|
||||
['traceroute', { from: 'fra', to: 'ggl' }],
|
||||
['peering_check', { network: 'nfx' }],
|
||||
['panel', { city: 'fra', tab: 'peer' }],
|
||||
['act', { action: 'renameGo', args: { name: 'Twin Tubes' } }],
|
||||
['actions'],
|
||||
['advance', { days: 60 }],
|
||||
['state', { path: 'pops' }],
|
||||
['results', { path: 'served' }],
|
||||
['status'],
|
||||
];
|
||||
// What differs by nature, not by game: how long a day took on this machine, and entity ids (uid() reads the clock).
|
||||
const strip = (v) => JSON.parse(JSON.stringify(v, (k, x) => (k === 'timing' || k === 'id' ? undefined : x)));
|
||||
async function play(s) {
|
||||
const out = [];
|
||||
for (const [name, args = {}] of SCRIPT) {
|
||||
try { out.push([name, strip(await TOOLS.find((t) => t.name === name).run(s, args))]); } catch (e) { out.push([name, { error: String(e.message) }]); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
test('the same scripted session gives the same outcomes headless and through the relay', async () => {
|
||||
const headless = createSession();
|
||||
const here = await play(headless);
|
||||
headless.close();
|
||||
|
||||
const srv = http.createServer((q, r) => { r.writeHead(404); r.end(); });
|
||||
const relay = createRelay({ server: srv });
|
||||
await new Promise((r) => srv.listen(PORT, '127.0.0.1', r));
|
||||
// The player's tab: the same page and seed, the same first game, and the agent's clock in Settings.
|
||||
const a = load({ url: `http://127.0.0.1:${PORT}/`, seed: 12345, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true, ms: 0 }) } });
|
||||
const s = createBrowserSession({ port: PORT });
|
||||
try {
|
||||
a.ev(HEADLESS_JS);
|
||||
a.ev("__mcpHeadless.newGame({city:'fra',name:'Scratch Networks',preset:'oncall'})");
|
||||
a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:${PORT}';apiAgentSync()`);
|
||||
await wait(400);
|
||||
assert.deepEqual(await s.ready({ waitMs: 5000 }), { ok: true }, 'the tab serves this checkout\'s contract');
|
||||
const there = await play(s);
|
||||
for (let i = 0; i < SCRIPT.length; i++) assert.deepEqual(there[i], here[i], `step ${i}: ${SCRIPT[i][0]} ${JSON.stringify(SCRIPT[i][1] || {})}`);
|
||||
assert.ok(here.some(([n, v]) => n === 'act' && v.outcome === 'decision'), 'the script meets a question');
|
||||
assert.ok(here.some(([, v]) => v.error), 'and an error');
|
||||
assert.equal(a.ev('S.day'), 90);
|
||||
assert.deepEqual(a.errors, []);
|
||||
} finally {
|
||||
a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)");
|
||||
await s.close();
|
||||
relay.close();
|
||||
await new Promise((r) => srv.close(r));
|
||||
}
|
||||
});
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
// The MCP server (scripts/mcp.js): an AI client plays, inspects and debugs the game through typed tools.
|
||||
// The MCP server (scripts/mcp.js): an AI client plays, inspects and debugs the game through typed tools. Over stdio
|
||||
// here; tests/mcp-http.test.js has the HTTP transport.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
|
|
@ -27,7 +28,7 @@ test('speaks MCP over stdio: initialize, list tools, call one, and errors as err
|
|||
assert.equal(init.result.protocolVersion, '2025-06-18');
|
||||
assert.equal(init.result.serverInfo.name, 'seriesoftubes');
|
||||
assert.ok(init.result.capabilities.tools);
|
||||
assert.equal((await ask({ id: 9, method: 'initialize', params: { protocolVersion: '1999-01-01' } })).result.protocolVersion, '2025-11-25', 'an unknown version gets the newest');
|
||||
assert.equal((await ask({ id: 9, method: 'initialize', params: { protocolVersion: '1999-01-01', capabilities: {}, clientInfo: { name: 'test', version: '1' } } })).result.protocolVersion, '2025-11-25', 'an unknown version gets the newest');
|
||||
await ask({ method: 'notifications/initialized' });
|
||||
const list = await ask({ id: 2, method: 'tools/list' });
|
||||
const names = list.result.tools.map((t) => t.name);
|
||||
|
|
@ -162,3 +163,36 @@ test('only game actions: files, slots, settings and the clock stay out of reach'
|
|||
assert.throws(() => T('act', { action: 'noSuchThing' }), /no action/);
|
||||
assert.throws(() => T('click', { button: 99 }), /No button 99/);
|
||||
});
|
||||
test('a running clock: days pass on their own, advance is refused and wait reads them', async () => {
|
||||
const s = createSession({ clock: 'realtime', paceMs: 30 }), T = tools(s);
|
||||
try {
|
||||
assert.equal(T('schema', { section: 'mode' }).clock, 'realtime');
|
||||
assert.match(T('schema', { section: 'clock' }), /runs on its own/);
|
||||
assert.throws(() => T('advance', { days: 1 }), /use wait/);
|
||||
const w = await T('wait', { days: 3, maxSeconds: 10 });
|
||||
assert.ok(w.daysRun >= 3, `three days passed by themselves (${w.daysRun})`);
|
||||
assert.equal(w.stoppedBecause, null);
|
||||
assert.ok(Array.isArray(w.log) && typeof w.cashChange === 'number');
|
||||
assert.deepEqual(s.errors(), []);
|
||||
} finally { s.close(); }
|
||||
// The agent's clock stands still between calls, and wait says to use advance.
|
||||
const s2 = createSession(), T2 = tools(s2);
|
||||
const d0 = T2('status').day;
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
assert.equal(T2('status').day, d0);
|
||||
await assert.rejects(T2('wait', { days: 1 }), /use advance/);
|
||||
});
|
||||
|
||||
test('--clock realtime over stdio: the instructions and the schema say whose clock it is', async () => {
|
||||
const child = spawn(process.execPath, [path.join(__dirname, '..', 'scripts', 'mcp.js'), '--clock', 'realtime', '--pace', '50'], { stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
let buf = '';
|
||||
const lines = [], waiters = [];
|
||||
child.stdout.on('data', (d) => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { lines.push(JSON.parse(buf.slice(0, i))); buf = buf.slice(i + 1); waiters.splice(0).forEach((w) => w()); } });
|
||||
const ask = async (msg) => { child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n'); const f = () => lines.find((l) => l.id === msg.id); while (!f()) await new Promise((r) => waiters.push(r)); return f(); };
|
||||
try {
|
||||
const init = await ask({ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } });
|
||||
assert.match(init.result.instructions, /runs on its own/);
|
||||
const mode = JSON.parse((await ask({ id: 2, method: 'tools/call', params: { name: 'schema', arguments: { section: 'mode' } } })).result.content[0].text);
|
||||
assert.deepEqual({ backend: mode.backend, clock: mode.clock, paceMs: mode.paceMs, transport: mode.transport }, { backend: 'headless', clock: 'realtime', paceMs: 50, transport: 'jsdom' });
|
||||
} finally { child.kill(); }
|
||||
});
|
||||
|
|
|
|||
|
|
@ -58,6 +58,20 @@ test('pages: every local file the site refers to is in the build', () => {
|
|||
for (const m of html.matchAll(/<link[^>]*rel="stylesheet"[^>]*href="(https?:[^"]+)"/g)) assert.match(m[1], /^https:\/\/fonts\.googleapis\.com\//);
|
||||
});
|
||||
|
||||
test('pages: the build carries no agent code, and is the page assembled without it', () => {
|
||||
// src/agent/ (the facade the MCP server drives) is development-only: one line in src/index.html, expanded by
|
||||
// the dev server and the MCP server, never by the build (docs/adr/0004-dev-only-code.md).
|
||||
const html = read('index.html');
|
||||
assert.doesNotMatch(html, /@include/, 'no include marker survives');
|
||||
for (const n of ['TUBES', 'API_CMD', 'API_DOMAINS', 'apiCall', 'apiDispatch']) assert.doesNotMatch(html, new RegExp(`\\b${n}\\b`), `${n} is not shipped`);
|
||||
const { load } = require('./harness');
|
||||
const { ev, errors } = load({ file: path.join(OUT, 'index.html') });
|
||||
assert.equal(ev('typeof TUBES'), 'undefined');
|
||||
ev("ACT.start({});ACT.launchBB({city:'fra'});for(let i=0;i<10;i++)dayTick()");
|
||||
assert.ok(ev('S.day') >= 10);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => {
|
||||
const dir = path.join(root, '.github', 'workflows');
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
|
|
|
|||
62
tests/traceroute-modes.test.js
Normal file
62
tests/traceroute-modes.test.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A triangle: Frankfurt-Amsterdam direct, or round through Paris.
|
||||
function setup(ev) {
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0");
|
||||
ev("ACT.launchBB({city:'fra'});ACT.buildPop({city:'par'});ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
|
||||
[['fra', 'par'], ['par', 'ams'], ['fra', 'ams']].forEach(([a, b], i) => ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal();S.links[S.links.length-1].tag=${i}`));
|
||||
ev("var D=S.links.find(l=>l.tag===2);compute()");
|
||||
}
|
||||
const hops = (ev, mode) => ev(`trPaths('fra',${JSON.stringify(mode)}).path('ams').length`);
|
||||
|
||||
test('a trace can follow the metrics, the lowest latency or the quietest links', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
assert.equal(hops(ev, 'normal'), 1, 'the short way round is the direct link');
|
||||
ev("ACT.setMetric({id:D.id,v:'avoid'})");
|
||||
assert.equal(hops(ev, 'normal'), 2, 'an avoided direct link sends the metric route round through Paris');
|
||||
assert.equal(hops(ev, 'fast'), 1, 'but lowest latency ignores the metric and goes direct');
|
||||
ev("ACT.setMetric({id:D.id,v:'normal'});compute()");
|
||||
assert.equal(hops(ev, 'scenic'), 1, 'with nothing busy, scenic is the plain route');
|
||||
ev("R.load[D.id]=capOf(D)*0.95");
|
||||
assert.equal(hops(ev, 'scenic'), 2, 'a busy direct link sends scenic round the quiet way');
|
||||
assert.equal(hops(ev, 'normal'), 1, 'while the metric route does not care');
|
||||
assert.equal(ev("trPaths('fra').path('ams').length"), 1, 'old callers without a mode still follow the metrics');
|
||||
assert.equal(JSON.parse(ev("JSON.stringify(traceroute('fra',{city:'ams'},'nonsense'))")).text.includes('traceroute to'), true, 'an unknown mode falls back');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the looking glass has the three route buttons, like a customer circuit, and each one re-runs the trace', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
const doc = dom.window.document;
|
||||
setup(ev);
|
||||
ev("ACT.setMetric({id:D.id,v:'avoid'});ACT.trace({city:'fra'})");
|
||||
const btns = () => [...doc.querySelectorAll('[data-act="traceMode"]')];
|
||||
assert.equal(doc.getElementById('trMode'), null, 'no drop-down');
|
||||
assert.deepEqual(btns().map(b => JSON.parse(b.dataset.args).m), ['normal', 'fast', 'scenic']);
|
||||
assert.deepEqual(btns().map(b => b.className.includes('pink')), [true, false, false], 'the chosen one is highlighted');
|
||||
doc.getElementById('trTo').value = 'city:ams';
|
||||
btns()[1].click();
|
||||
assert.equal(ev("UI.trMode"), 'fast');
|
||||
assert.deepEqual(btns().map(b => b.className.includes('pink')), [false, true, false]);
|
||||
assert.match(doc.querySelector('.term').textContent, /traceroute to ams/, 'the chosen destination is kept');
|
||||
assert.equal((doc.querySelector('.term').textContent.match(/cr1\.ams/g) || []).length, 1, 'one hop: straight there');
|
||||
ev("ACT.traceMode({m:'nonsense'})");
|
||||
assert.equal(ev("UI.trMode"), 'fast', 'an unknown mode changes nothing');
|
||||
ev("ACT.traceRun()");
|
||||
assert.equal(ev("UI.trMode"), 'fast', 'Run keeps the mode');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a trace that does not follow the metrics says it shows a circuit’s path, not the internet traffic’s', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
const doc = dom.window.document;
|
||||
setup(ev);
|
||||
ev("ACT.trace({city:'fra'})");
|
||||
assert.doesNotMatch(doc.getElementById('modal').textContent, /follows the metrics/);
|
||||
[...doc.querySelectorAll('[data-act="traceMode"]')][2].click();
|
||||
assert.match(doc.getElementById('modal').textContent, /follows the metrics\. This is the path a customer circuit on/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue