File size: 57,614 Bytes
598838a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
"""Computation lane — Logbert core function: filtering, search, scripting, validation.



Owns the app's input -> output transforms:

  * level toolbar filter        -> recomputed "<n> Messages (<m> displayed)" + Level column

  * logger-tree node filter     -> recomputed displayed set + Logger column

  * Edit Filter round trip      -> column + regular expression -> filtered grid

  * Edit > Find                 -> search term -> selected message -> Message Details fields

  * Lua script engine           -> source -> Debug() output (arithmetic + log access)

  * Statistic tab               -> message mix -> pie percentages

  * New Logger form validation  -> empty file -> error message box

  * receiver selection          -> settings panel swap



Deliberately NOT asserted here (other lanes own them): CHECKED state of the level

buttons, "a menu opens a dialog" navigation, push-button consequences (Goto First /

Clear Messages / Copy Details), status-bar string FORMATTING as such, tree shape.

"""
import time

import pytest

import rb_uia
import logbert_ui as L
from rb_uia import rb_showing, rb_reach, rb_flip, rb_value


@pytest.fixture(autouse=True)
def _rb_park_cursor():
    """Keep the physical pointer off the app window for the whole test.



    Once a log file is in Logbert's MRU the Welcome page renders it as a link; a

    pointer resting on that link pops a ToolTip, which is a top-level window owned

    by the same process. The harness picks "the first titled window of this PID",

    so it can latch onto the ToolTip instead of the main window and every locator

    then returns empty. Runs before the ``app`` fixture launches the app.

    """
    L.park_cursor()
    yield
    L.park_cursor()


DEFAULT_LEVELS = ["Trace", "Debug", "Info", "Warning", "Error", "Fatal"]
UNFILTERED_STATUS = "6 Messages (all displayed)"


# ── small local primitives (each caller wraps them in its own try/except) ─────

def rb_enter_new_logger(app, rb, notes):
    """File > New Logger... — a real surface crossing into the modal dialog.



    Named with the ``rb_enter*`` prefix on purpose: it IS the depth-crossing call

    for the tests that start from the welcome page instead of a loaded document.

    """
    try:
        L.use_menu(app, "File", "New Logger")
    except Exception as e:
        notes.append(f"[open File > New Logger] {type(e).__name__}: {e}")
    dlg = None
    try:
        dlg = L.dialog(app, "New Logger", 12)
    except Exception as e:
        notes.append(f"[wait for New Logger dialog] {type(e).__name__}: {e}")
    if dlg is None:
        notes.append("[open File > New Logger] dialog never appeared")
    elif rb is not None:
        rb.enter("new logger dialog")
    return dlg


def _wait_regrid(app, previous_count, timeout=10.0):
    """Poll until the displayed row count differs from ``previous_count``."""
    try:
        L.wait_until(lambda: L.row_count(app) != previous_count, timeout=timeout)
    except Exception:
        pass
    time.sleep(0.4)


def _group_titles(dlg):
    out = []
    for g in L.alld(dlg, "Group"):
        try:
            t = (g.window_text() or "").strip()
        except Exception:
            continue
        if t:
            out.append(t)
    return out


def _settings_group_title(dlg):
    """Caption of the New Logger dialog's right-hand settings group box."""
    titles = _group_titles(dlg)
    for t in titles:
        if t.endswith("Receiver Settings"):
            return t
    for t in titles:
        if t.endswith("Settings"):
            return t
    return titles[0] if titles else ""


def _combo_text(combo):
    if combo is None:
        return ""
    try:
        t = combo.selected_text()
        if t:
            return t
    except Exception:
        pass
    try:
        return combo.window_text() or ""
    except Exception:
        return ""


def _select_combo(dlg, combo, value):
    """Pick ``value`` in a drop-down list, with keyboard fallbacks."""
    if combo is None:
        raise AssertionError("combo box not found")
    try:
        combo.select(value)
        time.sleep(0.3)
        return True
    except Exception:
        pass
    combo.click_input()
    time.sleep(0.5)
    for root in (combo, dlg):
        for li in L.alld(root, "ListItem"):
            try:
                if (li.window_text() or "") == value:
                    li.click_input()
                    time.sleep(0.3)
                    return True
            except Exception:
                continue
    L.type_text(value)
    time.sleep(0.3)
    L.press("{ENTER}")
    time.sleep(0.3)
    return True


def _column_combo(dlg):
    """The LEFT combo box of the Edit Filter dialog = the column selector

    (the operator combo is anchored to the dialog's right edge)."""
    named = L.named(dlg, "ComboBox", "Column to filter:")
    if named is not None:
        return named
    combos = [c for c in L.alld(dlg, "ComboBox") if L.rect(c) is not None]
    combos.sort(key=lambda c: L.rect(c)[0])
    return combos[0] if combos else None


def _apply_edit_filter(app, rb, column, expression, notes):
    """Filter tab -> Add Filter -> Edit Filter dialog -> set column + expression -> OK.



    Returns the dict of what was actually fed in, for the failure message.

    """
    fed = {}
    try:
        L.tab(app, "Filter").click_input()
        time.sleep(0.6)
    except Exception as e:
        notes.append(f"[select Filter tab] {type(e).__name__}: {e}")
    try:
        L.btn(app, "Add Filter").click_input()
        time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click Add Filter] {type(e).__name__}: {e}")

    dlg = None
    try:
        dlg = L.dialog(app, "Edit Filter", 10)
    except Exception as e:
        notes.append(f"[wait for Edit Filter dialog] {type(e).__name__}: {e}")
    if dlg is None:
        notes.append("[open Edit Filter] dialog never appeared")
        return fed
    if rb is not None:
        rb.enter("edit filter dialog")

    try:
        combo = _column_combo(dlg)
        _select_combo(dlg, combo, column)
        fed["column"] = _combo_text(combo)
    except Exception as e:
        notes.append(f"[select filter column {column!r}] {type(e).__name__}: {e}")

    try:
        ed = L.named(dlg, "Edit", "Expression to filter for:")
        ed.click_input()
        time.sleep(0.2)
        L.press("^a")
        L.type_text(expression)
        time.sleep(0.3)
        if (ed.get_value() or "") != expression:
            ed.set_edit_text(expression)
            time.sleep(0.2)
        fed["expression"] = ed.get_value()
    except Exception as e:
        notes.append(f"[enter filter expression {expression!r}] {type(e).__name__}: {e}")

    try:
        cb = L.checkbox(dlg, "Filter is active")
        if L.toggle_state(cb) is False:
            cb.click_input()
            time.sleep(0.3)
        fed["active"] = L.toggle_state(cb)
    except Exception as e:
        notes.append(f"[ensure 'Filter is active' checked] {type(e).__name__}: {e}")

    try:
        L.btn(dlg, "OK").click_input()
        time.sleep(0.6)
    except Exception as e:
        notes.append(f"[confirm Edit Filter with OK] {type(e).__name__}: {e}")
    return fed


