File size: 53,870 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
"""Button lane — push-button EFFECT-BY-CONSEQUENCE for Logbert.



Every test here clicks ONE push button and scores the app-authored consequence of

that click:



  * Goto First / Goto Last Message -> the Message Details pane re-renders another

    message (exact Logger / Level / Date and Time / Thread / Message values)

  * Clear Messages                 -> the grid AND the logger tree empty out

  * Toggle Bookmark               -> the Bookmarks pane gains the row of whatever

    message was selected (proved twice, with two different selections)

  * Copy Details                  -> the selected message lands on the clipboard

  * Add Filter                    -> the modal 'Edit Filter' window appears

  * Edit Filter's Cancel          -> the window goes away and nothing is committed

  * Start script / Clear all output -> the Lua output box fills, then empties

  * Zoom In / Zoom Out            -> grid row rectangles grow, then shrink back

  * Message Details' own Zoom In  -> the detail field rows grow

  * New Logger's Cancel           -> the dialog closes without loading a document



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

buttons (Start / Stop, Logger Tree, Timeshift, the six level buttons) -> state lane;

filter / search / script VALUES as computations -> computation lane; "a menu command

opens a dialog" -> menu lane; tree shape and layout geometry -> structure lane.



Never clicked from here: Exit, Close All, tab close crosses, window chrome, the

Welcome hyperlinks, Save Raw data / Save as CSV, and OK in the Options dialog.

"""
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()


DETAIL_KEYS = ("Logger", "Level", "Date and Time", "Thread", "Message")

FIRST_MESSAGE = {
    "Logger": "Root.Alpha",
    "Level": "Trace",
    "Date and Time": "12:26:40.000",
    "Thread": "T1",
    "Message": "Trace level entry",
}
LAST_MESSAGE = {
    "Logger": "Root.Gamma",
    "Level": "Fatal",
    "Date and Time": "12:26:45.000",
    "Thread": "T6",
    "Message": "Fatal level entry",
}

UNFILTERED_STATUS = "6 Messages (all displayed)"


# ── small read-only primitives (every caller wraps them in its own try/except) ─

def _details(app):
    """The five identifying Message Details fields of the selected message."""
    got = L.details_fields(app)
    return {k: got.get(k) for k in DETAIL_KEYS}


def _wait_details_level(app, level, timeout=8.0):
    """Poll until the Message Details pane shows ``level``."""
    L.wait_until(lambda: (L.details_fields(app).get("Level") or "") == level,
                 timeout=timeout)
    time.sleep(0.25)


def _message_cells(app):
    """[(element, rect), ...] of the Messages grid 'Message' column, top -> bottom.



    Scoped to the Messages pane so the Bookmarks pane's own 'Message' column can

    never bleed in.

    """
    root = L.pane(app, "Messages") or app
    out = []
    for e in L.alld(root, "Edit"):
        try:
            n = e.window_text() or ""
        except Exception:
            continue
        if not n.startswith("Message Row "):
            continue
        r = L.rect(e)
        if r is not None and r[3] > r[1]:
            out.append((e, r))
    out.sort(key=lambda er: er[1][1])
    return out


def _grid_metrics(app):
    """(tallest visible row height, top-to-bottom span, visible row count).



    The row height is read as the MAX over the visible cells so a row that is

    clipped by the viewport edge can never fake a shrink.

    """
    cells = _message_cells(app)
    if not cells:
        return None
    heights = [r[3] - r[1] for _e, r in cells]
    span = max(r[3] for _e, r in cells) - min(r[1] for _e, r in cells)
    return (max(heights), span, len(cells))


def _detail_metrics(app):
    """(height of the 'Logger' value field, vertical pitch Logger -> Message)."""
    root = L.pane(app, "Message Details")
    if root is None:
        # The bottom dock shares one slot and the active panel is persisted across
        # launches, so bring Message Details forward before measuring.
        L.select_tab(app, "Message Details")
        root = L.pane(app, "Message Details")
    if root is None:
        return None
    got = {}
    for e in L.alld(root, "Edit"):
        try:
            n = e.window_text() or ""
        except Exception:
            continue
        if n in ("Logger", "Message") and n not in got:
            r = L.rect(e)
            if r is not None:
                got[n] = r
    if "Logger" not in got:
        return None
    lr = got["Logger"]
    pitch = (got["Message"][1] - lr[1]) if "Message" in got else 0
    return (lr[3] - lr[1], pitch)


def _buttons_named(root, name):
    """Every Button under ``root`` whose visible name is exactly ``name``."""
    out = []
    for b in L.alld(root, "Button"):
        try:
            if (b.window_text() or "") == name:
                out.append(b)
        except Exception:
            continue
    return out


def _row_mate(app, name, anchor, tol=8):
    """The button called ``name`` that shares ``anchor``'s toolbar row.



    Several toolbars of a loaded document carry a button with the very same

    visible name (every docked panel has its own 'Zoom In'), so the one under

    test is picked by POSITION — same horizontal band as a button that only the

    intended toolbar owns.  No auto_id / class_name is involved.

    """
    cands = [(b, L.rect(b)) for b in _buttons_named(app, name)]
    cands = [(b, r) for b, r in cands if r is not None]
    if not cands:
        return None
    ar = L.rect(anchor)
    if ar is None:
        return cands[0][0]
    same = [(b, r) for b, r in cands if abs(r[1] - ar[1]) <= tol]
    if same:
        same.sort(key=lambda br: br[1][0])
        return same[0][0]
    cands.sort(key=lambda br: abs(br[1][1] - ar[1]))
    return cands[0][0]


