From b884441ba0d10bdd3559748507a0991888f66194 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 19 Nov 2026 08:53:51 +0100 Subject: Phase 6: settings, saves, localization parity (M6) --- server/test/net/multiplayer_test.dart | 9 +- server/test/net/settings_test.dart | 560 ++++++++++++++++++++++++++++++++ server/test/net/ws_test_helpers.dart | 13 +- server/test/resource/ui_utils_test.dart | 48 --- 4 files changed, 577 insertions(+), 53 deletions(-) create mode 100644 server/test/net/settings_test.dart delete mode 100644 server/test/resource/ui_utils_test.dart (limited to 'server/test') diff --git a/server/test/net/multiplayer_test.dart b/server/test/net/multiplayer_test.dart index e3bb225..b336501 100644 --- a/server/test/net/multiplayer_test.dart +++ b/server/test/net/multiplayer_test.dart @@ -376,13 +376,16 @@ void main() { reason: 'current', ); - // undo: the state rolls back (the index carries the undone action's - // index, exactly like the reference app's server-side send). + // undo: the state rolls back. The wire index is the post-decrement one + // (the reference reports the pre-decrement index — its clients keep + // local state; our stateless web clients take the index at face value, + // so it must equal the state position). The description is the undone + // action's, as in the reference. table.bob.send({'t': 'undo'}); for (final client in table.everyone) { final update = await client.nextOf('update'); state = stateOf(update); - expect(update['index'], indexAtTurnDone); + expect(update['index'], indexAtTurnDone - 1); expect( TestClient.characterIn(state, 'Banner Spear')?['turnState'], 1, diff --git a/server/test/net/settings_test.dart b/server/test/net/settings_test.dart new file mode 100644 index 0000000..677af11 --- /dev/null +++ b/server/test/net/settings_test.dart @@ -0,0 +1,560 @@ +/// Phase 6 / Milestone M6: the settings split and multi-save over the wire +/// (PLAN.md section 4): +/// +/// * the `welcome` carries the server-side settings + save names +/// * `setSetting` is validated, broadcast to every screen, and persisted +/// * spectators cannot change settings or manage saves (role gate) +/// * `noStandees` toggles through `TrackStandeesCommand` (undoable) +/// * the locale setting localizes subsequent command descriptions +/// * `historyLength` / `redoDescription` drive the client undo/redo UI +/// * save → load (an undoable action) → delete of game states +/// * save → load → delete of character saves +/// * settings + saves survive a server restart (file-backed store) +library; + +import 'dart:io'; + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/settings_store.dart'; +import 'package:x_haven_server/net/protocol.dart'; + +import 'ws_test_helpers.dart'; + +/// A table: one player (alice, owns 'Blinkblade') and one spectator (bob). +class Table { + late TestGameServer server; + late TestClient alice; + late TestClient bob; + late Map aliceWelcome; + + Future setup({SettingsStore? settingsStore}) async { + server = await TestGameServer.boot(settingsStore: settingsStore); + try { + alice = await TestClient.connect(server.wsUrl); + bob = await TestClient.connect(server.wsUrl); + alice.sendHello(); + bob.sendHello(); + aliceWelcome = await alice.nextOf('welcome'); + await bob.nextOf('welcome'); + + // Alice adds a character: the session that adds one owns it and + // becomes a player (bob stays a spectator). + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + for (final client in [alice, bob]) { + await client.nextOf('update'); + await client.nextOf('seats'); + } + return this; + } catch (_) { + await server.shutdown(); + rethrow; + } + } + + Future teardown() async { + await alice.close(); + await bob.close(); + await server.shutdown(); + } +} + +void main() { + group('settings over the wire', () { + test('welcome carries the settings payload with empty save lists', + () async { + final table = await Table().setup(); + try { + final settings = table.aliceWelcome['settings'] as Map; + expect(settings['locale'], 'en'); + expect(settings['style'], 2, reason: 'Style.original'); + expect(settings['saves'], isEmpty); + expect(settings['characterSaves'], isEmpty); + // Every server-side (game-relevant) field is present. + for (final field in [ + 'noInit', 'noStandees', 'randomStandees', 'expireConditions', + 'autoAddStandees', 'autoAddSpawns', 'hideLootDeck', + 'showBattleGoalReminder', 'showReminders', 'showAmdDeck', + 'fhHazTerrainCalcInOGGloom', + ]) { + expect(settings[field], isA(), reason: field); + } + } finally { + await table.teardown(); + } + }); + + test('setSetting is broadcast to every screen, persisted, and welcome-served', + () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('hideLootDeck', true)); + + final aliceGot = await table.alice.nextOf('settings'); + final bobGot = await table.bob.nextOf('settings'); + expect(aliceGot['settings']['hideLootDeck'], isTrue); + expect(bobGot['settings']['hideLootDeck'], isTrue); + expect(getIt().hideLootDeck, isTrue); + + // A reconnecting client sees it in the welcome too. + final carol = await TestClient.connect(table.server.wsUrl); + carol.sendHello(); + final welcome = await carol.nextOf('welcome'); + expect((welcome['settings'] as Map)['hideLootDeck'], isTrue); + await carol.close(); + } finally { + await table.teardown(); + } + }); + + test('spectators cannot change settings or manage saves', () async { + final table = await Table().setup(); + try { + table.bob.send(Protocol.setSettingMessage('noInit', false)); + final error = await table.bob.nextOf('error'); + expect(error['code'], Protocol.errForbidden); + expect(getIt().noInit, isTrue, reason: 'unchanged'); + + table.bob.send(Protocol.saveMessage('slot')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + + table.bob.send(Protocol.loadSaveMessage('slot')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + + table.bob.send(Protocol.saveCharacterMessage('slot', 'Blinkblade')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + } finally { + await table.teardown(); + } + }); + + test('invalid setting names and values are rejected', () async { + final table = await Table().setup(); + try { + // Unknown name → rejected (the switch has no matching case). + table.alice.send(Protocol.setSettingMessage('bogus', true)); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + + // Wrong value types → rejected. + table.alice.send(Protocol.setSettingMessage('style', 'notAnInt')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + table.alice.send(Protocol.setSettingMessage('locale', 'xx')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + table.alice.send(Protocol.setSettingMessage('noInit', 'yes')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + + // Missing name → bad request. + table.alice.send(Protocol.setSettingMessage('', true)); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errBadRequest, + ); + + // Nothing was applied. + final settings = getIt(); + expect(settings.style, Style.original); + expect(settings.locale, 'en'); + expect(settings.noInit, isTrue); + } finally { + await table.teardown(); + } + }); + + test('style and locale are settable', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('style', 1)); + final styleUpdate = await table.alice.nextOf('settings'); + expect((styleUpdate['settings'] as Map)['style'], 1); + expect(getIt().style, Style.gloomhaven); + + table.alice.send(Protocol.setSettingMessage('locale', 'de')); + await table.bob.nextOf('settings'); // drain bob's copy + final localeUpdate = await table.alice.nextOf('settings'); + expect((localeUpdate['settings'] as Map)['locale'], 'de'); + } finally { + await table.teardown(); + } + }); + + test('noStandees toggles through TrackStandeesCommand (undoable)', () async { + final table = await Table().setup(); + try { + // After addCharacter the index is 0; the toggle adds one action. + table.alice.send(Protocol.setSettingMessage('noStandees', true)); + + // The command runs first: an update broadcast … + final update = await table.alice.nextOf('update'); + expect(update['index'], 1); + expect(update['description'], "Don't track standees"); + // … then the settings broadcast. + final settings = await table.alice.nextOf('settings'); + expect((settings['settings'] as Map)['noStandees'], isTrue); + + // The underlying command is undoable: the wire index is the + // post-decrement one, the description the undone action's. (As in + // the reference app, the setting itself is app state, not part of + // the undoable game snapshot — it stays true after the undo.) + table.alice.send({'t': 'undo'}); + final undo = await table.alice.nextOf('update'); + expect(undo['index'], 0); + expect(undo['description'], "Don't track standees"); + expect(getIt().noStandees, isTrue, + reason: 'settings are not part of the undoable game state'); + } finally { + await table.teardown(); + } + }); + + test('the locale setting localizes command descriptions', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('locale', 'de')); + await table.alice.nextOf('settings'); + await table.bob.nextOf('settings'); + + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + final update = await table.alice.nextOf('update'); + expect( + update['description'], + 'Initiative von Blinkblade festlegen', + reason: 'the German command description', + ); + } finally { + await table.teardown(); + } + }); + }); + + group('history metadata (undo/redo UI)', () { + test('historyLength and redoDescription travel in welcome and updates', + () async { + final server = await TestGameServer.boot(); + try { + final client = await TestClient.connect(server.wsUrl); + client.sendHello(); + final welcome = await client.nextOf('welcome'); + + // Fresh game: baseline (index -1), no history yet. + expect(welcome['index'], -1); + expect(welcome['historyLength'], 0); + expect(welcome['description'], isNull); + expect(welcome['redoDescription'], isNull); + expect(welcome['undoDescription'], isNull); + + // Add a character (index 0). + client.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + final add = await client.nextOf('update'); + final addDescription = add['description'] as String; + expect(add['description'], 'Add Blinkblade'); + expect(add['historyLength'], 1); + expect(add['redoDescription'], isNull); + expect(add['undoDescription'], addDescription); + + // Set initiative (index 1). + client.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + final setInit = await client.nextOf('update'); + final setInitDescription = setInit['description'] as String; + expect(setInit['historyLength'], 2); + expect(setInit['redoDescription'], isNull); + expect(setInit['undoDescription'], setInitDescription); + + // Undo to index 0: the wire index is the post-decrement one, the + // description the undone action's; redo becomes available. + client.send({'t': 'undo'}); + final undo1 = await client.nextOf('update'); + expect(undo1['index'], 0); + expect(undo1['description'], setInitDescription); + expect(undo1['historyLength'], 2); + expect(undo1['redoDescription'], setInitDescription); + expect(undo1['undoDescription'], addDescription); + + // Undo to the baseline (index -1): the stateless clients still get + // the push (the reference skips it — its clients keep local state). + client.send({'t': 'undo'}); + final baseline = await client.nextOf('update'); + expect(baseline['index'], -1); + expect(baseline['description'], addDescription); + expect(baseline['historyLength'], 2); + expect(baseline['redoDescription'], addDescription); + expect(baseline['undoDescription'], isNull); + + // Redo forward: the redo label empties out again. + client.send({'t': 'redo'}); + final redo1 = await client.nextOf('update'); + expect(redo1['index'], 0); + expect(redo1['description'], addDescription); + expect(redo1['redoDescription'], setInitDescription); + client.send({'t': 'redo'}); + final redo2 = await client.nextOf('update'); + expect(redo2['index'], 1); + expect(redo2['redoDescription'], isNull); + expect(redo2['undoDescription'], setInitDescription); + + // A fresh welcome carries the same metadata. + client.sendHello(); + final resync = await client.nextOf('welcome'); + expect(resync['historyLength'], 2); + expect(resync['redoDescription'], isNull); + expect(resync['undoDescription'], setInitDescription); + await client.close(); + } finally { + await server.shutdown(); + } + }); + }); + + group('multi-save', () { + test('save -> load (undoable) -> delete', () async { + final table = await Table().setup(); + try { + // State A: Blinkblade with initiative 5 (index 1). + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send(Protocol.saveMessage('alpha')); + final saved = await table.alice.nextOf('settings'); + expect(saved['settings']['saves'], ['alpha']); + expect(getIt().saves.keys, contains('alpha')); + + // Change the state: add a monster (index 2). + table.alice.sendCmd( + 'addMonster', + {'name': 'Test Boss (FH)', 'isAlly': false}, + ); + final added = await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + expect(added['index'], 2); + + // Load 'alpha': an undoable action — the index advances and the + // monster is gone again. + table.alice.send(Protocol.loadSaveMessage('alpha')); + final loaded = await table.alice.nextOf('update'); + expect(loaded['index'], 3); + expect(loaded['description'], 'Load saved game: alpha'); + final state = loaded['state'] as Map; + expect( + TestClient.characterIn(state, 'Test Boss (FH)'), + isNull, + reason: 'the loaded state has no monster', + ); + expect(TestClient.characterIn(state, 'Blinkblade'), isNotNull); + + // Every screen received the load. + final bobLoad = await table.bob.nextOf('update'); + expect(bobLoad['index'], 3); + + // Undo: back to the state with the monster (index 2). + table.alice.send({'t': 'undo'}); + final undone = await table.alice.nextOf('update'); + expect(undone['index'], 2); + expect( + TestClient.characterIn(undone['state'] as Map, 'Test Boss (FH)'), + isNotNull, + ); + + // Delete the save; loading it after is rejected. + table.alice.send(Protocol.deleteSaveMessage('alpha')); + final deleted = await table.alice.nextOf('settings'); + expect(deleted['settings']['saves'], isEmpty); + expect(getIt().saves.keys, isEmpty); + + table.alice.send(Protocol.loadSaveMessage('alpha')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + } finally { + await table.teardown(); + } + }); + + test('save names with missing fields get a clear error', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.saveMessage('')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errBadRequest, + ); + table.alice.send(Protocol.deleteSaveMessage('missing')); + // No error: deleting an unknown save is a silent no-op (the + // reference's deleteSave just removes from the map). + final settings = await table.alice.nextOf('settings'); + expect(settings['settings']['saves'], isEmpty); + } finally { + await table.teardown(); + } + }); + + test('character saves: save -> load (undoable) -> delete', () async { + final table = await Table().setup(); + try { + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 7}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send( + Protocol.saveCharacterMessage('Blinky backup', 'Blinkblade'), + ); + final saved = await table.alice.nextOf('settings'); + final characterSaves = saved['settings']['characterSaves'] as List; + expect( + characterSaves, + [{ + 'name': 'Blinky backup', + 'characterId': 'Blinkblade', + }], + ); + + // Change the character, then load the save back (an undoable + // action — the index advances). As in the reference app, a + // character save restores the identity (level/display/perks) and + // re-adds the character with a fresh battle state. + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 9}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send( + Protocol.loadCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + final loaded = await table.alice.nextOf('update'); + expect(loaded['description'], 'Load saved character: Blinky backup'); + final state = loaded['state'] as Map; + final character = TestClient.characterIn(state, 'Blinkblade')!; + final characterState = character['characterState'] as Map; + expect(characterState['display'], 'Blinky'); + expect(characterState['initiative'], 0, reason: 'fresh battle state'); + + // Delete; loading again is rejected. + table.alice.send( + Protocol.deleteCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + final deleted = await table.alice.nextOf('settings'); + expect(deleted['settings']['characterSaves'], isEmpty); + + table.alice.send( + Protocol.loadCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + } finally { + await table.teardown(); + } + }); + + test('saving a character not in the list is rejected', () async { + final table = await Table().setup(); + try { + table.alice.send( + Protocol.saveCharacterMessage('ghost', 'No Such Character'), + ); + final error = await table.alice.nextOf('error'); + expect(error['code'], Protocol.errRejected); + expect( + (error['message'] as String).contains('No Such Character'), + isTrue, + ); + } finally { + await table.teardown(); + } + }); + }); + + group('persistence across a restart', () { + late Directory dir; + + setUp(() { + dir = Directory.systemTemp.createTempSync('x-haven-settings-'); + }); + + tearDown(() { + if (dir.existsSync()) dir.deleteSync(recursive: true); + }); + + test('settings and save names survive a server restart', () async { + // First boot: change a setting, make a state save and a character + // save — all persisted into dir/saves/settings.json. + final first = await TestGameServer.boot( + settingsStore: FileSettingsStore(dir.path), + ); + final alice = await TestClient.connect(first.wsUrl); + alice.sendHello(); + await alice.nextOf('welcome'); + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + await alice.nextOf('update'); + await alice.nextOf('seats'); + + alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + await alice.nextOf('update'); + + alice.send(Protocol.setSettingMessage('hideLootDeck', true)); + await alice.nextOf('settings'); + alice.send(Protocol.setSettingMessage('locale', 'de')); + await alice.nextOf('settings'); + alice.send(Protocol.saveMessage('restart')); + await alice.nextOf('settings'); + alice.send(Protocol.saveCharacterMessage('backup', 'Blinkblade')); + await alice.nextOf('settings'); + + await alice.close(); + await first.shutdown(); + + // Second boot from the same directory: the settings are restored, + // and a fresh welcome serves them. + final second = await TestGameServer.boot( + settingsStore: FileSettingsStore(dir.path), + ); + try { + final settings = getIt(); + expect(settings.hideLootDeck, isTrue); + expect(settings.locale, 'de'); + expect(settings.saves.keys, contains('restart')); + expect( + settings.characterSaves.keys, + contains('backup\nBlinkblade'), + ); + + final client = await TestClient.connect(second.wsUrl); + client.sendHello(); + final welcome = await client.nextOf('welcome'); + final payload = welcome['settings'] as Map; + expect(payload['hideLootDeck'], isTrue); + expect(payload['locale'], 'de'); + expect(payload['saves'], ['restart']); + expect(payload['characterSaves'], [ + {'name': 'backup', 'characterId': 'Blinkblade'}, + ]); + await client.close(); + } finally { + await second.shutdown(); + } + }); + }); +} diff --git a/server/test/net/ws_test_helpers.dart b/server/test/net/ws_test_helpers.dart index 1903567..36d87c8 100644 --- a/server/test/net/ws_test_helpers.dart +++ b/server/test/net/ws_test_helpers.dart @@ -16,6 +16,8 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:x_haven_server/core/game_data.dart'; import 'package:x_haven_server/core/save_store.dart'; import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/settings_store.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'package:x_haven_server/net/app.dart'; import 'package:x_haven_server/net/game_server.dart'; @@ -37,15 +39,22 @@ class TestGameServer { static Future boot({ SaveStore? saveStore, SeatStore? seatStore, + SettingsStore? settingsStore, Duration heartbeatInterval = const Duration(seconds: 20), Duration deadTimeout = const Duration(seconds: 90), String dataDir = 'assets/testData/', }) async { // Same bootstrap as test/command/test_helpers.dart's setUpGame(), but - // with the caller's [saveStore] (persistence tests pass a FileSaveStore). - setupCore(saveStore: saveStore ?? InMemorySaveStore()); + // with the caller's stores (persistence tests pass the File* variants). + setupCore( + saveStore: saveStore ?? InMemorySaveStore(), + settingsStore: settingsStore ?? InMemorySettingsStore(), + ); final gs = getIt(); gs.init(); + // Same as bin/main.dart: restore the persisted settings (no-op when the + // store is empty, i.e. first run). + getIt().loadFromDisk(); await getIt().loadData(dataDir); gs.load(); final instance = TestGameServer._(); diff --git a/server/test/resource/ui_utils_test.dart b/server/test/resource/ui_utils_test.dart deleted file mode 100644 index fc44c02..0000000 --- a/server/test/resource/ui_utils_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// ignore_for_file: no-magic-number - -import 'package:test/test.dart'; -import 'package:x_haven_server/core/enums.dart'; -import 'package:x_haven_server/core/settings.dart'; -import 'package:x_haven_server/core/service_locator.dart'; -import 'package:x_haven_server/core/ui_utils.dart'; - -import '../command/test_helpers.dart'; - -/// The reference `ui_utils_test.dart` has no `reducePowerEnabled` group — -/// its groups (`hasGHVersion`, text-style helpers, dialog/toast widget -/// functions) all exercise unported widget code. This file instead covers -/// the single ported `ui_utils` function, `reducePowerEnabled`, mirroring -/// the reference implementation's documented semantics. -void main() { - setUpAll(() async { - await setUpGame(); - }); - - // ── reducePowerEnabled ──────────────────────────────────────────────────── - - group('reducePowerEnabled', () { - test('returns false by default (PowerMode.normal)', () { - expect(reducePowerEnabled(), isFalse); - }); - - test('returns true when powerMode is reducePower', () { - getIt().powerMode = PowerMode.reducePower; - expect(reducePowerEnabled(), isTrue); - getIt().powerMode = PowerMode.normal; - }); - - test('returns false for dimWhenIdle (top tier only)', () { - getIt().powerMode = PowerMode.dimWhenIdle; - expect(reducePowerEnabled(), isFalse); - getIt().powerMode = PowerMode.normal; - }); - - test('honors an explicitly passed Settings instance', () { - final settings = Settings(); - settings.powerMode = PowerMode.reducePower; - expect(reducePowerEnabled(settings: settings), isTrue); - settings.powerMode = PowerMode.normal; - expect(reducePowerEnabled(settings: settings), isFalse); - }); - }); -} -- cgit v1.3.1