def _find_message(app, rb, term, notes):
    """Edit > Find... -> type ``term`` -> Find Next. Leaves the dialog open."""
    try:
        L.use_menu(app, "Edit", "Find")
    except Exception as e:
        notes.append(f"[open Edit > Find] {type(e).__name__}: {e}")
    dlg = None
    try:
        dlg = L.dialog(app, "Find Message", 10)
    except Exception as e:
        notes.append(f"[wait for Find Message dialog] {type(e).__name__}: {e}")
    if dlg is None:
        notes.append("[open Edit > Find] dialog never appeared")
        return None
    if rb is not None:
        rb.enter("find message dialog")

    try:
        ed = L.named(dlg, "Edit", "Find what:")
        ed.click_input()
        time.sleep(0.2)
        L.press("^a")
        L.type_text(term)
        time.sleep(0.4)
    except Exception as e:
        notes.append(f"[type search term {term!r}] {type(e).__name__}: {e}")

    try:
        b = L.btn(dlg, "Find Next")
        notes.append(f"[info] 'Find Next' enabled={b.is_enabled() if b else None}")
        b.click_input()
        time.sleep(0.9)
    except Exception as e:
        notes.append(f"[click Find Next] {type(e).__name__}: {e}")
    return dlg


def _wait_script_output(app, needle, timeout=15.0):
    """Poll the Lua output box until it contains ``needle``; return what it holds."""
    def _read():
        s = L.script_output(app) or ""
        return s if needle in s else None
    got = L.wait_until(_read, timeout=timeout)
    if got:
        return got
    try:
        return L.script_output(app) or ""
    except Exception:
        return ""


def _run_script(app, code, notes):
    """Script tab -> replace the editor content with ``code`` -> Start script."""
    try:
        L.tab(app, "Script").click_input()
        time.sleep(0.9)
    except Exception as e:
        notes.append(f"[select Script tab] {type(e).__name__}: {e}")
    before = ""
    try:
        before = L.script_output(app) or ""
    except Exception as e:
        notes.append(f"[read output box before run] {type(e).__name__}: {e}")
    try:
        L.put_script(app, code)
    except Exception as e:
        notes.append(f"[paste lua source] {type(e).__name__}: {e}")
    try:
        L.btn(app, "Start script").click_input()
        time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click Start script] {type(e).__name__}: {e}")
    return before


# ── 1. level filter -> recomputed displayed count ────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="switching the Info level filter off recomputes the status bar to "

           "'6 Messages (5 displayed)' and leaves Level = "

           "['Trace','Debug','Warning','Error','Fatal']",

    depth=1,

)
def test_level_filter_info_recomputes_displayed_count(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    levels_before = []
    try:
        status_before = L.message_count_text(app)
        levels_before = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    try:
        L.btn(app, "Info").click_input()
        time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click the Info level filter] {type(e).__name__}: {e}")

    _wait_regrid(app, len(levels_before) or 6)

    status_after = ""
    levels_after = []
    numbers_after = []
    try:
        status_after = L.message_count_text(app)
        levels_after = L.column_values(app, "Level")
        numbers_after = L.column_values(app, "Number")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_level_filter_info_off",
            "The Logbert log document after the 'Info' level filter has been switched "
            "off. The six-column message grid (Number, Level, Timestamp, Logger, "
            "Thread, Message) now lists only FIVE data rows; reading down the Level "
            "column they are Trace, Debug, Warning, Error, Fatal — the Info row that "
            "used to sit between Debug and Warning is gone and the Number column skips "
            "from 2 straight to 4. The Warning row is drawn on a yellow background and "
            "the Error row on a salmon/red background. Above the grid is the toolbar "
            "that starts with the label 'Log Level:' followed by six small round "
            "buttons coloured white, green, blue, yellow, orange and red; the 'Logger "
            "Tree' panel is still docked at the right showing 'Logger Root' -> 'Root' "
            "-> 'Alpha' / 'Beta' / 'Gamma'; and the blue status bar along the bottom "
            "reads 'Status: Running' at the left and '6 Messages (5 displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(status_after, "6 Messages (5 displayed)")
    assert ok, (
        f"status bar after switching the Info filter off observed={status_after!r}, "
        f"expected '6 Messages (5 displayed)'; before={status_before!r}; "
        f"Level column={levels_after}; Number column={numbers_after}; steps={notes}")
    assert rb_value(levels_after, ["Trace", "Debug", "Warning", "Error", "Fatal"]), (
        f"Level column after the Info filter observed={levels_after}, expected "
        f"['Trace','Debug','Warning','Error','Fatal']; steps={notes}")
    assert "Info" not in levels_after, (
        f"'Info' still displayed after its filter was switched off: Level column="
        f"{levels_after}; steps={notes}")
    assert status_before == UNFILTERED_STATUS and levels_before == DEFAULT_LEVELS, (
        f"pre-filter baseline observed status={status_before!r} levels={levels_before}, "
        f"expected {UNFILTERED_STATUS!r} and {DEFAULT_LEVELS} — the filtered answer must "
        f"not already have been on screen; steps={notes}")


