Add a web page for configuring scenario features

Features can now be enabled, disabled, and configured from the web UI
while the game is running, without editing Lua files. The first five
features covered are AFK Kick, Chat Auto Reply, Death Markers, Mine
Depletion, and Station Auto Name.

Lua side: module/features.lua holds each feature's defaults, keeps the
overrides from the controller in storage, and patches them onto the
config table in place. Features.guard skips a feature's handlers while
it is disabled. The five config files move from exp_legacy into
exp_scenario/module/config and their control files now read config at
runtime instead of deciding at load which handlers to register. AFK
Kick times are now in minutes.

Controller side: features.ts lists the editable settings and their
defaults. Overrides that differ from the default are stored in
exp_scenario/features.json and guarded by the existing
exp_scenario.config.view/edit permissions. The instance plugin sends
them over rcon on start, on every change, and again after the
controller restarts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-09-28 17:56:14 +00:00
1 parent 46bb15e4a6
commit 88358b23b9
30 files changed
+1226 -89

No files matched your search

+46 -3
View File
@@ -4,6 +4,7 @@ import { Controller } from "@clusterio/controller";
import { ControllerPlugin } from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js";
import { seedRoles, seedGroups } from "../dist/node/seed.js";
import { features } from "../dist/node/features.js";
import * as roles from "@expcluster/roles";
import * as groups from "@expcluster/permission-groups";
import { ControllerPlugin as RolesPlugin } from "@expcluster/roles/dist/node/controller.js";
@@ -16,7 +17,7 @@ import { plugin } from "../dist/node/index.js";
lib.registerPluginPermissions([plugin]);
// The controller validates message classes against the link registry
for (const Message of [messages.SeedRequest, ...roles.plugin.messages, ...groups.plugin.messages]) {
for (const Message of [...plugin.messages, ...roles.plugin.messages, ...groups.plugin.messages]) {
lib.Link.register(Message);
}
@@ -29,9 +30,9 @@ t.after(() => {
});
/** Build the plugin around a real controller, which is side effect free while not started. */
async function startPlugin(t2, { withPlugins = true } = {}) {
async function startPlugin(t2, { withPlugins = true, databaseDirectory = t2.testdir() } = {}) {
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": t2.testdir(),
"controller.database_directory": databaseDirectory,
"controller.default_role_id": lib.Role.DefaultPlayerRoleId,
});
const controller = new Controller(logger, [], controllerConfig);
@@ -135,5 +136,47 @@ t.test("class ControllerPlugin", t2 => {
t3.notOk([...first.values()].filter(priority => priority === 2).length > 1, "seed priorities skip taken ones");
});
t2.test(".init() adds every feature with its defaults", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
const records = await plugin.handleFeatureListRequest();
t3.strictSame(records.map(record => record.id), features.map(feature => feature.name), "one record per feature");
t3.ok(records.every(record => record.enabled && !Object.keys(record.values).length), "enabled with no overrides");
});
t2.test(".handleFeatureUpdateRequest() stores the values which differ from the default", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
const broadcasts = [];
plugin.controller.subscriptions.broadcast = event => broadcasts.push(event);
const record = await plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest(
"death_markers", false, { show_map_markers: false, collect_corpses: true },
));
t3.strictSame(record.values, { show_map_markers: false }, "the default value is dropped");
t3.equal(plugin.features.get("death_markers").enabled, false, "the feature is disabled");
t3.strictSame(broadcasts.map(event => event.updates.map(update => update.id)), [["death_markers"]], "the update is broadcast");
const subscription = await plugin.handleFeatureSubscription({ lastRequestTimeMs: record.updatedAtMs - 1 });
t3.strictSame(subscription.updates.map(update => update.id), ["death_markers"], "subscribers catch up on the change");
});
t2.test(".handleFeatureUpdateRequest() rejects invalid values", async t3 => {
const { plugin } = await startPlugin(t3, { withPlugins: false });
await t3.rejects(
plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest("death_markers", true, { unknown: 1 })),
{ message: "Feature death_markers has no setting unknown" },
);
});
t2.test(".init() keeps stored features across restarts", async t3 => {
const databaseDirectory = t3.testdir();
const { plugin } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
await plugin.handleFeatureUpdateRequest(new messages.FeatureUpdateRequest("afk_kick", false, { afk_minutes: 5 }));
await plugin.onShutdown();
const { plugin: restarted } = await startPlugin(t3, { withPlugins: false, databaseDirectory });
const record = restarted.features.get("afk_kick");
t3.strictSame([record.enabled, record.values], [false, { afk_minutes: 5 }], "the stored record is loaded");
});
t2.end();
});
+51
View File
@@ -0,0 +1,51 @@
import fs from "node:fs";
import path from "node:path";
import t from "tap";
import { features, validateFeatureValues } from "../dist/node/features.js";
/** Read a literal default from a module/config file, only covers single line booleans, numbers, and strings. */
function luaDefault(source, key) {
const match = new RegExp(`^\\s*${key} = (true|false|-?[\\d.]+|"[^"]*"),`, "m").exec(source);
return match ? JSON.parse(match[1]) : undefined;
}
t.test("features", t2 => {
for (const feature of features) {
t2.test(feature.name, t3 => {
const file = path.join(import.meta.dirname, "..", "module", "config", `${feature.name}.lua`);
const source = fs.readFileSync(file, "utf8");
t3.match(source, `Features.register("${feature.name}"`, "the config file registers the feature");
for (const field of feature.fields) {
t3.equal(luaDefault(source, field.name), field.default, `${field.name} default matches the lua side`);
}
t3.end();
});
}
t2.end();
});
t.test("validateFeatureValues()", t2 => {
t2.same(
validateFeatureValues("death_markers", { show_map_markers: false, collect_corpses: true }),
{ show_map_markers: false },
"values equal to their default are dropped",
);
t2.throws(() => validateFeatureValues("unknown", {}), { message: "Unknown feature unknown" });
t2.throws(
() => validateFeatureValues("death_markers", { period_check_map_tags: 60 }),
{ message: "Feature death_markers has no setting period_check_map_tags" },
);
t2.throws(
() => validateFeatureValues("death_markers", { show_map_markers: "no" }),
{ message: "Setting show_map_markers of death_markers must be a boolean" },
);
t2.throws(
() => validateFeatureValues("afk_kick", { afk_minutes: 0 }),
{ message: "Setting afk_minutes of afk_kick must be at least 1" },
);
t2.throws(
() => validateFeatureValues("afk_kick", { afk_minutes: Infinity }),
{ message: "Setting afk_minutes of afk_kick must be a finite number" },
);
t2.end();
});
+120
View File
@@ -0,0 +1,120 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Instance } from "@clusterio/host";
import { InstancePlugin } from "../dist/node/instance.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.js";
// The instance validates message classes against the link registry
for (const Message of pluginDeclaration.messages) {
lib.Link.register(Message);
}
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
class TestConnector extends lib.BaseConnector {
constructor() {
super(lib.Address.fromShorthand({ instanceId: 1 }), lib.Address.fromShorthand({ hostId: 1 }));
this.valid = true;
this.connected = true;
this.hasSession = true;
}
send() {}
}
/** Build a plugin around a real instance with spies on what leaves it. */
async function startPlugin(t2, features = [new messages.FeatureRecord("death_markers", false, { show_map_markers: false })]) {
const instanceConfig = new lib.InstanceConfig("host");
instanceConfig.set("instance.id", 1);
instanceConfig.set("instance.name", "test");
const instance = new Instance(
{ assignGamePort: () => 1 }, new TestConnector(), t2.testdir(), "factorioDir", instanceConfig
);
const state = { sent: [], rcons: [] };
instance.server = {
handle: () => {},
sendRcon: async command => {
state.rcons.push(command);
return "";
},
};
instance.sendTo = async (dst, request) => {
state.sent.push(request);
return request instanceof messages.FeatureListRequest ? features : undefined;
};
const plugin = new InstancePlugin({ plugin: { name: "exp_scenario" }, instance, host: {}, logger });
await plugin.init();
return { plugin, instance, state };
}
/** The payload of a recorded rcon command. */
function decodeRcon(command) {
const match = command.match(/^\/sc exp_scenario\.features\.receive_update\(helpers\.json_to_table\[(=+)\[(.*)\]\1\]\)$/s);
return JSON.parse(match[2]);
}
t.test("class InstancePlugin", t2 => {
t2.test(".onStart() subscribes and sends every feature to lua", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onStart();
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes to updates first");
t3.ok(state.sent[1] instanceof messages.FeatureListRequest, "then lists the features");
t3.strictSame(
decodeRcon(state.rcons[0]),
[{ name: "death_markers", enabled: false, values: { show_map_markers: false } }],
);
});
t2.test(".handleFeatureUpdatedEvent() only sends while the game is up", async t3 => {
const { plugin, state } = await startPlugin(t3);
const event = new messages.FeatureUpdatedEvent([
new messages.FeatureRecord("afk_kick", true, { afk_minutes: 5 }),
new messages.FeatureRecord("removed", true, {}, 0, true),
]);
await plugin.handleFeatureUpdatedEvent(event);
t3.strictSame(state.rcons, [], "nothing is sent before start");
await plugin.onStart();
state.rcons.length = 0;
await plugin.handleFeatureUpdatedEvent(event);
t3.strictSame(decodeRcon(state.rcons[0]), [{ name: "afk_kick", enabled: true, values: { afk_minutes: 5 } }],
"deleted features are left out");
await plugin.onExit();
state.rcons.length = 0;
await plugin.handleFeatureUpdatedEvent(event);
t3.strictSame(state.rcons, [], "nothing is sent after exit");
});
t2.test(".onControllerConnectionEvent() syncs again after the controller restarts", async t3 => {
const { plugin, state } = await startPlugin(t3);
await plugin.onControllerConnectionEvent("connect");
t3.strictSame(state.sent, [], "nothing happens before start");
await plugin.onStart();
state.sent.length = 0;
state.rcons.length = 0;
await plugin.onControllerConnectionEvent("resume");
t3.strictSame(state.sent, [], "a resumed session keeps its subscription");
await plugin.onControllerConnectionEvent("connect");
t3.ok(state.sent[0] instanceof lib.SubscriptionRequest, "subscribes again");
t3.equal(state.rcons.length, 1, "and sends every feature");
});
t2.test(".luaSendFeatures() picks a long bracket the values do not close", async t3 => {
const { plugin, state } = await startPlugin(t3);
const name = "a]=]b]==]c";
await plugin.luaSendFeatures([new messages.FeatureRecord("station_auto_name", true, { station_name: name })]);
t3.match(state.rcons[0], "json_to_table[===[", "uses a level not found in the json");
t3.strictSame(decodeRcon(state.rcons[0])[0].values.station_name, name);
});
t2.end();
});
+8
View File
@@ -0,0 +1,8 @@
import path from "node:path";
import t from "tap";
import { reportLuaTests } from "../../test/lua/runner.js";
const envFile = path.join(import.meta.dirname, "module", "env.lua");
// Each file runs in its own lua state, and each test in a fresh environment
t.test("features.lua", t2 => reportLuaTests(t2, envFile, path.join(import.meta.dirname, "module", "features.lua")));
+46
View File
@@ -0,0 +1,46 @@
--[[-- Test environment for module/features.lua
Extends the shared stubs with a fresh copy of the features module and a stub
of exp_util storage which lets tests act out on_init and on_load.
Run as a chunk by test/lua/runner.js, receiving the shared folder. The suite
returned here becomes `...` in each test file.
]]
local shared_root = ... --- @type string
local source = assert(debug.getinfo(1, "S")).source:gsub("\\", "/")
local plugin_root = assert(source:match("^@(.*)/test/module/env%.lua$"))
local Framework = assert(loadfile(shared_root .. "/framework.lua"))() --- @type Framework
--- @class ExpScenario.TestEnv : Stubs
--- @field Features ExpScenario.Features A fresh copy of the features module
--- @field storage table The table registered with storage, as on_init would store it
--- @field on_load fun(tbl: table) Act out on_load with the given storage table
--- @field load_config fun(name: string): table Load module/config/<name>.lua
return Framework.suite(function(env)
--- @cast env ExpScenario.TestEnv
local callback --- @type fun(tbl: table)
env.extend_requires{
["modules/exp_util/storage"] = {
register = function(tbl, fn)
env.storage = tbl
callback = fn
end,
},
}
env.Features = assert(loadfile(plugin_root .. "/module/features.lua"))()
env.extend_requires{ ["modules/exp_scenario/features"] = env.Features }
function env.on_load(tbl)
env.storage = tbl
callback(tbl)
end
function env.load_config(name)
return assert(loadfile(plugin_root .. "/module/config/" .. name .. ".lua"))()
end
return env
end)
+63
View File
@@ -0,0 +1,63 @@
local Suite = ... --- @type Suite<ExpScenario.TestEnv>
Suite.test("register() enables features unless the defaults say otherwise", function(env)
Suite.eq(env.Features.register("on", { value = 1 }).enabled, true, "enabled by default")
Suite.eq(env.Features.register("off", { enabled = false }).enabled, false, "the defaults can disable it")
Suite.throws(function() env.Features.register("on", {}) end, "Feature already registered: on", "names are unique")
end)
Suite.test("receive_update() changes the registered table in place", function(env)
local config = env.Features.register("test", { flag = true, count = 5, text = "a" })
env.Features.receive_update{ { name = "test", enabled = false, values = { flag = false, count = 7 } } }
Suite.eq(config, { enabled = false, flag = false, count = 7, text = "a" }, "given values replace the defaults")
env.Features.receive_update{ { name = "test", enabled = true, values = { text = "b" } } }
Suite.eq(config, { enabled = true, flag = true, count = 5, text = "b" }, "values left out go back to their default")
Suite.eq(env.storage, { test = { enabled = true, text = "b" } }, "the overrides are kept in storage")
end)
Suite.test("receive_update() ignores values which can not be overridden", function(env)
local function check() return true end
local config = env.Features.register("test", { flag = true, check = check, icon = nil })
env.Features.receive_update{
{ name = "unknown", enabled = false, values = {} },
{ name = "test", enabled = true, values = { flag = "yes", check = false, icon = "x", extra = 1 } },
}
Suite.eq(config, { enabled = true, flag = true, check = check }, "wrong types, functions, and unknown keys are skipped")
Suite.eq(env.storage.unknown, nil, "unknown features are not stored")
end)
Suite.test("on_load applies the overrides from storage", function(env)
local config = env.Features.register("test", { flag = true })
env.on_load{ test = { enabled = false, flag = false } }
Suite.eq(config, { enabled = false, flag = false }, "the saved overrides apply")
env.Features.receive_update{ { name = "test", enabled = true, values = {} } }
Suite.eq(env.storage, { test = { enabled = true } }, "later updates go to the loaded storage table")
end)
Suite.test("guard() skips handlers while the feature is disabled", function(env)
local config = env.Features.register("test", {})
local calls = {}
local lib = env.Features.guard(config, {
events = { on_event = function(event) calls[#calls + 1] = event end },
on_nth_tick = { [60] = function(event) calls[#calls + 1] = event end },
on_init = function() end,
})
lib.events.on_event("a")
lib.on_nth_tick[60]("b")
env.Features.receive_update{ { name = "test", enabled = false, values = {} } }
lib.events.on_event("c")
lib.on_nth_tick[60]("d")
Suite.eq(calls, { "a", "b" }, "only called while enabled")
end)
Suite.test("config files register their feature", function(env)
local config = env.load_config("death_markers")
env.Features.receive_update{ { name = "death_markers", enabled = true, values = { show_map_markers = false } } }
Suite.eq(config.show_map_markers, false, "death_markers can be changed")
Suite.eq(config.period_check_map_tags, 60 * 60 * 5, "other values keep their default")
end)
return Suite.run()