def _focus_message_grid(app, notes):
    """Click the top-most 'Message' cell so the grid owns the keyboard focus."""
    try:
        cells = _message_cells(app)
        if not cells:
            notes.append("[focus message grid] no message cells found")
            return False
        cells[0][0].click_input()
        time.sleep(0.3)
        return True
    except Exception as e:
        notes.append(f"[focus message grid] {type(e).__name__}: {e}")
        return False


def rb_enter_edit_filter(app, rb, notes):
    """Click 'Add Filter' and wait for the modal 'Edit Filter' window.



    Named with the ``rb_enter*`` prefix on purpose: it IS the surface crossing

    into the dialog, so it bumps the depth tracker by one.

    """
    try:
        b = L.btn(app, "Add Filter")
        if b is None:
            notes.append("[click 'Add Filter'] button not found")
        else:
            b.click_input()
            time.sleep(0.4)
    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")
    elif rb is not None:
        rb.enter("edit filter dialog")
    return dlg


def rb_enter_new_logger(app, rb, notes):
    """File > New Logger... — the surface crossing into the New Logger dialog."""
    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 _dismiss(app, title, notes):
    """Leave the app clean: Cancel / Escape the dialog if it is still up."""
    try:
        if L.named(app, "Window", title) is not None:
            L.close_dialog(app, title)
            L.wait_until(lambda: L.named(app, "Window", title) is None, timeout=6)
    except Exception as e:
        notes.append(f"[dismiss {title!r} dialog] {type(e).__name__}: {e}")


# ── 1. Goto First Message -> details show the Trace entry ────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="clicking 'Goto First Message' repaints the Message Details pane from the "

           "last message to Logger 'Root.Alpha', Level 'Trace', Date and Time "

           "'12:26:40.000', Thread 'T1', Message 'Trace level entry'",

    depth=1,

)
def test_goto_first_message_shows_trace_entry(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 = None
    try:
        before = _details(app)
    except Exception as e:
        notes.append(f"[read details before] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Goto First Message")
        if b is None:
            notes.append("[click 'Goto First Message'] button not found")
        else:
            b.click_input()
            time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click 'Goto First Message'] {type(e).__name__}: {e}")

    after = None
    try:
        _wait_details_level(app, "Trace", timeout=8)
        after = _details(app)
    except Exception as e:
        notes.append(f"[read details after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_goto_first_message",
            "The Logbert log document right after the 'Goto First Message' toolbar "
            "button (an upward arrow near the left of the 'Log Level:' toolbar) was "
            "pressed. In the six-column message grid the FIRST data row — Number 1, "
            "Level Trace, Timestamp 12:26:40.000, Logger Root.Alpha, Thread T1, "
            "Message 'Trace level entry' — is highlighted as the selected row with a "
            "solid blue bar and white text, while the rows below keep their own "
            "colouring (the Warning row yellow, the Error row salmon/red). The "
            "'Message Details' panel docked along the bottom now mirrors that first "
            "row: its bold captions Logger: / Level: / Date and Time: / Thread: / "
            "Message: are followed by the values 'Root.Alpha', 'Trace', "
            "'12:26:40.000', 'T1' and 'Trace level entry' — no longer the Fatal / "
            "Root.Gamma / 12:26:45.000 message that was shown when the log loaded. "
            "The 'Logger Tree' panel is still docked at the right and the blue status "
            "bar still reads 'Status: Running' and '6 Messages (all displayed)'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"'Goto First Message' changed nothing in the Message Details pane: observed "
        f"{before} -> {after}, expected the pane to swap from the last message "
        f"({LAST_MESSAGE}) to the first one; steps={notes}")
    assert rb_value(after, FIRST_MESSAGE), (
        f"Message Details after the click observed={after}, expected exactly "
        f"{FIRST_MESSAGE}; steps={notes}")


# ── 2. Goto Last Message -> details show the Fatal entry ─────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="from the first message, clicking 'Goto Last Message' repaints the Message "

           "Details pane to Logger 'Root.Gamma', Level 'Fatal', Date and Time "

           "'12:26:45.000', Thread 'T6', Message 'Fatal level entry'",

    depth=1,

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

    try:
        b = L.btn(app, "Goto First Message")
        if b is None:
            notes.append("[click 'Goto First Message'] button not found")
        else:
            b.click_input()
            _wait_details_level(app, "Trace", timeout=8)
    except Exception as e:
        notes.append(f"[click 'Goto First Message'] {type(e).__name__}: {e}")

    before = None
    try:
        before = _details(app)
    except Exception as e:
        notes.append(f"[read details before] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Goto Last Message")
        if b is None:
            notes.append("[click 'Goto Last Message'] button not found")
        else:
            b.click_input()
            time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click 'Goto Last Message'] {type(e).__name__}: {e}")

    after = None
    try:
        _wait_details_level(app, "Fatal", timeout=8)
        after = _details(app)
    except Exception as e:
        notes.append(f"[read details after] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"'Goto Last Message' changed nothing in the Message Details pane: observed "
        f"{before} -> {after}, expected the pane to move off the first message "
        f"({FIRST_MESSAGE}); steps={notes}")
    assert rb_value(after, LAST_MESSAGE), (
        f"Message Details after the click observed={after}, expected exactly "
        f"{LAST_MESSAGE}; steps={notes}")


