Game server manager: web UI for Valheim and Project Zomboid servers

FastAPI + vanilla JS app run as a Docker container behind Caddy (HTTPS by
IP). install.sh installs or updates it on a server in one command, with
preflight checks and Docker setup; deploy.sh pushes a local checkout to a
server over SSH and runs install.sh there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
neil 2026-10-16 19:54:56 -07:00
commit cb9a6d1970
No known key found for this signature in database
20 changed files with 3801 additions and 0 deletions

681
app/static/app.js Normal file
View file

@ -0,0 +1,681 @@
const $ = (s) => document.querySelector(s);
async function api(path, opts = {}) {
const res = await fetch(path, opts);
if (res.status === 401 && !path.endsWith('/login')) { showLogin(); throw new Error('Not logged in'); }
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.detail || `Request failed (${res.status})`);
return data;
}
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
function fmtBytes(b) {
if (!b) return '0 B';
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.min(u.length - 1, Math.floor(Math.log(b) / Math.log(1024)));
return `${(b / 1024 ** i).toFixed(i >= 3 ? 1 : 0)} ${u[i]}`;
}
const fmtRate = (b) => `${fmtBytes(b)}/s`;
function setBar(id, pct) {
const el = $(id);
el.style.width = `${Math.min(100, pct)}%`;
el.style.background = pct > 90 ? 'var(--bad)' : pct > 70 ? 'var(--warn)' : 'var(--ok)';
}
// ---------- auth ----------
function showLogin() {
stopPolling();
$('#app-view').classList.add('hidden');
$('#login-view').classList.remove('hidden');
$('#login-password').focus();
}
function showApp() {
$('#login-view').classList.add('hidden');
$('#app-view').classList.remove('hidden');
startPolling();
}
$('#login-form').addEventListener('submit', async (e) => {
e.preventDefault();
$('#login-error').textContent = '';
try {
await api('/api/login', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: $('#login-password').value }),
});
$('#login-password').value = '';
showApp();
} catch (err) { $('#login-error').textContent = err.message; }
});
$('#logout-btn').addEventListener('click', async () => { await api('/api/logout', { method: 'POST' }); showLogin(); });
// ---------- dashboard ----------
let servers = [];
let stats = { host: {}, servers: {} };
let pollTimer = null;
const busy = new Set(); // server ids with an action in progress
function startPolling() {
if (pollTimer) return;
refresh();
pollTimer = setInterval(refresh, 3000);
}
function stopPolling() { clearInterval(pollTimer); pollTimer = null; }
async function refresh() {
try {
[servers, stats] = await Promise.all([api('/api/servers'), api('/api/stats')]);
renderHost();
renderServers();
if ($('#manage-dialog').open) renderPlayers();
if (view === 'backups') loadBackups();
} catch (e) { /* shown on next successful poll */ }
}
function renderHost() {
const h = stats.host;
if (!h.mem_total) return;
$('#m-cpu').textContent = `${h.cpu_percent}% of ${h.cpu_count} cores`;
setBar('#b-cpu', h.cpu_percent);
$('#m-mem').textContent = `${fmtBytes(h.mem_used)} / ${fmtBytes(h.mem_total)}`;
setBar('#b-mem', (100 * h.mem_used) / h.mem_total);
$('#m-swap').textContent = h.swap_total ? `${fmtBytes(h.swap_used)} / ${fmtBytes(h.swap_total)}` : 'none';
setBar('#b-swap', h.swap_total ? (100 * h.swap_used) / h.swap_total : 0);
$('#m-disk').textContent = `${fmtBytes(h.disk_used)} / ${fmtBytes(h.disk_total)}`;
setBar('#b-disk', (100 * h.disk_used) / h.disk_total);
$('#m-net').textContent = `Network: ↓ ${fmtRate(h.net_rx_rate)} ↑ ${fmtRate(h.net_tx_rate)}`;
}
function fmtDuration(sec) {
const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60);
if (h) return `${h}h ${m}m`;
return m ? `${m}m ${Math.floor(sec % 60)}s` : `${Math.floor(sec)}s`;
}
function playersLine(st) {
if (!st || !st.players) return '';
const n = st.players.length;
const stop = st.auto_stop_in != null ? ` <span class="muted">· auto stop in ${Math.ceil(st.auto_stop_in / 60)} min</span>` : '';
return `<div class="server-players${n ? '' : ' none'}">${n} player${n === 1 ? '' : 's'}${stop}</div>`;
}
// Actions that kick players (stop, restart, delete, saving settings) are blocked while anyone is
// online; the server refuses them too. Disabled buttons don't get hover events in every browser,
// so the tooltip sits on a wrapper.
function playersBlockReason(st, what) {
const n = st?.players?.length || 0;
return n ? `${n} player${n === 1 ? ' is' : 's are'} connected. ${what} is disabled until everyone has left, so nobody gets kicked mid-game.` : '';
}
function guardedButton(act, label, st, isBusy) {
const why = playersBlockReason(st, label);
if (!why) return `<button class="small" data-act="${act}" ${isBusy ? 'disabled' : ''}>${label}</button>`;
return `<span class="tip" title="${esc(why)}"><button class="small" data-act="${act}" disabled>${label}</button></span>`;
}
// Same guard for the manage dialog's buttons; re-applied on every poll while it is open.
function applyManageGuard() {
const st = stats.servers[managed?.id];
for (const [id, what] of [['settings-save', 'Saving settings'], ['manage-delete', 'Delete']]) {
const btn = $(`#${id}`);
if (btn.textContent.endsWith('…')) continue; // mid-request
const why = playersBlockReason(st, what);
btn.disabled = !!why;
$(`#${id}-tip`).title = why;
}
}
// Official Steam library art, stored in static/art/ (<game>-poster.jpg 300x450, <game>-header.jpg 460x215).
const GAME_ART = new Set(['valheim', 'zomboid']);
const artImg = (game, kind, cls) => (GAME_ART.has(game)
? `<img class="${cls}" src="/static/art/${game}-${kind}.jpg" alt="" loading="lazy">` : '');
// "just now", "5 mins ago", "3 hours ago", "2 days ago", "3 weeks ago"; a date after about a month.
function timeAgo(iso) {
const t = new Date(iso);
const sec = (Date.now() - t) / 1000;
const ago = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'} ago`;
if (sec < 60) return 'just now';
if (sec < 3600) return ago(Math.floor(sec / 60), 'min');
if (sec < 86400) return ago(Math.floor(sec / 3600), 'hour');
if (sec < 7 * 86400) return ago(Math.floor(sec / 86400), 'day');
if (sec < 30 * 86400) return ago(Math.floor(sec / (7 * 86400)), 'week');
return `on ${t.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}`;
}
const STATE_LABEL = { online: 'Online', starting: 'Starting…', exited: 'Stopped', created: 'Stopped', restarting: 'Restarting…' };
function renderServers() {
$('#empty-msg').classList.toggle('hidden', servers.length > 0);
const host = location.hostname;
$('#server-list').innerHTML = servers.map((s) => {
const st = stats.servers[s.id];
const running = s.state === 'online' || s.state === 'starting';
const badgeCls = s.state === 'online' ? 'online' : running || s.state === 'restarting' ? 'starting' : 'stopped';
const isBusy = busy.has(s.id);
const memPct = st && stats.host.mem_total ? (100 * st.mem_used) / stats.host.mem_total : 0;
return `
<div class="card server" data-id="${esc(s.id)}">
${artImg(s.game, 'poster', 'server-art')}
<div class="server-body">
<div class="server-top">
<div>
<div class="server-name">${esc(s.server_name)}<span class="badge ${badgeCls}">${isBusy ? 'Working…' : s.busy ? esc(s.busy) : STATE_LABEL[s.state] || esc(s.state)}</span></div>
<div class="server-meta">${esc(s.game_name)} · ${s.summary ? esc(s.summary) : `world <b>${esc(s.world)}</b>`} · connect to <b>${esc(host)}:${s.port}</b></div>
${running ? playersLine(st) : s.last_online ? `<div class="server-last-online" title="${esc(new Date(s.last_online).toLocaleString())}">Last online ${esc(timeAgo(s.last_online))}</div>` : ''}
</div>
<div class="server-actions">
${running
? `${guardedButton('restart', 'Restart', st, isBusy)}
${guardedButton('stop', 'Stop', st, isBusy)}`
: `<button class="small" data-act="start" ${isBusy ? 'disabled' : ''}>Start</button>`}
<button class="small primary manage-btn" data-act="manage" ${isBusy ? 'disabled' : ''}>Manage</button>
</div>
</div>
${running && st ? `
<div class="server-stats">
<div><div class="meter-label"><span>CPU</span><span class="stat-val">${st.cpu_percent}%</span></div><div class="bar"><div style="width:${Math.min(100, st.cpu_percent / (stats.host.cpu_count || 1))}%"></div></div></div>
<div><div class="meter-label"><span>Memory</span><span class="stat-val">${fmtBytes(st.mem_used)}</span></div><div class="bar"><div style="width:${memPct}%"></div></div></div>
<div><div class="meter-label"><span>Network</span><span class="stat-val">↓ ${fmtRate(st.net_rx_rate)} ↑ ${fmtRate(st.net_tx_rate)}</span></div></div>
</div>` : ''}
</div>
</div>`;
}).join('');
}
$('#server-list').addEventListener('click', async (e) => {
const btn = e.target.closest('button[data-act]');
if (!btn) return;
const card = btn.closest('.server');
const id = card.dataset.id;
const s = servers.find((x) => x.id === id);
const act = btn.dataset.act;
if (act === 'manage') return openManage(s);
const path = `/api/servers/${id}/${act}`;
const method = 'POST';
busy.add(id);
renderServers();
try { await api(path, { method }); } catch (err) { alert(err.message); }
busy.delete(id);
refresh();
});
// ---------- manage ----------
let managed = null; // server open in the manage dialog
async function openManage(s) {
managed = s;
$('#manage-title').textContent = s.server_name;
$('#manage-sub').textContent = `${s.game_name} · ${s.summary || `world ${s.world}`}`;
$('#settings-error').textContent = '';
$('#delete-data').checked = false;
$('#autostop-error').textContent = '';
renderPlayers();
$('#settings-fields').innerHTML = '<p class="muted small">Loading…</p>';
$('#manage-dialog').showModal();
try {
const { fields, values, backups, mods, auto_stop } = await api(`/api/servers/${s.id}/settings`);
$('#autostop-enabled').checked = auto_stop.enabled;
$('#autostop-minutes').value = auto_stop.minutes;
$('#mods-section').classList.toggle('hidden', !mods);
if (mods) $('#mods-summary').textContent = s.summary || '';
$('#world-section').classList.toggle('hidden', !backups);
$('#world-download').href = `/api/servers/${s.id}/world.zip`;
$('#settings-form').classList.toggle('hidden', !fields.length);
$('#settings-fields').innerHTML = fields.map((f) => `
<label>${esc(f.label)}
<input name="${esc(f.key)}" type="${f.type === 'number' ? 'number' : 'text'}" ${f.required === false ? '' : 'required'} value="${esc(values[f.key] ?? '')}"
${f.minlength ? `minlength="${f.minlength}"` : ''} ${f.min != null ? `min="${f.min}"` : ''} ${f.max != null ? `max="${f.max}"` : ''}>
${f.help ? `<span class="muted field-help">${esc(f.help)}</span>` : ''}
</label>`).join('');
$('#settings-restart-note').classList.toggle('hidden', !['online', 'starting'].includes(s.state));
} catch (err) { $('#settings-fields').innerHTML = ''; $('#settings-error').textContent = err.message; }
}
function renderPlayers() {
const s = servers.find((x) => x.id === managed?.id) || managed;
const st = stats.servers[s.id];
const list = st?.players;
let html;
if (!['online', 'starting'].includes(s.state)) html = 'The server is not running.';
else if (!st?.ready) html = 'Waiting for the server to come online…';
else if (!list) html = 'Couldn\'t get the player list from the server.';
else if (!list.length) html = 'No players connected.';
if (html) {
$('#players-body').innerHTML = `<p class="muted small" style="margin:0">${html}</p>`;
} else {
$('#players-body').innerHTML = `<table class="players-table">
<tr><th>Player</th><th>IP address</th><th>Connected</th><th>Ping</th></tr>
${list.map((p) => `<tr><td>${esc(p.name)}</td><td>${esc(p.ip || '–')}</td><td>${fmtDuration(p.connected_for)}</td>
<td${p.ping == null ? ' class="muted" title="This player\'s network doesn\'t answer ping"' : ''}>${p.ping == null ? '–' : `${p.ping} ms`}</td></tr>`).join('')}
</table>`;
}
applyManageGuard();
$('#autostop-status').textContent = st?.auto_stop_in != null
? `Nobody is online. Stopping in ${Math.ceil(st.auto_stop_in / 60)} min unless someone joins.` : '';
}
$('#autostop-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = $('#autostop-save');
btn.disabled = true; btn.textContent = 'Saving…';
$('#autostop-error').textContent = '';
try {
await api(`/api/servers/${managed.id}/autostop`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ enabled: $('#autostop-enabled').checked, minutes: +$('#autostop-minutes').value }),
});
btn.textContent = 'Saved';
setTimeout(() => { btn.textContent = 'Save'; }, 1500);
} catch (err) { $('#autostop-error').textContent = err.message; btn.textContent = 'Save'; }
btn.disabled = false;
refresh();
});
$('#manage-close').addEventListener('click', () => $('#manage-dialog').close());
$('#world-download').addEventListener('click', async (e) => {
e.preventDefault();
const a = e.currentTarget;
if (a.dataset.busy) return;
a.dataset.busy = '1'; a.textContent = 'Preparing…';
try {
const res = await fetch(a.href);
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).detail || `Download failed (${res.status})`);
const name = /filename="?([^"]+)"?/.exec(res.headers.get('Content-Disposition') || '')?.[1] || 'world.zip';
const url = URL.createObjectURL(await res.blob());
const tmp = Object.assign(document.createElement('a'), { href: url, download: name });
document.body.append(tmp); tmp.click(); tmp.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
} catch (err) { alert(err.message); }
delete a.dataset.busy; a.textContent = 'Download';
});
$('#manage-logs').addEventListener('click', () => openLogs(managed));
$('#open-mods').addEventListener('click', () => openMods(managed));
$('#settings-form').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = $('#settings-save');
const body = {};
for (const input of $('#settings-fields').querySelectorAll('input')) {
body[input.name] = input.type === 'number' ? +input.value : input.value;
}
btn.disabled = true; btn.textContent = 'Saving…';
$('#settings-error').textContent = '';
busy.add(managed.id); renderServers();
try {
const updated = await api(`/api/servers/${managed.id}/settings`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
busy.delete(managed.id);
managed = updated; // the container is recreated, so its id changes
$('#manage-dialog').close();
} catch (err) {
busy.delete(managed.id);
$('#settings-error').textContent = err.message;
} finally {
btn.disabled = false; btn.textContent = 'Save settings';
applyManageGuard();
refresh();
}
});
$('#manage-delete').addEventListener('click', async () => {
const s = managed;
const wipe = $('#delete-data').checked;
const msg = wipe
? `Delete "${s.server_name}" AND its world files? This cannot be undone.`
: `Delete "${s.server_name}"? The world files are kept on the VPS.`;
if (!confirm(msg)) return;
const btn = $('#manage-delete');
btn.disabled = true; btn.textContent = 'Deleting…';
busy.add(s.id); renderServers();
try {
await api(`/api/servers/${s.id}?delete_data=${wipe}`, { method: 'DELETE' });
$('#manage-dialog').close();
} catch (err) { alert(err.message); }
busy.delete(s.id);
btn.disabled = false; btn.textContent = 'Delete server';
applyManageGuard();
refresh();
});
// ---------- navigation ----------
let view = 'servers';
function showView() {
view = location.hash === '#backups' ? 'backups' : 'servers';
for (const v of ['servers', 'backups']) $(`#view-${v}`).classList.toggle('hidden', v !== view);
document.querySelectorAll('.tabs a').forEach((a) => a.classList.toggle('active', a.dataset.view === view));
$('#new-server-btn').classList.toggle('hidden', view !== 'servers');
if (view === 'backups') loadBackups();
}
window.addEventListener('hashchange', showView);
showView();
// ---------- backups ----------
const BACKUP_KINDS = [['auto', 'Automatic'], ['manual', 'Manual']];
function sessionNotes(b) {
const sn = b.session;
if (!sn) return b.type === 'manual' && 'session' in b ? 'Server was stopped' : '–';
const peak = `peak ${sn.peak} player${sn.peak === 1 ? '' : 's'}`;
return sn.running ? `${fmtDuration(sn.length)} into a running session · ${peak}` : `${fmtDuration(sn.length)} session · ${peak}`;
}
async function loadBackups() {
let data;
try { data = await api('/api/backups'); } catch (e) { return; }
const { backups, keep } = data;
// One card per server, ordered by its newest backup (the list arrives newest first).
const byServer = new Map();
for (const b of backups) {
if (!byServer.has(b.container)) byServer.set(b.container, []);
byServer.get(b.container).push(b);
}
$('#backup-list').innerHTML = byServer.size ? [...byServer.values()].map((list) => {
const b0 = list[0];
return `<div class="card backup-game">
<h3>${esc(b0.game_name || b0.game)} - ${esc(b0.server_name || b0.container)}${b0.world ? ` <span class="muted small">world ${esc(b0.world)}</span>` : ''}</h3>
${BACKUP_KINDS.map(([kind, label]) => {
const rows = list.filter((b) => b.type === kind);
if (!rows.length) return '';
return `<div class="backup-kind">
<h4>${label} <span class="muted small">${rows.length} of ${keep} kept</span></h4>
<table class="backups-table">
<tr><th>Created</th><th>Session notes</th><th>Size</th><th></th></tr>
${rows.map((b) => `<tr>
<td>${b.created ? esc(new Date(b.created).toLocaleString()) : ''}</td>
<td class="muted">${esc(sessionNotes(b))}</td>
<td>${fmtBytes(b.size)}</td>
<td class="row-end"><a class="button ghost small" href="/api/backups/${b.id.split('/').map(encodeURIComponent).join('/')}" download>Download</a></td>
</tr>`).join('')}
</table>
</div>`;
}).join('')}
</div>`;
}).join('') : '<p class="empty">No backups yet. See <b>About Backups</b> for when they are made.</p>';
}
$('#about-backups-btn').addEventListener('click', () => $('#about-backups').showModal());
$('#about-backups-close').addEventListener('click', () => $('#about-backups').close());
// ---------- logs ----------
let logSource = null;
const MAX_LOG_LINES = 3000;
// Colour each line by the most severe level it mentions.
function logLevel(line) {
if (/\b(ERROR|FATAL|CRITICAL|Exception|FAIL(ED)?)\b/i.test(line)) return 'error';
if (/\b(WARN(ING)?)\b/i.test(line)) return 'warn';
if (/\bDEBUG\b/.test(line)) return 'debug';
if (/\bINFO\b/.test(line)) return 'info';
return '';
}
function appendLogLines(lines) {
const body = $('#logs-body');
const atBottom = body.scrollTop + body.clientHeight >= body.scrollHeight - 30;
const frag = document.createDocumentFragment();
for (const line of lines) {
const div = document.createElement('div');
div.textContent = line || '\u00a0';
const lvl = logLevel(line);
if (lvl) div.className = `log-${lvl}`;
frag.append(div);
}
body.append(frag);
while (body.childElementCount > MAX_LOG_LINES) body.firstElementChild.remove();
if (atBottom) body.scrollTop = body.scrollHeight;
}
function setLogStatus(text, live) {
$('#logs-status').textContent = text;
$('#logs-status').classList.toggle('live', !!live);
}
function openLogs(s) {
$('#logs-title').textContent = `Logs: ${s.server_name}`;
$('#logs-body').replaceChildren();
setLogStatus('Connecting…');
$('#logs-dialog').showModal();
connectLogs(s);
}
function connectLogs(s) {
if (logSource) logSource.close();
const es = new EventSource(`/api/servers/${s.id}/logs/stream?tail=500`);
logSource = es;
let first = true;
es.onopen = () => setLogStatus('Live', true);
es.onmessage = (e) => {
if (first) { $('#logs-body').replaceChildren(); first = false; } // fresh tail on (re)connect
appendLogLines(JSON.parse(e.data));
};
es.addEventListener('end', () => { es.close(); setLogStatus('Server stopped. No new output.'); });
es.onerror = () => {
es.close();
setLogStatus('Disconnected. Reconnecting…');
setTimeout(() => { if (logSource === es && $('#logs-dialog').open) connectLogs(s); }, 3000);
};
}
$('#logs-close').addEventListener('click', () => $('#logs-dialog').close());
$('#logs-dialog').addEventListener('close', () => { if (logSource) logSource.close(); logSource = null; });
// ---------- wizard ----------
const wiz = { step: 1, game: null };
const form = $('#wizard-form');
$('#new-server-btn').addEventListener('click', async () => {
form.reset();
wiz.step = 1; wiz.game = null;
$('#upload-fields').classList.add('hidden');
$('#wiz-error').textContent = '';
const games = await api('/api/games');
wiz.games = Object.fromEntries(games.map((g) => [g.id, g]));
$('#game-list').innerHTML = games.map((g) => `
<button type="button" class="game-option" data-game="${esc(g.id)}">
${artImg(g.id, 'header', 'game-option-art')}
<span class="game-option-text"><b>${esc(g.name)}</b><span class="muted small">default port ${g.default_port}</span></span>
</button>`).join('');
showStep();
$('#wizard').showModal();
});
$('#game-list').addEventListener('click', (e) => {
const b = e.target.closest('.game-option');
if (!b) return;
wiz.game = b.dataset.game;
document.querySelectorAll('.game-option').forEach((x) => x.classList.toggle('selected', x === b));
goNext();
});
function showStep() {
document.querySelectorAll('.wiz-step').forEach((el) => el.classList.toggle('hidden', +el.dataset.step !== wiz.step));
$('#wiz-back').classList.toggle('hidden', wiz.step === 1);
$('#wiz-next').classList.toggle('hidden', wiz.step !== 2);
$('#wiz-create').classList.toggle('hidden', wiz.step !== 3);
$('#wiz-error').textContent = '';
}
async function goNext() {
if (wiz.step === 1) {
if (!wiz.game) return;
const { port } = await api(`/api/suggest-port?game=${wiz.game}`);
form.port.value = port;
setupGameFields();
wiz.step = 2;
} else if (wiz.step === 2) {
const err = validateStep2();
if (err) { $('#wiz-error').textContent = err; return; }
renderReview();
wiz.step = 3;
}
showStep();
}
// Show only the selected game's fields; hidden ones are disabled so they don't block validation.
function setupGameFields() {
const g = wiz.game;
$('#wiz-game-title').textContent = `${wiz.games[g].name} server`;
document.querySelectorAll('.game-fields').forEach((el) => {
const on = el.dataset.game === g;
el.classList.toggle('hidden', !on);
el.querySelectorAll('input, select').forEach((i) => { i.disabled = !on; });
});
const pw = form.password;
if (g === 'valheim') {
pw.required = true; pw.minLength = 5;
$('#password-help').textContent = '(at least 5 characters, not part of the server name)';
} else {
pw.required = false; pw.removeAttribute('minlength');
$('#password-help').textContent = '(optional; leave empty for an open server)';
updateMemoryHelp();
renderPresetMods();
}
}
// One recommended-mod checkbox (wizard and mod manager): name, note, and when it was last updated.
function presetLabel(p, inputAttrs) {
const updated = p.updated ? `Updated ${timeAgo(new Date(p.updated * 1000).toISOString())}` : '';
return `<label class="radio preset-mod"><input type="checkbox" ${inputAttrs}>
<span><span class="preset-name">${esc(p.name)}</span>${p.note ? ` <span class="muted small">${esc(p.note)}</span>` : ''}
${(p.includes || []).map((d) => `<span class="preset-include muted">+ ${esc(d)}</span>`).join('')}
${updated ? `<span class="preset-meta muted">${esc(updated)}</span>` : ''}</span></label>`;
}
// Build 42 mod checklist from /api/games; all ticked by default.
function renderPresetMods() {
const presets = wiz.games.zomboid.mod_presets || [];
$('#preset-mods').innerHTML = presets.map((m) => presetLabel(m, `name="preset_mods" value="${esc(m.key)}" checked`)).join('');
updatePresetVisibility();
}
function updatePresetVisibility() {
const b42 = form.branch.value === wiz.games.zomboid.preset_branch;
$('#preset-mods-fieldset').classList.toggle('hidden', !b42);
$('#preset-mods-b41').classList.toggle('hidden', b42);
form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.disabled = !b42; });
}
const checkedPresets = () => [...form.querySelectorAll('input[name="preset_mods"]:checked:not(:disabled)')];
$('#preset-all').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = true; }));
$('#preset-none').addEventListener('click', () => form.querySelectorAll('input[name="preset_mods"]').forEach((i) => { i.checked = false; }));
function updateMemoryHelp() {
const free = wiz.games?.zomboid?.free_memory_mb;
if (free == null) return;
const need = (+form.memory_mb.value || 0) + 768;
const el = $('#memory-help');
el.textContent = `Needs about ${need} MB free to start; ${free} MB is free right now.`
+ (need > free ? ' The server won\'t start until other servers free up memory or you lower this.' : '');
el.classList.toggle('error', need > free);
}
function validateStep2() {
const fields = [...form.querySelectorAll('.wiz-step[data-step="2"] input, .wiz-step[data-step="2"] select')]
.filter((i) => !i.disabled && i.type !== 'radio' && i.type !== 'file');
for (const input of fields) {
if (!input.checkValidity()) {
input.reportValidity();
return `Please fix the ${input.name.replace('_', ' ')}.`;
}
}
if (wiz.game === 'valheim') {
if (form.server_name.value.includes(form.password.value)) return 'The password cannot appear in the server name.';
if (form.world_source.value === 'upload' && !form.world_files.files.length) {
return 'Choose your world files to upload.';
}
}
return '';
}
function renderReview() {
const common = [
['Game', wiz.games[wiz.game].name],
['Server name', form.server_name.value],
['Password', form.password.value || '(none)'],
['Port', `${form.port.value} (and ${+form.port.value + 1}), UDP`],
];
const upload = form.world_source.value === 'upload';
const rows = wiz.game === 'valheim' ? [...common,
['World', form.world_name.value],
['World source', upload ? `Upload: ${[...form.world_files.files].map((f) => f.name).join(', ')}` : 'New world'],
] : [...common,
['Admin password', form.admin_password.value],
['Game version', form.branch.selectedOptions[0].textContent],
['Memory', `${form.memory_mb.value} MB`],
['Max players', form.max_players.value],
['Mods', checkedPresets().map((i) => i.closest('label').querySelector('.preset-name').textContent).join(', ') || 'None'],
];
$('#review').innerHTML = rows.map(([k, v]) => `<dt>${esc(k)}</dt><dd>${esc(v)}</dd>`).join('');
}
form.addEventListener('input', (e) => { if (e.target.name === 'memory_mb') updateMemoryHelp(); });
form.addEventListener('change', (e) => {
if (e.target.name === 'branch') updatePresetVisibility();
if (e.target.name === 'world_source') {
$('#upload-fields').classList.toggle('hidden', form.world_source.value !== 'upload');
}
// Pre-fill the world name from an uploaded file name.
if (e.target.name === 'world_files' && !form.world_name.value) {
const f = [...e.target.files].find((x) => /\.(zip|db|fwl)$/i.test(x.name) && !x.name.startsWith('_main.'));
if (f) form.world_name.value = f.name.replace(/\.(zip|db|fwl)$/i, '').replace(/[^A-Za-z0-9_]/g, '');
}
});
$('#wiz-next').addEventListener('click', goNext);
$('#wiz-back').addEventListener('click', () => { wiz.step -= 1; showStep(); });
$('#wiz-cancel').addEventListener('click', () => $('#wizard').close());
$('#wiz-create').addEventListener('click', async () => {
const btn = $('#wiz-create');
btn.disabled = true; btn.textContent = 'Creating…';
const fd = new FormData();
fd.append('game', wiz.game);
for (const k of ['server_name', 'password', 'port']) fd.append(k, form[k].value);
if (wiz.game === 'valheim') {
fd.append('world_name', form.world_name.value);
fd.append('world_source', form.world_source.value);
if (form.world_source.value === 'upload') {
for (const f of form.world_files.files) fd.append('world_files', f);
}
} else {
for (const k of ['admin_password', 'branch', 'memory_mb', 'max_players']) fd.append(k, form[k].value);
for (const i of checkedPresets()) fd.append('preset_mods', i.value);
}
try {
await api('/api/servers', { method: 'POST', body: fd });
$('#wizard').close();
refresh();
} catch (err) {
$('#wiz-error').textContent = err.message;
} finally {
btn.disabled = false; btn.textContent = 'Create server';
}
});
// ---------- boot ----------
api('/api/me').then((r) => (r.authenticated ? showApp() : showLogin())).catch(showLogin);
// Enter in the wizard should advance, not close the dialog.
form.addEventListener('submit', (e) => {
e.preventDefault();
if (wiz.step === 2) goNext();
else if (wiz.step === 3) $('#wiz-create').click();
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

301
app/static/index.html Normal file
View file

@ -0,0 +1,301 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Game Servers</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<!-- Login -->
<section id="login-view" class="hidden">
<form id="login-form" class="card login-card">
<h1>Game Servers</h1>
<input type="password" id="login-password" placeholder="Password" autocomplete="current-password" autofocus required>
<button type="submit" class="primary">Log in</button>
<p class="error" id="login-error"></p>
</form>
</section>
<!-- Dashboard -->
<section id="app-view" class="hidden">
<header>
<div class="brand">
<h1>Game Servers</h1>
<nav class="tabs">
<a href="#servers" data-view="servers">Servers</a>
<a href="#backups" data-view="backups">Backups</a>
</nav>
</div>
<div class="header-actions">
<button class="primary" id="new-server-btn">+ New game server</button>
<button class="ghost" id="logout-btn">Log out</button>
</div>
</header>
<div id="view-servers">
<div class="card" id="resources">
<h2>VPS resources</h2>
<div class="meters">
<div class="meter"><div class="meter-label"><span>CPU</span><span id="m-cpu">–</span></div><div class="bar"><div id="b-cpu"></div></div></div>
<div class="meter"><div class="meter-label"><span>Memory</span><span id="m-mem">–</span></div><div class="bar"><div id="b-mem"></div></div></div>
<div class="meter"><div class="meter-label"><span>Swap</span><span id="m-swap">–</span></div><div class="bar"><div id="b-swap"></div></div></div>
<div class="meter"><div class="meter-label"><span>Disk</span><span id="m-disk">–</span></div><div class="bar"><div id="b-disk"></div></div></div>
</div>
<p class="net" id="m-net"></p>
</div>
<h2 class="section-title">Servers</h2>
<div id="server-list"></div>
<p class="empty hidden" id="empty-msg">No servers yet. Click <b>+ New game server</b> to create one.</p>
</div>
<div id="view-backups" class="hidden">
<div class="row-between section-title">
<h2 style="margin:0">Backups</h2>
<button class="ghost" id="about-backups-btn">About Backups</button>
</div>
<div id="backup-list"></div>
</div>
</section>
<!-- About backups -->
<dialog id="about-backups">
<div class="logs-head"><h2 style="margin:0">About Backups</h2><button class="ghost" id="about-backups-close">Close</button></div>
<h3>What is backed up</h3>
<ul class="about-list">
<li><b>Valheim:</b> the world folder (<code>.db2</code>, <code>.fwl2</code>, <code>.ok</code>, <code>.chunks</code> and <code>.chunk</code> files), or the <code>.db</code> + <code>.fwl</code> pair for older worlds.</li>
<li><b>Project Zomboid:</b> the world save, the player database and the server's settings files.</li>
</ul>
<h3>Automatic backups</h3>
<ul class="about-list">
<li>A server run becomes eligible for a backup once <b>at least one player connects</b>.</li>
<li>If the server starts and nobody connects, no backup is made.</li>
<li>The backup is taken when that run ends: the server is stopped by hand or by auto stop, restarted,
or recreated after a settings change. Deleting a server also backs up an eligible run first.</li>
<li>Backups are taken after the server has stopped, so they hold the world as it was saved on shutdown.</li>
</ul>
<h3>Manual backups</h3>
<ul class="about-list">
<li>Made every time you use <b>Download</b> in a server's Manage panel: the zip you download is also saved here.</li>
<li>While the server is running this is its last autosave (Valheim saves about every 30 minutes). Stop the
server first for an up-to-the-minute copy.</li>
</ul>
<h3>Retention</h3>
<ul class="about-list">
<li>The newest <b>5 automatic</b> and newest <b>5 manual</b> backups are kept for each server. Older ones are
deleted when a new backup is made.</li>
<li>Backups are stored on the VPS in <code>/srv/gameservers/backups/&lt;game&gt;/&lt;auto|manual&gt;/</code>,
outside the server's own folder, so they are kept even if the server and its world files are deleted.</li>
</ul>
</dialog>
<!-- Wizard -->
<dialog id="wizard">
<form id="wizard-form" method="dialog">
<div class="wiz-step" data-step="1">
<h2>New game server</h2>
<p class="muted">Choose a game</p>
<div id="game-list" class="game-list"></div>
</div>
<div class="wiz-step hidden" data-step="2">
<h2 id="wiz-game-title">New server</h2>
<label>Server name <span class="muted">(shown in the server browser)</span>
<input name="server_name" required maxlength="60">
</label>
<label>Password <span class="muted" id="password-help"></span>
<input name="password">
</label>
<label>Port <span class="muted">(UDP; this port and the next one are used)</span>
<input name="port" type="number" min="1024" max="65534" required>
</label>
<div class="game-fields" data-game="valheim">
<label>World name <span class="muted">(letters, numbers, underscores)</span>
<input name="world_name" required pattern="[A-Za-z0-9_]{1,40}">
</label>
<fieldset>
<legend>World</legend>
<label class="radio"><input type="radio" name="world_source" value="new" checked> Create a new world</label>
<label class="radio"><input type="radio" name="world_source" value="upload"> Upload an existing world</label>
<div id="upload-fields" class="hidden">
<p class="muted small">Easiest: <b>zip your whole world folder</b> and upload the zip. Or select
<b>every file</b> inside the folder: the <code>_main.N.db2</code>, <code>.fwl2</code>, <code>.ok</code> and
<code>.chunks</code> files <i>and</i> all the <code>.chunk</code> files. Valheim throws away an incomplete
world and starts a new one. Older worlds saved as a <code>.db</code> + <code>.fwl</code> pair also work.
On Windows, worlds are in <code>%USERPROFILE%\AppData\LocalLow\IronGate\Valheim\worlds_local</code>.</p>
<label>World files <input type="file" name="world_files" multiple></label>
</div>
</fieldset>
</div>
<div class="game-fields" data-game="zomboid">
<label>Admin password <span class="muted">(for the in-game <code>admin</code> account; at least 5 characters)</span>
<input name="admin_password" required minlength="5">
</label>
<label>Game version
<select name="branch">
<option value="public">Build 42 (current stable)</option>
<option value="legacy41">Build 41 (legacy)</option>
</select>
</label>
<label>Memory (MB) <span class="muted">(Java heap; Build 42 with mods wants 4096 or more)</span>
<input name="memory_mb" type="number" min="1024" max="65536" step="256" value="4096" required>
<span class="field-help" id="memory-help"></span>
</label>
<label>Max players
<input name="max_players" type="number" min="1" max="100" value="8" required>
</label>
<fieldset id="preset-mods-fieldset">
<legend>Mods <span class="muted small">(Build 42)</span></legend>
<div class="row-between small"><span class="muted">Players get these from the Workshop when they join.</span>
<span><button type="button" class="ghost small" id="preset-all">All</button> <button type="button" class="ghost small" id="preset-none">None</button></span></div>
<div id="preset-mods" class="preset-mods"></div>
</fieldset>
<p class="muted small hidden" id="preset-mods-b41">The mod checklist is for Build 42. Add Build 41 mods after creating the server.</p>
<p class="muted small">Add or change mods later from <b>Manage → Mods</b>. The first start
downloads the game (about 7 GB) plus any mods and can take 10+ minutes.</p>
</div>
</div>
<div class="wiz-step hidden" data-step="3">
<h2>Review</h2>
<dl id="review"></dl>
<p class="muted small">The first start downloads the Valheim server (about 1 GB), so it can take a few minutes to come online.</p>
</div>
<p class="error" id="wiz-error"></p>
<div class="wiz-actions">
<button type="button" class="ghost" id="wiz-cancel">Cancel</button>
<span class="spacer"></span>
<button type="button" class="ghost hidden" id="wiz-back">Back</button>
<button type="button" class="primary hidden" id="wiz-next">Next</button>
<button type="button" class="primary hidden" id="wiz-create">Create server</button>
</div>
</form>
</dialog>
<!-- Manage (contents depend on the server's game type) -->
<dialog id="manage-dialog">
<div class="logs-head">
<div><h2 id="manage-title" style="margin:0">Manage</h2><div class="muted small" id="manage-sub"></div></div>
<button class="ghost" id="manage-close">Close</button>
</div>
<div class="manage-section">
<h3>Players</h3>
<div id="players-body"></div>
</div>
<form class="manage-section" id="autostop-form">
<h3>Server Auto Stop</h3>
<label class="radio"><input type="checkbox" id="autostop-enabled"> Auto stop server when no players are connected</label>
<label>Auto stop timeout (mins)
<input type="number" id="autostop-minutes" min="5" max="1440" step="5" value="15" required>
</label>
<p class="muted small" id="autostop-status"></p>
<p class="error" id="autostop-error"></p>
<div class="row-end"><button type="submit" class="primary" id="autostop-save">Save</button></div>
</form>
<form id="settings-form" class="manage-section">
<h3>Settings</h3>
<div id="settings-fields"></div>
<p class="muted small hidden" id="settings-restart-note">Saving restarts the server, which disconnects anyone playing.</p>
<p class="error" id="settings-error"></p>
<div class="row-end"><span class="tip" id="settings-save-tip"><button type="submit" class="primary" id="settings-save">Save settings</button></span></div>
</form>
<div class="manage-section hidden" id="mods-section">
<h3>Mods</h3>
<div class="row-between"><span class="muted small" id="mods-summary"></span><button class="ghost" id="open-mods">Manage mods</button></div>
</div>
<div class="manage-section hidden" id="world-section">
<h3>World</h3>
<div class="row-between">
<span class="muted small">Download the saved world as a zip; a copy is also kept in <b>Backups</b>. While the server
is running this is the last autosave; stop the server first for an up-to-the-minute copy.</span>
<a class="button ghost" id="world-download" download>Download</a>
</div>
</div>
<div class="manage-section">
<h3>Logs</h3>
<div class="row-between"><span class="muted small">Live, color-coded output from the game server.</span><button class="ghost" id="manage-logs">View logs</button></div>
</div>
<div class="manage-section danger-zone">
<h3>Delete server</h3>
<label class="radio"><input type="checkbox" id="delete-data"> Also delete the world files (cannot be undone)</label>
<div class="row-end"><span class="tip" id="manage-delete-tip"><button class="danger" id="manage-delete">Delete server</button></span></div>
</div>
</dialog>
<!-- Mod manager (Project Zomboid) -->
<dialog id="mods-dialog" class="wide">
<div class="logs-head">
<div><h2 id="mods-title" style="margin:0">Mods</h2><span class="muted small" id="mods-status"></span></div>
<button class="ghost" id="mods-close">Close</button>
</div>
<div class="mods-add">
<input id="mods-add-input" placeholder="Paste a Steam Workshop link or ID, or a collection link">
<button class="primary" id="mods-add-btn">Add</button>
</div>
<details class="mods-presets hidden" id="mods-presets" open>
<summary class="small"><b>Recommended mods</b> <span class="muted">(Build 42; ticking adds the Workshop items and enables their mods)</span></summary>
<div class="row-between small presets-bar"><span class="muted" id="mods-presets-count"></span>
<button type="button" class="ghost small" id="mods-presets-all">Add all</button></div>
<div id="mods-presets-list" class="preset-mods"></div>
</details>
<details class="mods-import">
<summary class="muted small">Import from another server's config</summary>
<textarea id="mods-import-text" rows="3" placeholder="WorkshopItems=2169435993;2392709985&#10;Mods=\ModOptions;\tsarslib"></textarea>
<div class="row-end"><button class="ghost small" id="mods-import-btn">Import</button></div>
</details>
<div id="mods-messages" class="msgs"></div>
<div class="mods-grid">
<div>
<h3>Workshop items <span class="muted small" id="items-count"></span></h3>
<div id="mods-items" class="mods-list"></div>
</div>
<div>
<div class="row-between"><h3>Enabled mods &amp; load order</h3>
<span><button class="ghost small" id="mods-enable-all" title="Enable every mod in the downloaded workshop items, then auto-sort">Enable all</button>
<button class="ghost small" id="mods-sort">Auto-sort</button></span></div>
<p class="muted small">Mods load top to bottom. Auto-sort puts each mod after the ones it requires.</p>
<ol id="mods-order" class="mods-list mods-order"></ol>
</div>
</div>
<div id="mods-issues-section" class="hidden">
<h3>Issues</h3>
<ul id="mods-issues" class="mods-issues"></ul>
</div>
<div class="mods-footer">
<label class="radio"><input type="checkbox" id="mods-auto-update"> Auto-update mods (checks every 15 min; warns players 5 min before restarting)</label>
<span class="spacer"></span>
<button class="ghost" id="mods-fetch" title="Download new items into the running server and read their mod IDs">Fetch mod info</button>
<button class="ghost" id="mods-save">Save for next restart</button>
<button class="primary" id="mods-apply">Save &amp; restart now</button>
</div>
</dialog>
<!-- Logs -->
<dialog id="logs-dialog" class="wide">
<div class="logs-head">
<div><h2 id="logs-title" style="margin:0">Logs</h2><span class="logs-status" id="logs-status"></span></div>
<button class="ghost" id="logs-close">Close</button>
</div>
<pre id="logs-body"></pre>
</dialog>
<script src="/static/app.js"></script>
<script src="/static/mods.js"></script>
</body>
</html>

490
app/static/mods.js Normal file
View file

@ -0,0 +1,490 @@
// Mod manager for Project Zomboid servers. Uses $, api, esc, fmtBytes and refresh from app.js.
const mm = {
server: null,
workshopIds: [], // workshop items to download, in order
mods: [], // enabled mod IDs, in load order
autoUpdate: true,
info: {}, // mod info read from the server by list-mods (cached on the VPS)
titles: {}, // workshop details from lookups, for items the server hasn't read yet
edited: false, // unsaved changes
timer: null,
};
async function openMods(s) {
Object.assign(mm, { server: s, edited: false }); // titles (with preview art) are kept between opens
$('#mods-title').textContent = `Mods: ${s.server_name}`;
showMsgs([]);
$('#mods-add-input').value = '';
$('#mods-dialog').showModal();
await loadMods(true);
loadPresets();
clearInterval(mm.timer);
mm.timer = setInterval(() => loadMods(false), 3000);
}
$('#mods-dialog').addEventListener('close', () => { clearInterval(mm.timer); refresh(); });
$('#mods-dialog').addEventListener('cancel', (e) => {
if (mm.edited && !confirm('Discard unsaved mod changes?')) e.preventDefault();
});
$('#mods-close').addEventListener('click', () => {
if (mm.edited && !confirm('Discard unsaved mod changes?')) return;
$('#mods-dialog').close();
});
async function loadMods(full) {
let d;
try { d = await api(`/api/servers/${mm.server.id}/mods`); } catch (err) {
// While a restart recreates the container, its old id is briefly gone.
if (err.message !== 'Server not found') showMsgs([{ level: 'error', text: err.message }]);
return;
}
mm.state = d;
mm.info = d.info || {};
// Don't overwrite edits the user hasn't saved yet.
if (full || !mm.edited) {
mm.workshopIds = [...d.workshop_ids];
mm.mods = [...d.mods];
mm.autoUpdate = d.auto_update;
$('#mods-auto-update').checked = d.auto_update;
}
// Steam details carry the preview art, which the server's own mod info doesn't have, so look up
// every item we don't have them for yet, downloaded or not.
const missingTitles = mm.workshopIds.filter((id) => !mm.titles[id]);
if (full && missingTitles.length) lookupTitles(missingTitles);
renderMods();
}
async function lookupTitles(ids) {
try {
const r = await api('/api/workshop/lookup', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: ids.join(' ') }),
});
for (const it of r.items) mm.titles[it.id] = it;
renderMods();
} catch { /* titles are nice to have */ }
}
const itemInfo = (id) => (mm.info.items || []).find((i) => i.id === id);
// Every mod the server knows about, by mod ID.
function knownMods() {
const out = {};
for (const it of mm.info.items || []) for (const m of it.mods) out[m.id] = { ...m, item: it.id };
return out;
}
// ---------- rendering ----------
function renderMods() {
const d = mm.state || {};
const parts = [];
if (d.busy) parts.push(d.busy);
else if (d.fetch_pending) parts.push('Waiting for the server to come online; mod info is fetched then');
else if (!d.running) parts.push('Server stopped');
else if (!d.ready) parts.push('Server starting…');
else parts.push('Server online');
if (mm.edited) parts.push('unsaved changes');
else if (d.dirty) parts.push('saved, applies on next restart');
if (mm.info.fetched) parts.push(`mod info from ${new Date(mm.info.fetched * 1000).toLocaleString()}`);
if (mm.info.error) parts.push(`last fetch failed: ${mm.info.error}`);
$('#mods-status').textContent = parts.join(' · ');
const busy = !!d.busy;
// Stopped or still starting: one click (re)starts as needed and fetches once it's online; the VPS does the waiting.
const startFirst = !d.running && !d.fetch_pending;
const waitFirst = d.running && !d.ready && !d.fetch_pending;
$('#mods-fetch').textContent = startFirst ? 'Start server and fetch mod info' : waitFirst ? 'Fetch mod info when online' : 'Fetch mod info';
$('#mods-fetch').disabled = busy || d.fetch_pending;
$('#mods-save').disabled = busy || !mm.edited;
$('#mods-apply').disabled = busy || (!mm.edited && !d.dirty);
$('#mods-apply').textContent = d.running ? 'Save & restart now' : 'Save & apply';
renderPresets();
renderItems();
renderOrder();
renderIssues();
}
// ---------- recommended mods (same list as the new-server wizard) ----------
let presetInfo = null; // {mods, branch} from /api/games
async function loadPresets() {
if (presetInfo) return;
try {
const z = (await api('/api/games')).find((g) => g.id === 'zomboid');
presetInfo = { mods: z?.mod_presets || [], branch: z?.preset_branch };
renderMods();
} catch { /* the rest of the manager works without it */ }
}
const presetOn = (p) => p.items.every((i) => mm.workshopIds.includes(i)) && p.mods.every((m) => mm.mods.includes(m));
function renderPresets() {
const show = !!presetInfo?.mods.length && mm.state?.branch === presetInfo.branch;
$('#mods-presets').classList.toggle('hidden', !show);
if (!show) return;
const busy = !!mm.state?.busy;
const on = presetInfo.mods.filter(presetOn).length;
$('#mods-presets-count').textContent = `${on} of ${presetInfo.mods.length} added`;
$('#mods-presets-all').disabled = busy || on === presetInfo.mods.length;
$('#mods-presets-list').innerHTML = presetInfo.mods.map((p) => presetLabel(p,
`data-preset="${esc(p.key)}" ${presetOn(p) ? 'checked' : ''} ${busy ? 'disabled' : ''}`)).join('');
}
// Dependencies come first in each preset, so appending keeps a working load order.
function addPreset(p) {
const newItems = p.items.filter((i) => !mm.workshopIds.includes(i));
mm.workshopIds.push(...newItems);
mm.mods.push(...p.mods.filter((m) => !mm.mods.includes(m)));
return newItems;
}
$('#mods-presets-all').addEventListener('click', () => {
const newItems = presetInfo.mods.flatMap(addPreset);
if (newItems.length) lookupTitles(newItems);
changed();
});
$('#mods-presets-list').addEventListener('change', (e) => {
const p = presetInfo.mods.find((x) => x.key === e.target.dataset.preset);
if (!p) return;
if (e.target.checked) {
const newItems = addPreset(p);
if (newItems.length) lookupTitles(newItems);
} else {
// Keep anything another ticked preset still needs (shared dependencies).
const keep = presetInfo.mods.filter((x) => x !== p && presetOn(x));
const keepItems = new Set(keep.flatMap((x) => x.items));
const keepMods = new Set(keep.flatMap((x) => x.mods));
mm.workshopIds = mm.workshopIds.filter((i) => !p.items.includes(i) || keepItems.has(i));
mm.mods = mm.mods.filter((m) => !p.mods.includes(m) || keepMods.has(m));
}
changed();
});
function renderItems() {
$('#items-count').textContent = mm.workshopIds.length ? `(${mm.workshopIds.length})` : '';
if (!mm.workshopIds.length) {
$('#mods-items').innerHTML = '<p class="muted small">No workshop items yet. Paste a link above to add one.</p>';
return;
}
$('#mods-items').innerHTML = mm.workshopIds.map((id) => {
const info = itemInfo(id);
const t = mm.titles[id] || {};
const title = info?.title || t.title || `Workshop item ${id}`;
const size = info?.size || t.size;
const mods = info?.mods || [];
let modsHtml;
if (mods.length) {
modsHtml = mods.map((m) => {
const on = mm.mods.includes(m.id);
const badges = [
m.maps.length ? `<span class="tag">map: ${esc(m.maps.join(', '))}</span>` : '',
m.error ? `<span class="tag tag-bad" title="${esc(m.error)}">can't load</span>` : '',
m.require.length ? `<span class="tag" title="Requires ${esc(m.require.join(', '))}">needs ${m.require.length}</span>` : '',
].join('');
return `<label class="radio mod-row"><input type="checkbox" data-mod="${esc(m.id)}" ${on ? 'checked' : ''}>
<span><b>${esc(m.name || m.id)}</b> <code>${esc(m.id)}</code> ${badges}</span></label>`;
}).join('');
} else if (info?.downloaded) {
modsHtml = '<p class="muted small">No mods found in this item.</p>';
} else {
modsHtml = `<p class="muted small">Mod IDs show up once the server has downloaded this item:
click <b>Fetch mod info</b> while the server is online, or restart it.</p>`;
}
const warn = t.zomboid === false || info?.available === false
? '<span class="tag tag-bad">not available / not a Project Zomboid item</span>' : '';
return `<div class="mod-item">
<div class="mod-item-head">
${t.preview ? `<img src="${esc(t.preview)}" alt="" loading="lazy">` : ''}
<div class="mod-item-title">
<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${esc(id)}" target="_blank" rel="noopener">${esc(title)}</a>
<div class="muted small">${esc(id)}${size ? ` · ${fmtBytes(size)}` : ''}${info?.downloaded ? ' · downloaded' : ''} ${warn}</div>
</div>
<button class="ghost small danger" data-remove="${esc(id)}" title="Remove item">✕</button>
</div>
${modsHtml}
</div>`;
}).join('');
}
function renderOrder() {
const known = knownMods();
if (!mm.mods.length) {
$('#mods-order').innerHTML = '<p class="muted small">No mods enabled. Tick mods on the left to enable them.</p>';
return;
}
$('#mods-order').innerHTML = mm.mods.map((id, i) => {
const m = known[id];
return `<li data-idx="${i}">
<span class="order-name"><b>${esc(m?.name || id)}</b> <code>${esc(id)}</code></span>
<span class="order-btns">
<button class="ghost small" data-move="-1" ${i === 0 ? 'disabled' : ''} title="Move up">↑</button>
<button class="ghost small" data-move="1" ${i === mm.mods.length - 1 ? 'disabled' : ''} title="Move down">↓</button>
<button class="ghost small danger" data-disable title="Disable">✕</button>
</span>
</li>`;
}).join('');
}
// Problems we can see from the mod info, plus the image's own startup warnings.
function modProblems() {
const known = knownMods();
const haveInfo = (mm.info.items || []).length > 0;
const enabled = new Set(mm.mods);
const pos = Object.fromEntries(mm.mods.map((m, i) => [m, i]));
const out = [];
const conflicts = new Set();
for (const id of mm.mods) {
const m = known[id];
if (!m) {
if (haveInfo) out.push({ level: 'warning', text: `${id}: not found in any downloaded workshop item.` });
continue;
}
if (m.error) out.push({ level: 'error', text: `${m.name || id}: ${m.error}` });
for (const r of m.require) {
if (!enabled.has(r)) out.push({ level: 'warning', text: `${m.name || id} requires ${r}, which isn't enabled (the server loads it if it's downloaded).` });
else if (pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadAfter) {
if (enabled.has(r) && pos[r] > pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load after ${r}. Auto-sort fixes this.` });
}
for (const r of m.loadBefore) {
if (enabled.has(r) && pos[r] < pos[id]) out.push({ level: 'warning', text: `${m.name || id} should load before ${r}. Auto-sort fixes this.` });
}
for (const r of m.incompatible) {
// Either mod may declare the conflict; report each pair once.
const pair = [id, r].sort().join('\u0000');
if (enabled.has(r) && !conflicts.has(pair)) {
conflicts.add(pair);
out.push({ level: 'error', text: `${m.name || id} is incompatible with ${known[r]?.name || r}.` });
}
}
}
return out;
}
function renderIssues() {
const fromServer = (mm.state?.issues || []).map((i) => ({ ...i, source: 'server log' }));
const all = [...modProblems(), ...fromServer];
$('#mods-issues-section').classList.toggle('hidden', !all.length);
$('#mods-issues').innerHTML = all.map((i) => `<li class="issue-${i.level}">
<span>${esc(i.text).replace(/\n/g, '<br>')}</span>${i.source ? `<span class="muted small"> (${i.source})</span>` : ''}
</li>`).join('');
}
// ---------- editing ----------
function changed() { mm.edited = true; renderMods(); }
$('#mods-items').addEventListener('change', (e) => {
const id = e.target.dataset.mod;
if (!id) return;
if (e.target.checked) { if (!mm.mods.includes(id)) mm.mods.push(id); } else mm.mods = mm.mods.filter((m) => m !== id);
changed();
});
$('#mods-items').addEventListener('click', (e) => {
const id = e.target.closest('[data-remove]')?.dataset.remove;
if (!id) return;
const its = itemInfo(id)?.mods.map((m) => m.id) || [];
mm.workshopIds = mm.workshopIds.filter((x) => x !== id);
mm.mods = mm.mods.filter((m) => !its.includes(m));
changed();
});
$('#mods-order').addEventListener('click', (e) => {
const li = e.target.closest('li');
const btn = e.target.closest('button');
if (!li || !btn) return;
const i = +li.dataset.idx;
if (btn.dataset.move) {
const j = i + +btn.dataset.move;
[mm.mods[i], mm.mods[j]] = [mm.mods[j], mm.mods[i]];
} else if ('disable' in btn.dataset) {
mm.mods.splice(i, 1);
}
changed();
});
$('#mods-auto-update').addEventListener('change', (e) => { mm.autoUpdate = e.target.checked; changed(); });
// Topological sort: requirements and loadModAfter go first, loadModBefore after. Otherwise keeps the current order.
// ---------- messages ----------
// [{level: info|success|warning|error, text, action?}]; "enable-all" adds an Enable all button.
function showMsgs(list) {
$('#mods-messages').innerHTML = list.map((m) => `<div class="msg msg-${m.level}">${esc(m.text)}${m.action === 'enable-all'
? '<div class="msg-actions"><button class="ghost small" data-msg-action="enable-all">Enable all mods</button></div>' : ''}</div>`).join('');
}
$('#mods-messages').addEventListener('click', (e) => {
if (e.target.dataset.msgAction === 'enable-all') enableAll();
});
// Enable every loadable mod in the listed workshop items the server has read, then auto-sort.
function enableAll() {
let added = 0;
let broken = 0;
const unknown = [];
for (const id of mm.workshopIds) {
const info = itemInfo(id);
if (!info?.downloaded) { unknown.push(id); continue; }
for (const m of info.mods) {
if (m.error) { broken += 1; continue; }
if (!mm.mods.includes(m.id)) { mm.mods.push(m.id); added += 1; }
}
}
autoSort();
const msgs = [];
if (added) msgs.push({ level: 'success', text: `Enabled ${added} mod${added === 1 ? '' : 's'} and sorted the load order. Save to apply.` });
else msgs.push({ level: 'info', text: 'No more mods to enable from the downloaded items.' });
if (broken) msgs.push({ level: 'warning', text: `${broken} mod${broken === 1 ? '' : 's'} left off because the server reports they can't load.` });
if (unknown.length) {
msgs.push({ level: 'warning', text: `${unknown.length} workshop item${unknown.length === 1 ? ' hasn\'t' : 's haven\'t'} been downloaded yet, so `
+ 'their mods aren\'t known. Save, click Fetch mod info while the server is online, then Enable all again.' });
}
showMsgs(msgs);
changed();
}
$('#mods-enable-all').addEventListener('click', enableAll);
// Put each enabled mod after the ones it requires or asks to load after. Returns whether the order changed.
function autoSort() {
const known = knownMods();
const set = new Set(mm.mods);
const after = Object.fromEntries(mm.mods.map((m) => [m, new Set()])); // m loads after these
for (const id of mm.mods) {
const m = known[id];
if (!m) continue;
for (const r of [...m.require, ...m.loadAfter]) if (set.has(r) && r !== id) after[id].add(r);
for (const r of m.loadBefore) if (set.has(r) && r !== id) after[r].add(id);
}
const out = [];
const placed = new Set();
while (out.length < mm.mods.length) {
const next = mm.mods.find((m) => !placed.has(m) && [...after[m]].every((r) => placed.has(r)))
|| mm.mods.find((m) => !placed.has(m)); // a cycle: keep going in the current order
out.push(next); placed.add(next);
}
if (out.join() === mm.mods.join()) return false;
mm.mods = out;
return true;
}
$('#mods-sort').addEventListener('click', () => { if (autoSort()) changed(); });
async function addFromText(text) {
showMsgs([]);
const btn = $('#mods-add-btn');
btn.disabled = true; btn.textContent = 'Looking up…';
try {
const r = await api('/api/workshop/lookup', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }),
});
const skipped = [];
let added = 0;
for (const it of r.items) {
mm.titles[it.id] = it;
if (!it.available || !it.zomboid) { skipped.push(it); continue; }
if (!mm.workshopIds.includes(it.id)) { mm.workshopIds.push(it.id); added += 1; }
}
const msgs = [];
for (const c of r.collections) msgs.push({ level: 'info', text: `Collection "${c.title || c.id}" has ${c.count} items.` });
if (added) msgs.push({ level: 'success', text: `Added ${added} workshop item${added === 1 ? '' : 's'}.` });
else if (!skipped.length) msgs.push({ level: 'info', text: 'Already in the list.' });
if (skipped.length) {
msgs.push({ level: 'error', text: `Skipped items:\n${skipped.map((it) => ` - ${it.id}${it.title ? ` (${it.title})` : ''}`).join('\n')}`
+ '\n\nThese items are either unavailable or not a Project Zomboid item.' });
}
if (added && r.collections.length) {
msgs.push({ level: 'info', action: 'enable-all', text: 'Adding items doesn\'t enable their mods. To enable everything: '
+ 'click Save for next restart, then Fetch mod info while the server is online (it downloads the items and reads '
+ 'their mod IDs), then Enable all, then Save & restart now.' });
}
showMsgs(msgs);
if (added) changed();
return true;
} catch (err) {
showMsgs([{ level: 'error', text: err.message }]);
return false;
} finally {
btn.disabled = false; btn.textContent = 'Add';
}
}
$('#mods-add-btn').addEventListener('click', async () => {
const text = $('#mods-add-input').value.trim();
if (text && await addFromText(text)) $('#mods-add-input').value = '';
});
$('#mods-add-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); $('#mods-add-btn').click(); } });
// "WorkshopItems=1;2" and "Mods=\A;\B" lines from a pzserver.ini.
$('#mods-import-btn').addEventListener('click', async () => {
const text = $('#mods-import-text').value;
const items = /^\s*WorkshopItems\s*=(.*)$/mi.exec(text)?.[1] || '';
const mods = /^\s*Mods\s*=(.*)$/mi.exec(text)?.[1] || '';
if (!items.trim() && !mods.trim()) { showMsgs([{ level: 'error', text: 'Paste the WorkshopItems= and Mods= lines.' }]); return; }
for (const m of mods.split(';').map((x) => x.trim().replace(/^\\+/, '')).filter(Boolean)) {
if (!mm.mods.includes(m)) mm.mods.push(m);
}
if (items.trim()) await addFromText(items.replace(/;/g, ' '));
$('#mods-import-text').value = '';
changed();
});
// ---------- saving ----------
async function saveMods(apply) {
if (apply === 'now' && mm.state?.running && !confirm(
'Restart the server now with these mods? Players online get a 60-second warning first; with nobody online it restarts right away.')) return;
showMsgs([]);
try {
const d = await api(`/api/servers/${mm.server.id}/mods`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ workshop_ids: mm.workshopIds, mods: mm.mods, auto_update: mm.autoUpdate, apply }),
});
mm.edited = false;
mm.state = d;
renderMods();
refresh();
if (apply === 'now') {
// The container is recreated, so its id changes; follow it by name.
watchForNewContainer();
}
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
}
function watchForNewContainer() {
const name = mm.server.container;
const t = setInterval(async () => {
try {
const list = await api('/api/servers');
const s = list.find((x) => x.container === name);
if (s && s.id !== mm.server.id) { mm.server = s; clearInterval(t); }
if (!s || !$('#mods-dialog').open) clearInterval(t);
} catch { clearInterval(t); }
}, 2000);
}
$('#mods-save').addEventListener('click', () => saveMods('later'));
$('#mods-apply').addEventListener('click', () => saveMods('now'));
$('#mods-fetch').addEventListener('click', async () => {
if (mm.edited) { await saveMods('later'); if (mm.edited) return; }
showMsgs([]);
const start = !mm.state?.ready; // also waits for a server that is still starting
try {
await api(`/api/servers/${mm.server.id}/mods/refresh${start ? '?start=true' : ''}`, { method: 'POST' });
if (start) {
showMsgs([{ level: 'info', text: `${mm.state?.running ? 'Waiting for the server to come online.' : 'Starting the server.'} `
+ 'Mod info is fetched automatically once it\'s online. The first start with new mods downloads them first, which '
+ 'can take a while. You can close this window.' }]);
watchForNewContainer(); // starting with saved changes recreates the container under a new id
}
loadMods(false);
} catch (err) { showMsgs([{ level: 'error', text: err.message }]); }
});