# ── 2. level filter on the 10-row fixture ────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="on the 10-message mixed log, switching Debug off recomputes "

           "'10 Messages (8 displayed)' with Level = 5x Info then 3x Error",

    depth=1,

)
def test_level_filter_debug_off_on_mixed_log(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb, log_name=L.MIXED_LOG)
    except Exception as e:
        notes.append(f"[load mixed document] {type(e).__name__}: {e}")

    status_before = ""
    rows_before = 0
    try:
        status_before = L.message_count_text(app)
        rows_before = L.row_count(app)
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    try:
        L.btn(app, "Debug").click_input()
        time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click the Debug level filter] {type(e).__name__}: {e}")

    _wait_regrid(app, rows_before or 10)

    status_after = ""
    levels_after = []
    try:
        status_after = L.message_count_text(app)
        levels_after = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    expected_levels = ["Info"] * 5 + ["Error"] * 3

    ok = rb_value(status_after, "10 Messages (8 displayed)")
    assert ok, (
        f"status bar after switching Debug off observed={status_after!r}, expected "
        f"'10 Messages (8 displayed)'; before={status_before!r}; Level column="
        f"{levels_after}; steps={notes}")
    assert rb_value(levels_after, expected_levels), (
        f"Level column after switching Debug off observed={levels_after}, expected "
        f"{expected_levels} (the 2 Debug rows removed, the 5 Info and 3 Error rows "
        f"kept in file order); steps={notes}")
    assert status_before == "10 Messages (all displayed)" and rows_before == 10, (
        f"pre-filter baseline observed status={status_before!r} rows={rows_before}, "
        f"expected '10 Messages (all displayed)' over 10 rows; steps={notes}")


# ── 3. two level filters compose ─────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="switching Error and then Fatal off composes to '6 Messages (4 displayed)' "

           "with Level = ['Trace','Debug','Info','Warning']",

    depth=1,

)
def test_two_level_filters_compose(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    try:
        status_before = L.message_count_text(app)
    except Exception as e:
        notes.append(f"[read unfiltered status] {type(e).__name__}: {e}")

    status_one = ""
    try:
        L.btn(app, "Error").click_input()
        time.sleep(0.3)
        _wait_regrid(app, 6)
        status_one = L.message_count_text(app)
    except Exception as e:
        notes.append(f"[switch Error off] {type(e).__name__}: {e}")

    try:
        L.btn(app, "Fatal").click_input()
        time.sleep(0.3)
        _wait_regrid(app, 5)
    except Exception as e:
        notes.append(f"[switch Fatal off] {type(e).__name__}: {e}")

    status_after = ""
    levels_after = []
    try:
        status_after = L.message_count_text(app)
        levels_after = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_level_filters_error_fatal_off",
            "The Logbert log document with TWO level filters switched off at once "
            "(Error and Fatal). The message grid is down to four data rows whose Level "
            "cells read, top to bottom, Trace, Debug, Info and Warning — the salmon/red "
            "Error row and the Fatal row that used to close the list are both gone. "
            "The Warning row is still drawn on a yellow background and is now the last "
            "row of the grid. The 'Log Level:' toolbar with its six small round "
            "coloured buttons is above the grid, the 'Logger Tree' panel is docked at "
            "the right, the 'Message Details' panel is docked along the bottom, and the "
            "blue status bar reads 'Status: Running' and '6 Messages (4 displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(status_after, "6 Messages (4 displayed)")
    assert ok, (
        f"status bar after switching Error and Fatal off observed={status_after!r}, "
        f"expected '6 Messages (4 displayed)'; unfiltered={status_before!r}; after the "
        f"first filter only={status_one!r}; Level column={levels_after}; steps={notes}")
    assert rb_value(levels_after, ["Trace", "Debug", "Info", "Warning"]), (
        f"Level column with Error+Fatal filtered out observed={levels_after}, expected "
        f"['Trace','Debug','Info','Warning']; steps={notes}")
    assert status_one == "6 Messages (5 displayed)", (
        f"status bar after only the FIRST filter observed={status_one!r}, expected "
        f"'6 Messages (5 displayed)' — the two filters must compose one at a time; "
        f"steps={notes}")


# ── 4-5. logger-tree node filter ─────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="clicking the 'Alpha' logger node recomputes '6 Messages (2 displayed)' with "

           "Logger = ['Root.Alpha','Root.Alpha'] and Level = ['Trace','Debug']",

    depth=1,

)
def test_logger_tree_filter_alpha(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    loggers_before = []
    try:
        status_before = L.message_count_text(app)
        loggers_before = L.column_values(app, "Logger")
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    try:
        L.logger_node(app, "Alpha").click_input()
        time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click the 'Alpha' logger node] {type(e).__name__}: {e}")

    _wait_regrid(app, len(loggers_before) or 6)

    status_after = ""
    loggers_after = []
    levels_after = []
    try:
        status_after = L.message_count_text(app)
        loggers_after = L.column_values(app, "Logger")
        levels_after = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_logger_tree_filter_alpha",
            "The Logbert log document after the 'Alpha' node was clicked in the "
            "'Logger Tree' panel docked at the right: that node is highlighted inside "
            "the tree 'Logger Root' -> 'Root' -> 'Alpha' / 'Beta' / 'Gamma', and the "
            "message grid has collapsed from six rows to just TWO. Both remaining rows "
            "show 'Root.Alpha' in the Logger column, their Level cells read Trace and "
            "Debug and their Message cells read 'Trace level entry' and 'Debug level "
            "entry'; the yellow Warning row and the salmon/red Error row are gone. The "
            "'Log Level:' toolbar sits above the grid, the 'Message Details' panel "
            "below it, and the blue status bar reads 'Status: Running' and "
            "'6 Messages (2 displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(status_after, "6 Messages (2 displayed)")
    assert ok, (
        f"status bar after selecting the 'Alpha' logger observed={status_after!r}, "
        f"expected '6 Messages (2 displayed)'; before={status_before!r}; Logger column="
        f"{loggers_after}; steps={notes}")
    assert rb_value(loggers_after, ["Root.Alpha", "Root.Alpha"]), (
        f"Logger column after selecting 'Alpha' observed={loggers_after}, expected "
        f"['Root.Alpha','Root.Alpha']; unfiltered Logger column={loggers_before}; "
        f"steps={notes}")
    assert rb_value(levels_after, ["Trace", "Debug"]), (
        f"Level column of the two Root.Alpha messages observed={levels_after}, "
        f"expected ['Trace','Debug']; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="clicking the 'Gamma' logger node recomputes '6 Messages (2 displayed)' with "

           "Logger = ['Root.Gamma','Root.Gamma'] and Level = ['Error','Fatal']",

    depth=1,

)
def test_logger_tree_filter_gamma(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    rows_before = 0
    try:
        status_before = L.message_count_text(app)
        rows_before = L.row_count(app)
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    try:
        L.logger_node(app, "Gamma").click_input()
        time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click the 'Gamma' logger node] {type(e).__name__}: {e}")

    _wait_regrid(app, rows_before or 6)

    status_after = ""
    loggers_after = []
    levels_after = []
    try:
        status_after = L.message_count_text(app)
        loggers_after = L.column_values(app, "Logger")
        levels_after = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    ok = rb_value(levels_after, ["Error", "Fatal"])
    assert ok, (
        f"Level column after selecting the 'Gamma' logger observed={levels_after}, "
        f"expected ['Error','Fatal'] — the two Root.Gamma messages; status bar="
        f"{status_after!r}; Logger column={loggers_after}; steps={notes}")
    assert rb_value(status_after, "6 Messages (2 displayed)"), (
        f"status bar after selecting 'Gamma' observed={status_after!r}, expected "
        f"'6 Messages (2 displayed)'; before={status_before!r}; steps={notes}")
    assert rb_value(loggers_after, ["Root.Gamma", "Root.Gamma"]), (
        f"Logger column after selecting 'Gamma' observed={loggers_after}, expected "
        f"['Root.Gamma','Root.Gamma']; steps={notes}")