# ── 3. Clear Messages -> empty grid AND empty logger tree ────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="clicking 'Clear Messages' empties the loaded document: 6 grid rows -> 0 and "

           "the 5 Logger Tree nodes -> none",

    depth=1,

)
def test_clear_messages_empties_grid_and_logger_tree(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 = None
    try:
        before = {"rows": L.row_count(app), "logger_tree": L.logger_tree_items(app)}
    except Exception as e:
        notes.append(f"[read grid + tree before] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Clear Messages")
        if b is None:
            notes.append("[click 'Clear Messages'] button not found")
        else:
            b.click_input()
            time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click 'Clear Messages'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: L.row_count(app) == 0, timeout=8)
        time.sleep(0.4)
        after = {"rows": L.row_count(app), "logger_tree": L.logger_tree_items(app)}
    except Exception as e:
        notes.append(f"[read grid + tree after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_clear_messages",
            "The same Logbert log document after the 'Clear Messages' toolbar button "
            "(the red cross icon on the 'Log Level:' toolbar) was pressed. The "
            "six-column message grid is now completely EMPTY: only the pale blue-grey "
            "column headers Number / Level / Timestamp / Logger / Thread / Message "
            "remain, above blank white space — the six Trace / Debug / Info / Warning "
            "/ Error / Fatal rows are gone, and with them the yellow Warning row and "
            "the salmon/red Error row. The 'Logger Tree' panel docked at the right, "
            "which listed 'Logger Root' -> 'Root' -> 'Alpha' / 'Beta' / 'Gamma', is "
            "empty too. The 'Message Details' panel along the bottom still shows its "
            "bold captions Logger: / Level: / Date and Time: / Thread: / Message: / "
            "Location: / Properties: but every value field beside them is blank. The "
            "toolbar, the document tabs and the blue status bar are still in place.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"'Clear Messages' left the document untouched: observed {before} -> {after}, "
        f"expected the grid rows and the logger tree nodes to be discarded; "
        f"steps={notes}")
    assert rb_value(after, {"rows": 0, "logger_tree": []}), (
        f"document content after 'Clear Messages' observed={after}, expected "
        f"{{'rows': 0, 'logger_tree': []}} (started from {before}); steps={notes}")


# ── 4. Toggle Bookmark -> the SELECTED (third) message is bookmarked ─────────

@pytest.mark.rb(

    jump_kind="value",

    expect="with the last message selected, 'Toggle Bookmark' adds exactly one "

           "Bookmarks row: Number '6', Message 'Fatal level entry'",

    depth=1,

)
def test_toggle_bookmark_records_last_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.tab(app, "Bookmarks").click_input()
        time.sleep(0.8)
    except Exception as e:
        notes.append(f"[select Bookmarks tab] {type(e).__name__}: {e}")

    before = None
    try:
        before = L.bookmark_rows(app)
    except Exception as e:
        notes.append(f"[read bookmarks before] {type(e).__name__}: {e}")

    # Select the LAST message with a toolbar button rather than arrow keys: clicking
    # a toolbar button takes keyboard focus away from the grid, so a following
    # {DOWN} would not move the selection.
    try:
        b = L.btn(app, "Goto Last Message")
        if b is None:
            notes.append("[click 'Goto Last Message'] button not found")
        else:
            b.click_input()
            time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click 'Goto Last Message'] {type(e).__name__}: {e}")

    selected = None
    try:
        selected = L.details_fields(app).get("Message")
    except Exception as e:
        notes.append(f"[read selected message] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Toggle Bookmark")
        if b is None:
            notes.append("[click 'Toggle Bookmark'] button not found")
        else:
            b.click_input()
            time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click 'Toggle Bookmark'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: len(L.bookmark_rows(app)) > 0, timeout=8)
        after = L.bookmark_rows(app)
    except Exception as e:
        notes.append(f"[read bookmarks after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_toggle_bookmark_last_message",
            "The bottom dock of the Logbert document showing its 'Bookmarks' tab "
            "after 'Toggle Bookmark' (the flag icon on the document toolbar) was "
            "pressed with the LAST message selected. The panel is captioned "
            "'Bookmarks' and carries its own small toolbar (remove bookmark, previous "
            "/ next bookmark, zoom in / zoom out) above a grid with a narrow icon "
            "column and the headers 'Number' and 'Message'. That grid holds exactly "
            "ONE row: a small bookmark flag, the number 3 and the text 'Info level "
            "entry'. The tab row along the bottom of the panel reads 'Message Details "
            "| Bookmarks | Filter | Statistic' with 'Bookmarks' selected. Above, the "
            "six-column message grid still lists all six messages with the third row "
            "(Info / Root.Beta / 'Info level entry') highlighted in blue, 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}")

    expected = [{"Number": "6", "Message": "Fatal level entry"}]
    assert rb_flip(before, after), (
        f"'Toggle Bookmark' added nothing to the Bookmarks pane: observed "
        f"{before} -> {after}, expected an empty bookmark list to gain one row; "
        f"steps={notes}")
    assert rb_value(after, expected), (
        f"Bookmarks rows observed={after}, expected {expected} — the bookmark must "
        f"carry the message that was selected ({selected!r}, the last row); "
        f"steps={notes}")


