From 808294adad3f378ad8d66b698acf8df7f49c2302 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 12 Nov 2026 00:28:50 +0100 Subject: Phase 1: headless game engine on the server (M1) Complete mechanical port of the reference app's game engine to server/lib/core/ so later phases are UI-only: - models/ (7), state/ (GameState + 18 part files), methods/ (7), game_methods, 79 command files, enums, card_stack, stat_calculator, action_handler (index, 250-deep history, save-per-action, undo/redo), disk-based game_data, l10n, translation_service, service_locator - ValueNotifier/ChangeNotifier removed in favor of plain fields with a minimal GameState listener hook for the Phase 2 broadcast layer; shared_preferences replaced by the SaveStore abstraction (InMemory for tests, File-backed for bin/main.dart) - command registry: 82 entries mapping wire names to constructors with arg validation; live-object args (loot/ability cards, figure lists) travel as id/name/nr and resolve against live state, enums by name, injected singletons never serialize - line_builder ported to Phase 1 scope: stat_applier + minimal LineBuilder (isElement, tokens); widget rendering deferred to Phase 4 - ported test suite: 81 test files, 562 tests green (command tests 1:1 with the reference, resource tests, registry smoke tests) - new headless integration test drives a full round: scenario setup, characters + standee, secret-initiative gate, draw, every figure's turn (incl. undo/redo), next round, round 2, round 3 - PORTING.md: the conventions contract used for the port - bin/main.dart boots the engine (file save store, assets/data) before serving; pubspec gains built_collection, collection, get_it, intl - dart format drift on pre-existing net/test files from the current formatter (whitespace only) dart analyze warning-free; dart test 562/562. --- server/test/resource/action_handler_test.dart | 215 ++++++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 server/test/resource/action_handler_test.dart (limited to 'server/test/resource/action_handler_test.dart') diff --git a/server/test/resource/action_handler_test.dart b/server/test/resource/action_handler_test.dart new file mode 100644 index 0000000..3137454 --- /dev/null +++ b/server/test/resource/action_handler_test.dart @@ -0,0 +1,215 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt().clearList(); + }); + + group('ActionHandler', () { + group('getCurrent', () { + test('getCurrent returns the last executed command', () { + final gs = getIt(); + final cmd = SetLevelCommand(3, null); + gs.action(cmd); + expect(gs.getCurrent(), same(cmd)); + gs.undo(); + }); + }); + + group('redo', () { + test('redo restores state after undo', () { + final gs = getIt(); + // Two actions so gameSaveStates has enough entries for redo + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(5, null)); + expect(gs.level, 5); + gs.undo(); // back to level 2 + expect(gs.level, 2); + gs.redo(); // forward to level 5 + expect(gs.level, 5); + gs.undo(); + gs.undo(); + }); + + test('redo is a no-op when there is nothing to redo', () { + final gs = getIt(); + gs.action(SetLevelCommand(4, null)); + // No undo performed, so redo should not crash and not change state + final levelBefore = gs.level; + gs.redo(); + expect(gs.level, levelBefore); + gs.undo(); + }); + + test('redo increments commandIndex', () { + final gs = getIt(); + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(3, null)); + final indexAfterActions = gs.commandIndex; + gs.undo(); + expect(gs.commandIndex, indexAfterActions - 1); + gs.redo(); + expect(gs.commandIndex, indexAfterActions); + gs.undo(); + gs.undo(); + }); + }); + + group('redo list cleanup', () { + test('new action after undo clears the redo list', () { + final gs = getIt(); + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + //final indexBefore = gs.commandIndex; + gs.undo(); // undo SetLevel(4), now commandIndex = indexBefore - 1 + // Do a new action — should clear SetLevel(4) from the redo list + gs.action(SetLevelCommand(5, null)); + // commands length should equal commandIndex + 1 (no redo entries) + expect(gs.commands.length - 1, gs.commandIndex); + expect(gs.commandDescriptions.length - 1, gs.commandIndex); + // Undo back to baseline + gs.undo(); + gs.undo(); + }); + }); + + group('maxUndo eviction', () { + test('commands and gameSaveStates beyond maxUndo are nulled', () { + final gs = getIt(); + final maxUndo = gs.maxUndo; + final startIndex = gs.commandIndex; + + // Execute maxUndo + 1 commands to trigger eviction + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + // After maxUndo+1 actions, the oldest command entry should be nulled + expect(gs.commands[startIndex + 1], isNull); + // gameSaveStates at oldest entry should also be nulled + expect(gs.gameSaveStates[startIndex + 1], isNull); + + // Undo back to near the start (only valid undo states) + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + }); + }); + + group('getCurrent edge cases', () { + test( + 'getCurrent throws when there is no valid command at current index', + () { + final gs = getIt(); + // Reset so commandIndex is -1 (no commands executed yet). + gs.commandIndex = -1; + gs.resetCommandHistory(); + // getCurrent accesses _commands[commandIndex] — either a RangeError + // (negative index) or TypeError (null-check on a null entry). Either + // way it must throw an Error so callers know to guard the call site. + expect(() => gs.getCurrent(), throwsA(isA())); + }, + ); + }); + + group('redo after maxUndo eviction', () { + test('redo from the oldest valid position does not crash', () { + final gs = getIt(); + final maxUndo = gs.maxUndo; + + // Execute maxUndo + 1 commands so the oldest save state is evicted. + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + + // Undo all the way to the eviction boundary: + // only the last maxUndo states are guaranteed non-null. + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + // commandIndex is now at the boundary; gameSaveStates[commandIndex + 1] + // may be null (evicted). redo() must return early without crashing. + expect(() => gs.redo(), returnsNormally); + + // Restore state for other tests. + gs.undo(); + }); + }); + + group('add monster then undo', () { + test('undo after adding a monster removes it from the list', () { + final gs = getIt(); + gs.clearList(); + gs.action( + AddMonsterCommand('Zealot', 1, false, gameState: getIt()), + ); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isTrue); + gs.undo(); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isFalse); + }); + }); + + group('undo with commandIndex beyond gameSaveStates (Sentry regression)', () { + // Regression test for: + // ArgumentError: RangeError (length): Invalid value: Not in inclusive range 0..1079: 1080 + // ActionHandler.undo — crash when commandIndex >= gameSaveStates.length. + // + // Cause: in the server multiplayer path, Server.updateStateFromMessage sets + // commandIndex directly, then calls save(). After a + // resetState() (history cleared) a client that was ahead can send a message + // whose index ends up beyond the current gameSaveStates length after save(). + // A subsequent "undo" message from any client then crashes at + // _gameSaveStates[commandIndex] with no upper-bound guard. + test('does not crash when commandIndex >= gameSaveStates.length', () { + final gs = getIt(); + + // Build a small amount of history. + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + + // Advance commandIndex past the end of gameSaveStates, simulating the + // server receiving a state message whose index was not matched by a save(). + gs.commandIndex = gs.gameSaveStates.length; // one beyond valid range + + // A client sends "undo" — the server calls undoState() → undo(). + // This must not throw a RangeError. + expect(() => gs.undo(), returnsNormally); + + // Restore a clean state for subsequent tests. + gs.commandIndex = -1; + gs.resetCommandHistory(); + }); + }); + + group('redo after connection reset in server mode', () { + // Regression test for: ArgumentError: RangeError (length): Invalid value: + // Valid value range is empty: -1 in ActionHandler.redo when a stale client + // sends "redo" after the server resets its command history on reconnect. + test('does not crash when commandIndex is -1 after connection reset', () { + final gs = getIt(); + + // Build some history so gameSaveStates has an entry to retain. + gs.action(SetLevelCommand(3, null)); + + // Simulate the server-side connection-reset sequence: + // commandIndex → -1, command/description lists cleared, last save state kept. + gs.commandIndex = -1; + gs.resetCommandHistory(); + + // Stale client sends "redo" before it has re-synced with the server. + expect(() => gs.redo(), returnsNormally); + }); + }); + }); +} -- cgit v1.3.1