ghast-client 0.5.3

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! The HUD (`Interests::HUD`) and tab completion on every version, from real packet bodies:
//! each packet is encoded with the version's generated codec, decoded by the version's wire
//! layer and applied by the engine; the countdown runs through engine ticks. The expected
//! values are the vanilla clients' rules, read in each version's client jar (see
//! `crate::hud`).

use super::tests::{Script, engine, join, names};
use super::*;
use crate::hud::{BossBarColor, BossBarStyle, HudEvent, Text, TitlePhase, TitleTimes};
use crate::version::ClientVersion;
use ghast_protocol::RawPacket;
use ghast_protocol::nbt::{AnonNbt, Tag};
use ghast_protocol::types::ByteString;

/// Every version the client engine runs.
#[cfg(not(feature = "v26_3"))]
const VERSIONS: [GameVersion; 5] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
];
/// With 26.3.
#[cfg(feature = "v26_3")]
const VERSIONS: [GameVersion; 6] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
    GameVersion::V26_3,
];

fn modern(v: GameVersion) -> bool {
    v.caps().configuration_state
}

/// A HUD packet to build.
#[derive(Debug, Clone)]
enum W {
    Title(&'static str),
    Subtitle(&'static str),
    Times(i32, i32, i32),
    /// 1.8 – 1.16.5 `clear` / 26.x `clear_titles` without reset.
    Clear,
    /// 1.8 – 1.16.5 `reset` / 26.x `clear_titles` with reset.
    Reset,
    /// 1.12 / 1.16.5 `title` action bar, 26.x `set_action_bar_text`.
    ActionBar(&'static str),
    /// Chat position 2 (1.8 – 1.16.5), an overlay system message (26.x).
    ChatOverlay(&'static str),
    /// A plain system chat message.
    ChatSystem(&'static str),
    Header(&'static str, &'static str),
    BossAdd(u128, &'static str, f32, i32, i32, u8),
    BossRemove(u128),
    BossProgress(u128, f32),
    BossTitle(u128, &'static str),
    BossStyle(u128, i32, i32),
    BossFlags(u128, u8),
    /// A tab-completion answer: transaction id (1.13+), start, length, matches.
    TabReply(i32, i32, i32, &'static [&'static str]),
}

fn json(s: &str) -> ByteString {
    ByteString::from(format!("{{\"text\":\"{s}\"}}"))
}

fn nbt(s: &str) -> AnonNbt {
    AnonNbt::from_tag(&Tag::String(s.into())).unwrap()
}

fn raw<P: ghast_protocol::Packet>(p: &P) -> Option<RawPacket> {
    Some(RawPacket::from_packet(p).unwrap())
}

/// 1.8 `title` body.
fn packet_1_8(w: &W) -> Option<RawPacket> {
    use ghast_protocol::v1_8::play::clientbound as cb;
    let title = |action, text: Option<&str>, t: Option<(i32, i32, i32)>| {
        raw(&cb::Title {
            action,
            text: text.map(json),
            fade_in: t.map(|t| t.0),
            stay: t.map(|t| t.1),
            fade_out: t.map(|t| t.2),
        })
    };
    match w {
        W::Title(s) => title(0, Some(s), None),
        W::Subtitle(s) => title(1, Some(s), None),
        W::Times(a, b, c) => title(2, None, Some((*a, *b, *c))),
        W::Clear => title(3, None, None),
        W::Reset => title(4, None, None),
        W::ChatOverlay(s) => raw(&cb::Chat {
            message: json(s),
            position: 2,
        }),
        W::ChatSystem(s) => raw(&cb::Chat {
            message: json(s),
            position: 1,
        }),
        W::Header(h, f) => raw(&cb::PlayerlistHeader {
            header: json(h),
            footer: json(f),
        }),
        W::TabReply(_, _, _, m) => raw(&cb::TabComplete {
            matches: m.iter().map(|s| ByteString::from(*s)).collect(),
        }),
        _ => None,
    }
}

/// 1.12.2 and 1.16.5: the same `title` and `boss_bar` layouts.
macro_rules! legacy_9 {
    ($m:ident, $w:expr, $chat:expr, $tab:expr) => {{
        use ghast_protocol::$m::play::clientbound as cb;
        let title = |action, text: Option<&str>, t: Option<(i32, i32, i32)>| {
            raw(&cb::Title {
                action,
                text: text.map(json),
                fade_in: t.map(|t| t.0),
                stay: t.map(|t| t.1),
                fade_out: t.map(|t| t.2),
            })
        };
        let boss = |id: u128, action, title: Option<&str>, health, color, div, flags| {
            raw(&cb::BossBar {
                entity_uuid: uuid::Uuid::from_u128(id),
                action,
                title: title.map(json),
                health,
                color,
                dividers: div,
                flags,
            })
        };
        match $w {
            W::Title(s) => title(0, Some(s), None),
            W::Subtitle(s) => title(1, Some(s), None),
            W::ActionBar(s) => title(2, Some(s), None),
            W::Times(a, b, c) => title(3, None, Some((*a, *b, *c))),
            W::Clear => title(4, None, None),
            W::Reset => title(5, None, None),
            W::ChatOverlay(s) => $chat(json(s), 2),
            W::ChatSystem(s) => $chat(json(s), 1),
            W::Header(h, f) => raw(&cb::PlayerlistHeader {
                header: json(h),
                footer: json(f),
            }),
            W::BossAdd(id, t, p, c, d, f) => {
                boss(*id, 0, Some(*t), Some(*p), Some(*c), Some(*d), Some(*f))
            }
            W::BossRemove(id) => boss(*id, 1, None, None, None, None, None),
            W::BossProgress(id, p) => boss(*id, 2, None, Some(*p), None, None, None),
            W::BossTitle(id, t) => boss(*id, 3, Some(*t), None, None, None, None),
            W::BossStyle(id, c, d) => boss(*id, 4, None, None, Some(*c), Some(*d), None),
            W::BossFlags(id, f) => boss(*id, 5, None, None, None, None, Some(*f)),
            W::TabReply(t, s, l, m) => $tab(*t, *s, *l, m),
        }
    }};
}

fn packet_1_12(w: &W) -> Option<RawPacket> {
    legacy_9!(
        v1_12_2,
        w,
        |message, position| raw(&cb::Chat { message, position }),
        |_, _, _, m: &&[&str]| raw(&cb::TabComplete {
            matches: m.iter().map(|s| ByteString::from(*s)).collect(),
        })
    )
}

fn packet_1_16(w: &W) -> Option<RawPacket> {
    legacy_9!(
        v1_16_5,
        w,
        |message, position| raw(&cb::Chat {
            message,
            position,
            sender: uuid::Uuid::nil(),
        }),
        |transaction_id, start, length, m: &&[&str]| raw(&cb::TabComplete {
            transaction_id,
            start,
            length,
            matches: m
                .iter()
                .map(
                    |s| ghast_protocol::defs::p754::play::clientbound::TabCompleteMatches {
                        r#match: ByteString::from(*s),
                        tooltip: Some(json("tip")),
                    }
                )
                .collect(),
        })
    )
}

macro_rules! modern_packet {
    ($m:ident, $w:expr) => {{
        use ghast_protocol::$m::play::clientbound as cb;
        let boss = |id: u128, action, title: Option<&str>, health, color, div, flags| {
            raw(&cb::BossBar {
                entity_uuid: uuid::Uuid::from_u128(id),
                action,
                title: title.map(nbt),
                health,
                color,
                dividers: div,
                flags,
            })
        };
        match $w {
            W::Title(s) => raw(&cb::SetTitleText { text: nbt(s) }),
            W::Subtitle(s) => raw(&cb::SetTitleSubtitle { text: nbt(s) }),
            W::Times(a, b, c) => raw(&cb::SetTitleTime {
                fade_in: *a,
                stay: *b,
                fade_out: *c,
            }),
            W::Clear => raw(&cb::ClearTitles { reset: false }),
            W::Reset => raw(&cb::ClearTitles { reset: true }),
            W::ActionBar(s) => raw(&cb::ActionBar { text: nbt(s) }),
            W::ChatOverlay(s) => raw(&cb::SystemChat {
                content: nbt(s),
                is_action_bar: true,
            }),
            W::ChatSystem(s) => raw(&cb::SystemChat {
                content: nbt(s),
                is_action_bar: false,
            }),
            W::Header(h, f) => raw(&cb::PlayerlistHeader {
                header: nbt(h),
                footer: nbt(f),
            }),
            W::BossAdd(id, t, p, c, d, f) => {
                boss(*id, 0, Some(*t), Some(*p), Some(*c), Some(*d), Some(*f))
            }
            W::BossRemove(id) => boss(*id, 1, None, None, None, None, None),
            W::BossProgress(id, p) => boss(*id, 2, None, Some(*p), None, None, None),
            W::BossTitle(id, t) => boss(*id, 3, Some(*t), None, None, None, None),
            W::BossStyle(id, c, d) => boss(*id, 4, None, None, Some(*c), Some(*d), None),
            W::BossFlags(id, f) => boss(*id, 5, None, None, None, None, Some(*f)),
            W::TabReply(t, s, l, m) => raw(&cb::TabComplete {
                transaction_id: *t,
                start: *s,
                length: *l,
                matches: m
                    .iter()
                    .map(
                        |s| ghast_protocol::defs::p775::play::clientbound::TabCompleteMatches {
                            r#match: ByteString::from(*s),
                            tooltip: Some(nbt("tip")),
                        },
                    )
                    .collect(),
            }),
        }
    }};
}

/// The packet for `w` on version `v` (`None` where the version has none).
fn packet(v: GameVersion, w: &W) -> Option<RawPacket> {
    match v {
        GameVersion::V1_8_9 => packet_1_8(w),
        GameVersion::V1_12_2 => packet_1_12(w),
        GameVersion::V1_16_5 => packet_1_16(w),
        GameVersion::V26_1 => modern_packet!(v26_1, w),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => modern_packet!(v26_3, w),
        _ => modern_packet!(v26_2, w),
    }
}

/// Whether the version's HUD filter lets `raw` through (with `interests`).
fn passes(v: GameVersion, raw: &RawPacket, interests: Interests) -> bool {
    let f = match v {
        GameVersion::V1_8_9 => crate::version::V1_8::play_filter(interests),
        GameVersion::V1_12_2 => crate::version::V1_12_2::play_filter(interests),
        GameVersion::V1_16_5 => crate::version::V1_16_5::play_filter(interests),
        GameVersion::V26_1 => crate::version::V26_1::play_filter(interests),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => crate::version::V26_3::play_filter(interests),
        _ => crate::version::V26_2::play_filter(interests),
    };
    f.contains(raw.id)
}

/// Decodes `raw` with the version's wire layer and hands it to the engine.
fn feed_raw(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
    let v = e.core.opts.caps.version;
    let p = match v {
        GameVersion::V1_8_9 => crate::version::V1_8::decode_play(raw, &mut ()),
        GameVersion::V1_12_2 => {
            crate::version::V1_12_2::decode_play(raw, &mut crate::version::Wire1_12::default())
        }
        GameVersion::V1_16_5 => crate::version::V1_16_5::decode_play(raw, &mut ()),
        GameVersion::V26_1 => {
            crate::version::V26_1::decode_play(raw, &mut crate::version::Wire26_1::default())
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            crate::version::V26_3::decode_play(raw, &mut crate::version::Wire26_3::default())
        }
        _ => crate::version::V26_2::decode_play(raw, &mut crate::version::Wire26_2::default()),
    }
    .unwrap();
    if let Some(p) = p {
        e.handle(p);
    }
}

/// Feeds `w` (it must exist on `v` and pass the HUD filter).
fn feed(e: &mut Engine<Box<dyn Sim>>, w: W) {
    let v = e.core.opts.caps.version;
    let raw = packet(v, &w).unwrap_or_else(|| panic!("{v:?}: no packet for {w:?}"));
    assert!(passes(v, &raw, Interests::HUD), "{v:?}: {w:?} filtered");
    feed_raw(e, &raw);
}

/// One behaviour tick; returns its HUD events, tab answers and chat texts.
fn tick(
    e: &mut Engine<Box<dyn Sim>>,
) -> (
    Vec<HudEvent>,
    Vec<crate::hud::TabCompletion>,
    Vec<String>,
    Option<crate::hud::Hud>,
) {
    let mut out = (Vec::new(), Vec::new(), Vec::new(), None);
    e.note_inbound(Instant::now());
    e.tick(
        &mut Script(|ctx: &mut TickContext<'_>| {
            out.0 = ctx.events().hud().to_vec();
            out.1 = ctx.events().tab_completions().to_vec();
            out.2 = ctx.events().chat.iter().map(|m| m.plain()).collect();
            out.3 = ctx.hud().cloned();
        }),
        Instant::now(),
    );
    out
}

fn hud_engine(v: GameVersion) -> Engine<Box<dyn Sim>> {
    let mut e = engine(v);
    join(&mut e);
    e.note_inbound(Instant::now());
    e.track_hud(true, false);
    e
}

fn t(s: &str) -> String {
    s.to_owned()
}

fn text(x: Option<&Text>) -> Option<String> {
    x.map(Text::plain)
}

/// Title, subtitle and their countdown through engine ticks: the subtitle waits for a title,
/// the default times give 100 ticks, the title shows on the tick it arrived minus one (the
/// HUD ticks after the packets), times restart a title that shows.
#[test]
fn title_countdown_on_every_version() {
    for v in VERSIONS {
        let mut e = hud_engine(v);
        feed(&mut e, W::Subtitle("small"));
        let (ev, _, _, h) = tick(&mut e);
        assert!(
            matches!(&ev[..], [HudEvent::Subtitle(x)] if x.plain() == "small"),
            "{v:?}"
        );
        let h = h.unwrap();
        assert!(h.title().is_none() && h.subtitle().is_none(), "{v:?}");
        assert_eq!(text(h.subtitle_text()), Some(t("small")), "{v:?}");

        feed(&mut e, W::Title("Big"));
        let (ev, _, _, h) = tick(&mut e);
        assert!(
            matches!(&ev[..], [HudEvent::Title(x)] if x.plain() == "Big"),
            "{v:?} {ev:?}"
        );
        let h = h.unwrap();
        assert_eq!(text(h.title()), Some(t("Big")), "{v:?}");
        assert_eq!(text(h.subtitle()), Some(t("small")), "{v:?}");
        assert_eq!(h.title_ticks(), 99, "{v:?}");
        assert_eq!(h.title_phase(), Some(TitlePhase::FadeIn), "{v:?}");

        // 30 ticks later the times change: the title restarts with them.
        for _ in 0..30 {
            tick(&mut e);
        }
        feed(&mut e, W::Times(5, 10, 5));
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(
            ev,
            vec![HudEvent::TitleTimes(TitleTimes::new(5, 10, 5))],
            "{v:?}"
        );
        assert_eq!(h.unwrap().title_ticks(), 19, "{v:?}");
        for _ in 0..18 {
            assert!(tick(&mut e).0.is_empty(), "{v:?}");
        }
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev, vec![HudEvent::TitleEnded], "{v:?}");
        let h = h.unwrap();
        assert!(h.title().is_none() && h.title_text().is_none(), "{v:?}");
        assert!(h.subtitle_text().is_none(), "{v:?}");
        // the times stay for the next title
        feed(&mut e, W::Title("Again"));
        assert_eq!(tick(&mut e).3.unwrap().title_ticks(), 19, "{v:?}");
    }
}

/// `clear` and `reset` per version.
#[test]
fn clear_and_reset_per_version() {
    for v in VERSIONS {
        let mut e = hud_engine(v);
        feed(&mut e, W::Times(2, 3, 4));
        feed(&mut e, W::Subtitle("s"));
        feed(&mut e, W::Title("T"));
        feed(&mut e, W::Clear);
        let (_, _, _, h) = tick(&mut e);
        let h = h.unwrap();
        assert!(h.title().is_none(), "{v:?}");
        if modern(v) {
            // clear_titles keeps the times
            assert_eq!(h.title_times(), TitleTimes::new(2, 3, 4), "{v:?}");
            assert!(h.title_text().is_none(), "{v:?}");
        } else {
            // setTitles(null, null, 0, 0, 0): the times are 0 and the next title does not show
            assert_eq!(h.title_times(), TitleTimes::new(0, 0, 0), "{v:?}");
            assert_eq!(text(h.title_text()), Some(t("T")), "{v:?}");
            feed(&mut e, W::Title("Hidden"));
            assert!(tick(&mut e).3.unwrap().title().is_none(), "{v:?}");
            feed(&mut e, W::Times(2, 3, 4));
        }

        feed(&mut e, W::Subtitle("s2"));
        feed(&mut e, W::Title("T2"));
        tick(&mut e);
        feed(&mut e, W::Reset);
        let (ev, _, _, h) = tick(&mut e);
        let h = h.unwrap();
        assert_eq!(h.title_times(), TitleTimes::DEFAULT, "{v:?}");
        if matches!(v, GameVersion::V1_8_9 | GameVersion::V1_12_2) {
            // an empty title with the old times (9), the subtitle stays on screen
            assert_eq!(h.title_ticks(), 8, "{v:?}");
            assert_eq!(text(h.title()), Some(String::new()), "{v:?}");
            assert_eq!(text(h.subtitle()), Some(t("s2")), "{v:?}");
            assert!(matches!(
                &ev[..],
                [HudEvent::Title(_), HudEvent::TitleTimes(_)]
            ));
        } else {
            assert!(
                h.title_text().is_none() && h.subtitle_text().is_none(),
                "{v:?}"
            );
            assert_eq!(
                ev,
                vec![HudEvent::TitlesCleared { reset_times: true }],
                "{v:?}"
            );
        }
        // 1.8 – 1.16.5: times all negative clear; 26.x keeps everything (and restarts).
        feed(&mut e, W::Title("N"));
        tick(&mut e);
        feed(&mut e, W::Times(-1, -1, -1));
        let h = tick(&mut e).3.unwrap();
        if modern(v) {
            assert_eq!(h.title_ticks(), 99, "{v:?}");
        } else {
            assert!(h.title().is_none() && h.title_text().is_none(), "{v:?}");
        }
    }
}

/// The action bar: the title action (1.12 / 1.16.5), `set_action_bar_text` (26.x) and chat at
/// the action bar position (every version) show for 60 ticks; the chat one is not reported
/// as chat without `Interests::CHAT`, and only the action bar position goes to the HUD.
#[test]
fn action_bar_on_every_version() {
    for v in VERSIONS {
        let mut e = hud_engine(v);
        if v != GameVersion::V1_8_9 {
            feed(&mut e, W::ActionBar("via title"));
            let (ev, _, _, h) = tick(&mut e);
            assert!(matches!(&ev[..], [HudEvent::ActionBar(x)] if x.plain() == "via title"));
            assert_eq!(h.unwrap().action_bar_ticks(), 59, "{v:?}");
        }
        feed(&mut e, W::ChatOverlay("hp 20"));
        feed(&mut e, W::ChatSystem("hello"));
        let (ev, _, chat, h) = tick(&mut e);
        assert_eq!(ev.len(), 1, "{v:?} {ev:?}");
        assert!(chat.is_empty(), "{v:?}: chat without the interest");
        let h = h.unwrap();
        assert_eq!(text(h.action_bar()), Some(t("hp 20")), "{v:?}");
        for _ in 0..58 {
            tick(&mut e);
        }
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev, vec![HudEvent::ActionBarEnded], "{v:?}");
        assert!(h.unwrap().action_bar().is_none(), "{v:?}");
        // with the chat interest both are chat too
        e.track_hud(true, true);
        feed(&mut e, W::ChatOverlay("x"));
        feed(&mut e, W::ChatSystem("y"));
        assert_eq!(tick(&mut e).2, vec![t("x"), t("y")], "{v:?}");
    }
}

/// Header and footer: 1.8 keeps an empty one, 1.12 / 1.16.5 / 26.x drop it (the oracle's
/// `hud.jsonl.gz` has the real clients doing so).
#[test]
fn tab_list_header_footer() {
    for v in VERSIONS {
        let mut e = hud_engine(v);
        feed(&mut e, W::Header("Welcome", ""));
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev, vec![HudEvent::TabList], "{v:?}");
        let h = h.unwrap();
        assert_eq!(text(h.header()), Some(t("Welcome")), "{v:?}");
        assert_eq!(h.footer().is_some(), v == GameVersion::V1_8_9, "{v:?}");
    }
}

/// Boss bars (1.9+): add, every update, the fog flag rules, remove; 1.8 has none.
#[test]
fn boss_bars_per_version() {
    for v in VERSIONS {
        assert_eq!(v.caps().boss_bars, v != GameVersion::V1_8_9, "{v:?}");
        if v == GameVersion::V1_8_9 {
            assert!(packet(v, &W::BossRemove(1)).is_none());
            continue;
        }
        let id = uuid::Uuid::from_u128(1);
        let mut e = hud_engine(v);
        // flags 2: music (1.12 reads fog from it too), then 4: fog only
        feed(&mut e, W::BossAdd(1, "Dragon", 0.5, 2, 1, 2));
        feed(&mut e, W::BossAdd(2, "Wither", 1.0, 5, 0, 4));
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev.len(), 2, "{v:?}");
        let h = h.unwrap();
        let b = &h.boss_bars()[0];
        assert_eq!((b.id, b.title.plain(), b.progress), (id, t("Dragon"), 0.5));
        assert_eq!(
            (b.color, b.style),
            (BossBarColor::Red, BossBarStyle::Notched6)
        );
        assert!(b.play_music && !b.darken_screen, "{v:?}");
        assert_eq!(b.create_fog, v == GameVersion::V1_12_2, "{v:?}");
        assert_eq!(
            h.boss_bars()[1].create_fog,
            v != GameVersion::V1_12_2,
            "{v:?}"
        );

        feed(&mut e, W::BossProgress(1, 0.25));
        feed(&mut e, W::BossTitle(1, "Dragon II"));
        feed(&mut e, W::BossStyle(1, 6, 4));
        // properties 1: darken; the fog flag is kept on 1.12 / 1.16.5, updated on 26.x
        feed(&mut e, W::BossFlags(2, 1));
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev.len(), 4, "{v:?}");
        let h = h.unwrap();
        let b = h.boss_bar(id).unwrap();
        assert_eq!((b.title.plain(), b.progress), (t("Dragon II"), 0.25));
        assert_eq!(
            (b.color, b.style),
            (BossBarColor::White, BossBarStyle::Notched20)
        );
        let w = &h.boss_bars()[1];
        assert!(w.darken_screen && !w.play_music, "{v:?}");
        assert_eq!(
            w.create_fog,
            !modern(v) && v != GameVersion::V1_12_2,
            "{v:?}"
        );

        // a re-add keeps the place, an update of an unknown bar is ignored, remove
        feed(&mut e, W::BossAdd(1, "Re", 1.0, 0, 0, 0));
        feed(&mut e, W::BossProgress(9, 0.0));
        feed(&mut e, W::BossRemove(2));
        let (ev, _, _, h) = tick(&mut e);
        assert_eq!(ev.len(), 2, "{v:?}");
        let h = h.unwrap();
        assert_eq!(h.boss_bars().len(), 1, "{v:?}");
        assert_eq!(h.boss_bars()[0].title.plain(), "Re", "{v:?}");
    }
}

