1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
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<String, dynamic> aliceWelcome;
Future<Table> 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<void> 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<bool>(), 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'] as Map)['hideLootDeck'], isTrue);
expect((bobGot['settings'] as Map)['hideLootDeck'], isTrue);
expect(getIt<Settings>().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<Settings>().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<Settings>();
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<Settings>().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<Settings>().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'] as Map)['saves'], ['alpha']);
expect(getIt<Settings>().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<String, dynamic>;
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<String, dynamic>, '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'] as Map)['saves'], isEmpty);
expect(getIt<Settings>().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'] as Map)['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'] as Map)['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<String, dynamic>;
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'] as Map)['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<Settings>();
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();
}
});
});
}
|