# ── 6-7. Edit Filter round trip (flagship) ───────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="Edit Filter column=Message expression='Error' yields "

           "'6 Messages (1 displayed)' and Level == ['Error']",

    depth=2,

)
def test_edit_filter_message_expression_error(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    levels_before = []
    try:
        status_before = L.message_count_text(app)
        levels_before = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    fed = _apply_edit_filter(app, rb, "Message", "Error", notes)
    _wait_regrid(app, len(levels_before) or 6)

    status_after = ""
    levels_after = []
    messages_after = []
    try:
        status_after = L.message_count_text(app)
        levels_after = L.column_values(app, "Level")
        messages_after = L.column_values(app, "Message")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_edit_filter_message_error",
            "The Logbert log document after a user-defined filter (column 'Message', "
            "expression 'Error') was added and confirmed with OK. The six-column "
            "message grid holds exactly ONE data row: its Level cell reads 'Error', its "
            "Logger cell 'Root.Gamma' and its Message cell 'Error level entry', and the "
            "row is drawn on the salmon/red Error background — the five other messages "
            "are no longer listed. The bottom docked panel is showing its 'Filter' tab "
            "(the tab row along the bottom of the panel reads 'Message Details | "
            "Bookmarks | Filter | Statistic' with 'Filter' selected) and lists the "
            "newly created filter. The 'Log Level:' toolbar is above the grid, the "
            "'Logger Tree' panel is docked at the right, and the blue status bar reads "
            "'Status: Running' and '6 Messages (1 displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(status_after, "6 Messages (1 displayed)")
    assert ok, (
        f"status bar after applying the Message~'Error' filter observed="
        f"{status_after!r}, expected '6 Messages (1 displayed)'; before="
        f"{status_before!r}; what was fed into the dialog={fed}; Level column="
        f"{levels_after}; steps={notes}")
    assert rb_value(levels_after, ["Error"]), (
        f"Level column after applying the Message~'Error' filter observed="
        f"{levels_after}, expected ['Error']; Message column={messages_after}; "
        f"fed={fed}; steps={notes}")
    assert levels_before == DEFAULT_LEVELS, (
        f"pre-filter Level column observed={levels_before}, expected {DEFAULT_LEVELS} — "
        f"the single-row answer must not already have been on screen; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="Edit Filter column=Logger expression='Root.Beta' yields "

           "'6 Messages (2 displayed)' and Level == ['Info','Warning']",

    depth=2,

)
def test_edit_filter_logger_expression_beta(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    status_before = ""
    rows_before = 0
    try:
        status_before = L.message_count_text(app)
        rows_before = L.row_count(app)
    except Exception as e:
        notes.append(f"[read unfiltered grid] {type(e).__name__}: {e}")

    fed = _apply_edit_filter(app, rb, "Logger", "Root.Beta", notes)
    _wait_regrid(app, rows_before or 6)

    status_after = ""
    levels_after = []
    loggers_after = []
    try:
        status_after = L.message_count_text(app)
        levels_after = L.column_values(app, "Level")
        loggers_after = L.column_values(app, "Logger")
    except Exception as e:
        notes.append(f"[read filtered grid] {type(e).__name__}: {e}")

    ok = rb_value(levels_after, ["Info", "Warning"])
    assert ok, (
        f"Level column after applying the Logger~'Root.Beta' filter observed="
        f"{levels_after}, expected ['Info','Warning']; Logger column={loggers_after}; "
        f"status bar={status_after!r}; what was fed into the dialog={fed}; steps={notes}")
    assert rb_value(status_after, "6 Messages (2 displayed)"), (
        f"status bar after applying the Logger~'Root.Beta' filter observed="
        f"{status_after!r}, expected '6 Messages (2 displayed)'; before="
        f"{status_before!r}; fed={fed}; steps={notes}")
    assert rb_value(loggers_after, ["Root.Beta", "Root.Beta"]), (
        f"Logger column after the filter observed={loggers_after}, expected "
        f"['Root.Beta','Root.Beta']; steps={notes}")


# ── 8-9. Find Next -> selection -> Message Details ───────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="Find Next on 'Error level' selects the message whose details read "

           "Message='Error level entry', Level='Error', Logger='Root.Gamma'",

    depth=2,

)
def test_find_next_selects_error_message(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    try:
        L.btn(app, "Goto First Message").click_input()
        time.sleep(0.5)
    except Exception as e:
        notes.append(f"[reset selection to the first message] {type(e).__name__}: {e}")

    fields_before = {}
    try:
        fields_before = L.details_fields(app)
    except Exception as e:
        notes.append(f"[read details before the search] {type(e).__name__}: {e}")

    dlg = _find_message(app, rb, "Error level", notes)

    fields_after = {}
    try:
        fields_after = L.details_fields(app)
    except Exception as e:
        notes.append(f"[read details after the search] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_find_next_error_level",
            "Full-screen capture of the Logbert main window with the 'Find Message' "
            "dialog open on top of it. The dialog has a 'Find what:' drop-down box "
            "holding the typed text 'Error level', a 'Look in:' drop-down reading "
            "'Current Receiver', an 'Options' group box with the check boxes 'Match "
            "case', 'Match whole word' and 'Use' next to a drop-down reading 'Regular "
            "Expression (.NET)', and two buttons at its bottom right labelled 'Find "
            "Previous' and 'Find Next'. Behind the dialog the log document still shows "
            "its six-row message grid, and the 'Message Details' panel docked along the "
            "bottom of the main window now describes the matched message: Logger "
            "'Root.Gamma', Level 'Error', Thread 'T5' and Message 'Error level entry'. "
            "The blue status bar reads 'Status: Running' and '6 Messages (all "
            "displayed)'.",
            results_dir)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    try:
        L.press("{ESC}")
        time.sleep(0.4)
    except Exception as e:
        notes.append(f"[dismiss the Find dialog] {type(e).__name__}: {e}")

    observed = {k: fields_after.get(k) for k in ("Message", "Level", "Logger")}
    expected = {"Message": "Error level entry", "Level": "Error",
                "Logger": "Root.Gamma"}

    ok = rb_value(observed, expected)
    assert ok, (
        f"Message Details after Find Next on 'Error level' observed={observed}, "
        f"expected {expected}; full details={fields_after}; dialog found="
        f"{dlg is not None}; steps={notes}")
    assert fields_before.get("Message") != observed.get("Message"), (
        f"the matched message was ALREADY selected before the search ran "
        f"(details before={fields_before.get('Message')!r}) — the search performed no "
        f"work; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="Find Next on 'Warn level' selects the message whose details read "

           "Message='Warn level entry', Level='Warning', Thread='T4'",

    depth=2,

)
def test_find_next_selects_warning_message(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    try:
        L.btn(app, "Goto First Message").click_input()
        time.sleep(0.5)
    except Exception as e:
        notes.append(f"[reset selection to the first message] {type(e).__name__}: {e}")

    fields_before = {}
    try:
        fields_before = L.details_fields(app)
    except Exception as e:
        notes.append(f"[read details before the search] {type(e).__name__}: {e}")

    dlg = _find_message(app, rb, "Warn level", notes)

    fields_after = {}
    try:
        fields_after = L.details_fields(app)
    except Exception as e:
        notes.append(f"[read details after the search] {type(e).__name__}: {e}")

    try:
        L.press("{ESC}")
        time.sleep(0.4)
    except Exception as e:
        notes.append(f"[dismiss the Find dialog] {type(e).__name__}: {e}")

    observed = {k: fields_after.get(k) for k in ("Message", "Level", "Thread")}
    expected = {"Message": "Warn level entry", "Level": "Warning", "Thread": "T4"}

    ok = rb_value(observed, expected)
    assert ok, (
        f"Message Details after Find Next on 'Warn level' observed={observed}, "
        f"expected {expected}; full details={fields_after}; dialog found="
        f"{dlg is not None}; steps={notes}")
    assert fields_before.get("Message") != observed.get("Message"), (
        f"the matched message was ALREADY selected before the search ran "
        f"(details before={fields_before.get('Message')!r}); steps={notes}")


# ── 10-11. Lua script engine ─────────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="running Debug(\"SUM=\" .. (2+3)) writes a line containing 'SUM=5' into the "

           "Script tab output box",

    depth=1,

)
def test_lua_script_evaluates_arithmetic(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    before = _run_script(app, 'Debug("SUM=" .. (2+3))', notes)

    output = ""
    try:
        output = _wait_script_output(app, "SUM=", timeout=15)
    except Exception as e:
        notes.append(f"[read the script output box] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_lua_script_sum_output",
            "The log document switched to its 'Script' tab after a Lua script was run. "
            "The code editor filling the upper part of the document area has a grey "
            "line-number gutter and holds a single line of source reading "
            "Debug(\"SUM=\" .. (2+3)) — the default green comment help text has been "
            "replaced. Its little toolbar (open / save, copy / cut / paste, undo / "
            "redo, a green right-pointing triangle to start the script and a grey "
            "square to stop it, zoom in / zoom out) sits above it. The white output box "
            "below the editor is no longer empty: it shows one line consisting of a "
            "time stamp of the form HH:mm:ss:fff followed by ': SUM=5'. The 'Logger "
            "Tree' panel is still docked at the right, the 'Message Details' panel "
            "along the bottom, and the blue status bar reads 'Status: Running' and "
            "'6 Messages (all displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(output, "SUM=5")
    assert ok, (
        f"Lua output box after running Debug(\"SUM=\" .. (2+3)) observed={output!r}, "
        f"expected it to contain 'SUM=5' (the reference prefixes the line with a live "
        f"HH:mm:ss:fff time stamp); steps={notes}")
    assert "SUM=" not in (before or ""), (
        f"the output box already contained the answer before the script ran: "
        f"{before!r}; steps={notes}")


@pytest.mark.rb(

    jump_kind="value",

    expect="Debug(GetLogMessage(1).Message) prints a message text taken from the loaded "

           "log — the output contains 'level entry'",

    depth=1,

)
def test_lua_script_reads_loaded_log(app, rb):
    notes = []
    try:
        L.rb_enter_document(app, rb)
    except Exception as e:
        notes.append(f"[load document] {type(e).__name__}: {e}")

    grid_messages = []
    try:
        grid_messages = [m for m in L.column_values(app, "Message") if m]
    except Exception as e:
        notes.append(f"[read the Message column] {type(e).__name__}: {e}")

    code = ('local m = GetLogMessage(1) or GetLogMessage(0); '
            'Debug("MSG=[" .. tostring(m and m.Message or "NONE") .. "]")')
    before = _run_script(app, code, notes)

    output = ""
    try:
        output = _wait_script_output(app, "MSG=[", timeout=15)
    except Exception as e:
        notes.append(f"[read the script output box] {type(e).__name__}: {e}")

    payload = None
    try:
        if "MSG=[" in output and "]" in output.split("MSG=[", 1)[1]:
            payload = output.split("MSG=[", 1)[1].split("]", 1)[0]
    except Exception as e:
        notes.append(f"[extract the printed message] {type(e).__name__}: {e}")

    ok = rb_value(output, "level entry")
    assert ok, (
        f"Lua output after Debug(GetLogMessage(1).Message) observed={output!r}, "
        f"expected it to carry a message text from the loaded log (every fixture "
        f"message ends in 'level entry'); extracted payload={payload!r}; steps={notes}")
    assert payload in grid_messages, (
        f"the text the script printed observed={payload!r} is not one of the messages "
        f"the grid actually displays {grid_messages} — GetLogMessage did not read the "
        f"loaded log; raw output={output!r}; steps={notes}")
    assert "MSG=[" not in (before or ""), (
        f"the output box already contained the answer before the script ran: "
        f"{before!r}; steps={notes}")


# ── 12. Statistic percentages ────────────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="the Statistic pie of the 10-message mixed log is labelled 20% / 30% / 50% "

           "(Debug 2, Error 3, Info 5)",

    depth=1,

)
def test_statistic_percentages_on_mixed_log(app, rb, results_dir):
    notes = []
    try:
        L.rb_enter_document(app, rb, log_name=L.MIXED_LOG)
    except Exception as e:
        notes.append(f"[load mixed document] {type(e).__name__}: {e}")

    labels_before = []
    try:
        labels_before = [v for v in (L.statistic_labels(app) or []) if v and v.strip()]
    except Exception as e:
        notes.append(f"[read pie labels before opening the tab] {type(e).__name__}: {e}")

    try:
        L.tab(app, "Statistic").click_input()
        time.sleep(0.8)
    except Exception as e:
        notes.append(f"[select the Statistic tab] {type(e).__name__}: {e}")

    labels = []
    try:
        L.wait_until(
            lambda: len([v for v in (L.statistic_labels(app) or [])
                         if v and v.strip()]) >= 3, timeout=10)
        labels = [v for v in (L.statistic_labels(app) or []) if v and v.strip()]
    except Exception as e:
        notes.append(f"[read the pie slice labels] {type(e).__name__}: {e}")

    observed = sorted(labels)

    try:
        rb_uia.screenshot_assert(
            "computation_statistic_pie_mixed_log",
            "The bottom docked panel of the log document switched to its 'Statistic' "
            "tab for a 10-message log made of 5 Info, 3 Error and 2 Debug entries. The "
            "panel shows a small pie chart divided into three slices whose percentage "
            "callout labels, drawn on thin leader lines, read 50%, 30% and 20% — the "
            "50% slice is by far the largest and the 20% slice the smallest. Next to "
            "the pie is a legend of small coloured swatches reading 'Debug: 2', "
            "'Info: 5' and 'Error: 3'; no Trace, Warning or Fatal entry is listed "
            "because the log contains none. The tab row along the bottom of the panel "
            "reads 'Message Details | Bookmarks | Filter | Statistic' with 'Statistic' "
            "selected. Above it the ten-row message grid, the 'Logger Tree' panel at "
            "the right and the blue status bar reading 'Status: Running' and "
            "'10 Messages (all displayed)' are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    ok = rb_value(observed, ["20%", "30%", "50%"])
    assert ok, (
        f"Statistic pie percentage labels observed={observed} (raw={labels}), expected "
        f"sorted ['20%','30%','50%'] computed from 2 Debug / 3 Error / 5 Info out of "
        f"10 messages; labels before the tab was opened={labels_before}; steps={notes}")
    assert len(labels) == 3, (
        f"number of labelled pie slices observed={len(labels)} ({labels}), expected "
        f"exactly 3 — only the levels that actually occur get a label; steps={notes}")
    assert "17%" not in labels, (
        f"pie labels observed={labels} still carry the six-equal-slices '17%' reading of "
        f"the one-per-level log — the percentages do not track the loaded message mix; "
        f"steps={notes}")


# ── 13. New Logger form validation ───────────────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="confirming the New Logger form with an empty 'File to observe:' raises the "

           "message 'The given log file does not exist. Please select an existing one.'",

    depth=2,

)
def test_new_logger_rejects_missing_file(app, rb, results_dir):
    notes = []
    dlg = rb_enter_new_logger(app, rb, notes)

    try:
        L.named(dlg, "ListItem", "Log4Net File Receiver").click_input()
        time.sleep(0.7)
    except Exception as e:
        notes.append(f"[select the Log4Net File Receiver] {type(e).__name__}: {e}")

    file_value = None
    try:
        ed = L.named(dlg, "Edit", "File to observe:")
        ed.set_edit_text("")
        time.sleep(0.2)
        if (ed.get_value() or ""):
            ed.click_input()
            L.press("^a")
            L.press("{DELETE}")
            time.sleep(0.2)
        file_value = ed.get_value()
    except Exception as e:
        notes.append(f"[clear 'File to observe:'] {type(e).__name__}: {e}")

    boxes_before = []
    try:
        boxes_before = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[list dialogs before OK] {type(e).__name__}: {e}")

    try:
        L.btn(dlg, "OK").click_input()
        time.sleep(0.6)
    except Exception as e:
        notes.append(f"[confirm the New Logger form] {type(e).__name__}: {e}")

    box = None
    try:
        box = L.dialog(app, "Logbert", 10)
        if box is not None:
            rb.enter("validation message box")
    except Exception as e:
        notes.append(f"[wait for the validation message box] {type(e).__name__}: {e}")

    observed = ""
    try:
        parts = []
        for t in L.alld(box, "Text"):
            s = (t.window_text() or "").strip()
            if s:
                parts.append(s)
        observed = " ".join(parts)
    except Exception as e:
        notes.append(f"[read the message box text] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_new_logger_missing_file_error",
            "Full-screen capture: a small modal message box has popped up in front of "
            "the 'New Logger' dialog, which itself sits over the Logbert main window. "
            "The message box's title bar reads 'Logbert', a round red error icon with a "
            "white cross sits at its left, the message text beside the icon reads 'The "
            "given log file does not exist. Please select an existing one.' and a "
            "single default-highlighted 'OK' button sits at the bottom of the box. "
            "Around and behind the message box the 'New Logger' dialog is still open, "
            "showing its tall list of receiver types down the left side and 'OK' / "
            "'Cancel' buttons at its bottom-right corner. No log document was opened: "
            "the main window behind is still on its 'Welcome' page, with no message "
            "grid and no 'Log Level:' toolbar of coloured round buttons.",
            results_dir)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    try:
        L.btn(box, "OK").click_input()
        time.sleep(0.5)
    except Exception as e:
        notes.append(f"[dismiss the message box] {type(e).__name__}: {e}")
    try:
        L.close_dialog(app, "New Logger")
    except Exception as e:
        notes.append(f"[dismiss the New Logger dialog] {type(e).__name__}: {e}")

    ok = rb_value(observed,
                  "The given log file does not exist. Please select an existing one.")
    assert ok, (
        f"validation message observed={observed!r}, expected 'The given log file does "
        f"not exist. Please select an existing one.'; the 'File to observe:' box held "
        f"{file_value!r} when OK was pressed; dialogs before OK={boxes_before}; "
        f"steps={notes}")
    assert "Logbert" not in boxes_before, (
        f"a 'Logbert' message box was already on screen BEFORE the form was submitted "
        f"({boxes_before}) — the error is not a consequence of the validation; "
        f"steps={notes}")


# ── 14. receiver selection -> settings panel swap ────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="picking 'Syslog File Receiver' retitles the New Logger settings group from "

           "'Log4Net UDP Receiver Settings' to 'Syslog File Receiver Settings'",

    depth=1,

)
def test_receiver_selection_swaps_settings_panel(app, rb, results_dir):
    notes = []
    dlg = rb_enter_new_logger(app, rb, notes)

    before_title = ""
    titles_before = []
    try:
        titles_before = _group_titles(dlg)
        before_title = _settings_group_title(dlg)
    except Exception as e:
        notes.append(f"[read the settings group caption] {type(e).__name__}: {e}")

    try:
        L.named(dlg, "ListItem", "Syslog File Receiver").click_input()
        time.sleep(0.9)
    except Exception as e:
        notes.append(f"[select the Syslog File Receiver] {type(e).__name__}: {e}")

    after_title = ""
    titles_after = []
    try:
        L.wait_until(
            lambda: _settings_group_title(dlg).startswith("Syslog"), timeout=6)
        titles_after = _group_titles(dlg)
        after_title = _settings_group_title(dlg)
    except Exception as e:
        notes.append(f"[re-read the settings group caption] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_receiver_settings_panel_swap",
            "The 'New Logger' dialog after 'Syslog File Receiver' was clicked in the "
            "tall receiver list that fills its left half — that entry is highlighted "
            "instead of the 'Log4Net UDP Receiver' entry that is selected when the "
            "dialog opens. The group box filling the right half of the dialog is now "
            "captioned 'Syslog File Receiver Settings' and holds the Syslog file "
            "receiver's own controls (a file-to-observe text box with a browse button "
            "and time-stamp format settings); the network interface drop-down, the "
            "'Port:' box showing 7071 and the 'Join Multicast Group:' check box of the "
            "Log4Net UDP settings it showed before are gone. 'OK' and 'Cancel' buttons "
            "sit at the bottom-right corner of the dialog.",
            results_dir, window=(dlg if dlg is not None else app))
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    try:
        L.close_dialog(app, "New Logger")
    except Exception as e:
        notes.append(f"[dismiss the New Logger dialog] {type(e).__name__}: {e}")

    ok = rb_value(after_title, "Syslog File Receiver Settings")
    assert ok, (
        f"settings group caption after picking 'Syslog File Receiver' observed="
        f"{after_title!r}, expected 'Syslog File Receiver Settings'; all group captions "
        f"in the dialog={titles_after}; steps={notes}")
    assert rb_flip(before_title, after_title), (
        f"the settings group caption did not change with the selection: observed "
        f"{before_title!r} -> {after_title!r}; captions before={titles_before}; "
        f"steps={notes}")
    assert rb_value(before_title, "Log4Net UDP Receiver Settings"), (
        f"settings group caption when the dialog opened observed={before_title!r}, "
        f"expected 'Log4Net UDP Receiver Settings' (the first receiver is preselected); "
        f"all captions={titles_before}; steps={notes}")


# ── 15. File > Open Log File... -> the app detects the format and loads it ───
#
# Logbert's headline entry point. LoadFileIntoLogger() sniffs the file itself
# (log4net first, then syslog) instead of asking which receiver to use, and it
# opens the document with continuous logging DISABLED — so this path is
# distinguishable from the New Logger path by the status bar reading
# "Status: Stopped" rather than "Status: Running".

@pytest.mark.rb(

    jump_kind="value",

    expect="picking sample_log4net.log in the 'Open' file chooser loads all 6 messages "

           "(Trace..Fatal) and the document reports 'Status: Stopped'",

    depth=2,

)
def test_open_log_file_detects_and_loads_the_log(app, rb, results_dir):
    notes = []

    before_rows = None
    try:
        before_rows = L.row_count(app)
    except Exception as e:
        notes.append(f"[count rows before] {type(e).__name__}: {e}")

    try:
        L.use_menu(app, "File", "Open Log File")
    except Exception as e:
        notes.append(f"[File > Open Log File...] {type(e).__name__}: {e}")

    chooser = None
    try:
        chooser = L.dialog(app, "Open", 12)
        if chooser is None:
            notes.append("[open the file chooser] the 'Open' dialog never appeared")
        else:
            rb.enter("open file chooser")
    except Exception as e:
        notes.append(f"[open the file chooser] {type(e).__name__}: {e}")

    wanted = L.fixture(L.DEFAULT_LOG)
    typed = ""
    try:
        name_box = L.named(chooser, "Edit", "File name:") if chooser is not None else None
        if name_box is None:
            notes.append("[type the path] no 'File name:' box in the chooser")
        else:
            name_box.click_input()
            time.sleep(0.5)
            L.press("^a")
            L.type_text(wanted)
            time.sleep(0.5)
            try:
                typed = name_box.get_value() or ""
            except Exception:
                typed = ""
            if L.DEFAULT_LOG not in typed:
                # The click may not have taken focus in time — write it directly.
                notes.append(f"[type the path] keystrokes landed as {typed!r}, retrying "
                             f"with a direct write")
                name_box.set_edit_text(wanted)
                time.sleep(0.4)
                try:
                    typed = name_box.get_value() or ""
                except Exception:
                    typed = ""
    except Exception as e:
        notes.append(f"[type the path] {type(e).__name__}: {e}")

    try:
        L.press("{ENTER}")
        L.wait_until(lambda: L.row_count(app) > 0, timeout=12)
    except Exception as e:
        notes.append(f"[confirm the chooser with Enter] {type(e).__name__}: {e}")

    try:
        if L.row_count(app) == 0 and L.named(app, "Window", "Open") is not None:
            # Enter was swallowed (autocomplete popup) — press the dialog's Open button.
            notes.append("[confirm the chooser] Enter did not close it, using 'Open'")
            open_btn = L.btn(L.named(app, "Window", "Open"), "Open")
            if open_btn is not None:
                open_btn.click_input()
                L.wait_until(lambda: L.row_count(app) > 0, timeout=12)
    except Exception as e:
        notes.append(f"[confirm the chooser with the Open button] {type(e).__name__}: {e}")

    try:
        time.sleep(0.6)
        L.normalize_document(app)
        rb.enter("document")
    except Exception as e:
        notes.append(f"[settle the document] {type(e).__name__}: {e}")

    levels = []
    run_state = ""
    tabs = []
    try:
        levels = L.column_values(app, "Level")
    except Exception as e:
        notes.append(f"[read the Level column] {type(e).__name__}: {e}")
    try:
        run_state = L.run_state_text(app)
    except Exception as e:
        notes.append(f"[read the status bar] {type(e).__name__}: {e}")
    try:
        tabs = [t.window_text() for t in L.alld(app, "TabItem")]
    except Exception as e:
        notes.append(f"[read the document tabs] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "computation_open_log_file_loaded",
            "The Logbert window after a log file was opened through 'File > Open Log "
            "File...'. A second document tab sits beside 'Welcome', labelled after the "
            "Log4Net File Receiver and the file sample_log4net.log. Its message grid has "
            "the columns 'Number', 'Level', 'Timestamp', 'Logger', 'Thread' and "
            "'Message' and holds exactly six rows numbered 1 to 6, whose Level column "
            "reads Trace, Debug, Info, Warning, Error and Fatal from top to bottom; the "
            "Warning row is drawn on a yellow background and the Error row on a "
            "red/salmon background. Timestamps run 12:26:40.000 to 12:26:45.000 and the "
            "Logger column shows Root.Alpha, Root.Alpha, Root.Beta, Root.Beta, "
            "Root.Gamma, Root.Gamma. A 'Logger Tree' panel is docked at the right with "
            "the nodes Logger Root > Root > Alpha, Beta, Gamma. The blue status bar "
            "along the bottom reads 'Status: Stopped' on the left and '6 Messages (all "
            "displayed)' beside it.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    expected_levels = ["Trace", "Debug", "Info", "Warning", "Error", "Fatal"]
    assert rb_value(levels, expected_levels), (
        f"Level column after opening the file through the chooser observed={levels}, "
        f"expected {expected_levels} — the app has to sniff the log4net format and "
        f"parse every record; rows before={before_rows}; file name box={typed!r}; "
        f"tabs={tabs}; steps={notes}")
    assert rb_value(run_state, "Status: Stopped"), (
        f"status bar run state observed={run_state!r}, expected 'Status: Stopped' — the "
        f"Open Log File path opens the document with continuous logging disabled, "
        f"unlike the New Logger path which reports 'Status: Running'; steps={notes}")
    assert rb_flip(before_rows, len(levels)), (
        f"the chooser loaded nothing: row count observed {before_rows} -> {len(levels)}; "
        f"steps={notes}")