/// Without the interest the HUD packets do not pass the filter and nothing is kept; the
/// tab-completion answer always passes.
#[test]
fn hud_only_with_interest() {
    for v in VERSIONS {
        for w in [W::Title("a"), W::Header("h", "f"), W::Times(1, 1, 1)] {
            let raw = packet(v, &w).unwrap();
            assert!(!passes(v, &raw, Interests::NONE), "{v:?} {w:?}");
        }
        if v != GameVersion::V1_8_9 {
            let raw = packet(v, &W::BossRemove(1)).unwrap();
            assert!(!passes(v, &raw, Interests::NONE), "{v:?}");
        }
        let raw = packet(v, &W::TabReply(0, 1, 2, &["/time"])).unwrap();
        assert!(passes(v, &raw, Interests::NONE), "{v:?}");
        let mut e = engine(v);
        join(&mut e);
        e.note_inbound(Instant::now());
        // decoded anyway (a raw packet subscription): ignored without the interest
        feed_raw(&mut e, &packet(v, &W::Title("x")).unwrap());
        assert!(e.core.hud.is_none());
        assert!(tick(&mut e).0.is_empty());
        e.track_hud(true, true);
        e.track_hud(false, true);
        assert!(e.core.hud.is_none());
    }
}

/// The request goes out in the tick's packets with the vanilla transaction id; the answer is
/// matched to it (1.13+ by id, 1.8 / 1.12 in order with the last word as the range).
#[test]
fn tab_complete_on_every_version() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        let mut asked = (0, 0);
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                asked.0 = ctx.tab_complete("/ti");
                asked.1 = ctx.tab_complete("/tp Al");
            }),
            Instant::now(),
        );
        assert_eq!(asked, (0, 1), "{v:?}");
        let out = e.outbound();
        let reqs: Vec<_> = out
            .iter()
            .filter_map(|o| match o {
                Outbound::TabComplete { id, text, .. } => Some((*id, text.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(reqs, vec![(0, t("/ti")), (1, t("/tp Al"))], "{v:?}");
        assert!(names(out).contains(&"tab_complete"));
        // the answers, in reverse order on 1.13+
        let (a, b) = if modern(v) || v == GameVersion::V1_16_5 {
            (
                W::TabReply(1, 4, 2, &["Alex"]),
                W::TabReply(0, 1, 2, &["time", "title"]),
            )
        } else {
            (
                W::TabReply(0, 0, 0, &["/time", "/title"]),
                W::TabReply(0, 0, 0, &["Alex"]),
            )
        };
        feed_raw(&mut e, &packet(v, &a).unwrap());
        feed_raw(&mut e, &packet(v, &b).unwrap());
        let (_, tabs, _, _) = tick(&mut e);
        assert_eq!(tabs.len(), 2, "{v:?}");
        let by = |r: u32| tabs.iter().find(|x| x.request == Some(r)).unwrap();
        let ti = by(0);
        let has_tips = v == GameVersion::V1_16_5 || modern(v);
        // 1.13+: the server's range; 1.8 / 1.12: the last word (here the whole line)
        let range = if has_tips { (1, 2) } else { (0, 3) };
        assert_eq!((ti.start, ti.length), range, "{v:?}");
        let tp = by(1);
        assert_eq!((tp.start, tp.length), (4, 2), "{v:?}");
        assert_eq!(tp.matches[0].text, "Alex", "{v:?}");
        let tip = tp.matches[0].tooltip.as_ref().map(Text::plain);
        assert_eq!(tip, has_tips.then(|| t("tip")), "{v:?}");
        if !has_tips {
            // the legacy range is the last word of the request
            assert_eq!(ti.transaction_id, None);
        }
    }
}

/// The request's wire bytes on every version.
#[test]
fn tab_complete_wire() {
    use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
    fn bodies<V: ClientVersion>(o: &Outbound) -> RawPacket
    where
        V::Wire: Default,
    {
        let mut enc = FrameEncoder::new();
        V::write_play(&mut enc, o, &mut V::Wire::default()).unwrap();
        let mut dec = FrameDecoder::new();
        dec.push(&enc.take());
        dec.next_packet().unwrap().unwrap()
    }
    let o = Outbound::TabComplete {
        id: 3,
        text: t("/ti"),
        assume_command: true,
        block: Some(ghast_protocol::BlockPos::new(1, 2, 3)),
    };
    let p = bodies::<crate::version::V1_8>(&o);
    let s: ghast_protocol::v1_8::play::serverbound::TabComplete = p.decode_as().unwrap();
    assert_eq!(
        (&*s.text, s.block),
        ("/ti", Some(ghast_protocol::BlockPos::new(1, 2, 3)))
    );
    let p = bodies::<crate::version::V1_12_2>(&o);
    let s: ghast_protocol::v1_12_2::play::serverbound::TabComplete = p.decode_as().unwrap();
    assert!(s.assume_command && s.looked_at_block.is_some());
    let p = bodies::<crate::version::V1_16_5>(&o);
    let s: ghast_protocol::v1_16_5::play::serverbound::TabComplete = p.decode_as().unwrap();
    assert_eq!((s.transaction_id, &*s.text), (3, "/ti"));
    let p = bodies::<crate::version::V26_1>(&o);
    let s: ghast_protocol::v26_1::play::serverbound::TabComplete = p.decode_as().unwrap();
    assert_eq!((s.transaction_id, &*s.text), (3, "/ti"));
    #[cfg(feature = "v26_3")]
    {
        let p = bodies::<crate::version::V26_3>(&o);
        assert_eq!(
            p.id,
            ghast_protocol::v26_3::play::serverbound::id::TAB_COMPLETE
        );
    }
}

/// 26.x: the start of a reconfiguration resets the HUD but keeps the action bar.
#[test]
fn reconfiguration_resets_the_hud() {
    for v in VERSIONS.into_iter().filter(|v| modern(*v)) {
        let mut e = hud_engine(v);
        feed(&mut e, W::BossAdd(1, "b", 1.0, 0, 0, 0));
        feed(&mut e, W::Header("h", "f"));
        feed(&mut e, W::Times(1, 1, 1));
        feed(&mut e, W::Title("t"));
        feed(&mut e, W::ActionBar("a"));
        tick(&mut e);
        e.handle(Inbound::StartConfiguration);
        let h = e.core.hud.as_deref().unwrap();
        assert!(h.boss_bars().is_empty() && h.header().is_none() && h.title().is_none());
        assert_eq!(h.title_times(), TitleTimes::DEFAULT);
        assert!(h.action_bar().is_some());
    }
}

// ---- the oracle golden (`tests/golden/<version>/hud.jsonl.gz`) ----------------------------------

/// The clientbound packet id of a golden packet kind on `v`.
fn golden_packet_id(v: GameVersion, kind: &str) -> i32 {
    macro_rules! legacy {
        ($m:ident, $boss:expr) => {{
            use ghast_protocol::$m::play::clientbound::id;
            match kind {
                "title" => id::TITLE,
                "chat" => id::CHAT,
                "playerlist_header" => id::PLAYERLIST_HEADER,
                "boss_bar" => $boss,
                _ => panic!("{v:?}: golden packet {kind}"),
            }
        }};
    }
    macro_rules! modern {
        ($m:ident) => {{
            use ghast_protocol::$m::play::clientbound::id;
            match kind {
                "set_title_text" => id::SET_TITLE_TEXT,
                "set_title_subtitle" => id::SET_TITLE_SUBTITLE,
                "set_title_time" => id::SET_TITLE_TIME,
                "clear_titles" => id::CLEAR_TITLES,
                "action_bar" => id::ACTION_BAR,
                "system_chat" => id::SYSTEM_CHAT,
                "playerlist_header" => id::PLAYERLIST_HEADER,
                "boss_bar" => id::BOSS_BAR,
                _ => panic!("{v:?}: golden packet {kind}"),
            }
        }};
    }
    match v {
        GameVersion::V1_8_9 => legacy!(v1_8, panic!("1.8.9 has no boss bars")),
        GameVersion::V1_12_2 => {
            legacy!(
                v1_12_2,
                ghast_protocol::v1_12_2::play::clientbound::id::BOSS_BAR
            )
        }
        GameVersion::V1_16_5 => {
            legacy!(
                v1_16_5,
                ghast_protocol::v1_16_5::play::clientbound::id::BOSS_BAR
            )
        }
        GameVersion::V26_1 => modern!(v26_1),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => modern!(v26_3),
        _ => modern!(v26_2),
    }
}

fn hex_bytes(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect()
}

/// The HUD state of a tick as the golden has it (texts plain; the action bar's text only
/// while it shows, as the client keeps the last one).
fn golden_state(h: &crate::hud::Hud) -> serde_json::Value {
    let s = |t: Option<&Text>| t.map(Text::plain).unwrap_or_default();
    let o = |t: Option<&Text>| t.map(Text::plain);
    let times = h.title_times();
    let bars: Vec<serde_json::Value> = h
        .boss_bars()
        .iter()
        .map(|b| {
            serde_json::json!([
                b.id.to_string(),
                b.title.plain(),
                b.progress.to_bits(),
                format!("{:?}", b.color),
                format!("{:?}", b.style),
                u8::from(b.darken_screen)
                    | u8::from(b.play_music) << 1
                    | u8::from(b.create_fog) << 2
            ])
        })
        .collect();
    serde_json::json!({
        "title": s(h.title_text()),
        "subtitle": s(h.subtitle_text()),
        "title_ticks": h.title_ticks(),
        "times": [times.fade_in, times.stay, times.fade_out],
        "bar": s(h.action_bar()),
        "bar_ticks": h.action_bar_ticks(),
        "header": o(h.header()),
        "footer": o(h.footer()),
        "bosses": bars,
    })
}

/// The golden's state in the form of [`golden_state`].
fn golden_expected(g: &serde_json::Value) -> serde_json::Value {
    let mut g = g.clone();
    if g["bar_ticks"].as_i64() == Some(0) {
        g["bar"] = serde_json::json!("");
    }
    let bosses: Vec<serde_json::Value> = g["bosses"]
        .as_array()
        .map(|a| {
            a.iter()
                .map(|b| {
                    let color = BossBarColor::from_wire(b["color"].as_i64().unwrap() as i32);
                    let style = BossBarStyle::from_wire(b["style"].as_i64().unwrap() as i32);
                    let progress = u32::from_str_radix(b["progress"][1].as_str().unwrap(), 16);
                    serde_json::json!([
                        b["id"],
                        b["name"],
                        progress.unwrap(),
                        format!("{:?}", color.unwrap()),
                        format!("{:?}", style.unwrap()),
                        b["flags"]
                    ])
                })
                .collect()
        })
        .unwrap_or_default();
    g["bosses"] = serde_json::json!(bosses);
    g
}

/// Replays `tests/golden/<version>/hud.jsonl.gz` through the engine: each tick's packet bytes
/// (decoded by the version's wire layer, through the HUD filter), one engine tick, then the HUD
/// as the behaviour sees it against the real client's. Returns (cases, ticks, diffs).
fn replay_hud_golden(v: GameVersion) -> (usize, usize, Vec<String>) {
    use std::io::BufRead;
    let path = format!(
        "{}/../../tests/golden/{}/hud.jsonl.gz",
        env!("CARGO_MANIFEST_DIR"),
        v.name()
    );
    let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
    let (mut cases, mut ticks, mut diffs) = (0, 0, Vec::new());
    let mut e = None;
    let mut name = String::new();
    for l in std::io::BufReader::new(flate2::read::GzDecoder::new(f)).lines() {
        let g: serde_json::Value = serde_json::from_str(&l.unwrap()).unwrap();
        if g["type"] == "case" {
            name = g["name"].as_str().unwrap().to_owned();
            e = Some(hud_engine(v));
            cases += 1;
            continue;
        }
        let e = e.as_mut().unwrap();
        for p in g["packets"].as_array().unwrap() {
            let raw = RawPacket {
                id: golden_packet_id(v, p["p"].as_str().unwrap()),
                body: bytes::Bytes::from(hex_bytes(p["hex"].as_str().unwrap())),
            };
            assert!(passes(v, &raw, Interests::HUD), "{v:?}: {p} filtered");
            feed_raw(e, &raw);
        }
        let h = tick(e).3.expect("the HUD is tracked");
        ticks += 1;
        let (ours, want) = (golden_state(&h), golden_expected(&g["hud"]));
        if ours != want && diffs.len() < 20 {
            diffs.push(format!("{v:?} {name} t{}: ours {ours} want {want}", g["t"]));
        }
    }
    (cases, ticks, diffs)
}

fn check_hud_golden(v: GameVersion) {
    let (cases, ticks, diffs) = replay_hud_golden(v);
    assert!(diffs.is_empty(), "{}", diffs.join("\n"));
    assert!(
        cases >= 6 && ticks > 1000,
        "{v:?}: {cases} cases, {ticks} ticks"
    );
    println!("{v:?}: {cases} cases, {ticks} ticks, 0 diffs");
}

/// The HUD golden of the real 1.8.9 client: 0 diffs.
#[test]
fn hud_matches_the_oracle_1_8_9() {
    check_hud_golden(GameVersion::V1_8_9);
}

/// The HUD golden of the real 1.12.2 client: 0 diffs.
#[test]
fn hud_matches_the_oracle_1_12_2() {
    check_hud_golden(GameVersion::V1_12_2);
}

/// The HUD golden of the real 1.16.5 client: 0 diffs.
#[test]
fn hud_matches_the_oracle_1_16_5() {
    check_hud_golden(GameVersion::V1_16_5);
}

/// The HUD golden of the real 26.1 client: 0 diffs.
#[test]
fn hud_matches_the_oracle_26_1() {
    check_hud_golden(GameVersion::V26_1);
}

/// The HUD golden of the real 26.2 client: 0 diffs.
#[test]
fn hud_matches_the_oracle_26_2() {
    check_hud_golden(GameVersion::V26_2);
}

/// The HUD golden of the real 26.3 client: 0 diffs.
#[cfg(feature = "v26_3")]
#[test]
fn hud_matches_the_oracle_26_3() {
    check_hud_golden(GameVersion::V26_3);
}

/// 1.8: command feedback as a 1.8 server sends it (`CommandHandler` failure: a red
/// `ChatComponentTranslation` with its arguments, serialised by Gson with its HTML escapes; a
/// success; a plain system line; player chat; the action bar) reaches the behaviour as chat,
/// with `Interests::CHAT` alone and with the HUD too (the action bar then only as HUD).
#[test]
fn legacy_command_feedback_reaches_chat() {
    // `blockdata 2 4 0 {}` on an unchanged sign: commands.blockdata.failed with the NBT
    let nbt = r#"{x:2,Text4:\"{\\\"extra\\\":[\\\"line \\u003c4\\u003e\\\"],\\\"text\\\":\\\"\\\"}\",y:4,Text3:\"\\\"\\\"\",z:0,id:\"Sign\"}"#;
    let failed =
        format!(r#"{{"translate":"commands.blockdata.failed","with":["{nbt}"],"color":"red"}}"#);
    let lines: [(String, i8); 5] = [
        (failed, 1),
        (
            r#"{"translate":"commands.testfor.success","with":["GhastBot9"]}"#.to_owned(),
            1,
        ),
        (r#"{"text":"Hello","color":"red"}"#.to_owned(), 1),
        (
            r#"{"translate":"chat.type.text","with":[{"text":"Bob"},"hi <3"]}"#.to_owned(),
            0,
        ),
        (r#"{"text":"over the hotbar"}"#.to_owned(), 2),
    ];
    for hud in [false, true] {
        let mut e = engine(GameVersion::V1_8_9);
        join(&mut e);
        e.note_inbound(Instant::now());
        let interests = if hud {
            e.track_hud(true, true);
            Interests::CHAT | Interests::HUD
        } else {
            Interests::CHAT
        };
        for (json, position) in &lines {
            let raw = RawPacket::from_packet(&ghast_protocol::v1_8::play::clientbound::Chat {
                message: ByteString::from(json.clone()),
                position: *position,
            })
            .unwrap();
            assert!(passes(GameVersion::V1_8_9, &raw, interests));
            feed_raw(&mut e, &raw);
        }
        let (_, _, chat, h) = tick(&mut e);
        assert_eq!(chat.len(), 5, "hud {hud}: {chat:?}");
        // the argument as the server's console prints it (the sign's stored JSON keeps its own
        // `<` escapes)
        let want = r#"commands.blockdata.failed {x:2,Text4:"{\"extra\":[\"line LT4GT\"],\"text\":\"\"}",y:4,Text3:"\"\"",z:0,id:"Sign"}"#
            .replace("LT", &format!("\\u{:04x}", 0x3c))
            .replace("GT", &format!("\\u{:04x}", 0x3e));
        assert_eq!(chat[0], want);
        assert_eq!(chat[3], "chat.type.text Bob hi <3");
        assert_eq!(chat[1], "commands.testfor.success GhastBot9");
        assert_eq!(chat[2], "Hello");
        assert_eq!(chat[4], "over the hotbar");
        if hud {
            assert_eq!(text(h.unwrap().action_bar()), Some(t("over the hotbar")));
        }
    }
}