From bff6a1c61237980fa3142c9106f667ef63935dc7 Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:58:25 +0000 Subject: [PATCH] Fix stale values, the unsynced page, and three smaller review finds - The page waited for nothing, so before the subscription delivered the records every feature looked enabled with its defaults, and an Apply in that window would have written that state. It now shows a spinner until synced, like the role page. - Values stored for a setting which was since renamed, removed, or changed type made every later save of that feature fail validation. The controller now reconciles the stored records with features.ts on start: stale values are dropped with a warning, records of removed features are deleted, and new features get their defaults. - update_config no longer stores overrides for unknown paths, so a stale key is warned about once instead of on every load. - The armor and gun inventory handlers of nuke protection are new to this branch and asserted on get_inventory, which is nil without a character. They return instead. - The AFK check ran every 30 minutes while afk_minutes and kick_minutes can be set as low as 1. It runs every minute. - sameValue lives in features.ts and isDefaultValue uses it, and the custom input branch of FieldInput is a single narrowed check. Co-Authored-By: Claude Fable 5.1 --- exp_scenario/controller.ts | 38 +++++++++++-- exp_scenario/features.ts | 38 +++++++++++-- exp_scenario/module/control/afk_kick.lua | 2 +- .../module/control/nuke_protection.lua | 3 +- exp_scenario/module/features.lua | 3 +- exp_scenario/test/controller.test.js | 14 +++++ exp_scenario/test/features.test.js | 12 +++- exp_scenario/test/module/features.lua | 1 + exp_scenario/web/components/FeaturesPage.tsx | 55 ++++++++++--------- 9 files changed, 124 insertions(+), 42 deletions(-) diff --git a/exp_scenario/controller.ts b/exp_scenario/controller.ts index 88295769..91ba2e45 100644 --- a/exp_scenario/controller.ts +++ b/exp_scenario/controller.ts @@ -6,7 +6,7 @@ import { GroupRecord, GroupPermissions, RoleMappingRecord } from "@expcluster/pe import { ControllerPlugin as RolesPlugin } from "@expcluster/roles/dist/node/controller.js"; import { ControllerPlugin as GroupsPlugin } from "@expcluster/permission-groups/dist/node/controller.js"; import * as messages from "./messages.js"; -import { features, validateFeatureValues } from "./features.js"; +import { features, pruneFeatureValues, validateFeatureValues } from "./features.js"; import { SeedRole, SeedGroup, seedRoles, seedGroups, flattenSeedPermissions } from "./seed.js"; export class ControllerPlugin { @@ -30,11 +30,7 @@ export class ControllerPlugin { ).bootstrap() ); - // Features added since the last start begin with their defaults - const missing = features.filter(feature => !this.features.has(feature.name)); - if (missing.length) { - this.features.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true))); - } + this.reconcileFeatures(); this.controller.subscriptions.handle(messages.FeatureUpdatedEvent, this.handleFeatureSubscription.bind(this)); this.features.on("update", this.featuresUpdated.bind(this)); @@ -50,6 +46,36 @@ export class ControllerPlugin { await this.features.save(); } + /** + * Bring the stored records in line with the features declared in features.ts. + * + * New features begin with their defaults, records of removed features are + * deleted, and values which no longer match a field are dropped so the + * feature can still be saved from the web interface. + */ + reconcileFeatures() { + const declared = new Map(features.map(feature => [feature.name, feature])); + for (const record of [...this.features.values()]) { + const feature = declared.get(record.id); + if (!feature) { + this.logger.warn(`Dropping stored config of removed feature ${record.id}`); + this.features.delete(record); + continue; + } + + const { kept, dropped } = pruneFeatureValues(feature, record.values); + if (dropped.length) { + this.logger.warn(`Dropping stored values of ${record.id} which no longer match a setting: ${dropped.join(", ")}`); + this.features.set(new messages.FeatureRecord(record.id, record.enabled, kept)); + } + } + + const missing = features.filter(feature => !this.features.has(feature.name)); + if (missing.length) { + this.features.setMany(missing.map(feature => new messages.FeatureRecord(feature.name, true))); + } + } + featuresUpdated(updates: messages.FeatureRecord[]) { this.controller.subscriptions.broadcast(new messages.FeatureUpdatedEvent(updates)); } diff --git a/exp_scenario/features.ts b/exp_scenario/features.ts index 663e835d..3327bbb8 100644 --- a/exp_scenario/features.ts +++ b/exp_scenario/features.ts @@ -276,10 +276,38 @@ function checkFieldValue(field: FeatureField, value: FeatureValue, label: string } } -/** Check if a value equals the default of its field, lists are compared by content. */ -export function isDefaultValue(field: FeatureField, value: FeatureValue) { - if (Array.isArray(value) && Array.isArray(field.default)) { - return value.length === field.default.length && value.every((item, index) => item === (field.default as string[])[index]); +/** Check if two values are equal, lists are compared by content. */ +export function sameValue(a: FeatureValue | undefined, b: FeatureValue | undefined) { + if (Array.isArray(a) && Array.isArray(b)) { + return a.length === b.length && a.every((item, index) => item === b[index]); } - return value === field.default; + return a === b; +} + +export function isDefaultValue(field: FeatureField, value: FeatureValue) { + return sameValue(value, field.default); +} + +/** + * Drop stored values which no longer match the fields of a feature, after a + * setting was renamed, removed, or changed type. + * + * @returns the values which are still valid, and the names of those dropped + */ +export function pruneFeatureValues(feature: Feature, values: Record) { + const kept: Record = {}; + const dropped: string[] = []; + for (const [key, value] of Object.entries(values)) { + const field = feature.fields.find(f => f.name === key); + try { + if (!field) { + throw new Error("removed"); + } + checkFieldValue(field, value, key); + kept[key] = value; + } catch { + dropped.push(key); + } + } + return { kept, dropped }; } diff --git a/exp_scenario/module/control/afk_kick.lua b/exp_scenario/module/control/afk_kick.lua index b2d82088..c257c420 100644 --- a/exp_scenario/module/control/afk_kick.lua +++ b/exp_scenario/module/control/afk_kick.lua @@ -98,7 +98,7 @@ return feature:guard{ [e.on_player_joined_game] = on_player_joined_game, }, on_nth_tick = { - [60 * 60 * 30] = check_afk_players, + [60 * 60] = check_afk_players, }, has_active_player = has_active_player, } diff --git a/exp_scenario/module/control/nuke_protection.lua b/exp_scenario/module/control/nuke_protection.lua index 33640a42..d661b278 100644 --- a/exp_scenario/module/control/nuke_protection.lua +++ b/exp_scenario/module/control/nuke_protection.lua @@ -30,7 +30,8 @@ local function check_items(player, type) local banned_items = config.banned_items local items = {} --- @type LuaItemStack[] - local inventory = assert(player.get_inventory(type)) + local inventory = player.get_inventory(type) + if not inventory then return end -- Check what items the player has for i = 1, #inventory do local item = inventory[i --[[@as uint]]] diff --git a/exp_scenario/module/features.lua b/exp_scenario/module/features.lua index db3f52c3..dd5748a6 100644 --- a/exp_scenario/module/features.lua +++ b/exp_scenario/module/features.lua @@ -263,8 +263,9 @@ function Feature:update_config(enabled, values) for path, value in pairs(values) do if self.fields[path] == nil then log("[WARNING] Unknown override for " .. self.name .. "." .. path) + else + overrides[path] = value end - overrides[path] = value end local old_values = {} diff --git a/exp_scenario/test/controller.test.js b/exp_scenario/test/controller.test.js index e856115c..3c9916b0 100644 --- a/exp_scenario/test/controller.test.js +++ b/exp_scenario/test/controller.test.js @@ -143,6 +143,20 @@ t.test("class ControllerPlugin", t2 => { t3.ok(records.every(record => record.enabled && !Object.keys(record.values).length), "enabled with no overrides"); }); + t2.test(".reconcileFeatures() drops stored values and features which no longer exist", async t3 => { + const databaseDirectory = t3.testdir(); + const { plugin } = await startPlugin(t3, { withPlugins: false, databaseDirectory }); + plugin.features.set(new messages.FeatureRecord("afk_kick", false, { afk_minutes: 5, trust_time: 600 })); + plugin.features.set(new messages.FeatureRecord("gone", true, {})); + 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 stale value is dropped, the rest kept"); + t3.notOk(restarted.features.has("gone"), "the removed feature is deleted"); + t3.ok(features.every(feature => restarted.features.has(feature.name)), "every declared feature still has a record"); + }); + t2.test(".handleFeatureUpdateRequest() stores the values which differ from the default", async t3 => { const { plugin } = await startPlugin(t3, { withPlugins: false }); const broadcasts = []; diff --git a/exp_scenario/test/features.test.js b/exp_scenario/test/features.test.js index 4446c8de..928e855f 100644 --- a/exp_scenario/test/features.test.js +++ b/exp_scenario/test/features.test.js @@ -1,7 +1,7 @@ import fs from "node:fs"; import path from "node:path"; import t from "tap"; -import { features, validateFeatureValues } from "../dist/node/features.js"; +import { features, pruneFeatureValues, validateFeatureValues } from "../dist/node/features.js"; /** Every lua file in the module, by path relative to it. */ function luaFiles(dir, prefix = "") { @@ -105,3 +105,13 @@ t.test("validateFeatureValues()", t2 => { t2.same(validateFeatureValues("spawn_area", { "turrets.enabled": false }), { "turrets.enabled": false }, "nested settings"); t2.end(); }); + +t.test("pruneFeatureValues()", t2 => { + const afkKick = features.find(feature => feature.name === "afk_kick"); + t2.same( + pruneFeatureValues(afkKick, { afk_minutes: 5, trust_time: 600, kick_minutes: "soon", active_role_id: null }), + { kept: { afk_minutes: 5, active_role_id: null }, dropped: ["trust_time", "kick_minutes"] }, + "removed settings and wrong types are dropped, valid values and optional nulls stay", + ); + t2.end(); +}); diff --git a/exp_scenario/test/module/features.lua b/exp_scenario/test/module/features.lua index d5a10c2e..fb85bdaf 100644 --- a/exp_scenario/test/module/features.lua +++ b/exp_scenario/test/module/features.lua @@ -53,6 +53,7 @@ Suite.test("update_config() ignores and logs values which can not be overridden" feature:update_config(true, { flag = "yes", check = false, icon = "x" }) Suite.eq(feature.config, { enabled = true, flag = true, check = check }, "wrong types, functions, and unknown keys are skipped") Suite.eq(#env.logged, 3, "each one is logged") + Suite.eq(env.storage.test, { enabled = true, flag = "yes", check = false }, "unknown keys are not stored") end) Suite.test("receive_update() updates known features", function(env) diff --git a/exp_scenario/web/components/FeaturesPage.tsx b/exp_scenario/web/components/FeaturesPage.tsx index d9dff19d..86e0ba04 100644 --- a/exp_scenario/web/components/FeaturesPage.tsx +++ b/exp_scenario/web/components/FeaturesPage.tsx @@ -1,10 +1,10 @@ import React, { useContext, useState } from "react"; -import { Button, Checkbox, Col, ConfigProvider, Divider, Input, InputNumber, Row, Select, Space, Switch } from "antd"; +import { Button, Checkbox, Col, ConfigProvider, Divider, Input, InputNumber, Row, Select, Space, Spin, Switch } from "antd"; import * as lib from "@clusterio/lib"; import { ControlContext, PageHeader, PageLayout, notifyErrorHandler, useAccount } from "@clusterio/web_ui"; -import { Feature, FeatureField, FeatureValue, features, isDefaultValue } from "../../features.js"; +import { Feature, FeatureField, FeatureValue, features, isDefaultValue, sameValue } from "../../features.js"; import { FeatureRecord, FeatureUpdateRequest } from "../../messages.js"; import { useFeatures } from "../index"; @@ -15,13 +15,6 @@ type PendingChanges = Record item === b[index]); - } - return a === b; -} - /** The stored state of a feature, with defaults for values which were not set. */ function storedState(feature: Feature, record: FeatureRecord | undefined): FeatureState { return { @@ -78,23 +71,23 @@ function searchFields(feature: Feature, query: string) { function FieldInput(props: { field: FeatureField, value: FeatureValue, disabled: boolean, onChange: (value: FeatureValue) => void }) { const { field, value, disabled, onChange } = props; const control = useContext(ControlContext); - const CustomInput = field.type !== "string_list" && field.inputComponent - ? control.inputComponents.get(field.inputComponent) - : undefined; - if (CustomInput && field.type !== "string_list") { - const fieldDefinition: lib.FieldDefinition = { - type: field.type, - title: field.title, - description: field.description, - optional: field.optional, - inputComponent: field.inputComponent, - }; - return } - onChange={onChange} - disabled={disabled} - />; + if (field.type !== "string_list" && field.inputComponent) { + const CustomInput = control.inputComponents.get(field.inputComponent); + if (CustomInput) { + const fieldDefinition: lib.FieldDefinition = { + type: field.type, + title: field.title, + description: field.description, + optional: field.optional, + inputComponent: field.inputComponent, + }; + return } + onChange={onChange} + disabled={disabled} + />; + } } switch (field.type) { @@ -228,11 +221,19 @@ function FeatureNav(props: { feature: Feature, enabled: boolean }) { export default function FeaturesPage() { const control = useContext(ControlContext); const account = useAccount(); - const [records] = useFeatures(); + const [records, synced] = useFeatures(); const [pending, setPending] = useState({}); const [search, setSearch] = useState(""); const canEdit = Boolean(account.hasPermission("exp_scenario.config.edit")); + // Until the subscription delivers the records every feature would look enabled with its defaults + if (!synced) { + return + + + ; + } + const stored = Object.fromEntries(features.map(feature => [feature.name, storedState(feature, records.get(feature.name))])); const current = (name: string): FeatureState => ({ enabled: pending[name]?.enabled ?? stored[name].enabled,