Files
aevolution/apps/evo-admin-api/portal/app.js
T
dingoandClaude Opus 5.5 cc2eaf2e05
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m42s
Foundation / checks (checks) (push) Successful in 6s
Foundation / checks (client) (push) Successful in 5s
Foundation / postgres-tools (push) Successful in 31s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / server-image (push) Successful in 4m45s
Foundation / checks (network) (push) Successful in 4s
Foundation / image (push) Successful in 5m31s
feat(cellular): energy cycles back through the spent pool (ADR-0182 section 14)
Energy cells used went to the region's heat store and never returned, so a
region without photosynthesizers drained: region 16's wildlife ate its energy
and starved, and its matter-only drip filled the deposit limit.

Two optional rules-13 tuning keys, adoptable live: spent.heat_recycle_per_mille
moves that share of the heat store to the spent pool at the end of every tick,
before the drip (1,000 closes the loop and returns heat built up before), and
spent.drip_absorb lets a drip at the deposit limit join the first existing bubble
at or after its spot. Both use the reserved word after the offer interval, so
rules without them keep their bytes, digests, checkpoints and replays. The DEV
revamp file turns both on. The region view reports heat and the cycle; the
portal counts heat in the region's energy and ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:18:24 -04:00

1533 lines
85 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ADR-0182 admin portal. Keycloak sign-in (authorization code with PKCE), then the
// admin API on this origin. Tokens stay in this tab: the access token in memory, the refresh
// and ID tokens in sessionStorage so a reload keeps the session. No third-party code.
const store = {
get: (k) => { try { return sessionStorage.getItem(k); } catch { return null; } },
set: (k, v) => { try { sessionStorage.setItem(k, v); } catch { /* private mode */ } },
drop: (...ks) => { try { ks.forEach((k) => sessionStorage.removeItem(k)); } catch { /* */ } },
};
let config = null;
let access = null; // { token, expires (ms) }
let refreshing = null; // In-flight refresh promise.
// ---------- DOM helpers (textContent only: nothing from the API is parsed as HTML) ----------
function h(tag, attrs = {}, ...children) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'style') Object.assign(el.style, v); // CSSOM: the CSP refuses style attributes.
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
for (const c of children.flat()) {
if (c === null || c === undefined || c === false) continue;
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
return el;
}
const main = () => document.getElementById('main');
function show(...nodes) { main().replaceChildren(...nodes); }
// ---------- Theme: the system's, or light or dark as chosen (kept in this browser) ----------
function savedTheme() { try { return localStorage.getItem('theme') || 'system'; } catch { return 'system'; } }
function applyTheme(choice) {
const root = document.documentElement;
if (choice === 'light' || choice === 'dark') root.dataset.theme = choice;
else delete root.dataset.theme;
for (const b of document.querySelectorAll('[data-theme-choice]')) b.classList.toggle('on', b.dataset.themeChoice === choice);
window.dispatchEvent(new Event('themechange'));
}
applyTheme(savedTheme());
for (const b of document.querySelectorAll('[data-theme-choice]')) {
b.addEventListener('click', () => {
try { localStorage.setItem('theme', b.dataset.themeChoice); } catch { /* private mode */ }
applyTheme(b.dataset.themeChoice);
});
}
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => window.dispatchEvent(new Event('themechange')));
// ---------- Formatting ----------
const fmtInt = (n) => (n === null || n === undefined ? '—' : Number(n).toLocaleString());
function fmtUnit(value, units) {
if (value === null || value === undefined) return '—';
let v = Number(value), i = 0;
while (Math.abs(v) >= 1000 && i < units.length - 1) { v /= 1000; i++; }
return `${v >= 100 || i === 0 ? Math.round(v) : v.toFixed(v >= 10 ? 1 : 2)} ${units[i]}`;
}
const fmtEnergy = (pj) => fmtUnit(pj, ['pJ', 'nJ', 'µJ', 'mJ', 'J']);
const fmtMass = (fg) => fmtUnit(fg, ['fg', 'pg', 'ng', 'µg', 'mg']);
const fmtLength = (um) => fmtUnit(um, ['µm', 'mm', 'm']);
function fmtTime(seconds) {
if (!seconds) return '—';
return new Date(seconds * 1000).toLocaleString();
}
function fmtAgo(seconds) {
if (!seconds) return '—';
const d = Math.round(Date.now() / 1000 - seconds);
if (Math.abs(d) < 60) return d >= 0 ? `${d}s ago` : `in ${-d}s`;
const m = Math.round(d / 60);
if (Math.abs(m) < 60) return m >= 0 ? `${m}m ago` : `in ${-m}m`;
const hr = Math.round(m / 60);
if (Math.abs(hr) < 48) return hr >= 0 ? `${hr}h ago` : `in ${-hr}h`;
return `${Math.round(hr / 24)}d ago`;
}
const short = (id) => (id ? `${id.slice(0, 8)}…` : '—');
function fmtDuration(seconds) {
const s = Math.max(0, Math.round(seconds || 0));
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
if (m < 60) return `${m}m ${s % 60}s`;
const hr = Math.floor(m / 60);
return hr < 48 ? `${hr}h ${m % 60}m` : `${Math.floor(hr / 24)}d ${hr % 24}h`;
}
// ---------- Sign-in ----------
function b64url(bytes) {
let s = '';
bytes.forEach((b) => { s += String.fromCharCode(b); });
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function randomText(n) {
const a = new Uint8Array(n);
crypto.getRandomValues(a);
return b64url(a);
}
const endpoint = (name) => `${config.issuer}/protocol/openid-connect/${name}`;
const redirectUri = () => `${location.origin}/`;
async function signIn() {
const verifier = randomText(48);
const state = randomText(16);
const challenge = b64url(new Uint8Array(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
store.set('pkce_verifier', verifier);
store.set('pkce_state', state);
store.set('return_to', location.hash || '#/accounts');
const url = new URL(endpoint('auth'));
url.search = new URLSearchParams({
client_id: config.client_id, redirect_uri: redirectUri(), response_type: 'code',
response_mode: 'query', scope: 'openid email', state, code_challenge: challenge,
code_challenge_method: 'S256',
});
location.assign(url);
}
async function tokenRequest(body) {
const res = await fetch(endpoint('token'), {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ client_id: config.client_id, ...body }),
});
if (!res.ok) throw new Error(`token endpoint ${res.status}`);
const t = await res.json();
access = { token: t.access_token, expires: Date.now() + (t.expires_in || 60) * 1000 };
if (t.refresh_token) store.set('refresh_token', t.refresh_token);
if (t.id_token) store.set('id_token', t.id_token);
return access.token;
}
async function finishSignIn() {
const params = new URLSearchParams(location.search);
const code = params.get('code');
if (!code && !params.get('error')) return false;
const expected = store.get('pkce_state');
const verifier = store.get('pkce_verifier');
const returnTo = store.get('return_to') || '#/accounts';
store.drop('pkce_state', 'pkce_verifier', 'return_to');
history.replaceState(null, '', `/${returnTo}`);
if (params.get('error') || !expected || params.get('state') !== expected || !verifier) {
throw new Error(`sign-in was not completed (${params.get('error') || 'state mismatch'})`);
}
await tokenRequest({ grant_type: 'authorization_code', code, redirect_uri: redirectUri(),
code_verifier: verifier });
return true;
}
async function token() {
if (access && access.expires - Date.now() > 30000) return access.token;
const refresh = store.get('refresh_token');
if (!refresh) return null;
refreshing = refreshing || tokenRequest({ grant_type: 'refresh_token', refresh_token: refresh })
.catch(() => { store.drop('refresh_token'); access = null; return null; })
.finally(() => { refreshing = null; });
return refreshing;
}
function signOut() {
const idToken = store.get('id_token');
store.drop('refresh_token', 'id_token');
access = null;
const url = new URL(endpoint('logout'));
url.search = new URLSearchParams({
client_id: config.client_id, post_logout_redirect_uri: redirectUri(),
...(idToken ? { id_token_hint: idToken } : {}),
});
location.assign(url);
}
class ApiError extends Error {
constructor(status, code, detail = {}) { super(code || `HTTP ${status}`); this.status = status; this.code = code; this.detail = detail; }
}
// `body` is sent as plain text (only tuning revisions take one).
async function api(path, retry = true, method = 'GET', body = undefined) {
const t = await token();
if (!t) throw new ApiError(401, 'signed_out');
const headers = { Authorization: `Bearer ${t}` };
if (body !== undefined) headers['Content-Type'] = 'text/plain; charset=utf-8';
const res = await fetch(path, { method, headers, body, cache: 'no-store' });
if (res.status === 401 && retry) { access = null; return api(path, false, method, body); }
if (!res.ok) {
let detail = {};
try { detail = await res.json(); } catch { /* plain text */ }
throw new ApiError(res.status, detail.error || (res.status === 413 ? 'too_large' : null), detail);
}
return res.json();
}
// ---------- Sortable tables ----------
function table(columns, rows, { onRow, sortKey, sortUp = false } = {}) {
let key = sortKey, up = sortUp;
const wrap = h('div', { class: 'table-wrap' });
const draw = () => {
const col = columns.find((c) => c.key === key);
const sorted = col ? [...rows].sort((a, b) => {
const va = col.sort ? col.sort(a) : a[col.key];
const vb = col.sort ? col.sort(b) : b[col.key];
const r = va === vb ? 0 : va === null || va === undefined ? 1 : vb === null || vb === undefined ? -1 : va < vb ? -1 : 1;
return up ? r : -r;
}) : rows;
const head = h('tr', {}, columns.map((c) => h('th', {
class: [c.num ? 'num' : '', c.key === key ? `sorted${up ? ' up' : ''}` : ''].join(' ').trim() || null,
onclick: () => { if (key === c.key) up = !up; else { key = c.key; up = !c.num; } draw(); },
}, c.label)));
const body = sorted.map((r) => h('tr', { class: onRow ? 'clickable' : null, onclick: onRow ? () => onRow(r) : null },
columns.map((c) => h('td', { class: c.num ? 'num' : null }, c.render ? c.render(r) : (r[c.key] ?? '—')))));
wrap.replaceChildren(h('table', {}, h('thead', {}, head), h('tbody', {}, body.length ? body
: h('tr', {}, h('td', { colspan: columns.length, class: 'muted' }, 'Nothing to show.')))));
};
draw();
return wrap;
}
function statusBadge(a) {
const life = h('span', { class: `badge ${a.status === 'alive' ? 'alive' : a.status === 'dead' ? 'dead' : ''}` },
a.status === 'no_life' ? 'no life' : a.status);
return a.banned ? h('span', {}, life, ' ', h('span', { class: 'badge dead' }, 'banned')) : life;
}
function sessionBadge(a) {
return a.logged_in ? h('span', { class: 'badge online' }, `online · region ${a.control_region}`)
: h('span', { class: 'muted' }, 'offline');
}
// ---------- Pages ----------
let stopPage = () => {};
async function accountsPage() {
const data = await api('/api/accounts');
const search = h('input', { type: 'search', placeholder: 'Filter by account, subject or status' });
const holder = h('div');
const columns = [
{ key: 'account', label: 'Account', render: (a) => h('span', { class: 'mono', title: a.account }, short(a.account)) },
{ key: 'subject', label: 'Keycloak subject', render: (a) => h('span', { class: 'mono muted', title: a.subject || '' }, a.subject ? short(a.subject) : '—') },
{ key: 'status', label: 'Status', render: statusBadge },
{ key: 'logged_in', label: 'Session', render: sessionBadge, sort: (a) => (a.logged_in ? 1 : 0) },
{ key: 'active_region', label: 'Region', render: (a) => a.active_region ?? '—', sort: (a) => Number(a.active_region ?? -1) },
{ key: 'lives', label: 'Lives', num: true },
{ key: 'deaths', label: 'Deaths', num: true },
{ key: 'resets', label: 'Resets', num: true },
{ key: 'mutation_choices', label: 'Mutation choices', num: true },
{ key: 'played_seconds', label: 'Time played', num: true, render: (a) => fmtDuration(a.played_seconds) },
{ key: 'created_at', label: 'Created', render: (a) => (a.created_at ? fmtAgo(a.created_at) : '—'), sort: (a) => a.created_at ?? 0 },
];
const draw = () => {
const q = search.value.trim().toLowerCase();
const rows = data.accounts.filter((a) => !q || [a.account, a.subject, a.status].some((v) => (v || '').toLowerCase().includes(q)));
holder.replaceChildren(table(columns, rows, { sortKey: 'created_at', onRow: (a) => { location.hash = `#/accounts/${a.account}`; } }));
};
search.addEventListener('input', draw);
const n = data.accounts.length;
const online = data.accounts.filter((a) => a.logged_in).length;
const alive = data.accounts.filter((a) => a.status === 'alive').length;
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Accounts'), h('div', { class: 'subtitle' }, `World ${data.world}`)),
h('div', { class: 'tools' }, search, h('button', { onclick: () => route() }, 'Refresh'))),
h('div', { class: 'stats' },
stat('Accounts', fmtInt(n)), stat('Online', fmtInt(online)), stat('Alive', fmtInt(alive)),
stat('Deaths', fmtInt(data.accounts.reduce((s, a) => s + (a.deaths || 0), 0)))),
holder);
draw();
}
function stat(label, value, sub) {
return h('div', { class: 'stat' }, h('div', { class: 'label' }, label),
h('div', { class: 'value' }, value, sub ? h('small', {}, ` ${sub}`) : null));
}
// persistence::LifeRefusal.
const rejections = ['accepted', 'refused: not enough funding', 'refused: no placement', 'cancelled', 'refused: already alive'];
async function livingOffspring(identities) {
// Living wildlife whose lineage root is one of the account's lives, in every viewable region.
const roots = new Set(identities);
let count = 0;
try {
const regions = await api('/api/regions');
for (const r of regions.regions.filter((x) => x.viewable)) {
try {
const view = await api(`/api/regions/${r.region}/view`);
count += view.cells.filter((c) => (c[6] & 1) && roots.has(c[14])).length;
} catch { /* region not ready */ }
}
} catch { return null; }
return count;
}
async function accountPage(id) {
const data = await api(`/api/accounts/${id}`);
const a = data.account;
const offspring = h('span', { class: 'muted' }, '…');
livingOffspring(data.lives.filter((l) => l.born !== null).map((l) => l.identity))
.then((n) => { offspring.textContent = n === null ? '—' : fmtInt(n); });
const note = h('span', { class: 'muted small' });
const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' });
const act = async (path, label, ask) => {
if (ask && !confirm(ask)) return;
try {
const q = new URLSearchParams(path.includes('?') ? path.split('?')[1] : '');
if (reason.value.trim()) q.set('reason', reason.value.trim());
await api(`/api/accounts/${a.account}/${path.split('?')[0]}?${q}`, true, 'POST');
route();
} catch (e) { note.textContent = `Could not ${label}: ${e.code || e.message}`; }
};
const actions = h('div', { class: 'card' }, h('h2', {}, 'Account actions'),
h('div', { class: 'window-controls' },
h('button', { onclick: () => act('logout', 'log out', `Log out ${short(a.account)} now? Its session closes within seconds.`) }, 'Log out'),
a.banned
? h('button', { onclick: () => act('ban?banned=0', 'lift the ban') }, 'Lift ban')
: h('button', { class: 'danger', onclick: () => act('ban?banned=1', 'ban', `Ban ${short(a.account)}? It is logged out and cannot sign in to play.`) }, 'Ban')),
reason, note,
data.bans.length ? h('table', { class: 'compact' }, h('tbody', {}, data.bans.slice(0, 8).map((b) =>
h('tr', {}, h('td', {}, fmtTime(b.at)), h('td', {}, b.banned ? h('span', { class: 'badge dead' }, 'banned') : 'lifted'),
h('td', { class: 'muted' }, (b.author || '').split(' (')[0]), h('td', { class: 'muted' }, b.reason || ''))))) : null);
const facts = h('dl', { class: 'facts' },
h('dt', {}, 'Account'), h('dd', { class: 'mono' }, a.account),
h('dt', {}, 'Keycloak subject'), h('dd', { class: 'mono' }, a.subject || '—'),
h('dt', {}, 'Issuer'), h('dd', { class: 'mono' }, a.issuer || '—'),
h('dt', {}, 'Status'), h('dd', {}, statusBadge(a)),
h('dt', {}, 'Session'), h('dd', {}, sessionBadge(a),
a.control_expires ? h('span', { class: 'muted' }, ` control ${a.logged_in ? 'until' : 'ended'} ${fmtTime(a.control_expires)}`) : null),
h('dt', {}, 'Active life'), h('dd', { class: 'mono' }, a.active_life ?? '—',
a.active_region ? h('span', {}, ' ', h('a', { href: `#/regions/${a.active_region}?account=${a.account}` }, `show in region ${a.active_region}`)) : null),
h('dt', {}, 'Created'), h('dd', {}, fmtTime(a.created_at)),
h('dt', {}, 'Last seen'), h('dd', {}, a.last_seen ? `${fmtTime(a.last_seen)} (${fmtAgo(a.last_seen)})` : '—'),
h('dt', {}, 'Living offspring'), h('dd', {}, offspring, h('span', { class: 'muted' }, ' wildlife descended from its lives')));
const lives = table([
{ key: 'request', label: 'Request', sort: (l) => Number(l.request) },
{ key: 'identity', label: 'Life', render: (l) => h('span', { class: 'mono' }, l.identity) },
{ key: 'region', label: 'Region' },
{ key: 'rejection', label: 'Outcome', render: (l) => (l.rejection ? h('span', { class: 'badge warn' }, rejections[l.rejection] || `refused ${l.rejection}`)
: l.born === null ? h('span', { class: 'muted' }, 'reserved') : l.ended_tick ? h('span', { class: 'badge dead' }, 'died') : h('span', { class: 'badge alive' }, 'alive')) },
{ key: 'born', label: 'Born (tick)', num: true, sort: (l) => Number(l.born ?? -1) },
{ key: 'ended_tick', label: 'Ended (tick)', num: true, sort: (l) => Number(l.ended_tick ?? -1) },
{ key: 'ended_at', label: 'Ended', render: (l) => fmtTime(l.ended_at), sort: (l) => l.ended_at ?? 0 },
], data.lives, { sortKey: 'request' });
show(
h('div', { class: 'head' }, h('div', {}, h('a', { class: 'crumb', href: '#/accounts' }, '← Accounts'), h('h1', {}, `Account ${short(a.account)}`))),
h('div', { class: 'stats' },
stat('Lives', fmtInt(a.lives)), stat('Deaths', fmtInt(a.deaths)), stat('Resets', fmtInt(a.resets)),
stat('Mutation choices', fmtInt(a.mutation_choices)),
stat('Time played', fmtDuration(a.played_seconds), `${fmtInt(a.sessions)} sessions`)),
h('div', { class: 'card' }, facts),
actions,
h('h2', { style: { marginTop: '24px' } }, 'Lives'), lives,
h('p', { class: 'muted' }, 'Time played counts sessions from schema 64 on; earlier play is not recorded.'));
}
// ---------- Region building blocks ----------
// Energy in pJ, matter in fg; the five channels in the view's order.
const channels = [
{ key: 'energy', label: 'Energy', short: 'Energy', fmt: (v) => fmtEnergy(v) },
{ key: 'carbon', label: 'Carbon', short: 'C', fmt: (v) => fmtMass(v) },
{ key: 'nitrogen', label: 'Nitrogen', short: 'N', fmt: (v) => fmtMass(v) },
{ key: 'phosphorus', label: 'Phosphorus', short: 'P', fmt: (v) => fmtMass(v) },
{ key: 'other', label: 'Other', short: 'Other', fmt: (v) => fmtMass(v) },
];
const channelNames = channels.map((c) => c.key);
const fmtChannel = (i, v) => channels[i].fmt(v);
const sum = (a) => a.reduce((s, v) => s + Number(v || 0), 0);
const addTo = (into, a) => { a.forEach((v, i) => { into[i] += Number(v || 0); }); return into; };
const tickSeconds = 0.05; // One 50 ms tick.
const depositLimit = 8192; // biology::max_cellular_liquid_deposits.
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
const swatch = (cls) => h('span', { class: `swatch ${cls}` });
const reasonInput = () => h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional, recorded)', class: 'grow' });
// replaceChildren without the nulls h() skips (the DOM would print them).
const fill = (el, ...nodes) => el.replaceChildren(...nodes.flat().filter((n) => n !== null && n !== undefined && n !== false));
const block = (title, aside, ...body) => h('div', { class: 'block' },
h('div', { class: 'block-head' }, h('h3', {}, title), aside || null), ...body);
// Amounts typed in friendly units: energy in µJ (10^6 pJ), matter in ng (10^6 fg).
function amountInputs() {
const fields = channels.map((c) => {
const input = h('input', { type: 'number', min: 0, step: 'any', placeholder: '0' });
return { c, input, node: h('div', { class: 'field' }, h('label', {}, swatch(c.key), `${c.label} ${c.key === 'energy' ? 'µJ' : 'ng'}`), input) };
});
const read = () => {
const out = {};
for (const { c, input } of fields) {
const v = Number(input.value || 0);
if (!Number.isFinite(v) || v < 0) throw new Error(`${c.label} must be a positive number`);
out[c.key] = String(Math.round(v * 1e6));
}
if (Object.values(out).every((v) => v === '0')) throw new Error('Enter at least one amount.');
return out;
};
const clear = () => fields.forEach(({ input }) => { input.value = ''; });
return { node: h('div', { class: 'field-grid' }, fields.map((f) => f.node)), read, clear };
}
// Five channel tiles: a main amount and an optional line under it.
function channelTiles(values, subs = []) {
return h('div', { class: 'channels' }, channels.map((c, i) =>
h('div', { class: `channel${Number(values[i]) ? '' : ' empty-ch'}` },
h('div', { class: 'name' }, swatch(c.key), c.label),
h('div', { class: 'amt' }, c.fmt(values[i])),
subs[i] ? h('div', { class: 'sub', title: subs[i] }, subs[i]) : null)));
}
const kindLabels = {
remove_cell: 'remove cell', grant_reserve: 'grant reserve', add_bubbles: 'add bubbles',
add_pool: 'add to spent pool', release_pool: 'release spent pool', spawn_wildlife: 'spawn wildlife',
adopt_tuning: 'adopt tuning',
};
// Admin commands (ADR-0182): queued now, applied by the region at its next ticks.
function commandSender(region, onQueued) {
return async (params, label, note, reason) => {
try {
const q = new URLSearchParams(params);
if (reason && reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/regions/${region}/commands?${q}`, true, 'POST');
if (note) { note.className = 'note good'; note.textContent = `Queued #${r.id} (${label}). The region applies it within a few seconds.`; }
if (reason) reason.value = '';
onQueued();
return true;
} catch (e) {
if (note) { note.className = 'note error'; note.textContent = `Could not queue ${label}: ${e.code || e.message}`; }
return false;
}
};
}
// The region's session window (ADR-0087): who may connect, until when. Writes go through the
// admin API as the signed-in admin; the region applies a change within about 5 seconds.
function sessionWindowBlock(region) {
const minutes = h('select', {}, [[30, '30 minutes'], [60, '1 hour'], [120, '2 hours'], [240, '4 hours']]
.map(([m, label]) => h('option', { value: m, selected: m === 240 }, label)));
const reason = reasonInput();
const note = h('div', { class: 'note' });
let busy = false;
const send = async (m) => {
if (busy) return;
if (m === 0 && !confirm(`Close sessions in region ${region}? Connected players are disconnected.`)) return;
busy = true;
try {
const q = new URLSearchParams({ minutes: String(m) });
if (reason.value.trim()) q.set('reason', reason.value.trim());
await api(`/api/regions/${region}/session-window?${q}`, true, 'POST');
reason.value = '';
note.className = 'note good';
note.textContent = 'Saved. The region applies it within about 5 seconds.';
} catch (e) {
note.className = 'note error';
note.textContent = `Could not change the window: ${e.message}`;
} finally {
busy = false;
load();
}
};
const openButton = h('button', { class: 'primary', onclick: () => send(Number(minutes.value)) }, 'Open');
const closeButton = h('button', { class: 'danger', onclick: () => send(0) }, 'Close sessions');
const status = h('div');
const history = h('div');
const badge = h('span', { class: 'badge' }, '…');
async function load() {
try {
const w = await api(`/api/regions/${region}/session-window`);
const current = w.history[0];
openButton.textContent = w.open ? 'Extend' : 'Open';
closeButton.disabled = !w.open;
badge.className = `badge ${w.open ? 'alive' : ''}`;
badge.replaceChildren(w.open ? h('span', { class: 'dot pulse' }) : '', w.open ? 'open' : 'closed');
status.replaceChildren(h('p', { class: 'hint' }, w.open
? `Players may connect until ${fmtTime(current.expires_at)} (closes ${fmtAgo(current.expires_at)}).`
: current && current.expires_at ? `Closed: the last window expired ${fmtAgo(current.expires_at)}.` : 'Closed: no window has been opened yet.'));
history.replaceChildren(w.history.length ? h('div', { class: 'list' }, w.history.slice(0, 8).map((x) =>
h('div', { class: 'list-item' },
h('div', { class: 'grow' }, x.expires_at ? `Opened until ${new Date(x.expires_at * 1000).toLocaleTimeString()}` : 'Closed',
h('div', { class: 'sub', title: x.author || '' }, `${(x.author || '').split(' (')[0]}${x.reason ? ` · ${x.reason}` : ''}`)),
h('span', { class: 'muted small' }, fmtAgo(x.created_at))))) : null);
} catch (e) {
status.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`));
}
}
const node = h('div', {},
block('Session window', badge, status,
h('div', { class: 'form-row' }, minutes, openButton, closeButton),
h('div', { class: 'form-row' }, reason), note),
block('History', null, history));
load();
return { node, load };
}
// Resource schedules (schema 65): a command repeated every N seconds while enabled. The game
// source for bubbles, a steady release of the spent pool, or a wildlife population top-up.
function schedulesBlock(region) {
const list = h('div');
const note = h('div', { class: 'note' });
const kind = h('select', {}, [['add_bubbles', 'Add bubbles'], ['release_pool', 'Release spent pool'], ['spawn_wildlife', 'Spawn wildlife']]
.map(([v, label]) => h('option', { value: v }, label)));
const count = h('input', { type: 'number', min: 1, max: 256, value: 10, class: 'count', title: 'bubbles or cells each time' });
const every = h('input', { type: 'number', min: 1, max: 86400, value: 30, class: 'count', title: 'seconds between runs' });
const amount = amountInputs();
kind.addEventListener('change', () => { amount.node.hidden = kind.value === 'spawn_wildlife'; });
const reason = reasonInput();
const fromSchedule = (x) => ({
id: x.id, kind: x.kind, count: String(x.count), interval: String(x.interval),
energy: x.amount[0], carbon: x.amount[1], nitrogen: x.amount[2], phosphorus: x.amount[3], other: x.amount[4],
});
const save = async (params, label) => {
try {
const q = new URLSearchParams(params);
if (reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/regions/${region}/schedules?${q}`, true, 'POST');
note.className = 'note good';
note.textContent = `Saved schedule #${r.id} (${label}).`;
reason.value = '';
load();
return true;
} catch (e) { note.className = 'note error'; note.textContent = `Could not save: ${e.code || e.message}`; return false; }
};
const add = () => {
let values;
try { values = kind.value === 'spawn_wildlife' ? {} : amount.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
save({ kind: kind.value, count: count.value, interval: every.value, enabled: '1', ...values }, 'new')
.then((ok) => { if (ok) amount.clear(); });
};
async function load() {
try {
const data = await api(`/api/regions/${region}/schedules`);
list.replaceChildren(data.schedules.length ? h('div', { class: 'list' }, data.schedules.map((x) =>
h('div', { class: 'list-item' },
h('span', { class: 'mono faint' }, `#${x.id}`),
h('div', { class: 'grow' }, `${kindLabels[x.kind] || x.kind} ×${x.count} every ${fmtDuration(x.interval)}`,
x.kind !== 'spawn_wildlife' ? h('div', { class: 'sub' }, `each: ${x.amount.map((v, i) => (Number(v) ? fmtChannel(i, v) : null)).filter(Boolean).join(' · ') || 'nothing'}`) : null),
x.enabled ? h('span', { class: 'badge alive' }, `on · ${fmtInt(x.runs)} runs`) : h('span', { class: 'badge' }, 'off'),
h('button', { onclick: () => save({ ...fromSchedule(x), enabled: x.enabled ? '0' : '1' }, x.enabled ? 'stopped' : 'started') }, x.enabled ? 'Stop' : 'Start'))))
: h('p', { class: 'hint' }, 'No schedules. A schedule repeats a command while it is on.'));
} catch (e) { list.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`)); }
}
const node = block('Resource schedules', null, list,
h('div', { class: 'action' },
h('div', { class: 'form-row' }, h('div', { class: 'field grow' }, h('label', {}, 'Repeat'), kind),
h('div', { class: 'field' }, h('label', {}, 'Count'), count),
h('div', { class: 'field' }, h('label', {}, 'Every (s)'), every)),
h('div', { class: 'form-row' }, amount.node),
h('div', { class: 'form-row' }, reason, h('button', { onclick: add }, 'Add schedule')), note));
load();
return { node, load };
}
// ---------- Tuning text (the Git `key = value` format) ----------
// Groups by the key's first part; a group's description is the comment block before its first
// key, a key's note its trailing comment. tuning.version (the format) is left out.
function parseTuning(text) {
const groups = new Map();
let comments = [];
for (const raw of (text || '').split('\n')) {
const line = raw.trim();
if (!line) { comments = []; continue; }
if (line.startsWith('#')) { comments.push(line.replace(/^#\s?/, '')); continue; }
const m = /^([A-Za-z0-9_.]+)\s*=\s*([^#]*?)\s*(?:#\s*(.*))?$/.exec(line);
if (!m) continue;
const name = m[1].split('.')[0];
if (m[1] === 'tuning.version') { comments = []; continue; }
if (!groups.has(name)) groups.set(name, { name, about: comments.join(' '), settings: [] });
groups.get(name).settings.push({ key: m[1], value: m[2], note: m[3] || '' });
comments = [];
}
return [...groups.values()];
}
// A readable gloss of a raw value from its key's unit suffix.
function gloss(key, value) {
const n = Number(String(value).replace(/_/g, ''));
if (!Number.isFinite(n)) return '';
if (/_pj$|_e_pj$/.test(key)) return fmtEnergy(n);
if (/_fg$/.test(key)) return fmtMass(n);
if (/_ticks$/.test(key)) return `${(n * tickSeconds).toLocaleString(undefined, { maximumFractionDigits: 2 })} s`;
if (/_ms$/.test(key)) return fmtDuration(n / 1000);
if (/_um$/.test(key)) return fmtLength(n);
if (/_mk$/.test(key)) return `${((n - 273150) / 1000).toLocaleString(undefined, { maximumFractionDigits: 1 })} °C`;
if (/per_mille$/.test(key) && !/per_point|per_k$/.test(key)) return `${(n / 10).toLocaleString()}%`;
if (/_ppm$/.test(key)) return `${(n / 10000).toLocaleString()}%`;
return '';
}
// The settings as collapsible groups, filtered by `query`; values differing from `compare`
// (a key → value map) are marked.
function settingsView(text, { query = '', compare = null, open = true } = {}) {
const q = query.trim().toLowerCase();
const groups = parseTuning(text).map((g) => ({
...g, settings: g.settings.filter((s) => !q || s.key.toLowerCase().includes(q) || s.note.toLowerCase().includes(q)),
})).filter((g) => g.settings.length);
if (!groups.length) return h('p', { class: 'hint' }, q ? 'No setting matches.' : 'No settings.');
return h('div', {}, groups.map((g) => h('details', { class: 'settings-group', open: open || !!q },
h('summary', {}, h('span', { class: 'label' }, g.name), h('span', { class: 'badge' }, g.settings.length)),
g.about ? h('p', { class: 'hint', style: { margin: '8px 0 4px 16px' } }, g.about) : null,
g.settings.map((s) => {
const before = compare ? compare.get(s.key) : undefined;
const changed = compare && before !== undefined && before !== s.value;
const added = compare && before === undefined;
const extra = gloss(s.key, s.value);
return h('div', { class: `setting${changed || added ? ' changed' : ''}`, title: changed ? `baseline: ${before}` : added ? 'not in the baseline' : '' },
h('span', { class: 'key' }, s.key.slice(g.name.length + 1) || s.key),
h('span', { class: 'val' }, s.value.replace(/_/g, ','), extra ? h('span', { class: 'muted', style: { fontWeight: 400 } }, ` ${extra}`) : null),
s.note || changed ? h('span', { class: 'why' }, [s.note, changed ? `baseline ${before.replace(/_/g, ',')}` : ''].filter(Boolean).join(' · ')) : null);
}))));
}
const tuningMap = (text) => new Map(parseTuning(text).flatMap((g) => g.settings.map((s) => [s.key, s.value])));
// ---------- Region list ----------
async function regionsPage() {
const data = await api('/api/regions');
show(
h('div', { class: 'head' }, h('div', {}, h('h1', {}, 'Regions'), h('div', { class: 'subtitle' }, `World ${data.world}`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
table([
{ key: 'region', label: 'Region', sort: (r) => Number(r.region) },
{ key: 'frame', label: 'Frame' },
{ key: 'lease_held', label: 'Lease', render: (r) => (r.lease_held ? h('span', { class: 'badge alive' }, `held · epoch ${r.lease_epoch}`) : h('span', { class: 'muted' }, 'free')) },
{ key: 'lease_expires', label: 'Lease expires', render: (r) => fmtAgo(r.lease_expires) },
{ key: 'tick', label: 'Head tick', num: true, render: (r) => fmtInt(r.tick), sort: (r) => Number(r.tick ?? -1) },
{ key: 'sequence', label: 'Commits', num: true, render: (r) => fmtInt(r.sequence), sort: (r) => Number(r.sequence ?? -1) },
{ key: 'committed_at', label: 'Last commit', render: (r) => fmtAgo(r.committed_at), sort: (r) => r.committed_at ?? 0 },
{ key: 'build', label: 'Build', render: (r) => h('span', { class: 'mono', title: r.build || '' }, r.build ? r.build.slice(0, 12) : '—') },
{ key: 'window_open', label: 'Sessions', render: windowBadge, sort: (r) => (r.window_open ? r.window_expires : 0) },
{ key: 'viewable', label: '', render: (r) => (r.viewable ? h('a', { href: `#/regions/${r.region}` }, 'Open view →') : h('span', { class: 'muted' }, 'no view')) },
], data.regions, { sortKey: 'region', onRow: (r) => { if (r.viewable) location.hash = `#/regions/${r.region}`; } }));
}
function windowBadge(r) {
return r.window_open ? h('span', { class: 'badge alive', title: fmtTime(r.window_expires) }, `open · closes ${fmtAgo(r.window_expires)}`)
: h('span', { class: 'badge' }, 'closed');
}
// ---------- Region view ----------
// Where a region's stock sits: the server's complete totals, or (an older server) sums over the
// listed cells and deposits.
function regionLedger(view) {
const zero = () => [0, 0, 0, 0, 0];
// Heat: energy the cells used that has not (yet) returned to the spent pool.
const heat = view.heat === undefined ? null : [Number(view.heat), 0, 0, 0, 0];
if (view.totals) {
const t = view.totals;
return { complete: true, reserve: t.reserve, body: t.body, bubbles: t.bubbles, pools: t.pools, patches: t.patches, spent: view.spent, heat };
}
const reserve = zero(), bubbles = zero(), pools = zero(), patches = zero();
for (const c of view.cells) addTo(reserve, c.reserve);
for (const d of view.deps) addTo(d.kind === 2 ? bubbles : d.kind === 1 ? pools : patches, d.stock);
return { complete: false, reserve, body: null, bubbles, pools, patches, spent: view.spent, heat };
}
// The rules-13 drip: every `interval` ticks, one bubble per non-empty channel of at most the cap;
// the energy cycle (ADR-0182 section 14): heat recycled per mille each tick, absorbing drip.
function dripPlan(view) {
if (!view.drip) return null;
const [interval, capE, capM, recycle = 0, absorb = 0] = view.drip.map(Number);
const caps = [capE, capM, capM, capM, capM];
const spent = view.spent.map(Number);
return {
interval, caps, recycle, absorb: absorb === 1,
next: spent.map((v, i) => Math.min(v, caps[i])),
drips: spent.map((v, i) => (caps[i] ? Math.ceil(v / caps[i]) : 0)),
};
}
async function regionPage(region, params) {
const highlight = params.get('account') || '';
const send = commandSender(region, () => commands.load());
let view = null, selected = null, timer = null, frame = 0, beats = 0;
let zoom = 1, panX = 0, panY = 0, drag = null;
// Tick pace: the last ticks seen and when the tick last moved.
const pace = { samples: [], movedAt: performance.now(), lastTick: null, fetchedAt: 0 };
const layers = { players: true, online: true, wildlife: true, pools: true, patches: true, energy: true, carbon: true, nitrogen: true, phosphorus: true, other: true };
// ----- Header and KPIs -----
const titleBadges = h('div', { class: 'title-row' });
const subtitle = h('div', { class: 'subtitle' }, 'Loading…');
const live = h('input', { type: 'checkbox', checked: true });
const kpi = (label) => {
const value = h('div', { class: 'value' }, '—'), sub = h('div', { class: 'sub' }), meter = h('div', { class: 'meter', hidden: true }, h('span'));
const node = h('div', { class: 'kpi' }, h('div', { class: 'label' }, label), value, sub, meter);
return {
node, meter,
set(v, s, cls = '', fill = null, meterCls = '') {
value.textContent = v; sub.textContent = s || ''; node.className = `kpi ${cls}`.trim();
meter.hidden = fill === null;
if (fill !== null) { meter.className = `meter ${meterCls}`.trim(); meter.firstChild.style.width = `${Math.max(0, Math.min(100, fill * 100))}%`; }
},
};
};
const k = {
tick: kpi('Tick'), cells: kpi('Population'), deposits: kpi('Deposit capacity'), energy: kpi('Region energy'),
matter: kpi('Region matter'), spent: kpi('Spent pool'), drip: kpi('Next drip'),
};
k.drip.meter.classList.add('smooth');
// ----- Map -----
const canvas = h('canvas');
const tip = h('div', { class: 'tooltip glass', hidden: true });
const banner = h('div', { class: 'map-banner glass', hidden: true });
const scaleLabel = h('div'), scaleRule = h('div', { class: 'rule' });
const chipRow = h('div', { class: 'map-layers' });
const chips = {};
const chip = (key, cls, label) => {
const count = h('span', { class: 'count' });
const node = h('label', { class: 'chip', title: `Show or hide ${label.toLowerCase()}` }, swatch(cls), label, count);
node.addEventListener('click', (e) => { e.preventDefault(); layers[key] = !layers[key]; node.classList.toggle('off', !layers[key]); paint(); });
chips[key] = { node, count };
return node;
};
chipRow.append(chip('players', 'player', 'Players'), chip('online', 'online', 'Connected'), chip('wildlife', 'wildlife', 'Wildlife'),
chip('pools', 'pool', 'Pools'), chip('patches', 'patch', 'Patches'),
...channels.map((c) => chip(c.key, c.key, `${c.label} bubbles`)));
const zoomBy = (factor) => { setZoom(zoom * factor, 0, 0); };
const mapCard = h('div', { class: 'map-card' },
h('div', { class: 'map-toolbar' }, chipRow,
h('div', { class: 'map-zoom' },
h('button', { title: 'Zoom in', onclick: () => zoomBy(1.6) }, '+'),
h('button', { title: 'Zoom out', onclick: () => zoomBy(1 / 1.6) }, '−'),
h('button', { title: 'Fit the region', onclick: () => { zoom = 1; panX = 0; panY = 0; paint(); } }, '⤢'))),
h('div', { class: 'map-stage' }, canvas, banner,
h('div', { class: 'map-foot' },
h('div', { class: 'map-hint glass' }, 'Click to inspect · scroll to zoom · drag to pan'),
h('div', { class: 'scale glass' }, scaleLabel, scaleRule)),
tip));
// ----- Side panel: tabs -----
const tabNames = [['inspect', 'Inspect'], ['resources', 'Resources'], ['actions', 'Actions'], ['tuning', 'Tuning'], ['access', 'Access']];
let tab = (() => { try { return localStorage.getItem('region-tab') || 'resources'; } catch { return 'resources'; } })();
const tabButtons = {}, tabBodies = {};
const actionsBadge = h('span', { class: 'tab-badge', hidden: true });
for (const [key, label] of tabNames) {
tabButtons[key] = h('button', { role: 'tab', onclick: () => openTab(key) }, label, key === 'actions' ? actionsBadge : null);
tabBodies[key] = h('div', { hidden: true });
}
const panelBody = h('div', { class: 'panel-body' }, Object.values(tabBodies));
function openTab(key) {
tab = key;
try { localStorage.setItem('region-tab', key); } catch { /* private mode */ }
for (const [name] of tabNames) { tabButtons[name].classList.toggle('on', name === key); tabBodies[name].hidden = name !== key; }
if (key === 'tuning') tuning.load();
}
// Inspect: the selected cell or deposit, else the region's player cells.
const inspect = h('div');
tabBodies.inspect.append(inspect);
let inspectFacts = null, inspectKey = null, goneText = '';
// Resources: the ledger, the spent pool and its drip, and pool actions.
const ledgerBox = h('div');
const dripBox = h('div');
const dripCountdown = h('span', { class: 'drip-count' }, '—');
const dripMeter = h('div', { class: 'meter smooth', style: { marginTop: '8px' } }, h('span'));
const dripEvery = h('span', { class: 'muted small' });
const poolAmount = amountInputs(), poolReason = reasonInput(), poolNote = h('div', { class: 'note' });
const releaseAmount = amountInputs(), releaseReason = reasonInput(), releaseNote = h('div', { class: 'note' });
const releaseCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' });
const withAmount = (amount, extra, label, note, reason) => {
let values;
try { values = amount.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
send({ ...extra, ...values }, label, note, reason).then((ok) => { if (ok) amount.clear(); });
};
tabBodies.resources.append(
block('Where the resources are', h('span', { class: 'muted' }, 'everything in the region'), ledgerBox),
block('Spent pool and drip', dripEvery,
h('div', { class: 'drip-card' },
h('div', { class: 'drip-top' }, h('span', { class: 'muted small' }, 'Next drip'), dripCountdown),
dripMeter, dripBox)),
block('Add to the spent pool', null,
h('p', { class: 'hint' }, 'The spent pool is the region\'s single reserve of dead and spent matter. It has no place on the map: the drip returns it as bubbles at random spots.'),
poolAmount.node,
h('div', { class: 'form-row' }, poolReason, h('button', { onclick: () => withAmount(poolAmount, { kind: 'add_pool' }, 'add to spent pool', poolNote, poolReason) }, 'Add to pool')),
poolNote),
block('Release the spent pool now', null,
h('p', { class: 'hint' }, 'Takes these amounts from the spent pool at once, as bubbles at random spots.'),
releaseAmount.node,
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Bubbles'), releaseCount), releaseReason,
h('button', { onclick: () => withAmount(releaseAmount, { kind: 'release_pool', count: releaseCount.value }, 'release spent pool', releaseNote, releaseReason) }, 'Release')),
releaseNote));
// Actions: wildlife, bubbles, schedules and the command log.
const spawnCount = h('input', { type: 'number', min: 1, max: 64, value: 10, class: 'count' });
const spawnReason = reasonInput(), spawnNote = h('div', { class: 'note' });
const bubbleCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' });
const bubbleAmount = amountInputs(), bubbleReason = reasonInput(), bubbleNote = h('div', { class: 'note' });
const commandLog = h('div');
const commands = {
async load() {
try {
const data = await api(`/api/regions/${region}/commands`);
const pending = data.commands.filter((c) => !c.applied_tick).length;
actionsBadge.hidden = !pending;
actionsBadge.textContent = `${pending}`;
commandLog.replaceChildren(data.commands.length ? h('div', { class: 'list' }, data.commands.slice(0, 12).map((c) =>
h('div', { class: 'list-item' },
h('span', { class: 'mono faint' }, `#${c.id}`),
h('div', { class: 'grow' }, kindLabels[c.kind] || c.kind, c.count ? ` ×${c.count}` : '',
c.kind === 'remove_cell' || c.kind === 'grant_reserve' ? h('span', { class: 'mono muted' }, ` ${c.target}`) : '',
c.kind === 'adopt_tuning' ? ` revision ${c.target}` : '',
h('div', { class: 'sub', title: c.author || '' }, (c.author || '').split(' (')[0])),
c.applied_tick ? h('span', { class: 'badge alive' }, `tick ${fmtInt(c.applied_tick)}`) : h('span', { class: 'badge warn' }, 'pending'))))
: h('p', { class: 'hint' }, 'No commands yet.'));
} catch (e) { commandLog.replaceChildren(h('p', { class: 'error' }, `Unavailable: ${e.message}`)); }
},
};
const schedules = schedulesBlock(region);
tabBodies.actions.append(
block('Spawn wildlife', null,
h('p', { class: 'hint' }, 'Founder wildlife at random spots, funded like any birth.'),
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Cells'), spawnCount), spawnReason,
h('button', { onclick: () => send({ kind: 'spawn_wildlife', count: spawnCount.value }, 'spawn wildlife', spawnNote, spawnReason) }, 'Spawn')),
spawnNote),
block('Add bubbles', null,
h('p', { class: 'hint' }, 'New stock from outside the region, split evenly over the bubbles.'),
bubbleAmount.node,
h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Bubbles'), bubbleCount), bubbleReason,
h('button', { onclick: () => withAmount(bubbleAmount, { kind: 'add_bubbles', count: bubbleCount.value }, 'add bubbles', bubbleNote, bubbleReason) }, 'Add')),
bubbleNote),
schedules.node,
block('Recent commands', null, commandLog));
// Tuning: what the region runs now.
const tuning = (() => {
const search = h('input', { type: 'search', placeholder: 'Filter settings', class: 'wide' });
const head = h('div');
const live_ = h('div');
const file = h('div');
let data = null, runningText = null, loadedAt = 0, running = null, tried = false;
const texts = new Map();
const draw = () => {
if (!data) return;
const baseline = data.baseline ? tuningMap(data.baseline.text) : null;
live_.replaceChildren(runningText ? settingsView(runningText, { query: search.value, compare: running && running.revision ? baseline : null })
: h('p', { class: 'hint' }, view && view.rules_sha256 ? 'This region runs rules that match neither the baseline file nor a stored revision, so their text is not available here.' : 'Live tuning applies to rules-13 regions only.'));
file.replaceChildren(data.region_file ? settingsView(data.region_file, { query: search.value, open: !!search.value.trim() })
: h('p', { class: 'hint' }, 'The admin API was started without the region tuning file.'));
};
search.addEventListener('input', draw);
async function load(force = false) {
tried = true;
try {
if (force || !data || performance.now() - loadedAt > 30000) { data = await api('/api/tuning'); loadedAt = performance.now(); }
const digest = view && view.rules_sha256;
const rev = digest ? data.revisions.find((r) => r.rules_sha256 === digest) : null;
running = rev ? { revision: rev.revision, label: `Revision #${rev.revision}`, about: rev.reason }
: digest && data.baseline && data.baseline.rules_sha256 === digest ? { revision: 0, label: 'Baseline file', about: 'the revamp file the region opened with' }
: digest ? { revision: null, label: `Unknown rules ${digest.slice(0, 8)}…` } : null;
if (rev) {
if (!texts.has(rev.revision)) texts.set(rev.revision, data.newest && data.newest.revision === rev.revision ? data.newest.text : (await api(`/api/tuning/${rev.revision}`)).text);
runningText = texts.get(rev.revision);
} else runningText = running && running.revision === 0 ? data.baseline.text : null;
head.replaceChildren(h('div', { class: 'block-head' },
h('div', {}, running ? h('span', { class: `badge ${running.revision === null ? 'warn' : 'alive'}` }, running.label) : h('span', { class: 'badge' }, `rules ${view ? view.rules : '—'}`),
running && running.about ? h('div', { class: 'hint', style: { margin: '6px 0 0' } }, running.about) : null),
h('a', { href: '#/tuning' }, 'Open the editor →')));
draw();
return running;
} catch (e) {
head.replaceChildren(h('p', { class: 'error' }, `Tuning unavailable: ${e.code || e.message}`));
return null;
}
}
tabBodies.tuning.append(
h('div', { class: 'block' }, head, search),
block('Live rules', h('span', { class: 'muted' }, 'rules 13 · adopt changes in the editor'), live_),
block('Region file', h('span', { class: 'muted' }, 'read at restart · shape at opening'), file));
return { load, get running() { return running; }, get tried() { return tried; } };
})();
const sessions = sessionWindowBlock(region);
tabBodies.access.append(sessions.node);
show(
h('div', { class: 'head' },
h('div', {}, h('a', { class: 'crumb', href: '#/regions' }, '← Regions'),
h('div', { class: 'title-row' }, h('h1', {}, `Region ${region}`), titleBadges), subtitle),
h('div', { class: 'tools' }, h('label', { class: 'chip glass', title: 'Refresh every second' }, live, 'Live'),
h('button', { onclick: () => load() }, 'Refresh'))),
h('div', { class: 'kpis' }, Object.values(k).map((x) => x.node)),
h('div', { class: 'region-grid' }, mapCard,
h('div', { class: 'panel' }, h('div', { class: 'tabs', role: 'tablist' }, Object.values(tabButtons)), panelBody)));
openTab(tab);
// ----- Map drawing -----
const cellObj = (c) => ({
life: c[0], organism: c[1], account: c[2], x: c[3], y: c[4], extent: c[5], flags: c[6], members: c[7],
reserve: c.slice(8, 13), bodyMass: c[13], root: c[14],
});
const depObj = (d) => {
// Energy counts in pJ, matter in fg; ~17 pJ per fg of food, so compare on that scale.
const stock = d.slice(5, 10);
const weights = [stock[0] / 17, stock[1], stock[2], stock[3], stock[4]];
return { id: d[0], kind: d[1], x: d[2], y: d[3], r: d[4], stock, top: weights.indexOf(Math.max(...weights)) };
};
const cellLayer = (c) => (c.flags & 1 ? 'wildlife' : c.flags & 2 ? 'online' : 'players');
const depLayer = (d) => (d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pools' : 'patches');
function geometry() {
// The backing store follows the laid-out size (the canvas is absolutely placed, so its own
// size never feeds back into the layout), at most 2x and 4,096 pixels a side.
const rect = canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2, 4096 / Math.max(1, rect.width, rect.height));
const w = Math.max(1, Math.round(rect.width * dpr)), hgt = Math.max(1, Math.round(rect.height * dpr));
if (canvas.width !== w || canvas.height !== hgt) { canvas.width = w; canvas.height = hgt; }
const [aw, ah] = view ? view.area : [1, 1];
const base = Math.min(w / aw, hgt / ah) * 0.94;
const s = base * zoom;
const ox = (w - aw * s) / 2 + panX * dpr, oy = (hgt - ah * s) / 2 + panY * dpr;
// World y grows upward; the canvas grows downward.
return { dpr, s, w, hgt, toX: (x) => ox + x * s, toY: (y) => oy + (ah - y) * s, fromX: (px) => (px - ox) / s, fromY: (py) => ah - (py - oy) / s };
}
function setZoom(next, mx, my) {
next = Math.min(96, Math.max(1, next));
const kz = next / zoom;
panX = mx - (mx - panX) * kz; panY = my - (my - panY) * kz;
zoom = next;
if (zoom === 1) { panX = 0; panY = 0; }
paint();
}
function centerOn(x, y) {
if (!view) return;
zoom = Math.max(zoom, 8);
const g = geometry();
panX = (view.area[0] / 2 - x) * g.s / g.dpr;
panY = (y - view.area[1] / 2) * g.s / g.dpr;
paint();
}
const niceLength = (um) => {
const p = 10 ** Math.floor(Math.log10(um));
return [5, 2, 1].map((m) => m * p).find((v) => v <= um) || p;
};
function paint() {
const g = geometry();
const ctx = canvas.getContext('2d');
if (!ctx) return; // The browser refused a context (lost or out of memory).
ctx.fillStyle = css('map-bg');
ctx.fillRect(0, 0, g.w, g.hgt);
if (!view) return;
const [aw, ah] = view.area;
// Grid lines at a round spacing at least ~60 px apart, then the region's edge.
const step = niceLength(Math.max(1, (60 * g.dpr) / g.s) * 2.2);
ctx.strokeStyle = css('map-grid');
ctx.lineWidth = g.dpr;
ctx.beginPath();
for (let x = step; x < aw; x += step) { ctx.moveTo(g.toX(x), g.toY(0)); ctx.lineTo(g.toX(x), g.toY(ah)); }
for (let y = step; y < ah; y += step) { ctx.moveTo(g.toX(0), g.toY(y)); ctx.lineTo(g.toX(aw), g.toY(y)); }
ctx.stroke();
ctx.strokeStyle = css('map-edge');
ctx.lineWidth = 1.5 * g.dpr;
ctx.strokeRect(g.toX(0), g.toY(ah), aw * g.s, ah * g.s);
const ring = (x, y, r) => {
ctx.strokeStyle = css('select'); ctx.lineWidth = 2 * g.dpr;
ctx.beginPath(); ctx.arc(x, y, r + 4 * g.dpr, 0, Math.PI * 2); ctx.stroke();
};
const poolFill = css('pool'), poolEdge = css('pool-edge'), patchFill = css('patch');
for (const d of view.deps) {
if (d.kind === 2 || !layers[depLayer(d)]) continue;
ctx.fillStyle = d.kind === 1 ? poolFill : patchFill;
ctx.strokeStyle = poolEdge; ctx.lineWidth = g.dpr;
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 3 * g.dpr), 0, Math.PI * 2); ctx.fill();
if (d.kind === 1) ctx.stroke();
}
const colors = channelNames.map(css);
for (const d of view.deps) {
if (d.kind !== 2 || !layers[channelNames[d.top]]) continue;
ctx.fillStyle = colors[d.top];
ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 1.6 * g.dpr), 0, Math.PI * 2); ctx.fill();
}
if (selected && selected.dep) {
const d = selected.dep;
ring(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 2 * g.dpr));
}
const fills = { wildlife: css('wildlife'), online: css('online'), players: css('player') };
for (const c of view.cells) {
const layer = cellLayer(c);
if (!layers[layer]) continue;
const faded = (c.flags & 12) !== 0;
const size = Math.max(c.extent * g.s, 4 * g.dpr);
const x = g.toX(c.x + c.extent / 2), y = g.toY(c.y + c.extent / 2);
ctx.globalAlpha = faded ? 0.4 : 0.95;
ctx.fillStyle = fills[layer];
ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1;
if ((highlight && c.account === highlight) || (selected && selected.cell && selected.cell.life === c.life)) ring(x, y, size / 2);
}
// Scale bar: a round length about 90 px long.
const len = niceLength((90 * g.dpr) / g.s);
scaleLabel.textContent = fmtLength(len);
scaleRule.style.width = `${(len * g.s) / g.dpr}px`;
}
function hit(px, py) {
if (!view) return null;
const g = geometry();
const wx = g.fromX(px * g.dpr), wy = g.fromY(py * g.dpr);
const slack = (5 * g.dpr) / g.s;
for (const c of view.cells) {
if (!layers[cellLayer(c)]) continue;
if (wx >= c.x - slack && wx <= c.x + c.extent + slack && wy >= c.y - slack && wy <= c.y + c.extent + slack) return { cell: c };
}
// Bubbles before pools: a pool is large and would hide the bubbles over it.
let best = null, bestD = Infinity;
for (const d of view.deps) {
if (!layers[depLayer(d)]) continue;
const r = Math.max(d.kind === 2 ? d.r : 0, slack);
const dist = (wx - d.x) ** 2 + (wy - d.y) ** 2;
if (d.kind === 2 && dist <= r * r && dist < bestD) { best = d; bestD = dist; }
}
if (best) return { dep: best };
for (const d of view.deps) {
if (d.kind === 2 || !layers[depLayer(d)]) continue;
const r = Math.max(d.r, slack);
if ((wx - d.x) ** 2 + (wy - d.y) ** 2 <= r * r) return { dep: d };
}
return null;
}
const depName = (d) => (d.kind === 2 ? 'Bubble' : d.kind === 1 ? 'Liquid pool' : 'Patch');
const cellName = (c) => (c.flags & 1 ? 'Wildlife cell' : c.flags & 2 ? 'Player cell (connected)' : 'Player cell');
function tipFor(found) {
if (found.cell) {
const c = found.cell;
return [h('div', { class: 'tip-title' }, swatch(cellLayer(c) === 'players' ? 'player' : cellLayer(c)), cellName(c)),
...[['Life', c.life], ['Members', c.members], ['Size', fmtLength(c.extent)], ['Reserve energy', fmtEnergy(c.reserve[0])],
['Reserve matter', fmtMass(sum(c.reserve.slice(1)))], ['Body mass', fmtMass(c.bodyMass)]]
.map(([a, b]) => h('div', { class: 'tip-row' }, h('span', {}, a), h('span', {}, String(b))))];
}
const d = found.dep;
return [h('div', { class: 'tip-title' }, swatch(d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pool' : 'patch'), `${depName(d)} #${d.id}`),
...channels.map((c, i) => (Number(d.stock[i]) ? h('div', { class: 'tip-row' }, h('span', {}, c.label), h('span', {}, c.fmt(d.stock[i]))) : null)),
h('div', { class: 'tip-row' }, h('span', {}, 'Radius'), h('span', {}, fmtLength(d.r)))];
}
// ----- Inspector -----
function select(found) {
selected = found;
inspectKey = null;
goneText = '';
drawInspector();
openTab('inspect');
paint();
}
function drawInspector() {
if (!view) return;
if (!selected) {
inspectKey = 'none';
const players = view.cells.filter((c) => !(c.flags & 1));
inspect.replaceChildren(
h('div', { class: 'empty' }, h('div', { class: 'big' }, goneText ? '∅' : '◎'), goneText || 'Click a cell, bubble or pool on the map to inspect it.'),
block(`Player cells`, h('span', { class: 'muted' }, fmtInt(players.length)),
players.length ? h('div', { class: 'list' }, players.map((c) => h('div', {
class: 'list-item clickable',
onclick: () => { select({ cell: c }); centerOn(c.x + c.extent / 2, c.y + c.extent / 2); },
}, swatch(c.flags & 2 ? 'online' : 'player'),
h('div', { class: 'grow' }, h('span', { class: 'mono' }, short(c.account)), h('div', { class: 'sub' }, `life ${c.life} · ${fmtLength(c.extent)}`)),
h('span', { class: 'muted small' }, fmtEnergy(c.reserve[0])))))
: h('p', { class: 'hint' }, 'No player cells are alive in this region.')));
return;
}
const key = selected.cell ? `c${selected.cell.life}` : `d${selected.dep.id}`;
if (inspectKey !== key) {
// Built once per selection so typed amounts survive the live refresh.
inspectKey = key;
inspectFacts = h('div');
const close = h('button', { class: 'ghost icon', title: 'Clear the selection', onclick: () => { selected = null; drawInspector(); paint(); } }, '✕');
const locate = h('button', { title: 'Center the map on it', onclick: () => {
const it = selected && (selected.cell || selected.dep);
if (it) centerOn(selected.cell ? it.x + it.extent / 2 : it.x, selected.cell ? it.y + it.extent / 2 : it.y);
} }, 'Locate');
if (selected.cell) {
const c = selected.cell;
const grant = amountInputs(), reason = reasonInput(), note = h('div', { class: 'note' });
const give = () => {
let values;
try { values = grant.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; }
send({ kind: 'grant_reserve', target: c.life, ...values }, `grant reserve to ${c.life}`, note, reason).then((ok) => { if (ok) grant.clear(); });
};
const remove = () => {
if (!confirm(`Remove ${c.flags & 1 ? 'wildlife' : 'player'} cell ${c.life}? Its body and reserve go to the spent pool.`)) return;
send({ kind: 'remove_cell', target: c.life }, `remove cell ${c.life}`, note, reason);
};
inspect.replaceChildren(
h('div', { class: 'inspect-head' }, swatch(cellLayer(c) === 'players' ? 'player' : cellLayer(c)), h('h2', { class: 'grow' }, cellName(c)), locate, close),
inspectFacts,
block('Grant reserve', null, grant.node, h('div', { class: 'form-row' }, reason, h('button', { onclick: give }, 'Grant')), note),
block('Remove', null, h('p', { class: 'hint' }, 'Kills the cell now; its body and reserve go to the spent pool.'),
h('button', { class: 'danger', onclick: remove }, 'Remove cell')));
} else {
const d = selected.dep;
inspect.replaceChildren(
h('div', { class: 'inspect-head' }, swatch(d.kind === 2 ? channelNames[d.top] : d.kind === 1 ? 'pool' : 'patch'), h('h2', { class: 'grow' }, `${depName(d)} #${d.id}`), locate, close),
inspectFacts,
h('div', { class: 'callout info', style: { marginTop: '14px' } },
h('div', {}, d.kind === 2 ? 'Cells collect bubbles by touching them.' : 'Pools and patches are fixed food sources cells collect from.',
' Admin commands do not target a single deposit: add stock with Add bubbles, or to the spent pool on the Resources tab.')));
}
}
if (selected.cell) {
const c = selected.cell;
inspectFacts.replaceChildren(
h('dl', { class: 'facts' },
h('dt', {}, 'Life'), h('dd', { class: 'mono' }, c.life),
h('dt', {}, 'Organism'), h('dd', { class: 'mono' }, c.organism, c.members > 1 ? h('span', { class: 'muted' }, ` ${c.members} cells`) : null),
h('dt', {}, 'Account'), h('dd', {}, c.account ? h('a', { class: 'mono', href: `#/accounts/${c.account}` }, c.account) : h('span', { class: 'muted' }, 'wildlife')),
h('dt', {}, 'Lineage root'), h('dd', { class: 'mono' }, c.root || '—'),
h('dt', {}, 'Size'), h('dd', {}, fmtLength(c.extent)),
h('dt', {}, 'Body mass'), h('dd', {}, fmtMass(c.bodyMass)),
h('dt', {}, 'Position'), h('dd', {}, `${fmtLength(c.x)}, ${fmtLength(c.y)}`),
h('dt', {}, 'State'), h('dd', {}, c.flags & 4 ? h('span', { class: 'badge warn' }, 'lingering') : c.flags & 8 ? h('span', { class: 'badge warn' }, 'suspended') : h('span', { class: 'badge alive' }, 'active'))),
h('h3', { style: { margin: '16px 0 0' } }, 'Reserve'), channelTiles(c.reserve));
} else {
const d = selected.dep;
inspectFacts.replaceChildren(
h('dl', { class: 'facts' },
h('dt', {}, 'Kind'), h('dd', {}, depName(d)),
h('dt', {}, 'Radius'), h('dd', {}, fmtLength(d.r)),
h('dt', {}, 'Position'), h('dd', {}, `${fmtLength(d.x)}, ${fmtLength(d.y)}`)),
h('h3', { style: { margin: '16px 0 0' } }, 'Contents'), channelTiles(d.stock));
}
}
// ----- Resources -----
function drawResources() {
const L = regionLedger(view);
const rows = [
['Cell reserves', L.reserve], ['Cell bodies', L.body], ['Bubbles', L.bubbles], ['Liquid pools', L.pools],
...(sum(L.patches) ? [['Patches', L.patches]] : []), ['Spent pool', L.spent],
...(L.heat ? [['Heat (used energy)', L.heat]] : []),
];
const total = rows.reduce((t, [, v]) => (v ? addTo(t, v) : t), [0, 0, 0, 0, 0]);
const held = [0, 0, 0, 0, 0], free = [0, 0, 0, 0, 0];
if (L.reserve) addTo(held, L.reserve);
if (L.body) addTo(held, L.body);
for (const v of [L.bubbles, L.pools, L.patches]) addTo(free, v);
const parts = [['In cells', held, 'var(--wildlife)'], ['Bubbles and pools', free, 'var(--accent)'], ['Spent pool', L.spent.map(Number), 'var(--warn)'],
...(L.heat ? [['Heat', L.heat, 'var(--bad)']] : [])];
fill(ledgerBox,
h('table', { class: 'ledger' },
h('thead', {}, h('tr', {}, h('th', {}, ''), channels.map((c) => h('th', { class: 'num' }, swatch(c.key), c.short)))),
h('tbody', {},
rows.map(([label, v]) => h('tr', {}, h('td', {}, label), channels.map((c, i) => h('td', { class: 'num' }, v ? c.fmt(v[i]) : '—')))),
h('tr', { class: 'total' }, h('td', {}, 'Total'), channels.map((c, i) => h('td', { class: 'num' }, c.fmt(total[i])))))),
h('div', { style: { marginTop: '12px' } }, channels.map((c, i) => h('div', { class: 'split-row' },
h('span', { class: 'muted' }, c.label),
h('div', { class: 'split', title: parts.map(([n, v]) => `${n}: ${c.fmt(v[i])}`).join('\n') },
parts.map(([, v, color]) => h('span', { style: { width: `${total[i] ? (100 * v[i]) / total[i] : 0}%`, background: color } })))))),
h('div', { class: 'split-legend' }, parts.map(([n, , color]) => h('span', {}, h('span', { class: 'swatch', style: { background: color } }), n))),
L.complete ? null : h('p', { class: 'hint', style: { marginTop: '8px' } }, 'Sums over the listed cells and deposits only (this region server predates complete totals).'));
const plan = dripPlan(view);
const notes = [];
const deposits = Number(view.deposits_total);
const absorbing = plan && plan.absorb;
if (deposits >= depositLimit) {
notes.push(absorbing
? `The region holds ${fmtInt(deposits)} deposits, its limit: drips join existing bubbles, and Add bubbles is refused until cells eat some.`
: `The region holds ${fmtInt(deposits)} deposits, its limit: the drip waits and new bubbles are refused until cells eat some.`);
}
else if (deposits >= depositLimit * 0.95) notes.push(`${fmtInt(depositLimit - deposits)} deposit places left before the limit of ${fmtInt(depositLimit)}.`);
if (pace.stalled) notes.push('The tick is not advancing, so nothing drips until the region ticks again.');
if (!plan) {
dripEvery.textContent = '';
fill(dripBox, h('p', { class: 'hint', style: { marginTop: '8px' } }, 'Only rules-13 regions drip their spent pool (this server does not report the drip).'));
return;
}
dripEvery.textContent = plan.interval ? `every ${(plan.interval * tickSeconds).toLocaleString()} s (${plan.interval} ticks)` : 'off';
if (!sum(plan.next)) notes.push('The spent pool is empty: drips release nothing.');
if (!plan.recycle && L.heat && L.heat[0]) notes.push(`Energy cells use is lost as heat (${fmtEnergy(L.heat[0])} so far): set spent.heat_recycle_per_mille to return it through the drip.`);
const dryIn = (i) => (!Number(view.spent[i]) ? h('span', { class: 'faint' }, 'empty') : plan.interval ? fmtDuration(plan.drips[i] * plan.interval * tickSeconds) : '—');
fill(dripBox,
h('table', { class: 'ledger', style: { marginTop: '12px' } },
h('thead', {}, h('tr', {}, h('th', {}, 'Channel'), h('th', { class: 'num' }, 'In the pool'), h('th', { class: 'num' }, 'Per drip'), h('th', { class: 'num' }, 'Empty in'))),
h('tbody', {}, channels.map((c, i) => h('tr', {},
h('td', {}, swatch(c.key), ' ', c.label),
h('td', { class: 'num' }, c.fmt(view.spent[i])),
h('td', { class: 'num' }, Number(plan.next[i]) ? c.fmt(plan.next[i]) : h('span', { class: 'faint' }, '—')),
h('td', { class: 'num' }, dryIn(i)))))),
h('div', { class: 'muted small', style: { marginTop: '8px' } }, `Each drip makes one bubble per non-empty channel, at most ${fmtEnergy(plan.caps[0])} of energy or ${fmtMass(plan.caps[1])} of one matter, at random spots${plan.absorb ? '; at the deposit limit it joins an existing bubble instead' : ''}.`),
h('div', { class: 'muted small', style: { marginTop: '4px' } }, plan.recycle
? `Energy cycle: ${(plan.recycle / 10).toLocaleString()}% of the region's heat returns to the spent pool every tick.`
: 'Energy cycle: off. Energy cells use stays as heat.'),
notes.length ? h('div', { style: { marginTop: '12px' } }, notes.map((n) => h('div', { class: 'callout' }, n))) : null);
}
// Estimated tick now, between fetches, from the measured pace.
const rate = () => {
const s = pace.samples;
if (s.length < 2) return 1 / tickSeconds;
const dt = (s[s.length - 1].t - s[0].t) / 1000;
return dt > 0 ? (s[s.length - 1].tick - s[0].tick) / dt : 1 / tickSeconds;
};
function animate() {
frame = requestAnimationFrame(animate);
if (!view) return;
const plan = dripPlan(view);
if (!plan || !plan.interval) { k.drip.set(plan ? 'off' : '—', plan ? 'drip interval 0' : 'rules 13 only'); dripCountdown.textContent = plan ? 'off' : '—'; return; }
const r = pace.stalled ? 0 : rate();
const est = Number(view.tick) + Math.min(5, (performance.now() - pace.fetchedAt) / 1000) * r;
const into = ((est % plan.interval) + plan.interval) % plan.interval;
const left = (plan.interval - into) / Math.max(r, 1e-9);
const text = pace.stalled ? 'paused' : `in ${left < 10 ? left.toFixed(1) : Math.round(left)} s`;
const fill = into / plan.interval;
const empty = !sum(plan.next);
k.drip.set(text, empty ? 'spent pool empty' : `${fmtEnergy(plan.next[0])} · ${fmtMass(sum(plan.next.slice(1)))}`, pace.stalled ? 'warn' : '', fill, empty ? 'warn' : '');
dripCountdown.textContent = text;
dripMeter.firstChild.style.width = `${fill * 100}%`;
}
// ----- Pointer -----
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
if (drag) {
if (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3) { drag.moved = true; canvas.classList.add('dragging'); }
panX = drag.panX + (e.clientX - drag.x); panY = drag.panY + (e.clientY - drag.y);
tip.hidden = true;
paint(); return;
}
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (!found) { tip.hidden = true; return; }
tip.replaceChildren(...tipFor(found));
tip.hidden = false;
const x = e.clientX - rect.left + 16, y = e.clientY - rect.top + 16;
tip.style.left = `${Math.min(x, rect.width - tip.offsetWidth - 8)}px`;
tip.style.top = `${Math.min(y, rect.height - tip.offsetHeight - 8)}px`;
});
canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; canvas.classList.remove('dragging'); });
canvas.addEventListener('mousedown', (e) => { drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false }; });
canvas.addEventListener('mouseup', (e) => {
const moved = drag && drag.moved;
drag = null;
canvas.classList.remove('dragging');
if (moved) return;
const rect = canvas.getBoundingClientRect();
const found = hit(e.clientX - rect.left, e.clientY - rect.top);
if (found) select(found);
});
canvas.addEventListener('wheel', (e) => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
setZoom(zoom * Math.exp(-e.deltaY * 0.0015), e.clientX - rect.left - rect.width / 2, e.clientY - rect.top - rect.height / 2);
}, { passive: false });
canvas.addEventListener('dblclick', () => { zoom = 1; panX = 0; panY = 0; paint(); });
const onResize = () => paint();
window.addEventListener('resize', onResize);
window.addEventListener('themechange', onResize);
// ----- Loading -----
async function load() {
try {
const raw = await api(`/api/regions/${region}/view`);
const now = performance.now();
const tick = Number(raw.tick);
if (pace.lastTick === null || tick !== pace.lastTick) pace.movedAt = now;
pace.lastTick = tick;
pace.fetchedAt = now;
pace.samples.push({ t: now, tick });
while (pace.samples.length > 2 && now - pace.samples[0].t > 10000) pace.samples.shift();
pace.stalled = now - pace.movedAt > 3000 && pace.samples.length > 2;
const digestChanged = view && view.rules_sha256 !== raw.rules_sha256;
view = { ...raw, cells: raw.cells.map(cellObj), deps: raw.deposits.map(depObj) };
const counts = raw.counts ? raw.counts.map(Number) : null;
const players = counts ? counts[0] : view.cells.filter((c) => !(c.flags & 1)).length;
const wild = counts ? counts[1] : view.cells.length - players;
const online = view.cells.filter((c) => !(c.flags & 1) && c.flags & 2).length;
const kinds = counts ? counts.slice(2) : [0, 1, 2].map((kd) => view.deps.filter((d) => d.kind === kd).length);
const byChannel = [0, 0, 0, 0, 0];
for (const d of view.deps) if (d.kind === 2) byChannel[d.top] += 1;
chips.players.count.textContent = fmtInt(players - online);
chips.online.count.textContent = fmtInt(online);
chips.wildlife.count.textContent = fmtInt(wild);
chips.pools.count.textContent = fmtInt(kinds[1]);
chips.patches.count.textContent = fmtInt(kinds[0]);
chips.patches.node.hidden = !kinds[0];
channels.forEach((c, i) => { chips[c.key].count.textContent = fmtInt(byChannel[i]); });
const L = regionLedger(view);
const totalOf = (i) => [L.reserve, L.body, L.bubbles, L.pools, L.patches, L.spent, L.heat].reduce((s, v) => s + (v ? Number(v[i]) : 0), 0);
const freeOf = (i) => [L.bubbles, L.pools, L.patches].reduce((s, v) => s + Number(v[i]), 0);
const energy = totalOf(0), matter = [1, 2, 3, 4].reduce((s, i) => s + totalOf(i), 0);
const freeMatter = [1, 2, 3, 4].reduce((s, i) => s + freeOf(i), 0);
const deposits = Number(raw.deposits_total);
const r = rate();
k.tick.set(fmtInt(tick), pace.stalled ? `not advancing for ${fmtDuration((now - pace.movedAt) / 1000)}` : `${r.toFixed(1)} ticks/s`, pace.stalled ? 'warn' : '');
k.cells.set(fmtInt(players + wild), `${fmtInt(players)} players · ${fmtInt(wild)} wildlife`, players + wild ? '' : 'warn');
k.deposits.set(`${fmtInt(deposits)} / ${fmtInt(depositLimit)}`, `${fmtInt(kinds[2])} bubbles · ${fmtInt(kinds[1])} pools`,
deposits >= depositLimit ? 'bad' : '', deposits / depositLimit, deposits >= depositLimit ? 'bad' : deposits >= depositLimit * 0.9 ? 'warn' : '');
k.energy.set(fmtEnergy(energy), `${fmtEnergy(freeOf(0))} free to eat`, energy ? '' : 'bad');
k.matter.set(fmtMass(matter), `${fmtMass(freeMatter)} free to eat`);
k.spent.set(fmtEnergy(raw.spent[0]), `${fmtMass(sum(raw.spent.slice(1)))} matter`);
const truncated = raw.cells_total > raw.cells.length || raw.deposits_total > raw.deposits.length;
fill(titleBadges,
pace.stalled ? h('span', { class: 'badge warn', title: 'The tick has not moved in the last few seconds' }, h('span', { class: 'dot' }), 'not ticking')
: h('span', { class: 'badge alive' }, h('span', { class: 'dot pulse' }), 'running'),
h('span', { class: 'badge' }, `rules ${raw.rules}`),
tuning.running ? h('span', { class: `badge ${tuning.running.revision === null ? 'warn' : ''}` }, tuning.running.label) : null,
truncated ? h('span', { class: 'badge warn', title: 'More cells or deposits than the view lists' }, 'view truncated') : null);
subtitle.textContent = `World ${raw.world} · ${fmtLength(raw.area[0])} × ${fmtLength(raw.area[1])} · updated ${new Date().toLocaleTimeString()}`;
subtitle.className = 'subtitle';
banner.hidden = !pace.stalled;
banner.textContent = pace.stalled ? `Tick ${fmtInt(tick)} has not advanced for ${fmtDuration((now - pace.movedAt) / 1000)}` : '';
if (selected) {
if (selected.cell) {
const again = view.cells.find((c) => c.life === selected.cell.life);
if (again) selected = { cell: again };
else { selected = null; goneText = 'The selected cell is gone (died or left).'; }
} else {
const again = view.deps.find((d) => d.id === selected.dep.id);
if (again) selected = { dep: again };
else { selected = null; goneText = 'The selected deposit is gone (eaten or merged).'; }
}
}
drawInspector();
drawResources();
if (digestChanged || !tuning.tried) tuning.load(digestChanged);
paint();
} catch (e) {
subtitle.textContent = e.status === 503 ? 'The region is not ready or cannot be reached.' : `Could not load the view: ${e.message}`;
subtitle.className = 'subtitle error';
titleBadges.replaceChildren(h('span', { class: 'badge dead' }, 'unreachable'));
}
}
const tick = () => {
timer = setTimeout(async () => {
if (live.checked && !document.hidden) {
await load();
beats += 1;
if (beats % 10 === 0) sessions.load();
if (beats % 5 === 0) commands.load();
if (beats % 15 === 0) schedules.load();
}
tick();
}, 1000);
};
await load();
commands.load();
tick();
animate();
stopPage = () => {
clearTimeout(timer);
cancelAnimationFrame(frame);
window.removeEventListener('resize', onResize);
window.removeEventListener('themechange', onResize);
};
}
// ---------- Tuning (schema 66) ----------
const tuningErrors = {
too_large: 'the text is too large', syntax: 'not a `key = value` line', unknown_key: 'unknown key',
duplicate_key: 'key given twice', invalid_value: 'not an integer', out_of_range: 'value out of range',
missing_key: 'required key missing', inconsistent: 'values contradict each other',
unsupported_version: 'unsupported tuning.version',
};
function tuningProblem(e) {
const d = e.detail || {};
if (e.code === 'invalid_tuning')
return `${d.line ? `Line ${d.line}: ` : ''}${tuningErrors[d.kind] || d.kind}${d.key ? ` (${d.key})` : ''}`;
if (e.code === 'invalid_rules') return 'The values parse but do not make valid rules (a bound or gate is out of range).';
if (e.code === 'safety_version_changed') return `reproduction.safety_version must stay ${d.expected}: it is fixed when a region opens.`;
if (e.code === 'invalid_text') return 'The text must be plain ASCII.';
if (e.code === 'too_large') return 'The text is over 64 KiB.';
return `Refused: ${e.code || e.message}`;
}
// Selects line `n` (1-based) of a textarea so the problem is in view.
function selectLine(area, n) {
const lines = area.value.split('\n');
if (!n || n > lines.length) return;
const start = lines.slice(0, n - 1).reduce((s, l) => s + l.length + 1, 0);
area.focus();
area.setSelectionRange(start, start + lines[n - 1].length);
const lineHeight = parseFloat(getComputedStyle(area).lineHeight) || 18;
area.scrollTop = Math.max(0, (n - 5) * lineHeight);
}
async function tuningPage() {
const data = await api('/api/tuning');
const area = h('textarea', { class: 'tuning', spellcheck: 'false', 'aria-label': 'Tuning text' });
const source = h('span', { class: 'muted' });
const reason = h('input', { type: 'text', class: 'wide', maxlength: 200, placeholder: 'Reason (recorded with the revision)' });
const note = h('div', { class: 'small' });
const regionsBox = h('div', { class: 'muted' }, 'Loading…');
const byDigest = new Map(data.revisions.map((r) => [r.rules_sha256, `revision ${r.revision}`]));
if (data.baseline && data.baseline.rules_sha256 && !byDigest.has(data.baseline.rules_sha256))
byDigest.set(data.baseline.rules_sha256, 'the baseline file');
let loadedText = '';
const load = (text, label) => { area.value = text; loadedText = text; source.textContent = label; note.textContent = ''; };
if (data.newest) load(data.newest.text, `Editing a copy of revision ${data.newest.revision}`);
else if (data.baseline) load(data.baseline.text, 'Editing a copy of the baseline file (no revisions yet)');
else load('', 'No baseline file and no revisions');
const say = (text, cls = 'muted') => { note.className = `small ${cls}`; note.textContent = text; };
const check = async () => {
try {
const r = await api('/api/tuning?check=1', true, 'POST', area.value);
const known = byDigest.get(r.rules_sha256);
say(known ? `Valid. These are the same rules as ${known}.` : `Valid. New rules ${r.rules_sha256.slice(0, 12)}…`, 'good');
return r;
} catch (e) {
say(tuningProblem(e), 'error');
if (e.detail && e.detail.line) selectLine(area, e.detail.line);
return null;
}
};
const adopt = async () => {
const ok = await check();
if (!ok) return;
const regions = data.regions.length === 1 ? `region ${data.regions[0]}` : `all ${data.regions.length} regions`;
if (!window.confirm(`Adopt this tuning in ${regions} of world ${data.world}?\n\nEach region switches at its next tick; the change is recorded in its history and cannot be undone except by adopting another revision.`)) return;
try {
const q = new URLSearchParams();
if (reason.value.trim()) q.set('reason', reason.value.trim());
const r = await api(`/api/tuning?${q}`, true, 'POST', area.value);
say(`Stored revision ${r.revision}; queued for ${r.regions} region(s).`, 'good');
reason.value = '';
setTimeout(() => route(), 1500);
} catch (e) {
say(tuningProblem(e), 'error');
}
};
const revert = () => load(loadedText, source.textContent);
// Which rules each region runs now, from its live view.
(async () => {
const rows = await Promise.all(data.regions.map(async (region) => {
try {
const v = await api(`/api/regions/${region}/view`);
const running = v.rules_sha256 ? byDigest.get(v.rules_sha256) : null;
return h('tr', {}, h('td', {}, h('a', { href: `#/regions/${region}` }, `Region ${region}`)),
h('td', {}, v.rules_sha256
? (running ? h('span', { class: 'badge alive' }, running) : h('span', { class: 'badge warn', title: v.rules_sha256 }, `other rules ${v.rules_sha256.slice(0, 8)}…`))
: h('span', { class: 'muted' }, `rules ${v.rules}`)),
h('td', { class: 'muted' }, `tick ${fmtInt(v.tick)}`));
} catch (e) {
return h('tr', {}, h('td', {}, `Region ${region}`), h('td', { class: 'muted', colspan: 2 }, `unavailable: ${e.code || e.message}`));
}
}));
regionsBox.replaceChildren(rows.length ? h('table', { class: 'compact' }, h('tbody', {}, rows)) : 'No regions configured.');
})();
const revisions = data.revisions.length ? h('table', { class: 'compact' }, h('tbody', {}, data.revisions.map((r) =>
h('tr', {},
h('td', { class: 'mono' }, `#${r.revision}`),
h('td', {}, h('div', {}, r.reason || h('span', { class: 'muted' }, 'no reason')),
h('div', { class: 'muted', title: r.author || '' }, `${(r.author || '').split(' (')[0]} · ${fmtAgo(r.created_at)}`)),
h('td', {}, r.adopted >= r.regions && r.regions > 0
? h('span', { class: 'badge alive', title: r.last_tick ? `last at tick ${r.last_tick}` : '' }, `adopted ${r.adopted}/${r.regions}`)
: h('span', { class: 'badge warn' }, `pending ${r.adopted}/${r.regions}`)),
h('td', {}, h('button', {
onclick: async () => {
try { const t = await api(`/api/tuning/${r.revision}`); load(t.text, `Editing a copy of revision ${t.revision}`); } catch (e) { say(`Could not load: ${e.code || e.message}`, 'error'); }
},
}, 'Load')))))) : h('p', { class: 'muted' }, 'No revisions yet: regions run the rules they opened with.');
show(
h('div', { class: 'head' },
h('div', {}, h('h1', {}, 'Cellular tuning'), h('div', { class: 'subtitle' }, `World ${data.world} · rules 13 · every region adopts the same revision`)),
h('div', { class: 'tools' }, h('button', { onclick: () => route() }, 'Refresh'))),
h('div', { class: 'tuning-layout' },
h('div', { class: 'card' },
h('div', { class: 'head' }, source,
h('div', { class: 'tools' },
data.baseline ? h('button', { class: 'ghost', onclick: () => load(data.baseline.text, 'Editing a copy of the baseline file') }, 'Load baseline') : null,
h('button', { class: 'ghost', onclick: revert }, 'Revert'))),
area,
h('div', { class: 'action' }, reason,
h('div', { class: 'row' }, h('button', { onclick: check }, 'Check'), h('button', { class: 'primary', onclick: adopt }, 'Adopt')),
note)),
h('div', { class: 'side' },
h('div', { class: 'card' }, h('h2', {}, 'Regions'), regionsBox),
h('div', { class: 'card' }, h('h2', {}, 'Revisions'), revisions),
data.region_file ? h('div', { class: 'card' }, h('h2', {}, 'Region file'),
h('p', { class: 'hint' }, 'cellular.tuning from Git, read only: read when a region starts (shape and currents when it opens). Changing it takes a commit and a sync.'),
settingsView(data.region_file, { open: false })) : null,
h('div', { class: 'card muted small' },
'The file format is the Git revamp tuning file (key = value, integers). A region adopts a revision at a tick recorded in its trace, so replay and recovery reproduce it. ',
'reproduction.safety_version cannot change live, and playtest.* keys only matter when a region opens.'))));
}
// ---------- Routing ----------
async function route() {
stopPage();
stopPage = () => {};
const [path, query] = (location.hash.slice(1) || '/accounts').split('?');
const parts = path.split('/').filter(Boolean);
const params = new URLSearchParams(query || '');
for (const a of document.querySelectorAll('[data-route]')) a.classList.toggle('active', a.dataset.route === parts[0]);
try {
if (parts[0] === 'accounts' && parts[1]) await accountPage(parts[1]);
else if (parts[0] === 'regions' && parts[1]) await regionPage(parts[1], params);
else if (parts[0] === 'regions') await regionsPage();
else if (parts[0] === 'tuning') await tuningPage();
else await accountsPage();
main().focus({ preventScroll: true });
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
if (e instanceof ApiError && e.status === 403) {
return show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'Not an administrator'),
h('p', { class: 'muted' }, 'Your account does not have the aevolution-admin role.'),
h('button', { onclick: signOut }, 'Sign out'))));
}
show(h('p', { class: 'error' }, `Could not load this page: ${e.message}`), h('button', { onclick: () => route() }, 'Try again'));
}
}
function signedOut() {
document.getElementById('who').textContent = '';
document.getElementById('sign-out').hidden = true;
show(h('div', { class: 'center' }, h('div', {}, h('h1', {}, 'AEvolution admin'),
h('p', { class: 'muted' }, 'Sign in with an account that has the aevolution-admin role.'),
h('button', { class: 'primary', onclick: signIn }, 'Sign in'))));
}
async function start() {
config = await (await fetch('/config.json', { cache: 'no-store' })).json();
document.getElementById('sign-out').addEventListener('click', signOut);
try {
await finishSignIn();
} catch (e) {
show(h('p', { class: 'error' }, e.message), h('button', { class: 'primary', onclick: signIn }, 'Sign in again'));
return;
}
if (!(await token())) return signedOut();
const env = document.getElementById('env');
if (env) { env.textContent = `World ${config.world}`; env.hidden = !config.world; }
try {
const me = await api('/api/me');
document.getElementById('who').textContent = me.email || me.subject;
document.getElementById('sign-out').hidden = false;
} catch (e) {
if (e instanceof ApiError && e.status === 401) return signedOut();
}
window.addEventListener('hashchange', route);
await route();
}
start();