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

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

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

174 lines
12 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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

'use strict';
/*
* Shared state and small view helpers of the military / expansion screens (browser only; loads after main.js).
*
* App.mil.moves { outgoing, incoming, at }: the last GET /movements, the single source for the nav badge,
* the POP banner, the movements screen and the map lines. Emits App.emit('movements').
* App.refreshMovements() refetch it (coalesced). Called by the ticker when something arrived, by push, by the poll.
* App.refreshReportsUnread() refetch the unread count of reports (nav badge on Reports).
* App.refreshTowns() refetch /me and update the POP list WITHOUT resetting the session (after a settle/takeover).
* App.mil.* helpers unitName, unitsText, typeLabel, coordLink, countdown, chips ...
*
* Countdowns are elements with data-cd = server-clock deadline in ms; one ticker keeps all of them current, so screens
* only create them (mil.countdown) and never run their own timers for display.
*/
(function () {
const { h, icon } = UI;
const D = UpstreamData;
const Mil = UpstreamMil;
const api = App.api;
const mil = App.mil = { moves: { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false }, reportsUnread: 0 };
// ------------------------------------------------------------------ names and small pieces
mil.unitName = (id) => (UpstreamI18n.strings.en['unit.' + id + '.name'] ? App.t('unit.' + id + '.name') : id);
mil.unitDesc = (id) => (UpstreamI18n.strings.en['unit.' + id + '.desc'] ? App.t('unit.' + id + '.desc') : '');
mil.typeLabel = (type) => (UpstreamI18n.strings.en['move.type.' + type] ? App.t('move.type.' + type) : type);
mil.reportTypeLabel = (type) => (UpstreamI18n.strings.en['report.type.' + type] ? App.t('report.type.' + type) : type);
mil.unitIcon = (id) => icon(Mil.ROLE_ICON[(D.UNITS[id] || {}).role] || 'units');
mil.townName = (id) => { const t = App.state.towns.find((x) => x.id === id); return t ? t.name : null; };
mil.ownTown = (id) => App.state.towns.find((x) => x.id === id) || null;
// "3 × Script crew, 2 × Botnet"
mil.unitsText = (units) => {
const parts = [];
for (const u of D.UNIT_ORDER) if (units && units[u] > 0) parts.push(App.fmt.num(units[u]) + ' × ' + mil.unitName(u));
return parts.length ? parts.join(', ') : '—';
};
// Clock time (local) at server time `ms`.
mil.clockTime = (ms) => {
try { return new Date(ms).toLocaleTimeString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
};
mil.dayTime = (ms) => {
try { return new Date(ms).toLocaleString(App.state.lang === 'nb' ? 'nb-NO' : 'en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); } catch (e) { return ''; }
};
// A link that jumps to the map at (x, y). Closes any sheet first.
mil.coordLink = (x, y, label) => h('button', { class: 'mil-coord mono', type: 'button', 'aria-label': App.t('mil.showOnMap', { x, y }), onclick: () => { UI.closeSheet(); App.go('map', { x, y, zoom: 40 }); } },
icon('map'), label || (x + ', ' + y));
// A movement endpoint ({ townId, x, y, name, owner? }) as text + coordinates link.
mil.endLink = (end) => h('span', { class: 'mil-end' }, end.name ? h('span', { class: 'mil-end-name', text: end.name }) : null, mil.coordLink(end.x, end.y));
// Resource chips: { fiber, hardware, capital } (zero entries are skipped).
mil.resChips = (res, signed) => {
const out = [];
for (const r of D.RESOURCES) if (res && res[r]) out.push(h('span', { class: 'cost ' + r }, icon(r), h('b', { text: (signed ? '+' : '') + App.fmt.num(res[r]) })));
return h('div', { class: 'costs' }, out.length ? out : h('span', { class: 'dimmer', text: '—' }));
};
// <b class="mono" data-cd="<deadline ms>">m:ss</b>, kept current by the ticker below.
mil.countdown = (deadline, opts) => {
const el = h('b', { class: 'mono mil-cd' + (opts && opts.cls ? ' ' + opts.cls : ''), dataset: { cd: String(deadline) } });
el.textContent = App.fmt.clock(deadline - App.now());
return el;
};
// Progress 0..1 of a movement.
mil.progress = (m, now) => Math.max(0, Math.min(1, (now - m.departAt) / Math.max(1, m.arriveAt - m.departAt)));
// ------------------------------------------------------------------ the ticker: countdowns + "something arrived" refetch
let lastMovesFetch = 0;
App.onTick((now) => {
for (const el of document.querySelectorAll('[data-cd]')) {
const s = App.fmt.clock(Number(el.dataset.cd) - now);
if (el.textContent !== s) el.textContent = s;
}
if (!App.state.user || !mil.moves.loaded) return;
// a movement is over (arrived / returned): the server dropped it, so refetch (retry no more often than every 3 s)
const due = mil.moves.outgoing.concat(mil.moves.incoming, mil.moves.alliedIncoming || []).some((m) => m.arriveAt - now < -600);
if (due && Date.now() - lastMovesFetch > 3000) { lastMovesFetch = Date.now(); App.refreshMovements().catch(() => {}); }
});
// ------------------------------------------------------------------ refetchers
let movesFlight = null;
App.refreshMovements = () => {
if (!App.state.user || !App.state.operator) return Promise.resolve(null);
if (movesFlight) return movesFlight;
lastMovesFetch = Date.now();
movesFlight = api.get('/movements').then((r) => {
// a settle that is no longer on the wire has resolved: the POP list changed (the push-less path to the same refresh)
const settled = mil.moves.loaded && mil.moves.outgoing.some((m) => m.type === 'settle' && !(r.outgoing || []).some((n) => n.id === m.id));
if (settled) App.refreshTowns().catch(() => {});
mil.moves = { outgoing: r.outgoing || [], incoming: r.incoming || [], alliedIncoming: r.alliedIncoming || [], at: r.serverTime, loaded: true };
App.setBadge('movements', mil.moves.incoming.length, 'alert');
App.emit('movements', mil.moves);
return mil.moves;
}).finally(() => { movesFlight = null; });
return movesFlight;
};
let reportsFlight = null;
App.refreshReportsUnread = () => {
if (!App.state.user) return Promise.resolve(null);
if (reportsFlight) return reportsFlight;
reportsFlight = api.get('/reports', { limit: 1 }).then((r) => {
mil.reportsUnread = r.unread || 0;
App.setBadge('reports', mil.reportsUnread, 'info');
App.emit('reportsUnread', mil.reportsUnread);
return mil.reportsUnread;
}).finally(() => { reportsFlight = null; });
return reportsFlight;
};
// The POP list changed (founded, conquered, lost): refresh /me without the destructive parts of setSession.
let townsFlight = null;
const townSig = (list) => list.map((t) => t.id + ':' + t.name + ':' + (t.isCapital ? 1 : 0)).join('|');
App.refreshTowns = () => {
const st = App.state;
if (!st.user) return Promise.resolve();
if (townsFlight) return townsFlight;
townsFlight = (async () => {
const me = await api.get('/me');
const op = (me.operators || [])[0] || null;
if (!op) return;
const before = townSig(st.towns);
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
if (App.checkWorld) App.checkWorld(); // the world may have ended while we were away
let gone = false;
if (!st.towns.some((t) => t.id === st.townId)) {
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;
st.townId = pick ? pick.id : null; st.townData = null; gone = true;
}
// only a real change rebuilds the screens (a redraw resets the scroll position, and this runs on every poll)
if (gone) { App.emit('townchange', st.townId); if (st.townId) App.refreshTown().catch(() => {}); }
if (gone || townSig(st.towns) !== before) App.emit('towns', st.towns);
})().finally(() => { townsFlight = null; });
return townsFlight;
};
// Another of the player's POPs (GET /towns/:id), for the send dialog. -> { town, serverTime }
mil.loadTown = (id) => api.get('/towns/' + id);
App.on('session', (st) => {
if (st && st.user) { App.refreshMovements().catch(() => {}); App.refreshReportsUnread().catch(() => {}); return; }
mil.moves = { outgoing: [], incoming: [], alliedIncoming: [], at: 0, loaded: false };
mil.reportsUnread = 0;
App.setBadge('movements', 0, 'alert'); App.setBadge('reports', 0, 'info');
});
// ------------------------------------------------------------------ the notification feed (screens/alerts.js) learns our types
const kinds = App.alertKinds;
const townTxt = (id) => mil.townName(id) || '#' + id;
kinds.incoming = (n, p) => ({ icon: 'alert', title: App.t('alerts.incoming'), detail: App.t('alerts.incoming.at', { town: townTxt(p.toTownId), time: mil.clockTime(p.arriveAt) }), go: 'movements' });
kinds.report = (n, p) => ({ icon: 'report', title: App.t('alerts.report', { type: mil.reportTypeLabel(p.type) }), detail: '', go: 'reports', params: { open: p.reportId } });
kinds.train_done = (n, p) => ({ icon: 'units', title: App.t('alerts.train_done', { n: App.fmt.num(p.count), unit: mil.unitName(p.unit) }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
kinds.research_done = (n, p) => ({ icon: 'flask', title: App.t('alerts.research_done', { unit: mil.unitName(p.unit), stat: App.t('stat.' + p.stat), level: p.level }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
// Cargo that did not fit the Rack hall when it came home / arrived (cargoLost, exact amounts per resource): said out loud, never silent.
const lostText = (lost) => (D.RESOURCES.some((r) => lost && lost[r] > 0) ? [App.t('alerts.cargo_lost', { what: D.RESOURCES.filter((r) => lost[r] > 0).map((r) => App.fmt.num(lost[r]) + ' ' + App.resName(r)).join(', ') })] : []);
kinds.movement_returned = (n, p) => ({ icon: 'return', title: App.t('alerts.movement_returned'), detail: [mil.unitsText(p.units)].concat(D.RESOURCES.some((r) => p.cargo && p.cargo[r]) ? [Object.keys(p.cargo).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', ')] : [], lostText(p.cargoLost)).filter(Boolean).join(' · '), go: 'movements' });
kinds.movement_lost = () => ({ icon: 'alert', title: App.t('alerts.movement_lost'), detail: '', go: 'movements' });
kinds.transport_arrived = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_arrived', { town: townTxt(p.townId) }), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).concat(lostText(p.cargoLost)).join(' · '), go: 'movements' });
kinds.transport_delivered = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_delivered'), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' });
kinds.units_offline = (n, p) => ({ icon: 'power', title: App.t('alerts.units_offline'), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' });
kinds.units_decommissioned = (n, p) => ({ icon: 'power', title: App.t('alerts.units_decommissioned'), detail: mil.unitsText(p.units), go: 'units' });
kinds.town_lost = (n, p) => ({ icon: 'alert', title: App.t('alerts.town_lost', { name: p.name }), detail: p.by ? App.t('alerts.town_lost.by', { name: p.by.name }) : '', go: 'pop' });
kinds.town_gained = (n, p) => ({ icon: 'pop', title: App.t('alerts.town_gained', { name: p.name }), detail: '', go: 'pop' });
kinds.reinforcements_sent_home = (n, p) => ({ icon: 'return', title: App.t('alerts.reinforcements_home'), detail: mil.unitsText(p.units), go: 'units' });
// garrisons at backbone landing sites (docs/DECISIONS.md E6)
const siteGo = (p) => ({ go: 'world', params: Number.isInteger(p.index) ? { site: p.index } : null });
kinds.garrison_arrived = (n, p) => Object.assign({ icon: 'shield', title: App.t('alerts.garrison_arrived', { n: Number.isInteger(p.index) ? p.index + 1 : '?' }), detail: mil.unitsText(p.units) }, siteGo(p));
kinds.garrison_released = (n, p) => Object.assign({ icon: 'return', title: App.t('alerts.garrison_released', { n: Number.isInteger(p.index) ? p.index + 1 : '?' }), detail: [App.t('alerts.garrison_released.' + (p.reason === 'alliance_dissolved' || p.reason === 'left_alliance' || p.reason === 'town_lost' ? p.reason : 'other')), mil.unitsText(p.units)].filter(Boolean).join(' · ') }, siteGo(p));
}());