204
app/static/style.css Normal file
View file

@ -0,0 +1,204 @@
:root {
--bg: #0f1216;
--card: #181d23;
--border: #2a313a;
--text: #e6e9ed;
--muted: #8b95a1;
--accent: #e0a040;
--accent-text: #1a1206;
--ok: #4cc38a;
--warn: #e0a040;
--bad: #e5534b;
--bar: #262d36;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 15px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
}
section { max-width: 960px; margin: 0 auto; padding: 16px; }
h1 { font-size: 22px; margin: 0; }
h2 { font-size: 17px; margin: 0 0 12px; }
.hidden { display: none !important; }
.muted { color: var(--muted); font-weight: normal; }
.small { font-size: 13px; }
.error { color: var(--bad); min-height: 1em; margin: 8px 0 0; }
code { font-size: 12px; word-break: break-all; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
button, a.button {
font: inherit; border-radius: 8px; padding: 8px 14px; cursor: pointer;
border: 1px solid var(--border); background: transparent; color: var(--text);
}
a.button { text-decoration: none; white-space: nowrap; display: inline-block; }
button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 600; }
button.danger { color: var(--bad); }
button:disabled { opacity: .5; cursor: default; }
button.small { padding: 4px 10px; font-size: 13px; }
input:not([type=radio]):not([type=checkbox]):not([type=file]), select, textarea {
width: 100%; font: inherit; padding: 9px 11px; margin-top: 4px;
background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 8px;
}
input[type=file] { display: block; margin-top: 4px; max-width: 100%; color: var(--muted); }
label { display: block; margin-bottom: 14px; font-weight: 500; }
label.radio { display: flex; gap: 8px; align-items: center; font-weight: normal; margin-bottom: 8px; }
fieldset { border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin: 0; }
legend { padding: 0 6px; color: var(--muted); }
/* login */
#login-view { min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.login-card { width: 100%; max-width: 340px; display: flex; flex-direction: column; gap: 12px; }
/* header */
header { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
.header-actions { display: flex; gap: 8px; }
.brand { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; }
.tabs { display: flex; gap: 4px; }
.tabs a { color: var(--muted); text-decoration: none; padding: 6px 12px; border-radius: 8px; font-weight: 500; }
.tabs a:hover { color: var(--text); }
.tabs a.active { color: var(--text); background: var(--card); box-shadow: 0 0 0 1px var(--border) inset; }
/* backups */
#backup-list { display: grid; gap: 12px; }
.backup-game h3 { font-size: 16px; margin: 0 0 4px; }
.backup-kind { margin-top: 12px; }
.backup-kind h4 { font-size: 14px; margin: 0 0 6px; }
.backups-table { width: 100%; border-collapse: collapse; font-size: 13px; font-variant-numeric: tabular-nums; }
.backups-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; }
.backups-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); vertical-align: middle; }
.backups-table a.button.small { padding: 4px 10px; font-size: 13px; }
#about-backups h3 { font-size: 15px; margin: 16px 0 6px; }
.about-list { margin: 0; padding-left: 20px; font-size: 14px; }
.about-list li { margin: 4px 0; }
a { color: var(--accent); }
/* resources */
.meters { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 14px; }
.meter-label { display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px; }
.meter-label span:last-child { color: var(--muted); font-variant-numeric: tabular-nums; }
.bar { height: 8px; background: var(--bar); border-radius: 4px; overflow: hidden; }
.bar > div { height: 100%; width: 0; background: var(--ok); transition: width .5s, background .5s; }
.net { margin: 12px 0 0; font-size: 13px; color: var(--muted); }
.section-title { margin: 24px 0 12px; }
.empty { color: var(--muted); text-align: center; padding: 24px; }
/* server cards */
#server-list { display: grid; gap: 12px; }
.server { display: flex; gap: 14px; align-items: flex-start; }
.server-body { display: grid; gap: 12px; flex: 1; min-width: 0; }
.server-art { width: 72px; aspect-ratio: 2 / 3; object-fit: cover; border-radius: 6px; flex: none; background: var(--bar); }
@media (max-width: 520px) { .server-art { width: 52px; } }
.server-top { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; align-items: flex-start; }
.server-name { font-weight: 600; font-size: 16px; }
.server-meta { color: var(--muted); font-size: 13px; }
.badge { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid currentColor; margin-left: 6px; vertical-align: 2px; }
.badge.online { color: var(--ok); }
.badge.starting { color: var(--warn); }
.badge.stopped { color: var(--muted); }
.server-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; font-size: 13px; }
.server-stats .stat-val { color: var(--muted); font-variant-numeric: tabular-nums; }
.server-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.tip { display: inline-flex; }
.tip button:disabled { pointer-events: none; }
.server-players { font-size: 13px; color: var(--ok); margin-top: 2px; }
.server-players.none { color: var(--muted); }
.server-last-online { font-size: 13px; color: var(--muted); margin-top: 2px; }
.players-table { width: 100%; border-collapse: collapse; font-size: 13px; font-variant-numeric: tabular-nums; }
.players-table th { text-align: left; color: var(--muted); font-weight: normal; padding: 0 8px 6px 0; }
.players-table td { padding: 6px 8px 6px 0; border-top: 1px solid var(--border); }
.players-table td:first-child { word-break: break-all; }
/* dialogs */
dialog {
background: var(--card); color: var(--text); border: 1px solid var(--border); border-radius: 12px;
padding: 20px; width: min(520px, calc(100vw - 32px)); max-height: calc(100vh - 32px);
}
dialog.wide { width: 95vw; max-width: 95vw; }
#mods-dialog.wide { width: min(1200px, 95vw); }
dialog::backdrop { background: rgba(0,0,0,.6); }
.wiz-actions { display: flex; gap: 8px; margin-top: 16px; }
.spacer { flex: 1; }
.game-list { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
.game-option { text-align: left; padding: 0; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; }
.game-option:hover { border-color: var(--muted); }
.game-option-art { width: 100%; aspect-ratio: 460 / 215; object-fit: cover; display: block; background: var(--bar); }
.game-option-text { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; }
.game-option.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.preset-mods { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0 12px; margin-top: 10px; }
.preset-mods label.radio { margin-bottom: 6px; align-items: flex-start; }
.preset-mods input { margin-top: 4px; }
.preset-meta { display: block; font-size: 12px; }
.preset-include { display: block; font-size: 12px; }
.presets-bar { margin-top: 8px; }
#review { display: grid; grid-template-columns: auto 1fr; gap: 6px 16px; margin: 0; }
#review dt { color: var(--muted); }
#review dd { margin: 0; word-break: break-all; }
.logs-head { display: flex; justify-content: space-between; align-items: center; }
#logs-body {
background: var(--bg); border: 1px solid var(--border); border-radius: 8px; padding: 10px;
font-size: 12px; height: 75vh; overflow: auto; margin-top: 12px; white-space: pre-wrap; word-break: break-all;
}
/* manage dialog */
.manage-section { border-top: 1px solid var(--border); margin-top: 16px; padding-top: 14px; }
.manage-section h3 { font-size: 15px; margin: 0 0 10px; }
.row-end { display: flex; justify-content: flex-end; }
.row-between { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.danger-zone h3 { color: var(--bad); }
.field-help { display: block; font-size: 12px; margin-top: 4px; }
.server-actions .manage-btn { margin-left: 6px; }
/* log viewer */
.logs-status { font-size: 12px; color: var(--muted); }
.logs-status.live { color: var(--ok); }
.logs-status.live::before { content: "● "; }
#logs-body { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.4; }
.log-error { color: #ff7b72; }
.log-warn { color: #e3b341; }
.log-info { color: #79c0ff; }
.log-debug { color: var(--muted); }
/* mod manager */
.mods-add { display: flex; gap: 8px; margin-top: 14px; }
.mods-add input { margin-top: 0 !important; }
.mods-import { margin-top: 8px; }
.mods-presets { margin-top: 10px; border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; }
.mods-presets summary { cursor: pointer; }
.mods-import textarea { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; margin: 6px 0; }
.mods-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 8px; }
@media (max-width: 760px) { .mods-grid { grid-template-columns: 1fr; } }
.mods-grid h3, #mods-issues-section h3 { font-size: 15px; margin: 8px 0; }
.mods-list { max-height: 45vh; overflow: auto; border: 1px solid var(--border); border-radius: 8px; padding: 8px; margin: 0; }
.mod-item { border-bottom: 1px solid var(--border); padding: 8px 0; }
.mod-item:last-child { border-bottom: 0; }
.mod-item-head { display: flex; gap: 10px; align-items: center; margin-bottom: 6px; }
.mod-item-head img { width: 48px; height: 48px; object-fit: cover; border-radius: 6px; flex: none; }
.mod-item-title { flex: 1; min-width: 0; }
.mod-item-title a { color: var(--text); font-weight: 600; text-decoration: none; }
.mod-item-title a:hover { text-decoration: underline; }
.mod-row { margin: 4px 0 4px 6px; align-items: flex-start; }
.mod-row code, .mods-order code { color: var(--muted); }
.tag { display: inline-block; font-size: 11px; padding: 0 6px; border: 1px solid var(--border); border-radius: 999px; color: var(--muted); margin-left: 4px; }
.tag-bad { color: var(--bad); border-color: var(--bad); }
.mods-order { padding-left: 32px; }
.mods-order li { padding: 4px 0; border-bottom: 1px solid var(--border); }
.mods-order li:last-child { border-bottom: 0; }
.mods-order li { display: list-item; }
.mods-order li > .order-name { display: inline-block; max-width: calc(100% - 110px); word-break: break-all; }
.order-btns { float: right; display: inline-flex; gap: 4px; }
.mods-issues { margin: 0; padding-left: 20px; font-size: 13px; max-height: 25vh; overflow: auto; }
.mods-issues li { margin: 4px 0; }
.issue-error { color: var(--bad); }
.issue-warning { color: var(--warn); }
.msgs { display: grid; gap: 6px; margin-top: 8px; }
.msg { font-size: 13px; white-space: pre-line; border-left: 3px solid currentColor; padding: 6px 10px; border-radius: 4px; background: var(--bg); }
.msg-info { color: #79c0ff; }
.msg-success { color: var(--ok); }
.msg-warning { color: var(--warn); }
.msg-error { color: var(--bad); }
.msg-actions { margin-top: 6px; }
.mods-footer { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 14px; border-top: 1px solid var(--border); padding-top: 12px; }
.mods-footer label { margin: 0; font-size: 13px; }