/// Phase 2 / Milestone M2: the full multiplayer + secrets scenario over a /// real WebSocket — two players (alice, bob) and one spectator (carol): /// /// * secret initiative never reaches non-owners; reveal on draw /// * rejected duplicate draw (error to the sender only) /// * draw blocked until all initiative values are entered /// * spectator role gating (commands forbidden, claim allowed) /// * claim / release / re-claim of seats /// * reconnect resync with per-connection masking /// * undo/redo requested by players, broadcast to everyone /// * dead-connection cleanup with seat release library; import 'package:test/test.dart'; import 'package:x_haven_server/core/service_locator.dart'; import 'package:x_haven_server/core/settings.dart'; import 'package:x_haven_server/net/protocol.dart'; import 'ws_test_helpers.dart'; /// A table with two players and one spectator, mid-setup. class Table { late TestGameServer server; late TestClient alice; // will own 'Blinkblade' late TestClient bob; // will own 'Banner Spear' late TestClient carol; // spectator String aliceId = ''; String bobId = ''; String carolId = ''; List get everyone => [alice, bob, carol]; Future setup() async { server = await TestGameServer.boot(); try { getIt().noInit = false; // exercise the initiative gate alice = await TestClient.connect(server.wsUrl); bob = await TestClient.connect(server.wsUrl); carol = await TestClient.connect(server.wsUrl); alice.sendHello(); bob.sendHello(); carol.sendHello(); aliceId = (await alice.nextOf('welcome'))['session'] as String; bobId = (await bob.nextOf('welcome'))['session'] as String; carolId = (await carol.nextOf('welcome'))['session'] as String; // Each player adds their own character: the session that adds a // character owns it and becomes a player. alice.sendCmd( 'addCharacter', {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, ); bob.sendCmd( 'addCharacter', {'id': 'Banner Spear', 'edition': 'Frosthaven', 'display': 'Spear', 'level': 1}, ); for (final client in everyone) { await client.nextOf('update'); await client.nextOf('seats'); await client.nextOf('update'); await client.nextOf('seats'); } return this; } catch (_) { await server.shutdown(); rethrow; } } Future teardown() async { for (final client in everyone) { await client.close(); } await server.shutdown(); } /// Both players enter initiative: alice 5, bob 3. Consumes the updates. Future enterInitiative() async { alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); for (final client in everyone) { await client.nextOf('update'); await client.nextOf('update'); } } /// alice taps the draw button; consumes the updates on all three screens. Future draw() async { alice.sendCmd('draw'); for (final client in everyone) { await client.nextOf('update'); } } } void main() { late Table table; var tableBuilt = false; setUp(() async { table = await Table().setup(); tableBuilt = true; }); tearDown(() async { // When setUp failed before the table was built, setup() has already // shut the server down — nothing to tear down. if (tableBuilt) { await table.teardown(); } }); Map stateOf(Map message) => Map.from(message['state'] as Map); test('secret initiative never reaches non-owners; reveal on draw', () async { // --- bob enters 3 ------------------------------------------------------ table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); // The owner sees their own value; the other player's value is masked. expect( TestClient.initiativeIn(stateOf(await table.bob.nextOf('update')), 'Banner Spear'), 3, reason: 'bob sees his own initiative', ); expect( TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Banner Spear'), null, reason: 'bob\'s value is masked for alice', ); expect( TestClient.initiativeIn( stateOf(await table.carol.nextOf('update')), 'Banner Spear', ), null, reason: 'the spectator sees no initiative at all', ); // --- alice enters 5 ---------------------------------------------------- table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); expect( TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Blinkblade'), 5, ); expect( TestClient.initiativeIn( stateOf(await table.bob.nextOf('update')), 'Blinkblade', ), null, ); expect( TestClient.initiativeIn( stateOf(await table.carol.nextOf('update')), 'Blinkblade', ), null, ); // --- draw: initiative becomes public to everyone ----------------------- await table.draw(); for (final client in table.everyone) { // The draw update was consumed; resync via a fresh welcome to assert // the revealed state on every screen. client.sendHello(); final state = stateOf(await client.nextOf('welcome')); expect( state['roundState'], 1, reason: 'playTurns on every screen', ); expect( TestClient.initiativeIn(state, 'Blinkblade'), 5, reason: '${client == table.alice ? 'alice' : client == table.bob ? 'bob' : 'carol'} sees the public value', ); expect(TestClient.initiativeIn(state, 'Banner Spear'), 3); } // Lower initiative acts first. table.alice.sendHello(); final state = stateOf(await table.alice.nextOf('welcome')); expect( TestClient.characterIn(state, 'Banner Spear'), isNotNull, ); final list = state['currentList'] as List; final spearIndex = list.indexWhere((item) => item is Map && item['id'] == 'Banner Spear'); final blinkIndex = list.indexWhere((item) => item is Map && item['id'] == 'Blinkblade'); expect(spearIndex, lessThan(blinkIndex), reason: '3 < 5'); }); test('duplicate draw is rejected; the error goes to the sender only', () async { await table.enterInitiative(); await table.draw(); table.alice.sendCmd('draw'); final error = await table.alice.nextOf('error'); expect(error['code'], Protocol.errRejected); expect(error['message'], 'the round has already been drawn'); // No update, no seats: the other screens never heard about the // rejected command. await Future.delayed(const Duration(milliseconds: 200)); expect(table.bob.flush(), isEmpty); expect(table.carol.flush(), isEmpty); }); test('draw is blocked until every player has entered initiative', () async { table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); for (final client in table.everyone) { await client.nextOf('update'); } table.alice.sendCmd('draw'); final error = await table.alice.nextOf('error'); expect(error['code'], Protocol.errRejected); expect(error['message'], contains('initiative')); await Future.delayed(const Duration(milliseconds: 200)); expect(table.bob.flush(), isEmpty); table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); for (final client in table.everyone) { await client.nextOf('update'); } table.alice.sendCmd('draw'); final update = await table.alice.nextOf('update'); expect(stateOf(update)['roundState'], 1); }); test('spectator commands are forbidden; claiming is how they join', () async { // A gated command as a spectator: rejected with a role error. table.carol.sendCmd( 'changeHealth', {'change': -1, 'figureId': 'Blinkblade'}, ); final error = await table.carol.nextOf('error'); expect(error['code'], Protocol.errForbidden); expect(error['message'], contains('claim a character')); // Undo/redo are player-only too. table.carol.send({'t': 'undo'}); expect((await table.carol.nextOf('error'))['code'], Protocol.errForbidden); // Claiming a character is allowed for spectators — but only if it is // unclaimed. table.carol.sendClaim('Blinkblade'); final rejected = await table.carol.nextOf('error'); expect(rejected['code'], Protocol.errRejected); expect(rejected['message'], contains('already claimed')); // Unknown character. table.carol.sendClaim('Nyx'); final noSuch = await table.carol.nextOf('error'); expect(noSuch['code'], Protocol.errRejected); expect(noSuch['message'], contains('Nyx')); }); test('nextRound is rejected before the round has started', () async { table.alice.sendCmd('nextRound'); final error = await table.alice.nextOf('error'); expect(error['code'], Protocol.errRejected); expect(error['message'], 'the round has not started yet'); }); test('claim flow: disconnect releases the seat; re-claim works', () async { // carol cannot claim a character bob owns. table.carol.sendClaim('Banner Spear'); expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected); // bob leaves: his character becomes unclaimed. await table.bob.close(); final seatsForAlice = await table.alice.nextOf('seats'); expect(TestClient.seatsOf(seatsForAlice)['Banner Spear'], null); expect(TestClient.seatsOf(seatsForAlice)['Blinkblade'], table.aliceId); final seatsForCarol = await table.carol.nextOf('seats'); expect(TestClient.seatsOf(seatsForCarol)['Banner Spear'], null); // carol claims the freed character and becomes its owner. table.carol.sendClaim('Banner Spear'); final seats2 = await table.carol.nextOf('seats'); expect(TestClient.seatsOf(seats2)['Banner Spear'], table.carolId); final seats2ForAlice = await table.alice.nextOf('seats'); expect(TestClient.seatsOf(seats2ForAlice)['Banner Spear'], table.carolId); // Re-asserting an existing ownership is a no-op (no error, same table). table.carol.sendClaim('Banner Spear'); final seats3 = await table.carol.nextOf('seats'); expect(TestClient.seatsOf(seats3)['Banner Spear'], table.carolId); expect(TestClient.seatsOf(seats3)['Blinkblade'], table.aliceId); // carol still cannot claim alice's character. table.carol.sendClaim('Blinkblade'); expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected); }); test('reconnect resync: full welcome, released seat, re-claim', () async { table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); // The last update on every screen carries the index to expect in a // fresh welcome. var lastUpdateIndex = -1; for (final client in table.everyone) { await client.nextOf('update'); final second = await client.nextOf('update'); lastUpdateIndex = second['index'] as int; } // alice leaves; her seat is released. await table.alice.close(); final seats = await table.bob.nextOf('seats'); expect(TestClient.seatsOf(seats)['Blinkblade'], null); // Reconnect with the same session id (the cookie's job). final alice2 = await TestClient.connect( table.server.wsUrl, session: table.aliceId, ); alice2.sendHello(); final welcome = await alice2.nextOf('welcome'); expect(welcome['session'], table.aliceId); expect(welcome['role'], Protocol.roleSpectator, reason: 'seat was released'); expect(welcome['index'], lastUpdateIndex, reason: 'full resync, same index'); // While the seat is free, even her own old value is masked for her. final welcomeState = stateOf(welcome); expect(welcomeState['roundState'], 0, reason: 'still choosing initiative'); expect(TestClient.initiativeIn(welcomeState, 'Blinkblade'), null); expect(TestClient.initiativeIn(welcomeState, 'Banner Spear'), null); // Re-claim her character, then resync: the value is hers to see again. alice2.sendClaim('Blinkblade'); await alice2.nextOf('seats'); await table.bob.nextOf('seats'); alice2.sendHello(); final welcome2 = await alice2.nextOf('welcome'); expect(welcome2['role'], Protocol.rolePlayer); expect( TestClient.initiativeIn(stateOf(welcome2), 'Blinkblade'), 5, reason: 'the owner sees their own secret again', ); expect(TestClient.initiativeIn(stateOf(welcome2), 'Banner Spear'), null); await alice2.close(); }); test('undo/redo: player requests, every screen resyncs', () async { await table.enterInitiative(); await table.draw(); // Initiative order: 'Banner Spear' (3) first, then 'Blinkblade' (5). table.bob.sendCmd('turnDone', {'id': 'Banner Spear'}); final turnDone = await table.bob.nextOf('update'); // The other screens carry the same update too — drain them so the // undo/redo updates below are the only ones queued. await table.alice.nextOf('update'); await table.carol.nextOf('update'); final indexAtTurnDone = turnDone['index'] as int; var state = stateOf(turnDone); expect( TestClient.characterIn(state, 'Banner Spear')?['turnState'], 2, reason: 'done', ); expect( TestClient.characterIn(state, 'Blinkblade')?['turnState'], 1, reason: 'current', ); // undo: the state rolls back (the index carries the undone action's // index, exactly like the reference app's server-side send). 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( TestClient.characterIn(state, 'Banner Spear')?['turnState'], 1, reason: 'current again', ); expect( TestClient.characterIn(state, 'Blinkblade')?['turnState'], 0, reason: 'waiting again', ); expect(update['event'], {'type': 'none'}); } // redo: forward again. table.bob.send({'t': 'redo'}); for (final client in table.everyone) { final update = await client.nextOf('update'); state = stateOf(update); expect(update['index'], indexAtTurnDone); expect( TestClient.characterIn(state, 'Banner Spear')?['turnState'], 2, ); expect(TestClient.characterIn(state, 'Blinkblade')?['turnState'], 1); } }); test('dead connection cleanup: a quiet socket is closed, the seat released', () async { // Short timeouts: the sweep runs every 100 ms, dead after 400 ms quiet. await table.teardown(); table.server = await TestGameServer.boot( heartbeatInterval: const Duration(milliseconds: 100), deadTimeout: const Duration(milliseconds: 400), ); getIt().noInit = false; table.alice = await TestClient.connect(table.server.wsUrl); table.bob = await TestClient.connect(table.server.wsUrl); table.carol = await TestClient.connect(table.server.wsUrl); table.alice.sendHello(); table.bob.sendHello(); table.carol.sendHello(); table.aliceId = (await table.alice.nextOf('welcome'))['session'] as String; table.bobId = (await table.bob.nextOf('welcome'))['session'] as String; table.carolId = (await table.carol.nextOf('welcome'))['session'] as String; table.alice.sendCmd( 'addCharacter', {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, ); for (final client in [table.alice, table.bob, table.carol]) { await client.nextOf('update'); await client.nextOf('seats'); } // Keep bob and carol alive so only alice is swept. table.bob.send({'t': 'ping'}); table.carol.send({'t': 'ping'}); await table.bob.nextOf('pong'); await table.carol.nextOf('pong'); // alice goes quiet (no pings) — the sweep must close her and release // the seat so the others can re-claim. await table.alice.closedFuture.timeout( const Duration(seconds: 5), ); final seats = await table.bob.nextOf('seats'); expect(TestClient.seatsOf(seats)['Blinkblade'], null); final seatsForCarol = await table.carol.nextOf('seats'); expect(TestClient.seatsOf(seatsForCarol)['Blinkblade'], null); await table.bob.close(); await table.carol.close(); await table.server.shutdown(); }); }