# ── 5. Toggle Bookmark on a DIFFERENT message ────────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="with the first message selected, 'Toggle Bookmark' adds exactly one "

           "Bookmarks row: Number '1', Message 'Trace level entry'",

    depth=1,

)
def test_toggle_bookmark_records_first_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.tab(app, "Bookmarks").click_input()
        time.sleep(0.8)
    except Exception as e:
        notes.append(f"[select Bookmarks tab] {type(e).__name__}: {e}")

    before = None
    try:
        before = L.bookmark_rows(app)
    except Exception as e:
        notes.append(f"[read bookmarks before] {type(e).__name__}: {e}")

    _focus_message_grid(app, notes)

    try:
        b = L.btn(app, "Goto First Message")
        if b is None:
            notes.append("[click 'Goto First Message'] button not found")
        else:
            b.click_input()
            time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click 'Goto First Message'] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Toggle Bookmark")
        if b is None:
            notes.append("[click 'Toggle Bookmark'] button not found")
        else:
            b.click_input()
            time.sleep(0.3)
    except Exception as e:
        notes.append(f"[click 'Toggle Bookmark'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: len(L.bookmark_rows(app)) > 0, timeout=8)
        after = L.bookmark_rows(app)
    except Exception as e:
        notes.append(f"[read bookmarks after] {type(e).__name__}: {e}")

    expected = [{"Number": "1", "Message": "Trace level entry"}]
    assert rb_flip(before, after), (
        f"'Toggle Bookmark' added nothing to the Bookmarks pane: observed "
        f"{before} -> {after}, expected an empty bookmark list to gain one row; "
        f"steps={notes}")
    assert rb_value(after, expected), (
        f"Bookmarks rows observed={after}, expected {expected} — bookmarking the "
        f"FIRST message must record that message, not a fixed row; steps={notes}")


# ── 6. Copy Details -> the selected message reaches the clipboard ────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="'Copy Details' overwrites the clipboard with the selected message — the "

           "text carries 'Root.Alpha', 'Trace' and 'Trace level entry'",

    depth=1,

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

    try:
        b = L.btn(app, "Goto First Message")
        if b is None:
            notes.append("[click 'Goto First Message'] button not found")
        else:
            b.click_input()
            _wait_details_level(app, "Trace", timeout=8)
    except Exception as e:
        notes.append(f"[click 'Goto First Message'] {type(e).__name__}: {e}")

    selected = None
    try:
        selected = _details(app)
    except Exception as e:
        notes.append(f"[read details before copy] {type(e).__name__}: {e}")

    before = ""
    try:
        L.set_clipboard("RB-EMPTY")
        time.sleep(0.2)
        before = L.get_clipboard()
    except Exception as e:
        notes.append(f"[seed the clipboard] {type(e).__name__}: {e}")

    try:
        pane = L.pane(app, "Message Details")
        b = (L.btn(pane, "Copy Details") if pane is not None else None) or \
            L.btn(app, "Copy Details")
        if b is None:
            notes.append("[click 'Copy Details'] button not found")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Copy Details'] {type(e).__name__}: {e}")

    after = ""
    try:
        L.wait_until(lambda: "RB-EMPTY" not in (L.get_clipboard() or ""), timeout=8)
        after = L.get_clipboard() or ""
    except Exception as e:
        notes.append(f"[read the clipboard after] {type(e).__name__}: {e}")

    tokens = ("Root.Alpha", "Trace", "Trace level entry")
    hits = {t: rb_value(after, t) for t in tokens}

    assert rb_flip(before, after), (
        f"'Copy Details' left the clipboard untouched: it still holds {before!r} "
        f"(observed after={after!r}); the seeded sentinel must be replaced by the "
        f"selected message {selected}; steps={notes}")
    assert "RB-EMPTY" not in after, (
        f"clipboard after 'Copy Details' observed={after!r}, expected the seeded "
        f"'RB-EMPTY' sentinel to be gone; steps={notes}")
    assert all(hits.values()), (
        f"clipboard after 'Copy Details' observed={after!r}, expected it to carry the "
        f"selected message's Logger / Level / Message {tokens}; per-token match="
        f"{hits}; details pane showed {selected}; steps={notes}")


# ── 7. Add Filter -> the 'Edit Filter' window appears (depth 2) ──────────────

@pytest.mark.rb(

    jump_kind="reach",

    expect="clicking 'Add Filter' on the Filter panel opens a modal Window titled 'Edit "

           "Filter' carrying 'Filter is active', 'Expression to filter for:' and OK / "

           "Cancel",

    depth=2,

)
def test_add_filter_opens_edit_filter_dialog(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.tab(app, "Filter").click_input()
        time.sleep(0.8)
    except Exception as e:
        notes.append(f"[select Filter tab] {type(e).__name__}: {e}")

    before = set()
    titles_before = []
    try:
        before = rb_showing(app)
        titles_before = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[snapshot before] {type(e).__name__}: {e}")

    dlg = rb_enter_edit_filter(app, rb, notes)

    after = set()
    try:
        after = rb_showing(app)
    except Exception as e:
        notes.append(f"[snapshot with dialog] {type(e).__name__}: {e}")

    contents = {}
    try:
        contents = {
            "Filter is active": L.checkbox(dlg, "Filter is active") is not None,
            "Expression to filter for:":
                L.named(dlg, "Edit", "Expression to filter for:") is not None,
            "OK": L.btn(dlg, "OK") is not None,
            "Cancel": L.btn(dlg, "Cancel") is not None,
        }
    except Exception as e:
        notes.append(f"[inspect dialog contents] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_add_filter_dialog",
            "The 'Edit Filter' dialog that the Filter panel's 'Add Filter' button "
            "opened: a small framed child window centred over the Logbert main "
            "window, its caption reading 'Edit Filter'. At the top sits a checkbox "
            "labelled 'Filter is active' which is already ticked. Below it a row of "
            "two drop-down boxes — the left one choosing the log column to filter on "
            "(showing 'Number') and the right one the match operator (showing "
            "'Match') — and beneath them a labelled, still-empty text field "
            "'Expression to filter for:'. Two push buttons, 'OK' and 'Cancel', sit in "
            "the dialog's bottom-right corner. The greyed-out Logbert main window "
            "with its message grid is visible behind 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}")

    _dismiss(app, "Edit Filter", notes)

    titles_after = []
    try:
        titles_after = L.dialog_titles(app)
    except Exception as e:
        notes.append(f"[window nodes after dismiss] {type(e).__name__}: {e}")

    assert rb_reach(before, after, target="Window|Edit Filter", source=None), (
        f"'Add Filter' opened no 'Edit Filter' window; window nodes before="
        f"{titles_before}; newly visible keys={sorted(after - before)[:15]}; "
        f"steps={notes}")
    assert contents and all(contents.values()), (
        f"'Edit Filter' dialog contents observed={contents}, expected the 'Filter is "
        f"active' checkbox, the 'Expression to filter for:' field and both OK and "
        f"Cancel buttons; steps={notes}")
    assert "Edit Filter" not in titles_after, (
        f"window nodes after dismissing observed={titles_after}, expected the 'Edit "
        f"Filter' window to be gone; steps={notes}")


# ── 8. Edit Filter's Cancel -> dialog gone, nothing committed (depth 2) ──────

@pytest.mark.rb(

    jump_kind="transition",

    expect="'Cancel' in the Edit Filter dialog removes the 'Edit Filter' Window node and "

           "leaves the grid unfiltered at 6 rows / '6 Messages (all displayed)'",

    depth=2,

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

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

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

    dlg = rb_enter_edit_filter(app, rb, notes)

    before = None
    try:
        before = (L.named(app, "Window", "Edit Filter") is not None,
                  rows_before, status_before)
    except Exception as e:
        notes.append(f"[state with dialog up] {type(e).__name__}: {e}")

    try:
        b = L.btn(dlg, "Cancel") if dlg is not None else None
        if b is None:
            notes.append("[click 'Cancel'] button not found in the Edit Filter dialog")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Cancel'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: L.named(app, "Window", "Edit Filter") is None, timeout=8)
        time.sleep(0.3)
        after = (L.named(app, "Window", "Edit Filter") is not None,
                 L.row_count(app), L.message_count_text(app))
    except Exception as e:
        notes.append(f"[state after cancel] {type(e).__name__}: {e}")

    _dismiss(app, "Edit Filter", notes)

    still_up, rows_after, status_after = (after if after is not None
                                          else (None, None, None))

    assert rb_flip(before, after), (
        f"'Cancel' did not dismiss the Edit Filter dialog: observed (dialog present, "
        f"rows, status) {before} -> {after}, expected the dialog present flag to go "
        f"True -> False; steps={notes}")
    assert still_up is False, (
        f"'Edit Filter' window still present after Cancel: observed={after}, dialog "
        f"titles={L.dialog_titles(app)}; steps={notes}")
    assert rows_after == 6 and status_after == UNFILTERED_STATUS, (
        f"grid after cancelling observed rows={rows_after} / status={status_after!r}, "
        f"expected 6 and {UNFILTERED_STATUS!r} — Cancel must not commit a filter "
        f"(before: rows={rows_before}, status={status_before!r}); steps={notes}")


# ── 9. Start script -> the Lua output box fills ──────────────────────────────

@pytest.mark.rb(

    jump_kind="value",

    expect="'Start script' runs the Lua editor content and the previously empty output "

           "box gains a printed line containing 'BTN-OK'",

    depth=1,

)
def test_start_script_prints_to_output_box(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.tab(app, "Script").click_input()
        time.sleep(0.9)
    except Exception as e:
        notes.append(f"[select Script tab] {type(e).__name__}: {e}")

    before = None
    try:
        before = L.script_output(app) or ""
    except Exception as e:
        notes.append(f"[read output box before] {type(e).__name__}: {e}")

    try:
        L.put_script(app, 'Debug("BTN-OK")')
    except Exception as e:
        notes.append(f"[paste the lua source] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Start script")
        if b is None:
            notes.append("[click 'Start script'] button not found")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Start script'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: "BTN-OK" in (L.script_output(app) or ""), timeout=10)
        after = L.script_output(app) or ""
    except Exception as e:
        notes.append(f"[read output box after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_start_script_output",
            "The 'Script' tab of the Logbert document just after the 'Start script' "
            "toolbar button (the green right-pointing triangle) was pressed. The "
            "upper half is the Lua code editor with its grey line-number gutter down "
            "the left edge, now holding the single pasted line Debug(\"BTN-OK\"). The "
            "white output box underneath, which was completely empty before the run, "
            "now shows one printed line whose visible text ends in 'BTN-OK' (preceded "
            "by the run's own HH:mm:ss:fff timestamp). The output box has its own "
            "small buttons for clearing the output and toggling word wrap. The 'Log "
            "Level:' toolbar above, the 'Logger Tree' panel at the right and the blue "
            "status bar reading 'Status: Running' are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"'Start script' produced no output: the Lua output box observed "
        f"{before!r} -> {after!r}, expected it to go from empty to a printed line; "
        f"steps={notes}")
    assert rb_value(after, "BTN-OK"), (
        f"Lua output box observed={after!r}, expected it to contain 'BTN-OK' printed "
        f"by Debug(\"BTN-OK\"); steps={notes}")


# ── 10. Clear all output -> the Lua output box empties again ────────────────

@pytest.mark.rb(

    jump_kind="transition",

    expect="after a script run has filled the Lua output box, 'Clear all output' takes "

           "it back to empty",

    depth=1,

)
def test_clear_all_output_empties_script_output(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.tab(app, "Script").click_input()
        time.sleep(0.9)
    except Exception as e:
        notes.append(f"[select Script tab] {type(e).__name__}: {e}")

    try:
        L.put_script(app, 'Debug("BTN-CLEAR")')
    except Exception as e:
        notes.append(f"[paste the lua source] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Start script")
        if b is None:
            notes.append("[click 'Start script'] button not found")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Start script'] {type(e).__name__}: {e}")

    before = None
    try:
        L.wait_until(lambda: "BTN-CLEAR" in (L.script_output(app) or ""), timeout=10)
        before = L.script_output(app) or ""
    except Exception as e:
        notes.append(f"[read the filled output box] {type(e).__name__}: {e}")

    try:
        b = L.btn(app, "Clear all output")
        if b is None:
            notes.append("[click 'Clear all output'] button not found")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Clear all output'] {type(e).__name__}: {e}")

    after = None
    try:
        L.wait_until(lambda: (L.script_output(app) or "").strip() == "", timeout=8)
        after = L.script_output(app) or ""
    except Exception as e:
        notes.append(f"[read the emptied output box] {type(e).__name__}: {e}")

    assert before is not None and "BTN-CLEAR" in before, (
        f"the output box was never filled, so 'Clear all output' had nothing to "
        f"clear: observed={before!r}, expected a line containing 'BTN-CLEAR'; "
        f"steps={notes}")
    assert rb_flip(before, after), (
        f"'Clear all output' changed nothing: the Lua output box observed "
        f"{before!r} -> {after!r}, expected the printed line to be discarded; "
        f"steps={notes}")
    assert after is not None and after.strip() == "", (
        f"Lua output box after 'Clear all output' observed={after!r}, expected it to "
        f"be empty; steps={notes}")


# ── 11. Zoom In on the Messages toolbar -> taller grid rows ─────────────────

@pytest.mark.rb(

    jump_kind="transition",

    expect="the Messages toolbar 'Zoom In' enlarges the grid font so the message row "

           "rectangles get taller than the default",

    depth=1,

)
def test_zoom_in_enlarges_message_rows(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:
        b = L.btn(app, "Goto First Message")
        if b is not None:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[scroll grid to the top] {type(e).__name__}: {e}")

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

    zoom = None
    try:
        zoom = _row_mate(app, "Zoom In", L.btn(app, "Toggle Bookmark"))
        if zoom is None:
            notes.append("[locate Messages toolbar 'Zoom In'] button not found")
    except Exception as e:
        notes.append(f"[locate Messages toolbar 'Zoom In'] {type(e).__name__}: {e}")

    try:
        if zoom is not None:
            zoom.click_input()
            time.sleep(0.4)
            zoom.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Zoom In' twice] {type(e).__name__}: {e}")

    after = None
    try:
        if before is not None:
            L.wait_until(
                lambda: (_grid_metrics(app) or (0, 0, 0))[0] != before[0], timeout=6)
        time.sleep(0.3)
        after = _grid_metrics(app)
    except Exception as e:
        notes.append(f"[measure rows after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_zoom_in_message_rows",
            "The Logbert message grid after the 'Zoom In' magnifier (the one on the "
            "main document toolbar, next to the bookmark flag) was pressed twice. The "
            "six messages Trace / Debug / Info / Warning / Error / Fatal are rendered "
            "in a visibly LARGER font and every row is noticeably taller than the "
            "compact default, so the six rows fill much more of the grid area and the "
            "text under the Number / Level / Timestamp / Logger / Thread / Message "
            "headers is bigger. The column headers themselves keep their original "
            "size, the Warning row is still yellow and the Error row still salmon/red, "
            "the first row stays selected in blue, and the 'Logger Tree' panel at the "
            "right, the 'Message Details' panel at the bottom and the blue status bar "
            "are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"'Zoom In' left the grid geometry identical: (row height, span, cells) "
        f"observed {before} -> {after}, expected taller rows; steps={notes}")
    assert before is not None and after is not None and after[0] > before[0], (
        f"message row height observed {before[0] if before else None} -> "
        f"{after[0] if after else None} px, expected after_h > before_h after two "
        f"'Zoom In' clicks (full metrics {before} -> {after}); steps={notes}")


# ── 12. Zoom Out -> the rows shrink back ────────────────────────────────────

@pytest.mark.rb(

    jump_kind="transition",

    expect="'Zoom Out' undoes 'Zoom In': the message row rectangles shrink back to (or "

           "below) their original height",

    depth=1,

)
def test_zoom_out_restores_message_rows(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:
        b = L.btn(app, "Goto First Message")
        if b is not None:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[scroll grid to the top] {type(e).__name__}: {e}")

    base = None
    try:
        base = _grid_metrics(app)
    except Exception as e:
        notes.append(f"[measure rows at default zoom] {type(e).__name__}: {e}")

    zoom_in = zoom_out = None
    try:
        anchor = L.btn(app, "Toggle Bookmark")
        zoom_in = _row_mate(app, "Zoom In", anchor)
        zoom_out = _row_mate(app, "Zoom Out", anchor)
        if zoom_in is None or zoom_out is None:
            notes.append("[locate Messages toolbar zoom buttons] not both found")
    except Exception as e:
        notes.append(f"[locate Messages toolbar zoom buttons] {type(e).__name__}: {e}")

    zoomed = None
    try:
        if zoom_in is not None:
            zoom_in.click_input()
            time.sleep(0.4)
            zoom_in.click_input()
            time.sleep(0.4)
        if base is not None:
            L.wait_until(
                lambda: (_grid_metrics(app) or (0, 0, 0))[0] != base[0], timeout=6)
        time.sleep(0.3)
        zoomed = _grid_metrics(app)
    except Exception as e:
        notes.append(f"[click 'Zoom In' twice] {type(e).__name__}: {e}")

    try:
        if zoom_out is not None:
            zoom_out.click_input()
            time.sleep(0.4)
            zoom_out.click_input()
            time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click 'Zoom Out' twice] {type(e).__name__}: {e}")

    restored = None
    try:
        if zoomed is not None:
            L.wait_until(
                lambda: (_grid_metrics(app) or (0, 0, 0))[0] != zoomed[0], timeout=6)
        time.sleep(0.3)
        restored = _grid_metrics(app)
    except Exception as e:
        notes.append(f"[measure rows after zoom out] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_zoom_out_message_rows",
            "The same Logbert message grid after 'Zoom In' was pressed twice and then "
            "the neighbouring 'Zoom Out' magnifier twice. The rows have shrunk back to "
            "their compact default: all six messages (Trace, Debug, Info, Warning, "
            "Error, Fatal) are again drawn in small text and together occupy only the "
            "upper part of the grid area, leaving empty white space below — the "
            "enlarged, tall rows are gone. The Warning row is still yellow, the Error "
            "row still salmon/red, the first row stays selected in blue, and the "
            "'Logger Tree' panel at the right, the 'Message Details' panel at the "
            "bottom and the blue status bar reading 'Status: Running' / '6 Messages "
            "(all displayed)' are unchanged.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert base is not None and zoomed is not None and zoomed[0] > base[0], (
        f"the 'Zoom In' precondition failed: row height observed "
        f"{base[0] if base else None} -> {zoomed[0] if zoomed else None} px "
        f"(metrics {base} -> {zoomed}); steps={notes}")
    assert rb_flip(zoomed, restored), (
        f"'Zoom Out' left the enlarged grid untouched: (row height, span, cells) "
        f"observed {zoomed} -> {restored}, expected the rows to shrink; steps={notes}")
    assert restored is not None and restored[0] < zoomed[0] and restored[0] <= base[0], (
        f"message row height observed default={base[0] if base else None} -> "
        f"zoomed={zoomed[0] if zoomed else None} -> after zoom out="
        f"{restored[0] if restored else None} px, expected the final height to be "
        f"below the zoomed one and no larger than the default; steps={notes}")


# ── 13. New Logger's Cancel -> dialog closes, no document loaded ─────────────

@pytest.mark.rb(

    jump_kind="transition",

    expect="'Cancel' in the New Logger dialog removes the 'New Logger' Window node and "

           "loads no document — the message grid stays empty",

    depth=1,

)
def test_new_logger_cancel_loads_nothing(app, rb):
    notes = []

    dlg = rb_enter_new_logger(app, rb, notes)

    before = None
    try:
        before = (L.named(app, "Window", "New Logger") is not None, L.row_count(app))
    except Exception as e:
        notes.append(f"[state with dialog up] {type(e).__name__}: {e}")

    try:
        b = L.btn(dlg, "Cancel") if dlg is not None else None
        if b is None:
            notes.append("[click 'Cancel'] button not found in the New Logger dialog")
        else:
            b.click_input()
            time.sleep(0.4)
    except Exception as e:
        notes.append(f"[click 'Cancel'] {type(e).__name__}: {e}")

    after = None
    titles = []
    tabs = []
    try:
        L.wait_until(lambda: L.named(app, "Window", "New Logger") is None, timeout=8)
        time.sleep(0.3)
        after = (L.named(app, "Window", "New Logger") is not None, L.row_count(app))
    except Exception as e:
        notes.append(f"[state after cancel] {type(e).__name__}: {e}")
    try:
        titles = L.dialog_titles(app)
        tabs = [t.window_text() or "" for t in L.alld(app, "TabItem")]
    except Exception as e:
        notes.append(f"[read window nodes / tabs] {type(e).__name__}: {e}")

    _dismiss(app, "New Logger", notes)

    still_up, rows_after = after if after is not None else (None, None)

    assert rb_flip(before, after), (
        f"'Cancel' did not dismiss the New Logger dialog: (dialog present, grid rows) "
        f"observed {before} -> {after}, expected the dialog present flag to go "
        f"True -> False; steps={notes}")
    assert still_up is False, (
        f"'New Logger' window still present after Cancel: observed={after}, window "
        f"nodes={titles}; steps={notes}")
    assert rows_after == 0, (
        f"message grid rows after cancelling observed={rows_after}, expected 0 — Cancel "
        f"must not load a log; document tabs={tabs}; steps={notes}")
    assert not any(t.startswith("Log4Net") for t in tabs), (
        f"document tabs after cancelling observed={tabs}, expected no receiver "
        f"document tab to have been created; steps={notes}")


# ── 14. Message Details' own Zoom In -> taller detail rows ──────────────────

@pytest.mark.rb(

    jump_kind="transition",

    expect="the Message Details panel's own 'Zoom In' enlarges its field font so the "

           "'Logger' value row gets taller",

    depth=1,

)
def test_message_details_zoom_in_enlarges_fields(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 = None
    try:
        before = _detail_metrics(app)
    except Exception as e:
        notes.append(f"[measure detail fields before] {type(e).__name__}: {e}")

    zoom = None
    try:
        pane = L.pane(app, "Message Details")
        zoom = (L.btn(pane, "Zoom In") if pane is not None else None) or \
            _row_mate(app, "Zoom In", L.btn(app, "Copy Details"))
        if zoom is None:
            notes.append("[locate Message Details 'Zoom In'] button not found")
    except Exception as e:
        notes.append(f"[locate Message Details 'Zoom In'] {type(e).__name__}: {e}")

    try:
        if zoom is not None:
            zoom.click_input()
            time.sleep(0.4)
            zoom.click_input()
            time.sleep(0.5)
    except Exception as e:
        notes.append(f"[click the details 'Zoom In' twice] {type(e).__name__}: {e}")

    after = None
    try:
        if before is not None:
            L.wait_until(
                lambda: (_detail_metrics(app) or (0, 0)) != before, timeout=6)
        time.sleep(0.3)
        after = _detail_metrics(app)
    except Exception as e:
        notes.append(f"[measure detail fields after] {type(e).__name__}: {e}")

    try:
        rb_uia.screenshot_assert(
            "button_details_zoom_in",
            "The 'Message Details' panel docked along the bottom of the Logbert "
            "document after ITS OWN 'Zoom In' magnifier — the small vertical toolbar "
            "at the panel's left edge, next to the 'Copy Details' icon — was pressed "
            "twice. The bold field captions 'Logger:', 'Level:', 'Date and Time:', "
            "'Thread:', 'Message:', 'Location:' and 'Properties:' and the read-only "
            "values beside them are drawn in a visibly LARGER font than the default, "
            "so each labelled row is taller and the block of detail rows takes up more "
            "vertical space inside the panel (the lowest rows may be pushed out of "
            "sight at the panel's bottom edge). The message grid above with its six "
            "rows, the 'Logger Tree' panel at the right and the blue status bar are "
            "unchanged, and the panel's tab row still reads 'Message Details | "
            "Bookmarks | Filter | Statistic'.",
            results_dir, window=app)
    except Exception as e:
        notes.append(f"[screenshot] {type(e).__name__}: {e}")

    assert rb_flip(before, after), (
        f"the Message Details 'Zoom In' left the field geometry identical: "
        f"(Logger field height, Logger->Message pitch) observed {before} -> {after}, "
        f"expected taller detail rows; steps={notes}")
    assert (before is not None and after is not None
            and (after[0] > before[0] or after[1] > before[1])), (
        f"detail field geometry observed {before} -> {after}, expected the 'Logger' "
        f"value row to grow (height {before[0] if before else None} -> "
        f"{after[0] if after else None} px) or the Logger->Message pitch to grow "
        f"({before[1] if before else None} -> {after[1] if after else None} px) after "
        f"two clicks; steps={notes}")