From 6338cc914298fa32dffb7cd1fedbc77032243511 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 28 Oct 2026 07:54:28 -0400 Subject: [PATCH] feat(admin): region page redesign, resource ledger, drip and dark mode The region view adds the rules-13 drip and complete counts and totals over every life and deposit. The region page is rebuilt around the map: a KPI strip (tick pace, population, deposit capacity, region energy and matter, spent pool, next drip), layer toggles that double as the legend, zoom and a scale, and tabs for inspecting cells and deposits, resources (where each channel sits, the spent pool and each channel's next drip), actions, the running tuning and session access. The admin API serves the region tuning file read only (--region-tuning). Light and dark themes. Co-Authored-By: Claude Opus 5.5 --- apps/evo-admin-api/main.cpp | 17 +- apps/evo-admin-api/portal/app.js | 1225 ++++++++++++----- apps/evo-admin-api/portal/index.html | 8 +- apps/evo-admin-api/portal/style.css | 636 +++++++-- .../admin-portal-dev/deployment.yaml | 6 +- docs/STATUS.md | 10 + .../adr/0182-admin-portal-and-world-tuning.md | 9 + include/evo/server/admin/admin_api.hpp | 7 +- .../server/lifecycle/cellular_admin_view.hpp | 8 +- src/server/admin/admin_api.cpp | 2 + src/server/lifecycle/cellular_admin_view.cpp | 67 +- tests/cellular_admin_view_tests.cpp | 76 + tests/grant_broker_tests.cpp | 4 +- 13 files changed, 1595 insertions(+), 480 deletions(-) diff --git a/apps/evo-admin-api/main.cpp b/apps/evo-admin-api/main.cpp index ff2db48..a9eee87 100644 --- a/apps/evo-admin-api/main.cpp +++ b/apps/evo-admin-api/main.cpp @@ -3,11 +3,13 @@ // evo-admin-api --listen ADDRESS:PORT --world N --jwks JSON --oidc-issuer URL // --audience NAME --client NAME --role NAME --assets DIR // --pg-passfile F --pg-service F [--region REGION=HOST:PORT ...] [--baseline-tuning F] +// [--region-tuning F] // // --assets holds the portal's index.html, app.js and style.css. Each --region names a // region's operations address, whose /admin/view the portal may show; those regions adopt // tuning revisions. --baseline-tuning is the revamp tuning file they opened with, shown -// until the first revision. No token is printed. +// until the first revision; --region-tuning the region tuning file they start with, shown +// read only. No token is printed. #include "evo/persistence/postgres.hpp" #include "evo/server/admin/admin_api.hpp" @@ -35,7 +37,8 @@ void on_stop(int) { } struct Options { - std::string listen, jwks, oidc_issuer, audience, client, role, assets, baseline_tuning; + std::string listen, jwks, oidc_issuer, audience, client, role, assets, baseline_tuning, + region_tuning; std::uint64_t world{}; std::map regions; // Region to its operations address. persistence::PgOptions pg; @@ -74,6 +77,8 @@ std::optional parse(int argc, char** argv) { o.assets = value; else if (flag == "--baseline-tuning") o.baseline_tuning = value; + else if (flag == "--region-tuning") + o.region_tuning = value; else if (flag == "--pg-service") pg_service = value; else if (flag == "--pg-passfile") @@ -169,6 +174,14 @@ int main(int argc, char** argv) { } config.baseline_tuning = std::move(*baseline); } + if (!options->region_tuning.empty()) { + auto region = read_file(options->region_tuning); + if (!region) { + std::puts("error region-tuning"); + return 2; + } + config.region_tuning = std::move(*region); + } config.portal_config_json = "{\"issuer\":\"" + options->oidc_issuer + "\",\"client_id\":\"" + options->client + "\",\"world\":" + std::to_string(options->world) + "}\n"; diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js index 19bf793..341998f 100644 --- a/apps/evo-admin-api/portal/app.js +++ b/apps/evo-admin-api/portal/app.js @@ -18,6 +18,7 @@ function h(tag, attrs = {}, ...children) { 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)); @@ -31,6 +32,24 @@ function h(tag, attrs = {}, ...children) { 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) { @@ -234,7 +253,7 @@ async function accountsPage() { 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('span', { class: 'muted' }, `World ${data.world}`)), + 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)), @@ -317,21 +336,275 @@ async function accountPage(id) { { 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', { href: '#/accounts' }, '← Accounts'), h('h1', {}, `Account ${short(a.account)}`))), + 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', {}, 'Lives'), lives, + 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('span', { class: 'muted' }, `World ${data.world}`)), + 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) }, @@ -344,249 +617,272 @@ async function regionsPage() { { 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' })); + ], 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 online', title: fmtTime(r.window_expires) }, `open · closes ${fmtAgo(r.window_expires)}`) - : h('span', { class: 'muted' }, 'closed'); -} - -// 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 sessionWindowCard(region) { - const card = h('div', { class: 'card' }); - 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 = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' }); - const note = h('div', { class: 'muted small' }); - 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.textContent = 'Saved. The region applies it within about 5 seconds.'; - } catch (e) { - 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', { onclick: () => send(0) }, 'Close sessions'); - const status = h('div'); - const history = h('div'); - 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; - status.replaceChildren(w.open - ? h('div', {}, h('span', { class: 'badge online' }, 'open'), ` until ${fmtTime(current.expires_at)} (closes ${fmtAgo(current.expires_at)})`) - : h('div', {}, h('span', { class: 'badge' }, 'closed'), current && current.expires_at ? ` expired ${fmtAgo(current.expires_at)}` : '')); - history.replaceChildren(w.history.length ? h('table', { class: 'compact' }, h('tbody', {}, w.history.slice(0, 8).map((x) => - h('tr', {}, h('td', {}, fmtAgo(x.created_at)), - h('td', {}, x.expires_at ? `opened until ${new Date(x.expires_at * 1000).toLocaleTimeString()}` : 'closed'), - h('td', { class: 'muted', title: x.author || '' }, (x.author || '').split(' (')[0]), - h('td', { class: 'muted' }, x.reason || ''))))) : h('p', { class: 'muted' }, 'No window has been opened yet.')); - } catch (e) { - status.textContent = `Unavailable: ${e.message}`; - } - } - card.replaceChildren(h('h2', {}, 'Session window'), status, - h('div', { class: 'window-controls' }, minutes, openButton, closeButton), reason, note, history); - load(); - return { card, load }; -} - -// Amounts typed in friendly units: energy in µJ (10^6 pJ), matter in ng (10^6 fg). -function amountInputs() { - const make = (label) => h('input', { type: 'number', min: 0, step: 'any', placeholder: label, class: 'amount' }); - const fields = { energy: make('energy µJ'), carbon: make('C ng'), nitrogen: make('N ng'), phosphorus: make('P ng'), other: make('other ng') }; - const read = () => { - const out = {}; - for (const [name, input] of Object.entries(fields)) { - const v = Number(input.value || 0); - if (!Number.isFinite(v) || v < 0) throw new Error(`${name} must be a positive number`); - out[name] = String(Math.round(v * 1e6)); - } - return out; - }; - const clear = () => Object.values(fields).forEach((input) => { input.value = ''; }); - return { node: h('div', { class: 'amounts' }, Object.values(fields)), read, clear }; -} - -const kindLabels = { - remove_cell: 'remove cell', grant_reserve: 'grant reserve', add_bubbles: 'add bubbles', - add_pool: 'add to pool', release_pool: 'release pool', spawn_wildlife: 'spawn wildlife', - adopt_tuning: 'adopt tuning', -}; - -// Admin commands (ADR-0182): queued now, applied by the region at its next ticks. -function commandsCard(region) { - const note = h('div', { class: 'muted small' }); - const history = h('div'); - const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' }); - async function send(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}/commands?${q}`, true, 'POST'); - note.textContent = `Queued #${r.id} (${label}). The region applies it within a few seconds.`; - reason.value = ''; - load(); - return true; - } catch (e) { - note.textContent = `Could not queue ${label}: ${e.code || e.message}`; - return false; - } - } - const spawnCount = h('input', { type: 'number', min: 1, max: 64, value: 10, class: 'count' }); - const bubbleCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' }); - const bubbleAmount = amountInputs(); - const poolAmount = amountInputs(); - const releaseCount = h('input', { type: 'number', min: 1, max: 256, value: 20, class: 'count' }); - const releaseAmount = amountInputs(); - const withAmount = (amount, extra, label) => { - let values; - try { values = amount.read(); } catch (e) { note.textContent = e.message; return; } - send({ ...extra, ...values }, label).then((ok) => { if (ok) amount.clear(); }); - }; - async function load() { - try { - const data = await api(`/api/regions/${region}/commands`); - history.replaceChildren(data.commands.length ? h('table', { class: 'compact' }, h('tbody', {}, data.commands.slice(0, 10).map((c) => - h('tr', {}, h('td', { class: 'mono' }, `#${c.id}`), h('td', {}, kindLabels[c.kind] || c.kind, - c.count ? ` ×${c.count}` : '', c.kind === 'remove_cell' || c.kind === 'grant_reserve' ? ` ${c.target}` : '', - c.kind === 'adopt_tuning' ? ` revision ${c.target}` : ''), - h('td', {}, c.applied_tick ? h('span', { class: 'badge alive' }, `tick ${c.applied_tick}`) : h('span', { class: 'badge warn' }, 'pending')), - h('td', { class: 'muted', title: c.author || '' }, (c.author || '').split(' (')[0]))))) : h('p', { class: 'muted' }, 'No commands yet.')); - } catch (e) { - history.textContent = `Unavailable: ${e.message}`; - } - } - const card = h('div', { class: 'card' }, - h('h2', {}, 'Region actions'), - h('div', { class: 'action' }, h('strong', {}, 'Spawn wildlife'), h('div', { class: 'row' }, spawnCount, - h('button', { onclick: () => send({ kind: 'spawn_wildlife', count: spawnCount.value }, 'spawn wildlife') }, 'Spawn'))), - h('div', { class: 'action' }, h('strong', {}, 'Add bubbles'), bubbleAmount.node, h('div', { class: 'row' }, bubbleCount, h('span', { class: 'muted' }, 'bubbles'), - h('button', { onclick: () => withAmount(bubbleAmount, { kind: 'add_bubbles', count: bubbleCount.value }, 'add bubbles') }, 'Add'))), - h('div', { class: 'action' }, h('strong', {}, 'Add to spent pool'), poolAmount.node, - h('div', { class: 'row' }, h('button', { onclick: () => withAmount(poolAmount, { kind: 'add_pool' }, 'add to pool') }, 'Add to pool'))), - h('div', { class: 'action' }, h('strong', {}, 'Release spent pool as bubbles'), releaseAmount.node, - h('div', { class: 'row' }, releaseCount, h('span', { class: 'muted' }, 'bubbles'), - h('button', { onclick: () => withAmount(releaseAmount, { kind: 'release_pool', count: releaseCount.value }, 'release pool') }, 'Release'))), - reason, note, h('h2', {}, 'Recent commands'), history); - load(); - return { card, load, send }; -} - -// 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 schedulesCard(region) { - const list = h('div'); - const note = h('div', { class: 'muted small' }); - 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(); - const reason = h('input', { type: 'text', maxlength: 200, placeholder: 'Reason (optional)' }); - 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.textContent = `Saved schedule #${r.id} (${label}).`; - reason.value = ''; - load(); - return true; - } catch (e) { 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.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('table', { class: 'compact' }, h('tbody', {}, data.schedules.map((x) => - h('tr', {}, - h('td', { class: 'mono' }, `#${x.id}`), - h('td', {}, `${kindLabels[x.kind] || x.kind} ×${x.count} every ${fmtDuration(x.interval)}`, - x.kind !== 'spawn_wildlife' ? h('div', { class: 'muted' }, `per run: ${fmtEnergy(x.amount[0])}, ${x.amount.slice(1).map(fmtMass).join(' / ')}`) : null), - h('td', {}, x.enabled ? h('span', { class: 'badge alive' }, `on · ${x.runs} runs`) : h('span', { class: 'badge' }, 'off')), - h('td', {}, h('button', { onclick: () => save({ ...fromSchedule(x), enabled: x.enabled ? '0' : '1' }, x.enabled ? 'disabled' : 'enabled') }, x.enabled ? 'Stop' : 'Start')))))) : h('p', { class: 'muted' }, 'No schedules.')); - } catch (e) { list.textContent = `Unavailable: ${e.message}`; } - } - const card = h('div', { class: 'card' }, h('h2', {}, 'Resource schedules'), list, - h('div', { class: 'action' }, h('strong', {}, 'New schedule'), - h('div', { class: 'row' }, kind, count, h('span', { class: 'muted' }, 'every'), every, h('span', { class: 'muted' }, 's')), - amount.node, h('div', { class: 'row' }, h('button', { onclick: add }, 'Add schedule'))), - reason, note); - load(); - return { card, load }; + 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 ---------- -const channelNames = ['energy', 'carbon', 'nitrogen', 'phosphorus', 'other']; -const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim(); +// 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]; + 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 }; + } + 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 }; +} +// The rules-13 drip: every `interval` ticks, one bubble per non-empty channel of at most the cap. +function dripPlan(view) { + if (!view.drip) return null; + const [interval, capE, capM] = view.drip.map(Number); + const caps = [capE, capM, capM, capM, capM]; + const spent = view.spent.map(Number); + return { + interval, caps, + 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 canvas = h('canvas'); - const tip = h('div', { class: 'tooltip', hidden: true }); - const note = h('div', { class: 'overlay-note' }, 'Scroll to zoom, drag to pan, double-click to reset.'); - const statsBox = h('div', { class: 'stats' }); - const detail = h('div', { class: 'card' }, h('span', { class: 'muted' }, 'Select a cell to see it here.')); - const status = h('span', { class: 'muted' }); - const show_ = { players: true, wildlife: true, pools: true, bubbles: true }; - const toggle = (k, label) => h('label', {}, h('input', { type: 'checkbox', checked: true, onchange: (e) => { show_[k] = e.target.checked; paint(); } }), label); - const live = h('input', { type: 'checkbox', checked: true }); - const sessions = sessionWindowCard(region); - const commands = commandsCard(region); - const schedules = schedulesCard(region); - let view = null, selected = null, timer = null, beats = 0; + 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', { href: '#/regions' }, '← Regions'), h('h1', {}, `Region ${region}`), status), - h('div', { class: 'tools' }, h('label', {}, live, ' Live (1 s)'), h('button', { onclick: () => load() }, 'Refresh'))), - statsBox, - h('div', { class: 'region-layout' }, - h('div', { class: 'canvas-wrap' }, canvas, tip, note), - h('div', { class: 'side' }, - sessions.card, - detail, - commands.card, - schedules.card, - h('div', { class: 'card' }, h('h2', {}, 'Show'), h('div', { class: 'toggles' }, - toggle('players', 'Player cells'), toggle('wildlife', 'Wildlife'), toggle('pools', 'Pools'), toggle('bubbles', 'Bubbles'))), - h('div', { class: 'card' }, h('h2', {}, 'Legend'), h('div', { class: 'legend' }, - h('span', { class: 'swatch player' }), 'Player cell', - h('span', { class: 'swatch online' }), 'Player cell, connected', - h('span', { class: 'swatch wildlife' }), 'Wildlife', - h('span', { class: 'swatch pool' }), 'Pool', - ...channelNames.flatMap((c) => [h('span', { class: `swatch ${c}` }), `Bubble, mostly ${c}`])))))); + 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], + reserve: c.slice(8, 13), bodyMass: c[13], root: c[14], }); - const depObj = (d) => ({ id: d[0], kind: d[1], x: d[2], y: d[3], r: d[4], stock: d.slice(5, 10) }); + 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() { const rect = canvas.getBoundingClientRect(); @@ -594,183 +890,421 @@ async function regionPage(region, params) { 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); + 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, toX: (x) => ox + x * s, toY: (y) => oy + (ah - y) * s, fromX: (px) => (px - ox) / s, fromY: (py) => ah - (py - oy) / s }; + 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 ctx = canvas.getContext('2d'); const g = geometry(); - ctx.clearRect(0, 0, canvas.width, canvas.height); + ctx.fillStyle = css('map-bg'); + ctx.fillRect(0, 0, g.w, g.hgt); if (!view) return; const [aw, ah] = view.area; - ctx.strokeStyle = css('line'); + // 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); - if (show_.pools) { - ctx.fillStyle = css('pool'); - ctx.strokeStyle = css('accent'); - for (const d of view.deps) if (d.kind !== 2) { - ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 2 * g.dpr), 0, Math.PI * 2); ctx.fill(); - } + + 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(); } - if (show_.bubbles) { - const colors = channelNames.map(css); - for (const d of view.deps) if (d.kind === 2) { - // Energy counts in pJ, matter in fg; ~17 pJ per fg of food, so compare on that scale. - const weights = [d.stock[0] / 17, d.stock[1], d.stock[2], d.stock[3], d.stock[4]]; - const top = weights.indexOf(Math.max(...weights)); - ctx.fillStyle = colors[top]; - ctx.beginPath(); ctx.arc(g.toX(d.x), g.toY(d.y), Math.max(d.r * g.s, 1.5 * g.dpr), 0, Math.PI * 2); ctx.fill(); - } + 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 wild = (c.flags & 1) !== 0; - if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue; - const online = (c.flags & 2) !== 0, faded = (c.flags & 12) !== 0; - const size = Math.max(c.extent * g.s, 3 * g.dpr); + 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.9; - ctx.fillStyle = wild ? css('wildlife') : online ? css('online') : css('player'); + 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; - const marked = (highlight && c.account === highlight) || (selected && selected.life === c.life); - if (marked) { - ctx.strokeStyle = css('warn'); ctx.lineWidth = 2 * g.dpr; - ctx.beginPath(); ctx.arc(x, y, size / 2 + 4 * g.dpr, 0, Math.PI * 2); ctx.stroke(); - } + 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 = 4 / g.s * g.dpr; - for (const c of view ? view.cells : []) { - const wild = (c.flags & 1) !== 0; - if ((wild && !show_.wildlife) || (!wild && !show_.players)) continue; + 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 }; } - if (show_.bubbles || show_.pools) { - for (const d of view ? view.deps : []) { - if ((d.kind === 2 && !show_.bubbles) || (d.kind !== 2 && !show_.pools)) continue; - const r = Math.max(d.r, slack); - if ((wx - d.x) ** 2 + (wy - d.y) ** 2 <= r * r) return { dep: d }; - } + // 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; } - function cellLines(c) { - const kind = c.flags & 1 ? 'Wildlife' : c.flags & 2 ? 'Player (connected)' : 'Player'; - return [ - ['Kind', kind], ['Life', c.life], ['Organism', c.organism], ['Account', c.account || '—'], - ['Members', c.members], ['Size', fmtLength(c.extent)], ['Body mass', fmtMass(c.bodyMass)], - ['Reserve energy', fmtEnergy(c.reserve[0])], - ['Reserve C / N / P / other', c.reserve.slice(1).map(fmtMass).join(' / ')], - ['Position', `${fmtLength(c.x)}, ${fmtLength(c.y)}`], - ]; - } - function showDetail(c) { - selected = c; - const grant = amountInputs(); - const remove = () => { - if (!confirm(`Remove ${c.flags & 1 ? 'wildlife' : 'player'} cell ${c.life}? Its body and reserve go to the spent pool.`)) return; - commands.send({ kind: 'remove_cell', target: c.life }, `remove cell ${c.life}`); - }; - const give = () => { - let values; - try { values = grant.read(); } catch (e) { return alert(e.message); } - commands.send({ kind: 'grant_reserve', target: c.life, ...values }, `grant reserve to ${c.life}`) - .then((ok) => { if (ok) grant.clear(); }); - }; - detail.replaceChildren(h('h2', {}, c.flags & 1 ? 'Wildlife cell' : 'Player cell'), - h('dl', { class: 'facts' }, cellLines(c).flatMap(([k, v]) => [h('dt', {}, k), h('dd', { class: k === 'Life' || k === 'Account' ? 'mono' : null }, v)])), - c.account ? h('p', {}, h('a', { href: `#/accounts/${c.account}` }, 'Open account →')) : null, - h('div', { class: 'action' }, h('strong', {}, 'Grant reserve'), grant.node, - h('div', { class: 'row' }, h('button', { onclick: give }, 'Grant'), h('button', { class: 'danger', onclick: remove }, 'Remove cell')))); - paint(); + 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], + ]; + 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)']]; + 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); + if (deposits >= depositLimit) notes.push(`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.'); + 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.`), + 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; } - const lines = found.cell - ? cellLines(found.cell).slice(0, 7) - : [['Kind', found.dep.kind === 2 ? 'Bubble' : 'Pool'], ['Energy', fmtEnergy(found.dep.stock[0])], - ['C / N / P / other', found.dep.stock.slice(1).map(fmtMass).join(' / ')], ['Radius', fmtLength(found.dep.r)]]; - tip.replaceChildren(...lines.map(([k, v]) => h('div', {}, h('span', { class: 'muted' }, `${k}: `), String(v)))); + tip.replaceChildren(...tipFor(found)); tip.hidden = false; - tip.style.left = `${Math.min(e.clientX - rect.left + 14, rect.width - 290)}px`; - tip.style.top = `${e.clientY - rect.top + 14}px`; + 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.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 wasDrag = drag && (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3); + const moved = drag && drag.moved; drag = null; - if (wasDrag) return; + canvas.classList.remove('dragging'); + if (moved) return; const rect = canvas.getBoundingClientRect(); const found = hit(e.clientX - rect.left, e.clientY - rect.top); - if (found && found.cell) showDetail(found.cell); + if (found) select(found); }); canvas.addEventListener('wheel', (e) => { e.preventDefault(); const rect = canvas.getBoundingClientRect(); - const mx = e.clientX - rect.left - rect.width / 2, my = e.clientY - rect.top - rect.height / 2; - const factor = Math.exp(-e.deltaY * 0.0015); - const next = Math.min(64, Math.max(1, zoom * factor)); - const k = next / zoom; - panX = mx - (mx - panX) * k; panY = my - (my - panY) * k; - zoom = next; - if (zoom === 1) { panX = 0; panY = 0; } - paint(); + 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 players = view.cells.filter((c) => !(c.flags & 1)); - const online = players.filter((c) => c.flags & 2).length; - const wild = view.cells.length - players.length; - const bubbles = view.deps.filter((d) => d.kind === 2).length; - const spentMatter = raw.spent.slice(1).reduce((s, v) => s + v, 0); - statsBox.replaceChildren( - stat('Tick', fmtInt(raw.tick)), stat('Cells', fmtInt(raw.cells_total)), - stat('Players', fmtInt(players.length), `${online} connected`), stat('Wildlife', fmtInt(wild)), - stat('Bubbles', fmtInt(bubbles), `${fmtInt(raw.deposits_total - bubbles)} pools`), - stat('Spent pool', fmtEnergy(raw.spent[0]), fmtMass(spentMatter)), - stat('Area', `${fmtLength(raw.area[0])} × ${fmtLength(raw.area[1])}`)); + 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].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; - status.textContent = ` rules ${raw.rules}${truncated ? ' · view truncated' : ''} · updated ${new Date().toLocaleTimeString()}`; - status.className = truncated ? 'error' : 'muted'; + 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) { - const again = view.cells.find((c) => c.life === selected.life); - if (again) showDetail(again); else { selected = null; detail.replaceChildren(h('span', { class: 'muted' }, 'The selected cell is gone (died or left).')); } + 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) { - status.textContent = ` ${e.status === 503 ? 'region not ready or unreachable' : e.message}`; - status.className = 'error'; + 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(); - if (++beats % 10 === 0) sessions.load(); + beats += 1; + if (beats % 10 === 0) sessions.load(); if (beats % 5 === 0) commands.load(); if (beats % 15 === 0) schedules.load(); } @@ -778,8 +1312,15 @@ async function regionPage(region, params) { }, 1000); }; await load(); + commands.load(); tick(); - stopPage = () => { clearTimeout(timer); window.removeEventListener('resize', onResize); }; + animate(); + stopPage = () => { + clearTimeout(timer); + cancelAnimationFrame(frame); + window.removeEventListener('resize', onResize); + window.removeEventListener('themechange', onResize); + }; } // ---------- Tuning (schema 66) ---------- @@ -891,7 +1432,7 @@ async function tuningPage() { show( h('div', { class: 'head' }, - h('div', {}, h('h1', {}, 'Cellular tuning'), h('span', { class: 'muted' }, `World ${data.world} · rules 13 · every region adopts the same revision`)), + 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' }, @@ -906,6 +1447,9 @@ async function tuningPage() { 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.')))); @@ -955,6 +1499,9 @@ async function start() { return; } if (!(await token())) return signedOut(); + const env = document.getElementById('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; diff --git a/apps/evo-admin-api/portal/index.html b/apps/evo-admin-api/portal/index.html index ef7e49b..7f770c9 100644 --- a/apps/evo-admin-api/portal/index.html +++ b/apps/evo-admin-api/portal/index.html @@ -20,7 +20,13 @@
- + +
+ + + +
+
diff --git a/apps/evo-admin-api/portal/style.css b/apps/evo-admin-api/portal/style.css index 7afa1c2..03f7f27 100644 --- a/apps/evo-admin-api/portal/style.css +++ b/apps/evo-admin-api/portal/style.css @@ -1,217 +1,591 @@ -/* ADR-0182 admin portal. Tokens first; dark is the default, light follows the system. */ +/* ADR-0182 admin portal. Tokens first: light by default, dark from the system or the header's + theme switch (html[data-theme]). The region map reads the map tokens when it paints. */ :root { - --bg: #0f1419; - --panel: #161d24; - --panel-2: #1c252e; - --line: #2a3640; - --text: #dbe3ea; - --muted: #8a99a6; - --accent: #4fb3ff; - --good: #3ecf8e; - --warn: #f2b84b; - --bad: #ff6b6b; - --player: #4f8dff; - --online: #5ff2ff; - --wildlife: #3ecf8e; - --pool: rgba(120, 170, 255, 0.16); - --energy: #ffd84d; - --carbon: #b0b7bf; - --nitrogen: #9b7bff; - --phosphorus: #ff9a3c; - --other: #ff6fb5; - --radius: 8px; - --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; - color-scheme: dark; + --bg: #f3f5f8; + --panel: #ffffff; + --panel-2: #f6f8fa; + --panel-3: #eef1f5; + --line: #e1e6ec; + --line-strong: #cfd6de; + --text: #17202a; + --muted: #5f6c79; + --faint: #8b96a2; + --accent: #2563eb; + --accent-soft: rgba(37, 99, 235, 0.1); + --on-accent: #ffffff; + --good: #15925f; + --good-soft: rgba(21, 146, 95, 0.1); + --warn: #b7791f; + --warn-soft: rgba(183, 121, 31, 0.12); + --bad: #d64545; + --bad-soft: rgba(214, 69, 69, 0.1); + --shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 1px 3px rgba(16, 24, 40, 0.06); + --shadow-pop: 0 8px 24px rgba(16, 24, 40, 0.14); + /* Region map. */ + --map-bg: #fbfcfd; + --map-grid: rgba(23, 32, 42, 0.05); + --map-edge: #cfd6de; + --map-glass: rgba(255, 255, 255, 0.86); + --player: #2f6fed; + --online: #06b6d4; + --wildlife: #16a34a; + --pool: rgba(37, 99, 235, 0.1); + --pool-edge: rgba(37, 99, 235, 0.45); + --patch: rgba(120, 90, 40, 0.14); + --select: #f59e0b; + --energy: #eab308; + --carbon: #4b5563; + --nitrogen: #8b5cf6; + --phosphorus: #f97316; + --other: #ec4899; + --radius: 10px; + --radius-sm: 7px; + --mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; + color-scheme: light; } -@media (prefers-color-scheme: light) { - :root { - --bg: #f5f7f9; - --panel: #ffffff; - --panel-2: #eef2f5; - --line: #d6dde3; - --text: #18212a; - --muted: #5d6b77; - --accent: #0b6bcb; - --pool: rgba(30, 90, 200, 0.12); - --carbon: #59626b; - color-scheme: light; +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #0b0f14; + --panel: #121820; + --panel-2: #161e27; + --panel-3: #1c2531; + --line: #232d3a; + --line-strong: #2f3b4b; + --text: #e4eaf0; + --muted: #8d9aa8; + --faint: #64717f; + --accent: #5b9dff; + --accent-soft: rgba(91, 157, 255, 0.14); + --on-accent: #06101f; + --good: #3ecf8e; + --good-soft: rgba(62, 207, 142, 0.12); + --warn: #f2b84b; + --warn-soft: rgba(242, 184, 75, 0.13); + --bad: #ff6b6b; + --bad-soft: rgba(255, 107, 107, 0.12); + --shadow: 0 1px 2px rgba(0, 0, 0, 0.4); + --shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55); + --map-bg: #070b10; + --map-grid: rgba(140, 170, 200, 0.06); + --map-edge: #2a3646; + --map-glass: rgba(18, 24, 32, 0.86); + --player: #5b9dff; + --online: #5ff2ff; + --wildlife: #3ecf8e; + --pool: rgba(91, 157, 255, 0.12); + --pool-edge: rgba(91, 157, 255, 0.5); + --patch: rgba(200, 160, 90, 0.14); + --select: #ffd166; + --energy: #ffd84d; + --carbon: #a3adb8; + --nitrogen: #a78bfa; + --phosphorus: #ff9a3c; + --other: #ff6fb5; + color-scheme: dark; } } +:root[data-theme="dark"] { + --bg: #0b0f14; + --panel: #121820; + --panel-2: #161e27; + --panel-3: #1c2531; + --line: #232d3a; + --line-strong: #2f3b4b; + --text: #e4eaf0; + --muted: #8d9aa8; + --faint: #64717f; + --accent: #5b9dff; + --accent-soft: rgba(91, 157, 255, 0.14); + --on-accent: #06101f; + --good: #3ecf8e; + --good-soft: rgba(62, 207, 142, 0.12); + --warn: #f2b84b; + --warn-soft: rgba(242, 184, 75, 0.13); + --bad: #ff6b6b; + --bad-soft: rgba(255, 107, 107, 0.12); + --shadow: 0 1px 2px rgba(0, 0, 0, 0.4); + --shadow-pop: 0 10px 30px rgba(0, 0, 0, 0.55); + --map-bg: #070b10; + --map-grid: rgba(140, 170, 200, 0.06); + --map-edge: #2a3646; + --map-glass: rgba(18, 24, 32, 0.86); + --player: #5b9dff; + --online: #5ff2ff; + --wildlife: #3ecf8e; + --pool: rgba(91, 157, 255, 0.12); + --pool-edge: rgba(91, 157, 255, 0.5); + --patch: rgba(200, 160, 90, 0.14); + --select: #ffd166; + --energy: #ffd84d; + --carbon: #a3adb8; + --nitrogen: #a78bfa; + --phosphorus: #ff9a3c; + --other: #ff6fb5; + color-scheme: dark; +} + +/* ---------- Base ---------- */ * { box-sizing: border-box; } +[hidden] { display: none !important; } html, body { margin: 0; } body { background: var(--bg); color: var(--text); - font: 14px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + -webkit-font-smoothing: antialiased; } a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; } +h1 { font-size: 22px; font-weight: 650; letter-spacing: -0.01em; margin: 0; } +h2 { font-size: 15px; font-weight: 600; margin: 0 0 10px; } +h3 { font-size: 13px; font-weight: 600; margin: 0; } +.muted { color: var(--muted); } +.faint { color: var(--faint); } +.mono { font-family: var(--mono); font-size: 12.5px; } +.num { font-variant-numeric: tabular-nums; } +.error { color: var(--bad); } +.good { color: var(--good); } +.small { font-size: 12px; } +.center { display: grid; place-items: center; min-height: 55vh; text-align: center; } +.center h1 { margin-bottom: 6px; } +.center .muted { margin-bottom: 18px; } + button { font: inherit; + font-weight: 500; color: var(--text); - background: var(--panel-2); - border: 1px solid var(--line); - border-radius: 6px; - padding: 5px 12px; + background: var(--panel); + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + padding: 6px 13px; cursor: pointer; + transition: background 0.12s, border-color 0.12s, color 0.12s; + white-space: nowrap; } -button:hover { border-color: var(--accent); } -button.primary { background: var(--accent); border-color: var(--accent); color: #fff; } -button.ghost { background: transparent; } +button:hover { border-color: var(--accent); color: var(--accent); } +button:disabled { opacity: 0.5; cursor: default; } +button:disabled:hover { border-color: var(--line-strong); color: var(--text); } +button.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); } +button.primary:hover { filter: brightness(1.08); color: var(--on-accent); } +button.ghost { background: transparent; border-color: transparent; color: var(--muted); } +button.ghost:hover { background: var(--panel-3); color: var(--text); } +button.danger { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 45%, transparent); } +button.danger:hover { background: var(--bad-soft); border-color: var(--bad); } +button.icon { padding: 5px 9px; line-height: 1; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + input[type="search"], input[type="text"], input[type="number"], select { font: inherit; color: var(--text); background: var(--panel); - border: 1px solid var(--line); - border-radius: 6px; - padding: 5px 10px; - min-width: 240px; + border: 1px solid var(--line-strong); + border-radius: var(--radius-sm); + padding: 6px 10px; + min-width: 0; } -.muted { color: var(--muted); } -.mono { font-family: var(--mono); font-size: 12.5px; } +input:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } +input[type="search"] { width: 280px; } +input[type="checkbox"] { accent-color: var(--accent); } +/* ---------- Top bar ---------- */ .bar { display: flex; align-items: center; - gap: 24px; - padding: 10px 20px; - background: var(--panel); + gap: 28px; + height: 56px; + padding: 0 22px; + background: color-mix(in srgb, var(--panel) 88%, transparent); + backdrop-filter: saturate(1.4) blur(10px); border-bottom: 1px solid var(--line); position: sticky; top: 0; - z-index: 2; + z-index: 10; } -.brand { font-weight: 700; color: var(--text); letter-spacing: 0.02em; } -.brand span { color: var(--accent); font-weight: 500; } +.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; color: var(--text); letter-spacing: 0.01em; } +.brand:hover { text-decoration: none; } +.brand::before { + content: ""; + width: 18px; + height: 18px; + border-radius: 50%; + background: radial-gradient(circle at 35% 35%, var(--online), var(--player) 55%, var(--wildlife)); + box-shadow: 0 0 12px color-mix(in srgb, var(--online) 45%, transparent); +} +.brand span { color: var(--muted); font-weight: 500; } .sections { display: flex; gap: 20px; flex: 1; } -.section { display: flex; align-items: center; gap: 4px; } +.section { display: flex; align-items: center; gap: 2px; } .section-name { text-transform: uppercase; - font-size: 11px; - letter-spacing: 0.08em; - color: var(--muted); - margin-right: 6px; + font-size: 10.5px; + font-weight: 600; + letter-spacing: 0.1em; + color: var(--faint); + margin-right: 10px; } -.section a { padding: 5px 10px; border-radius: 6px; color: var(--text); } -.section a.active { background: var(--panel-2); color: var(--accent); } -.who { display: flex; align-items: center; gap: 10px; } +.section a { padding: 6px 12px; border-radius: var(--radius-sm); color: var(--muted); font-weight: 500; } +.section a:hover { color: var(--text); background: var(--panel-3); text-decoration: none; } +.section a.active { background: var(--accent-soft); color: var(--accent); } +.who { display: flex; align-items: center; gap: 12px; } +.env { + font-size: 11px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--warn); + background: var(--warn-soft); + border-radius: 999px; + padding: 2px 9px; +} +.theme-switch { display: flex; background: var(--panel-3); border-radius: 999px; padding: 2px; } +.theme-switch button { + border: 0; + background: transparent; + color: var(--muted); + border-radius: 999px; + padding: 3px 9px; + font-size: 13px; + line-height: 1.3; +} +.theme-switch button:hover { color: var(--text); } +.theme-switch button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } -main { padding: 20px; max-width: 1600px; margin: 0 auto; } -h1 { font-size: 20px; margin: 0 0 4px; } -h2 { font-size: 15px; margin: 20px 0 8px; } -.head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; } +/* ---------- Page ---------- */ +main { padding: 22px 24px 40px; max-width: 1760px; margin: 0 auto; } +main:focus { outline: none; } +.head { display: flex; align-items: flex-end; justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-bottom: 18px; } +.head .crumb { display: inline-block; font-size: 12.5px; margin-bottom: 4px; color: var(--muted); } +.head .crumb:hover { color: var(--accent); } +.title-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .tools { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.subtitle { color: var(--muted); margin-top: 3px; } .card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); - padding: 14px 16px; + padding: 16px 18px; + box-shadow: var(--shadow); } -.stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-bottom: 14px; } -.stat { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 10px 12px; } -.stat .label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); } -.stat .value { font-size: 18px; font-weight: 600; margin-top: 2px; } -.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); } +.card + .card { margin-top: 14px; } +.card-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; } +.card-head h2 { margin: 0; } -.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); } +.stats, .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 18px; } +.stat, .kpi { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 12px 14px; + box-shadow: var(--shadow); + min-width: 0; +} +.stat .label, .kpi .label { + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.07em; + color: var(--muted); + display: flex; + align-items: center; + gap: 6px; +} +.stat .value, .kpi .value { font-size: 21px; font-weight: 650; margin-top: 4px; font-variant-numeric: tabular-nums; letter-spacing: -0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.stat .value small { font-size: 12px; font-weight: 400; color: var(--muted); } +.kpi .sub { font-size: 12px; color: var(--muted); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.kpi.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); } +.kpi.warn .value { color: var(--warn); } +.kpi.bad { border-color: color-mix(in srgb, var(--bad) 55%, var(--line)); } +.kpi.bad .value { color: var(--bad); } +.kpi .meter { margin-top: 8px; } + +.meter { height: 5px; border-radius: 999px; background: var(--panel-3); overflow: hidden; } +.meter > span { display: block; height: 100%; background: var(--accent); border-radius: 999px; } +.meter.warn > span { background: var(--warn); } +.meter.bad > span { background: var(--bad); } +.meter.smooth > span { transition: width 0.25s linear; } + +/* ---------- Tables ---------- */ +.table-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); box-shadow: var(--shadow); background: var(--panel); } table { border-collapse: collapse; width: 100%; background: var(--panel); } -th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; } -th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; } +th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--line); white-space: nowrap; } +tbody tr:last-child td { border-bottom: 0; } +th { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); background: var(--panel-2); cursor: pointer; user-select: none; } +th.sorted { color: var(--text); } th.sorted::after { content: " ▾"; } th.sorted.up::after { content: " ▴"; } td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } tbody tr:hover { background: var(--panel-2); } tbody tr.clickable { cursor: pointer; } +table.compact { font-size: 12.5px; background: transparent; } +table.compact td { padding: 6px 4px; white-space: normal; vertical-align: top; } +table.compact tr:hover { background: transparent; } .badge { - display: inline-block; + display: inline-flex; + align-items: center; + gap: 5px; font-size: 11.5px; - padding: 1px 8px; + font-weight: 500; + padding: 1px 9px; border-radius: 999px; - border: 1px solid var(--line); + background: var(--panel-3); color: var(--muted); + white-space: nowrap; } -.badge.alive { color: var(--good); border-color: var(--good); } -.badge.dead { color: var(--bad); border-color: var(--bad); } -.badge.online { color: var(--online); border-color: var(--online); } -.badge.warn { color: var(--warn); border-color: var(--warn); } +.badge.alive { color: var(--good); background: var(--good-soft); } +.badge.dead { color: var(--bad); background: var(--bad-soft); } +.badge.online { color: var(--accent); background: var(--accent-soft); } +.badge.warn { color: var(--warn); background: var(--warn-soft); } +.badge .dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; } +.badge .dot.pulse { animation: pulse 1.6s ease-in-out infinite; } +@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } } -dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 6px 18px; margin: 0; } +dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 7px 18px; margin: 0; } dl.facts dt { color: var(--muted); } -dl.facts dd { margin: 0; } +dl.facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; } +.window-controls { display: flex; gap: 8px; margin: 12px 0 8px; flex-wrap: wrap; } -.region-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 14px; } -@media (max-width: 1000px) { .region-layout { grid-template-columns: 1fr; } } -.canvas-wrap { - position: relative; - background: var(--panel); +/* ---------- Region page ---------- */ +.region-grid { display: grid; grid-template-columns: minmax(0, 1fr) clamp(420px, 30vw, 560px); gap: 16px; align-items: start; } +@media (max-width: 1150px) { .region-grid { grid-template-columns: 1fr; } } + +.map-card { + display: flex; + flex-direction: column; + height: max(560px, calc(100vh - 250px)); border: 1px solid var(--line); border-radius: var(--radius); + background: var(--panel); overflow: hidden; - aspect-ratio: 1 / 1; - max-height: calc(100vh - 230px); - width: 100%; + box-shadow: var(--shadow); +} +.map-toolbar { display: flex; align-items: flex-start; gap: 12px; padding: 10px 12px; border-bottom: 1px solid var(--line); } +.map-stage { position: relative; flex: 1; min-height: 0; background: var(--map-bg); } +.map-stage canvas { display: block; width: 100%; height: 100%; cursor: crosshair; } +.map-stage canvas.dragging { cursor: grabbing; } +.glass { + background: var(--map-glass); + backdrop-filter: blur(8px); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + box-shadow: var(--shadow); +} +.map-layers { flex: 1; display: flex; flex-wrap: wrap; gap: 6px; } +.chip { + display: inline-flex; + background: var(--panel-2); + border: 1px solid var(--line); + align-items: center; + gap: 7px; + font-size: 12.5px; + font-weight: 500; + padding: 4px 10px 4px 8px; + border-radius: 999px; + color: var(--text); + cursor: pointer; + user-select: none; +} +.chip .count { color: var(--muted); font-variant-numeric: tabular-nums; } +.chip.off { opacity: 0.45; } +.chip.off .swatch { background: transparent !important; } +.chip:hover { border-color: var(--accent); } +.map-zoom { display: flex; overflow: hidden; flex: none; border: 1px solid var(--line-strong); border-radius: var(--radius-sm); } +.map-zoom button { border: 0; border-radius: 0; background: transparent; padding: 5px 11px; font-size: 15px; line-height: 1.2; } +.map-zoom button + button { border-left: 1px solid var(--line); } +.map-zoom button:hover { background: var(--panel-3); } +.map-foot { position: absolute; left: 12px; right: 12px; bottom: 10px; display: flex; justify-content: space-between; align-items: flex-end; gap: 10px; pointer-events: none; } +.map-hint { font-size: 12px; color: var(--muted); padding: 3px 9px; } +.scale { font-size: 11.5px; color: var(--muted); padding: 4px 9px 3px; text-align: center; } +.scale .rule { height: 6px; border: 1.5px solid var(--muted); border-top: 0; margin-top: 2px; } +.map-banner { + position: absolute; + left: 50%; + top: 12px; + transform: translateX(-50%); + padding: 6px 14px; + font-size: 12.5px; + color: var(--warn); + border-color: color-mix(in srgb, var(--warn) 50%, var(--line)); } -.canvas-wrap canvas { display: block; width: 100%; height: 100%; cursor: crosshair; } -.overlay-note { position: absolute; left: 10px; bottom: 8px; font-size: 12px; color: var(--muted); pointer-events: none; } .tooltip { position: absolute; pointer-events: none; - background: var(--panel-2); - border: 1px solid var(--line); - border-radius: 6px; - padding: 6px 8px; + padding: 8px 10px; font-size: 12px; - max-width: 280px; - z-index: 1; + min-width: 170px; + max-width: 290px; + z-index: 3; + box-shadow: var(--shadow-pop); } -.side { display: flex; flex-direction: column; gap: 12px; } -.legend { display: grid; grid-template-columns: 14px 1fr; gap: 6px 8px; align-items: center; font-size: 13px; } -.swatch { width: 12px; height: 12px; border-radius: 50%; } +.tooltip .tip-title { font-weight: 600; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; } +.tooltip .tip-row { display: flex; justify-content: space-between; gap: 14px; } +.tooltip .tip-row span:first-child { color: var(--muted); } + +.swatch { width: 10px; height: 10px; border-radius: 50%; flex: none; display: inline-block; } .swatch.player { background: var(--player); } .swatch.online { background: var(--online); } .swatch.wildlife { background: var(--wildlife); } -.swatch.pool { background: var(--pool); border: 1px solid var(--accent); } +.swatch.pool { background: var(--pool); border: 1.5px solid var(--pool-edge); } +.swatch.patch { background: var(--patch); border: 1.5px solid var(--faint); border-radius: 2px; } .swatch.energy { background: var(--energy); } .swatch.carbon { background: var(--carbon); } .swatch.nitrogen { background: var(--nitrogen); } .swatch.phosphorus { background: var(--phosphorus); } .swatch.other { background: var(--other); } -.toggles { display: flex; flex-direction: column; gap: 6px; } -.toggles label { display: flex; gap: 8px; align-items: center; cursor: pointer; } -.error { color: var(--bad); } -.good { color: var(--good); } -.center { display: grid; place-items: center; min-height: 50vh; text-align: center; } -.window-controls { display: flex; gap: 8px; margin: 10px 0 8px; flex-wrap: wrap; } -.side input[type="text"] { width: 100%; min-width: 0; } -.small { font-size: 12px; margin-top: 6px; } -table.compact { margin-top: 10px; font-size: 12.5px; background: transparent; } -table.compact td { padding: 4px 6px; white-space: normal; } -button:disabled { opacity: 0.5; cursor: default; } -.action { border-top: 1px solid var(--line); padding-top: 10px; margin-top: 10px; } -.action .row { display: flex; gap: 8px; align-items: center; margin-top: 6px; flex-wrap: wrap; } -.amounts { display: grid; grid-template-columns: repeat(auto-fill, minmax(88px, 1fr)); gap: 6px; margin-top: 6px; } -input.amount, input.count { min-width: 0; width: 100%; } -input.count { width: 80px; } -button.danger { color: var(--bad); border-color: var(--bad); } -.tuning-layout { display: grid; grid-template-columns: minmax(0, 1fr) 380px; gap: 14px; } -@media (max-width: 1000px) { .tuning-layout { grid-template-columns: 1fr; } } + +/* Side panel with tabs. */ +.panel { + position: sticky; + top: 72px; + max-height: calc(100vh - 88px); + display: flex; + flex-direction: column; + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow: hidden; +} +@media (max-width: 1150px) { .panel { position: static; max-height: none; } } +.tabs { flex: none; display: flex; gap: 2px; padding: 8px 8px 0; border-bottom: 1px solid var(--line); background: var(--panel-2); overflow-x: auto; } +.tabs button { + border: 0; + border-radius: var(--radius-sm) var(--radius-sm) 0 0; + background: transparent; + color: var(--muted); + padding: 8px 12px 9px; + font-size: 13px; + border-bottom: 2px solid transparent; + margin-bottom: -1px; +} +.tabs button:hover { color: var(--text); background: transparent; } +.tabs button.on { color: var(--accent); border-bottom-color: var(--accent); background: var(--panel); } +.tabs .tab-badge { margin-left: 6px; font-size: 10.5px; padding: 0 6px; border-radius: 999px; background: var(--warn-soft); color: var(--warn); } +.panel-body { overflow-y: auto; padding: 4px 18px 18px; flex: 1; } +.block { padding: 16px 0; border-bottom: 1px solid var(--line); } +.block:last-child { border-bottom: 0; } +.block-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; } +.block-head .muted { font-size: 12px; } +.hint { font-size: 12.5px; color: var(--muted); margin: 0 0 10px; } +.empty { text-align: center; color: var(--muted); padding: 26px 10px; } +.empty .big { font-size: 26px; margin-bottom: 6px; opacity: 0.6; } + +/* Forms. */ +.field-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } +.field { display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.field label { font-size: 11.5px; color: var(--muted); display: flex; align-items: center; gap: 5px; } +.field input, .field select { width: 100%; } +.form-row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; margin-top: 10px; } +.form-row .grow { flex: 1; min-width: 120px; } +.form-row input.count { width: 84px; } +input.wide, .wide { width: 100%; } +.note { font-size: 12.5px; margin-top: 8px; min-height: 0; } +.note:empty { display: none; } +.segmented { display: inline-flex; background: var(--panel-3); border-radius: var(--radius-sm); padding: 2px; gap: 2px; flex-wrap: wrap; } +.segmented button { border: 0; background: transparent; color: var(--muted); padding: 4px 10px; font-size: 12.5px; border-radius: 5px; } +.segmented button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } + +/* Resource ledger. */ +table.ledger { font-size: 12.5px; background: transparent; } +table.ledger th { background: transparent; cursor: default; padding: 6px 6px; font-size: 10.5px; } +table.ledger td { padding: 6px 6px; } +table.ledger td:first-child, table.ledger th:first-child { padding-left: 0; } +table.ledger td:last-child, table.ledger th:last-child { padding-right: 0; } +table.ledger tr.total td { font-weight: 650; border-top: 1px solid var(--line-strong); } +table.ledger tr:hover { background: transparent; } +table.ledger th .swatch { margin-right: 4px; vertical-align: -1px; width: 8px; height: 8px; } +.split { display: flex; height: 8px; border-radius: 999px; overflow: hidden; background: var(--panel-3); } +.split > span { display: block; height: 100%; } +.split-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: 11.5px; color: var(--muted); margin-top: 6px; } +.split-legend span { display: inline-flex; align-items: center; gap: 5px; } +.split-row { display: grid; grid-template-columns: 80px 1fr; gap: 10px; align-items: center; margin-top: 8px; font-size: 12px; } + +/* Spent pool and drip. */ +.drip-card { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 12px 14px; } +.drip-top { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; } +.drip-count { font-size: 20px; font-weight: 650; font-variant-numeric: tabular-nums; } +.channels { display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: 6px; margin-top: 10px; } +.channel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 6px 8px; min-width: 0; } +.channel .name { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 5px; } +.channel .amt { font-weight: 600; font-variant-numeric: tabular-nums; font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.channel .sub { font-size: 11px; color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.channel.empty-ch { opacity: 0.55; } +.callout { + display: flex; + gap: 10px; + padding: 10px 12px; + border-radius: var(--radius-sm); + font-size: 12.5px; + background: var(--warn-soft); + color: var(--text); + border: 1px solid color-mix(in srgb, var(--warn) 35%, transparent); + margin-bottom: 12px; +} +.callout::before { content: "!"; flex: none; width: 18px; height: 18px; border-radius: 50%; background: var(--warn); color: var(--panel); font-weight: 700; display: grid; place-items: center; font-size: 12px; } +.callout.info { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 30%, transparent); } +.callout.info::before { content: "i"; background: var(--accent); } + +/* Lists in the panel. */ +.list { display: flex; flex-direction: column; } +.list-item { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--line); font-size: 12.5px; } +.list-item:last-child { border-bottom: 0; } +.list-item .grow { flex: 1; min-width: 0; } +.list-item.clickable { cursor: pointer; } +.list-item.clickable:hover .grow { color: var(--accent); } +.list-item .sub { color: var(--muted); font-size: 11.5px; } + +/* Inspector. */ +.inspect-head { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; } +.inspect-head .swatch { width: 14px; height: 14px; } +.inspect-head h2 { margin: 0; } +.inspect-head .grow { flex: 1; } + +/* Tuning settings. */ +.settings-group { margin-top: 6px; } +.settings-group summary { + cursor: pointer; + list-style: none; + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 0; + font-weight: 600; + font-size: 12.5px; + text-transform: capitalize; + border-bottom: 1px solid var(--line); +} +.settings-group summary::-webkit-details-marker { display: none; } +.settings-group summary::before { content: "▸"; color: var(--faint); margin-right: 8px; transition: transform 0.15s; display: inline-block; } +.settings-group[open] summary::before { transform: rotate(90deg); } +.settings-group summary .label { flex: 1; } +.setting { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; padding: 6px 0 6px 16px; border-bottom: 1px dashed var(--line); font-size: 12.5px; } +.setting:last-child { border-bottom: 0; } +.setting .key { font-family: var(--mono); font-size: 12px; overflow-wrap: anywhere; } +.setting .val { font-family: var(--mono); font-size: 12px; font-weight: 600; text-align: right; } +.setting .why { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; } +.setting.changed .val { color: var(--accent); } +mark { background: var(--warn-soft); color: inherit; border-radius: 2px; } + +/* ---------- Tuning editor ---------- */ +.tuning-layout { display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 16px; align-items: start; } +@media (max-width: 1100px) { .tuning-layout { grid-template-columns: 1fr; } } +.tuning-layout .side { display: flex; flex-direction: column; gap: 14px; } +.tuning-layout .side .card + .card { margin-top: 0; } textarea.tuning { display: block; width: 100%; - min-height: 60vh; - box-sizing: border-box; + min-height: 62vh; font-family: var(--mono); font-size: 12.5px; - line-height: 1.5; + line-height: 1.55; color: var(--text); background: var(--panel-2); border: 1px solid var(--line); - border-radius: 6px; - padding: 10px 12px; + border-radius: var(--radius-sm); + padding: 12px 14px; resize: vertical; tab-size: 4; } -textarea.tuning:focus { outline: none; border-color: var(--accent); } -.card input[type="text"].wide { width: 100%; min-width: 0; box-sizing: border-box; } +textarea.tuning:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-soft); } +.action { border-top: 1px solid var(--line); padding-top: 12px; margin-top: 12px; } +.action .row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; } diff --git a/deploy/kubernetes/admin-portal-dev/deployment.yaml b/deploy/kubernetes/admin-portal-dev/deployment.yaml index 39f7717..6f020e2 100644 --- a/deploy/kubernetes/admin-portal-dev/deployment.yaml +++ b/deploy/kubernetes/admin-portal-dev/deployment.yaml @@ -47,7 +47,8 @@ spec: --audience aevolution-admin --client aevolution-admin-portal \ --role aevolution-admin --assets /usr/local/share/evo-admin-portal \ --pg-service /run/postgres/pg_service.conf --pg-passfile /run/postgres/pgpass \ - --baseline-tuning /etc/evo/tuning/cellular-revamp.tuning "${regions[@]}" + --baseline-tuning /etc/evo/tuning/cellular-revamp.tuning \ + --region-tuning /etc/evo/tuning/cellular.tuning "${regions[@]}" env: - {name: ADMIN_WORLD, value: "100"} # Space-separated REGION=HOST:PORT: each region's operations address for /admin/view. @@ -78,7 +79,7 @@ spec: volumeMounts: - {name: connection, mountPath: /run/postgres, readOnly: true} # The revamp tuning file the regions opened with: the portal's baseline until the - # first tuning revision (ADR-0182 section 13). + # first tuning revision (ADR-0182 section 13); the region tuning file, shown read only. - {name: tuning, mountPath: /etc/evo/tuning, readOnly: true} volumes: - name: tuning @@ -87,6 +88,7 @@ spec: defaultMode: 0444 items: - {key: cellular-revamp.tuning, path: cellular-revamp.tuning} + - {key: cellular.tuning, path: cellular.tuning} - name: connection secret: secretName: aevolution-admin-pg diff --git a/docs/STATUS.md b/docs/STATUS.md index fad6992..d57a9e2 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,15 @@ # Project status and next steps +## Admin region page - 2026-10-28 + +The admin portal's region page is reorganized around the map: a KPI strip (tick pace, +population, deposit capacity, region energy and matter, spent pool, next drip), a map with +layer toggles, zoom and a scale, and tabs for inspecting cells and deposits, the region's +resources (where every channel sits, the spent pool and its drip), actions, the running +tuning and session access. The region view adds complete counts and totals and the drip +rules; the portal has light and dark themes. See +[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 13. + ## Live tuning - 2026-10-27 The admin portal's Tuning page edits the world's rules-13 tuning (the Git revamp file diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index f362365..759de8a 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -263,6 +263,15 @@ Sections 1-2 are delivered without a new owner format or opening, so running rul the line, key and kind of a problem, Adopt stores the revision with a reason, the revision list shows how many regions adopted each, and each region shows which revision its live rules match (`rules_sha256` in the region view). +- **Region page (2026-10-28).** The region view also carries the rules-13 drip + (`drip`: interval, energy and matter bubble caps) and, over every life and deposit whatever + the listing limits, `counts` (players, wildlife, patches, pools, bubbles) and `totals` + (reserve, body, patch, pool and bubble stock). The region page shows where the region's + stock sits, the spent pool with each channel's next drip and time to empty, a countdown to + the next drip at the measured tick pace, the deposit capacity (8,192) and whether the tick + is advancing. Its Tuning tab lists the settings the region runs (the matching revision or + baseline text) and the region tuning file (`--region-tuning`, the mounted `cellular.tuning`, + read only). The portal has light and dark themes. Live today: everything the revamp file holds, including the drip (`spent.drip_interval_ticks`, `spent.drip_bubble_pj`, `spent.drip_bubble_fg`). Section 4's new drip settings (bubbles per diff --git a/include/evo/server/admin/admin_api.hpp b/include/evo/server/admin/admin_api.hpp index 1994fd5..c15e5d8 100644 --- a/include/evo/server/admin/admin_api.hpp +++ b/include/evo/server/admin/admin_api.hpp @@ -43,8 +43,9 @@ // [&energy=PJ][&carbon=FG]...[&reason=R] // creates (no id) or replaces a schedule repeating // add_bubbles, release_pool or spawn_wildlife -// GET /api/tuning the world's rules-13 tuning revisions, the newest text -// and the baseline file regions opened with (schema 66) +// GET /api/tuning the world's rules-13 tuning revisions, the newest text, +// the baseline file regions opened with (schema 66) and +// the region tuning file they restart with (read only) // GET /api/tuning/ one revision's text // POST /api/tuning[?check=1][&reason=R] the request body is a tuning text (the Git // revamp file format): checked, then stored as a new @@ -61,6 +62,8 @@ struct AdminConfig { std::vector view_regions; // The revamp tuning file the world's regions opened with (empty: unknown). std::string baseline_tuning; + // The region tuning file (shape, movement, currents) they read at startup (empty: unknown). + std::string region_tuning; std::string portal_config_json; // Served at /config.json. std::string content_security_policy; // Sent with every portal file. std::chrono::milliseconds db_timeout{3000}; diff --git a/include/evo/server/lifecycle/cellular_admin_view.hpp b/include/evo/server/lifecycle/cellular_admin_view.hpp index 04a7a2c..71253ec 100644 --- a/include/evo/server/lifecycle/cellular_admin_view.hpp +++ b/include/evo/server/lifecycle/cellular_admin_view.hpp @@ -12,7 +12,10 @@ // it is not a simulation output, a checkpoint or a client protocol. // // {"world":W,"region":R,"tick":T,"rules":N,["rules_sha256":"hex",]"area":[w,h], -// "spent":[e,c,n,p,o],"cells_total":N,"deposits_total":N, +// "spent":[e,c,n,p,o],["drip":[interval_ticks,bubble_pj,bubble_fg],] +// "cells_total":N,"deposits_total":N, +// "counts":[players,wildlife,patches,pools,bubbles], +// "totals":{"reserve":[e,c,n,p,o],"body":[...],"patches":[...],"pools":[...],"bubbles":[...]}, // "cells":[["life","organism","account",x,y,extent,flags,members, // reserve_e,reserve_c,reserve_n,reserve_p,reserve_o,body_mass,"root"],...], // "deposits":[[id,kind,x,y,radius,e,c,n,p,o],...]} @@ -25,6 +28,9 @@ // in pJ, matter in fg. Cells and deposits beyond the limits are left out (by ascending life id and // deposit id); the totals still count them. `rules_sha256` is given by the caller (the SHA-256 // of encode_cellular_revamp_rules, which tuning revisions are adopted by) and left out when empty. +// `drip` is the rules-13 spent-pool drip (cellular_drip_spent), left out before rules 13. +// `counts` and `totals` cover every life and deposit, whatever the limits: the region's stock +// is the totals plus `spent`. namespace evo::server { struct CellularAdminViewLimits { std::size_t cells{4096}, deposits{16384}; diff --git a/src/server/admin/admin_api.cpp b/src/server/admin/admin_api.cpp index c524bca..8957377 100644 --- a/src/server/admin/admin_api.cpp +++ b/src/server/admin/admin_api.cpp @@ -810,6 +810,8 @@ OpsResponse AdminApi::tuning() { out += "{\"text\":" + json_string(config_.baseline_tuning) + ",\"rules_sha256\":" + (checked ? "\"" + hex(checked->digest) + "\"" : std::string{"null"}) + "}"; } + out += ",\"region_file\":"; + out += config_.region_tuning.empty() ? std::string{"null"} : json_string(config_.region_tuning); out += ",\"newest\":"; if (newest->empty()) out += "null"; diff --git a/src/server/lifecycle/cellular_admin_view.cpp b/src/server/lifecycle/cellular_admin_view.cpp index 4242d8f..ed4df5f 100644 --- a/src/server/lifecycle/cellular_admin_view.cpp +++ b/src/server/lifecycle/cellular_admin_view.cpp @@ -1,6 +1,7 @@ #include "evo/server/lifecycle/cellular_admin_view.hpp" #include +#include #include #include #include @@ -17,6 +18,25 @@ void append_inventory(std::string& out, const accounting::Inventory& inventory) append(out, channel.value); } } +// Energy then the four matter channels, summed without the inventory's overflow checks: a +// region's stock is far below 2^64 in every channel. +using Totals = std::array; +void add(Totals& totals, const accounting::Inventory& inventory) { + totals[0] += inventory.energy.value; + for (std::size_t i = 0; i < inventory.matter.size(); ++i) + totals[i + 1] += inventory.matter[i].value; +} +void append_totals(std::string& out, std::string_view name, const Totals& totals) { + out += "\""; + out += name; + out += "\":["; + for (std::size_t i = 0; i < totals.size(); ++i) { + if (i != 0) + out.push_back(','); + append(out, totals[i]); + } + out.push_back(']'); +} } // namespace std::string cellular_account_text(const LifeAccount& account) { @@ -60,11 +80,56 @@ std::string render_cellular_admin_view(const CellularLives& state, append(out, state.area().height_um); out += "],\"spent\":["; append_inventory(out, state.spent()); - out += "],\"cells_total\":"; + out.push_back(']'); + if (state.rules_version() >= cellular_lives_revamp_rules) { + const auto& rules = state.revamp_rules(); + out += ",\"drip\":["; + append(out, rules.drip_interval_ticks); + out.push_back(','); + append(out, rules.drip_bubble_pj); + out.push_back(','); + append(out, rules.drip_bubble_fg); + out.push_back(']'); + } + out += ",\"cells_total\":"; append(out, lives.size()); out += ",\"deposits_total\":"; append(out, patches.size()); + // Counts and stock over every life and deposit, beyond the listing limits. + std::array counts{}; // Players, wildlife, patches, pools, bubbles. + Totals reserve{}, body{}; + std::array deposits_by_kind{}; + for (const auto& life : lives) { + ++counts[life.account == LifeAccount{} ? 1 : 0]; + add(reserve, life.reserve); + add(body, life.body); + } + for (const auto& patch : patches) { + const auto kind = static_cast(patch.kind); + if (kind < deposits_by_kind.size()) { + ++counts[2 + kind]; + add(deposits_by_kind[kind], patch.stock); + } + } + out += ",\"counts\":["; + for (std::size_t i = 0; i < counts.size(); ++i) { + if (i != 0) + out.push_back(','); + append(out, counts[i]); + } + out += "],\"totals\":{"; + append_totals(out, "reserve", reserve); + out.push_back(','); + append_totals(out, "body", body); + out.push_back(','); + append_totals(out, "patches", deposits_by_kind[0]); + out.push_back(','); + append_totals(out, "pools", deposits_by_kind[1]); + out.push_back(','); + append_totals(out, "bubbles", deposits_by_kind[2]); + out.push_back('}'); + // Lives are kept in ascending life id; a prefix is the lowest ids. out += ",\"cells\":["; const auto cells = std::min(lives.size(), limits.cells); diff --git a/tests/cellular_admin_view_tests.cpp b/tests/cellular_admin_view_tests.cpp index 2c2f689..f11cede 100644 --- a/tests/cellular_admin_view_tests.cpp +++ b/tests/cellular_admin_view_tests.cpp @@ -1,6 +1,7 @@ #include "evo/server/lifecycle/cellular_admin_view.hpp" #include "fixtures/cellular_ecology.hpp" +#include #include #include @@ -59,12 +60,87 @@ void renders_cells_and_deposits() { "deposit limit keeps ids 1 and 2"); const auto none = render_cellular_admin_view(*state, {}, {.cells = 0, .deposits = 0}); require(none.find("\"cells\":[],\"deposits\":[]}") != std::string::npos, "empty lists"); + + // Counts and totals cover everything, whatever the limits; no drip before rules 13. + std::array reserve{}, body{}, bubbles{}; + std::array kinds{}; + const auto add = [](std::array& totals, const accounting::Inventory& stock) { + totals[0] += stock.energy.value; + for (std::size_t i = 0; i < 4; ++i) + totals[i + 1] += stock.matter[i].value; + }; + for (const auto& life : state->lives()) { + add(reserve, life.reserve); + add(body, life.body); + } + for (const auto& patch : state->habitat().patches()) { + ++kinds[static_cast(patch.kind)]; + if (patch.kind == biology::CellularDepositKind::mote) + add(bubbles, patch.stock); + } + const auto list = [](const std::array& totals) { + std::string text = "["; + for (std::size_t i = 0; i < totals.size(); ++i) + text += (i == 0 ? "" : ",") + std::to_string(totals[i]); + return text + "]"; + }; + const auto counts = "\"counts\":[4,0," + std::to_string(kinds[0]) + "," + + std::to_string(kinds[1]) + "," + std::to_string(kinds[2]) + "]"; + require(reserve[0] > 0 && body[1] > 0, "the fixture's cells hold stock"); + for (const auto& text : {view, none}) { + require(text.find(counts) != std::string::npos, "counts"); + require(text.find("\"totals\":{\"reserve\":" + list(reserve) + ",\"body\":" + list(body) + + ",") != std::string::npos, + "cell totals"); + require(text.find(",\"bubbles\":" + list(bubbles) + "}") != std::string::npos, + "bubble totals"); + require(text.find("\"drip\"") == std::string::npos, "a drip before rules 13"); + } +} + +// The trial liquid rules (cellular_revamp_owner_tests). +CellularLiquidRules liquid() { + return {.currents = {5, 48'000, 48'000, 250, 2, 4, 3'000, 6'000, 60, 300}, + .founder = {.thrust_q10 = 20'480, + .reverse_thrust_q10 = 20'480, + .forward_drag_ppm = 95'163, + .lateral_drag_ppm = 95'163, + .turn = 3'276}, + .deposits = {.drift_radius_um = 200, + .max_drift_q10 = 100 * 1'024, + .drift_decay_ppm = 95'163, + .merged_cap = 8, + .bubble_radius_um = biology::cellular_mote_radius_um}}; +} + +// A rules-13 owner's view carries its spent-pool drip. +void renders_the_drip() { + auto state = opening(7, true, 2, false); + checked(state->advance_tick({}), "genesis tick"); + state = checked(state->migration_upgrade_candidate(), "boundary upgrade"); + state = checked(state->maturation_upgrade_candidate(), "maturation upgrade"); + state = checked(state->inheritance_upgrade_candidate(), "inheritance upgrade"); + state = checked(state->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); + state = checked(state->liquid_upgrade_candidate(liquid()), "liquid upgrade"); + CellularRevampRules rules{.body = {.essential_upkeep_per_thousand = 250}, + .burn_pj_per_kfg = {2'000, 2'000, 2'000, 2'000}, + .step = {.engulf_ratio_milli = 1'500, + .engulf_reserve_percent = 100, + .kill_bubble_per_thousand = 500}, + .drip_interval_ticks = 20, + .drip_bubble_pj = 20'000'000, + .drip_bubble_fg = 1'000'000}; + state = checked(state->revamp_upgrade_candidate(rules), "revamp upgrade"); + const auto view = render_cellular_admin_view(*state, {}); + require(view.find("],\"drip\":[20,20000000,1000000],\"cells_total\":") != std::string::npos, + "rules-13 drip"); } } // namespace int main() { try { renders_cells_and_deposits(); + renders_the_drip(); } catch (const std::exception& error) { std::fprintf(stderr, "%s\n", error.what()); return 1; diff --git a/tests/grant_broker_tests.cpp b/tests/grant_broker_tests.cpp index 921db33..90c3ee3 100644 --- a/tests/grant_broker_tests.cpp +++ b/tests/grant_broker_tests.cpp @@ -648,6 +648,7 @@ void admin_api_tests(const Realm& realm) { config.world = 9831; config.view_regions = {1}; config.baseline_tuning = baseline; + config.region_tuning = file("cellular.tuning"); AdminApi tuned{config, *TokenVerifier::from_jwks(realm.jwks("sig-1"), admin_rules), [] { return connect_as(env("EVO_PG_ADMIN_USER")); }, @@ -665,7 +666,8 @@ void admin_api_tests(const Realm& realm) { CHECK(none.member("newest")->kind() == JsonValue::Kind::null && none.member("revisions")->array()->empty() && none.member("baseline")->member("text")->string() == baseline && - digest.size() == 64 && none.member("regions")->array()->at(0).string() == "1"); + digest.size() == 64 && none.member("regions")->array()->at(0).string() == "1" && + none.member("region_file")->string() == config.region_tuning); // Bodies go to /api/tuning only; check=1 stores nothing. CHECK(tuned